Files
Lab505/README.md
2026-10-12 15:24:08 +07:00

2291 lines
75 KiB
Markdown

# Lab505 — Tài liệu học C# qua thực tế
> Tài liệu này **không chỉ mô tả hệ thống** — nó giải thích *tại sao* code được viết theo cách đó, dùng code thật của dự án làm ví dụ. Bạn chỉ cần biết C# cơ bản (class, method, if/else) là có thể đọc được.
---
## Mục lục
1. [Dự án làm gì? — Bức tranh lớn](#1-dự-án-làm-gì--bức-tranh-lớn)
2. [Interface — Hợp đồng, không phải triển khai](#2-interface--hợp-đồng-không-phải-triển-khai)
3. [Abstract Class — Chia sẻ code chung giữa các driver](#3-abstract-class--chia-sẻ-code-chung-giữa-các-driver)
4. [Dependency Injection — Ai tạo object, ai cung cấp](#4-dependency-injection--ai-tạo-object-ai-cung-cấp)
5. [Singleton vs Scoped vs Transient — Vòng đời object](#5-singleton-vs-scoped-vs-transient--vòng-đời-object)
6. [async/await — Tại sao mọi thứ đều bất đồng bộ](#6-asyncawait--tại-sao-mọi-thứ-đều-bất-đồng-bộ)
7. [CancellationToken — Cách hủy tác vụ đang chạy](#7-cancellationtoken--cách-hủy-tác-vụ-đang-chạy)
8. [Event & Delegate — Thông báo khi state thay đổi](#8-event--delegate--thông-báo-khi-state-thay-đổi)
9. [Thread Safety — Khi nhiều luồng đụng nhau](#9-thread-safety--khi-nhiều-luồng-đụng-nhau)
10. [IHostedService — Background task chạy suốt vòng đời app](#10-ihostedservice--background-task-chạy-suốt-vòng-đời-app)
11. [Extension Methods — Tổ chức code theo nhóm](#11-extension-methods--tổ-chức-code-theo-nhóm)
12. [Guard Pattern — Kiểm tra điều kiện trước khi thực thi](#12-guard-pattern--kiểm-tra-điều-kiện-trước-khi-thực-thi)
13. [Strategy Pattern — Đổi hành vi lúc runtime](#13-strategy-pattern--đổi-hành-vi-lúc-runtime)
14. [Options Pattern — Đọc config từ appsettings.json](#14-options-pattern--đọc-config-từ-appsettingsjson)
15. [TaskCompletionSource — Chờ sự kiện không cần polling](#15-taskcompletionsource--chờ-sự-kiện-không-cần-polling)
16. [record — Kiểu dữ liệu bất biến hiện đại](#16-record--kiểu-dữ-liệu-bất-biến-hiện-đại)
17. [Func\<\> và Action\<\> — Delegate như tham số](#17-func-và-action--delegate-như-tham-số)
18. [Bảo mật mật khẩu — PBKDF2 và Constant-time Compare](#18-bảo-mật-mật-khẩu--pbkdf2-và-constant-time-compare)
19. [SemaphoreSlim — lock dùng được với async](#19-semaphoreslim--lock-dùng-được-với-async)
20. [IDisposable — Dọn dẹp tài nguyên, tránh memory leak](#20-idisposable--dọn-dẹp-tài-nguyên-tránh-memory-leak)
21. [Claims — Định danh và quyền hạn trong mỗi request](#21-claims--định-danh-và-quyền-hạn-trong-mỗi-request)
22. [Roslyn Script Engine — Compile và chạy C# lúc runtime](#22-roslyn-script-engine--compile-và-chạy-c-lúc-runtime)
23. [Generics \<T\> và out parameter — Hai pattern thấy ở mọi nơi](#23-generics-t-và-out-parameter--hai-pattern-thấy-ở-mọi-nơi)
24. [Cài đặt & Chạy](#24-cài-đặt--chạy)
---
## 1. Dự án làm gì? — Bức tranh lớn
**Lab505** điều khiển 5 thiết bị robot công nghiệp qua giao diện web. Điểm thú vị về mặt kỹ thuật:
- Hệ thống phải hoạt động với **phần cứng thật** và **mô phỏng (simulation)** — cùng một code
- **30+ sinh viên** có thể dùng cùng lúc — mỗi người có môi trường simulation riêng
- Robot di chuyển liên tục → UI phải cập nhật **real-time** mà không cần F5
- Nhiều người cùng muốn điều khiển robot → cần **lock** để tránh xung đột
5 thiết bị:
| Ký hiệu | Thiết bị | Giao thức kết nối |
|---------|---------|------------------|
| **IMR** | Robot di động trong kho | OPC UA + VDA5050 REST |
| **AMR** | Robot di động ngoài kho | VDA5050 REST |
| **Dobot** | Cánh tay robot | OPC UA |
| **Conveyor** | Băng tải C1, C2 | Modbus TCP |
| **ASRS** | Kệ lưu trữ tự động | Modbus TCP |
---
## 2. Interface — Hợp đồng, không phải triển khai
### Vấn đề không có interface
Tưởng tượng bạn viết code điều khiển robot thẳng vào FlowService:
```csharp
// Không tốt — code bị ràng buộc cứng vào OPC UA
public class FlowService
{
private OpcUaClient _opcClient;
public async Task MoveImrToAbb()
{
await _opcClient.WriteNode("ns=3;s=IMR.MoveTo", "Abb");
// Nếu muốn dùng simulation thay vì OPC UA → phải sửa class này
// Nếu OPC UA thay bằng giao thức khác → phải sửa class này
}
}
```
Vấn đề: mỗi khi thay đổi cách kết nối thiết bị, phải sửa toàn bộ business logic.
### Giải pháp: Interface
**Interface** là "hợp đồng" — nói *cái gì* có thể làm, không nói *làm thế nào*.
Trong dự án, `IDriverContext` là interface gom tất cả driver:
```csharp
// Lab505/Application/Contexts/IDriverContext.cs
public interface IDriverContext
{
bool IsReal { get; }
// Drivers — chỉ khai báo, không có code thực thi
ImrVdaDriver Imr { get; }
AmrVdaDriver Amr { get; }
IConveyorDriver Conveyor { get; }
IAsrsDriver Asrs { get; }
IDobotDriver Dobot { get; }
// State
RobotState ImrState { get; }
SystemCondition SystemCondition { get; }
// Workflow
FlowService Workflow { get; }
DeviceGroupLock Locks { get; }
}
```
Sau đó có **hai class implement** interface này:
```
IDriverContext
├── RealDriverContext → dùng thiết bị thật (OPC UA, Modbus, VDA5050)
└── SimDriverContext → dùng simulator (giả lập trong memory)
```
`FlowService` chỉ nhận `IDriverContext` — không biết bên dưới là real hay sim:
```csharp
public class FlowService
{
private readonly IDriverContext _ctx;
public FlowService(IDriverContext ctx) { _ctx = ctx; }
public async Task MoveImrToAbb(CancellationToken ct)
{
await _ctx.Imr.MoveToAbb(ct); // Không quan tâm real hay sim
}
}
```
### Interface cho từng thiết bị
Conveyor và ASRS dùng interface riêng vì có nhiều cách implement:
```csharp
public interface IConveyorDriver
{
Task StartAsync(ConveyorId id, ConveyorDirection dir, CancellationToken ct = default);
Task StopAsync(ConveyorId id, CancellationToken ct = default);
ConveyorStatusDto GetStatus();
}
// Real: dùng Modbus TCP kết nối PLC
public class ConveyorDriver : IConveyorDriver { ... }
// Sim: cập nhật state trong memory
public class SimConveyorDriver : IConveyorDriver { ... }
```
> **Quy tắc để nhớ:** Nếu một class có thể được thay thế bằng một class khác với hành vi khác nhau → dùng interface.
---
## 3. Abstract Class — Chia sẻ code chung giữa các driver
### Vấn đề
IMR và AMR đều dùng VDA5050. Nếu không tổ chức tốt:
```csharp
// Viết trùng code
public class ImrVdaDriver
{
public async Task CallSimple(string action, CancellationToken t)
{
CheckOnline(); // Trùng nhau
var a = new RobotAction { ... }; // Trùng nhau
await Api.PostInstantAction(...); // Trùng nhau
}
}
public class AmrVdaDriver
{
public async Task CallSimple(string action, CancellationToken t)
{
CheckOnline(); // y hệt
var a = new RobotAction { ... }; // y hệt
await Api.PostInstantAction(...); // y hệt
}
}
```
### Giải pháp: Abstract Class
`VdaDriverBase` chứa code **dùng chung**, các subclass chỉ viết phần **riêng**:
```csharp
// Lab505/Infrastructure/Drivers/VdaDriverBase.cs
public abstract class VdaDriverBase(
IApiService api, RobotState state, string robotId,
IStatePollTrigger pollTrigger, INotificationService notif)
{
protected readonly IApiService Api = api;
public RobotState State { get; } = state;
protected readonly string RobotId = robotId;
// ── Code dùng chung — IMR và AMR đều dùng ──────────────────
protected void CheckOnline()
{
if (!State.IsOnline_Vda)
throw new InvalidOperationException(
$"{RobotId}: thiết bị offline, không thể gửi lệnh");
}
protected async Task CallSimple(string action, CancellationToken t)
{
CheckOnline();
var a = new RobotAction {
ActionId = Guid.NewGuid().ToString("N"),
ActionType = action
};
await Api.PostInstantAction(RobotId, a, t);
pollTrigger.TriggerRefresh(); // Poll ngay để lấy state mới
notif.Notify($"[{RobotId}] {action} sent", "info");
}
// ── Method abstract — mỗi subclass override khác nhau ──────
public abstract Task Cancel_Vda(CancellationToken t = default);
}
```
`ImrVdaDriver` kế thừa và chỉ viết phần riêng của IMR:
```csharp
// Lab505/Infrastructure/Drivers/Imr/ImrVdaDriver.cs
public class ImrVdaDriver(
IApiService api, RobotState state,
IStatePollTrigger pollTrigger, INotificationService notif,
ImrCommandGuard guard)
: VdaDriverBase(api, state, "IMR", pollTrigger, notif)
{
private readonly ImrCommandGuard _guard = guard;
// IMR-specific: di chuyển đến trạm ABB
public Task MoveToAbb(CancellationToken t = default)
{
_guard.RequireCanMoveToABB(); // Kiểm tra điều kiện trước
return DockToStation("Abb", t); // Gọi method từ base class
}
// IMR-specific: load hàng
public override Task Load_Vda(CancellationToken t = default)
{
_guard.RequireCanLoad();
return CallSimple("Load", t); // CallSimple từ base class
}
// Override abstract
public override Task Cancel_Vda(CancellationToken t = default)
=> CancelWithNotify(t);
}
```
### So sánh Interface vs Abstract Class
| | Interface | Abstract Class |
|---|-----------|---------------|
| **Mục đích** | Định nghĩa hành vi (cái gì) | Chia sẻ code chung (làm thế nào) |
| **Kế thừa** | Một class có thể implement nhiều | Chỉ kế thừa một |
| **Có code không** | Không (chỉ signature) | Có thể có code |
| **Dùng khi nào** | Muốn đổi implementation | Muốn tái sử dụng code |
---
## 4. Dependency Injection — Ai tạo object, ai cung cấp
### Vấn đề không có DI
```csharp
// Không tốt — FlowService tự tạo dependencies
public class FlowService
{
private ImrVdaDriver _imr;
public FlowService()
{
// FlowService phải biết cách tạo ImrVdaDriver
// → phải biết cả IApiService, RobotState, INotificationService...
// → coupling rất cao, khó test
var api = new VdaApiService(new HttpClient(), "https://...");
var state = new RobotState();
_imr = new ImrVdaDriver(api, state, ...);
}
}
```
### Giải pháp: DI Container
ASP.NET Core có **DI Container** — một "kho" chứa tất cả object. Bạn chỉ cần:
1. Đăng ký object vào container (trong `Program.cs`)
2. Khai báo cần gì trong constructor → container tự cung cấp
```csharp
// Program.cs — đăng ký
builder.Services.AddSingleton<RobotState>(); // Tạo 1 lần, dùng mãi
builder.Services.AddSingleton<IApiService, VdaApiService>();
builder.Services.AddSingleton<ImrCommandGuard>();
builder.Services.AddSingleton<ImrVdaDriver>(); // DI tự inject RobotState vào
builder.Services.AddSingleton<FlowService>(); // DI tự inject ImrVdaDriver vào
```
```csharp
// FlowService — chỉ khai báo cần gì, không tự tạo
public class FlowService
{
private readonly ImrVdaDriver _imr;
// Constructor: DI container sẽ tự điền tham số này
public FlowService(ImrVdaDriver imr)
{
_imr = imr; // Nhận từ DI, không tự tạo
}
}
```
### Primary Constructor (C# 12)
Dự án dùng cú pháp mới hơn — viết gọn hơn:
```csharp
// Cách cũ (C# 10 trở về)
public class ImrVdaDriver
{
private readonly ImrCommandGuard _guard;
public ImrVdaDriver(IApiService api, RobotState state, ImrCommandGuard guard)
{
_guard = guard;
}
}
// Cách mới (C# 12) — dự án dùng cách này
public class ImrVdaDriver(
IApiService api, RobotState state,
IStatePollTrigger pollTrigger, INotificationService notif,
ImrCommandGuard guard)
: VdaDriverBase(api, state, "IMR", pollTrigger, notif)
{
private readonly ImrCommandGuard _guard = guard; // Vẫn lưu vào field nếu cần
}
```
---
## 5. Singleton vs Scoped vs Transient — Vòng đời object
Khi đăng ký DI, phải chọn **lifetime** — object được tạo khi nào, bị hủy khi nào.
### Ba loại lifetime
**Singleton** — Tạo **một lần duy nhất**, dùng suốt vòng đời app:
```csharp
builder.Services.AddSingleton<RobotState>();
// → Cùng một RobotState instance cho tất cả request
// → Phù hợp với: trạng thái robot, driver kết nối thiết bị, lock
```
**Scoped** — Tạo **một lần mỗi HTTP request**:
```csharp
builder.Services.AddScoped<UserContextResolver>();
// → Mỗi request HTTP nhận một UserContextResolver mới
// → Phù hợp với: những gì cần biết user hiện tại là ai
```
**Transient** — Tạo **mới mỗi lần inject**:
```csharp
builder.Services.AddTransient<SomeHelper>();
// → Mỗi lần inject nhận instance mới
// → Phù hợp với: object nhẹ, stateless
```
### Ví dụ thực tế trong dự án
```csharp
// Program.cs
// Singleton — tồn tại suốt app, tất cả user dùng chung
builder.Services.AddSingleton<RobotState>(); // Trạng thái robot IMR (shared)
builder.Services.AddSingleton<ImrVdaDriver>(); // Driver kết nối IMR
builder.Services.AddSingleton<DeviceGroupLock>(); // Lock toàn hệ thống
builder.Services.AddSingleton<RealDriverContext>();// Stack real hardware
// Scoped — tạo mới mỗi request để biết user nào đang gọi
builder.Services.AddScoped<UserContextResolver>(); // Resolver per-request
// Singleton per-user — UserSimPool tạo SimDriverContext riêng cho mỗi user
builder.Services.AddSingleton<UserSimPool>();
// → Bên trong UserSimPool: Dictionary<int, SimDriverContext>
// key = userId, value = context riêng của user đó
```
> **Cảnh báo phổ biến:** Không inject Scoped service vào Singleton. Singleton sống mãi, Scoped chỉ sống trong 1 request — nếu Singleton giữ reference đến Scoped, Scoped sẽ không bị hủy đúng cách.
---
## 6. async/await — Tại sao mọi thứ đều bất đồng bộ
### Vấn đề với code đồng bộ
Giao tiếp với robot mất thời gian: gửi lệnh qua mạng, chờ phản hồi, có thể mất 1-30 giây. Nếu code đồng bộ:
```csharp
// Code đồng bộ — CHẶN thread trong 10 giây
public void MoveImrToAbb()
{
var result = httpClient.Post(...); // Thread bị block ở đây 10 giây
// → Server không thể xử lý request nào khác trong lúc này!
}
```
Web server có giới hạn thread pool. Nếu 30 sinh viên cùng gửi lệnh robot, 30 thread bị chặn → server hết thread → timeout.
### Giải pháp: async/await
```csharp
// Code bất đồng bộ — KHÔNG chặn thread
public async Task MoveImrToAbb(CancellationToken t = default)
{
// await: "nhả" thread về pool trong khi chờ HTTP response
// Khi response về → thread pool cấp thread mới tiếp tục
await httpClient.PostAsync(..., t);
// Tiếp tục ở đây sau khi response về
}
```
`async/await` không tạo thêm thread — nó *tái sử dụng* thread hiệu quả hơn.
### Quy tắc trong dự án
**1. Method nào gọi I/O (network, disk) → phải async:**
```csharp
// Gọi HTTP → async
protected async Task CallSimple(string action, CancellationToken t)
{
await Api.PostInstantAction(RobotId, a, t);
}
// Gọi OPC UA → async
public async Task MoveToNodeAsync(string nodeId, CancellationToken t)
{
await _opcNode.WriteValueAsync(nodeId, t);
}
```
**2. Method nào gọi async method → cũng phải async (chain):**
```csharp
public async Task RunPhase4(CancellationToken ct)
{
await _ctx.Imr.MoveToAbb(ct); // async
await _ctx.Dobot.PickUp(ct); // async
}
```
**3. `Task.WhenAll` — chạy song song thay vì tuần tự:**
```csharp
// Tuần tự: IMR poll xong rồi mới poll AMR → 300ms + 300ms = 600ms
await UpdateOne("IMR", imrState, stopToken);
await UpdateOne("AMR2WS", amrState, stopToken);
// Song song: IMR và AMR poll cùng lúc → max(300ms, 300ms) = 300ms
await Task.WhenAll(
UpdateOne("IMR", imrState, stopToken),
UpdateOne("AMR2WS", amrState, stopToken));
```
Đây là code thật trong `VdaStatePoller`:
```csharp
// Lab505/Infrastructure/State/VdaStatePoller.cs
private async Task Loop(CancellationToken stopToken)
{
while (!stopToken.IsCancellationRequested)
{
// IMR và AMR poll đồng thời — không để robot này chờ robot kia
await Task.WhenAll(
UpdateOne("IMR", imrState, stopToken),
UpdateOne("AMR2WS", amrState, stopToken));
await Task.Delay(300, linked.Token); // Chờ 300ms rồi poll lại
}
}
```
---
## 7. CancellationToken — Cách hủy tác vụ đang chạy
### Vấn đề
Workflow chạy 10 phút. Sinh viên muốn dừng khẩn cấp giữa chừng. Nếu không có cơ chế hủy → phải chờ hết 10 phút.
### CancellationToken là gì
`CancellationToken` là một "cờ" — khi bị cancel, mọi `await` đang dùng nó sẽ ném `OperationCanceledException`.
```csharp
// Tạo source (nơi ra lệnh hủy)
var cts = new CancellationTokenSource();
// Khởi chạy workflow, truyền token vào
_ = Task.Run(() => RunWorkflow(cts.Token));
// Khi cần dừng:
cts.Cancel(); // → Tất cả await dùng cts.Token sẽ throw OperationCanceledException
```
### Truyền token xuyên suốt call chain
Mọi method trong dự án đều nhận `CancellationToken`:
```csharp
// FlowService
public async Task RunFullCycle(int times, CancellationToken ct)
{
for (int i = 0; i < times; i++)
{
await Phase1_Init(ct); // ct truyền xuống
await Phase2_AsrsToC2(ct); // ct truyền xuống
// ...
}
}
// VdaDriverBase
protected async Task CallSimple(string action, CancellationToken t)
{
await Api.PostInstantAction(RobotId, a, t); // t truyền xuống HTTP call
}
```
Khi user bấm Emergency Stop:
```
cts.Cancel()
→ ct bị cancel
→ Phase2 đang await → OperationCanceledException
→ RunFullCycle propagate exception
→ Workflow dừng
```
### Xử lý cancel đúng cách
```csharp
// VdaStatePoller — ví dụ xử lý cancel
private async Task Loop(CancellationToken stopToken)
{
while (!stopToken.IsCancellationRequested)
{
try
{
await Task.WhenAll(...);
}
catch (OperationCanceledException) when (stopToken.IsCancellationRequested)
{
return; // App đang shutdown → thoát sạch
}
catch (Exception ex)
{
// Lỗi thật sự (network, etc.) → log và tiếp tục
notif?.Notify($"Poll lỗi: {ex.Message}", "error");
}
// Chờ 300ms, có thể bị ngắt sớm bởi TriggerRefresh()
using var linked = CancellationTokenSource.CreateLinkedTokenSource(
stopToken, _delayCts.Token);
try
{
await Task.Delay(300, linked.Token);
}
catch (OperationCanceledException) when (!stopToken.IsCancellationRequested)
{
// TriggerRefresh() gọi — ngắt delay sớm, tiếp tục poll ngay
// Không return vì stopToken chưa bị cancel
}
}
}
```
**`when (condition)`** trong catch — chỉ catch khi điều kiện đúng. Rất tiện để phân biệt "cancel do app shutdown" vs "cancel do trigger".
### LinkedTokenSource — Kết hợp nhiều token
```csharp
// TriggerRefresh — ngắt delay sớm để poll ngay sau khi gửi lệnh
public void TriggerRefresh()
{
// Thay thế _delayCts bằng cái mới, cancel cái cũ
var old = Interlocked.Exchange(ref _delayCts, new CancellationTokenSource());
old.Cancel(); // → linked token bị cancel → Task.Delay throw → loop poll ngay
}
```
---
## 8. Event & Delegate — Thông báo khi state thay đổi
### Vấn đề
Robot di chuyển → `RobotState` được cập nhật → UI cần biết để re-render. Nhưng `RobotState` không nên biết gì về UI.
### Event là gì
**Event** là cơ chế "pub/sub" — publisher phát sự kiện, subscriber đăng ký lắng nghe.
```csharp
// Publisher — RobotState không biết ai subscribe
public class RobotState
{
public event Action? OnUpdated; // Khai báo event
public void UpdateVda(bool online, StateMsg? stateMsg, ...)
{
// ... cập nhật state ...
// Chỉ fire event khi thực sự có thay đổi (tránh spam re-render)
bool changed = IsOnline_Vda != online || ...;
if (changed) OnUpdated?.Invoke(); // Gọi tất cả subscriber
}
}
```
```csharp
// Subscriber — StatePushService đăng ký lắng nghe
public class StatePushService
{
public StatePushService(RobotState imrState, IHubContext<DeviceHub> hub)
{
// Đăng ký: khi imrState thay đổi → gọi PushImrState
imrState.OnUpdated += async () => await PushImrState();
}
private async Task PushImrState()
{
// Push qua SignalR về browser
await _hub.Clients.All.SendAsync("ImrStateUpdated", GetImrDto());
}
}
```
### Chuỗi thông báo hoàn chỉnh
```
VdaStatePoller (poll 300ms)
→ gọi state.UpdateVda(...)
→ state so sánh dữ liệu mới vs cũ
→ nếu khác: OnUpdated?.Invoke()
→ StatePushService nhận sự kiện
→ SignalR broadcast về tất cả browser
→ Blazor component re-render
```
### `?.Invoke()` — Null-safe event
```csharp
OnUpdated?.Invoke();
// Tương đương:
if (OnUpdated != null) OnUpdated.Invoke();
// Nếu không có ai subscribe → không gọi gì → không crash
```
### Event trong DeviceCommandQueue
```csharp
// DeviceCommandQueue.cs
public event Action? OnChanged; // Fire khi queue state thay đổi
public bool Submit(string label, Func<CancellationToken, Task> work)
{
lock (_gate)
{
// ...
}
OnChanged?.Invoke(); // Notify UI cập nhật trạng thái queue
if (kick) RunNext();
return true;
}
```
---
## 9. Thread Safety — Khi nhiều luồng đụng nhau
### Vấn đề
Server ASP.NET Core xử lý nhiều request song song. Nhiều luồng có thể đọc/ghi cùng một object cùng lúc → **race condition** → dữ liệu bị hỏng.
### Ví dụ race condition
```csharp
// Không thread-safe
public class Counter
{
private int _count = 0;
public void Increment()
{
_count++; // Thực ra là: đọc → cộng → ghi (3 bước)
// Nếu 2 thread cùng đọc _count = 5, cùng cộng 1
// Thread A ghi 6, Thread B ghi 6
// → Mất 1 lần tăng
}
}
```
### Giải pháp 1: `lock` statement
```csharp
// DeviceCommandQueue.cs — sử dụng lock
public sealed class DeviceCommandQueue
{
private readonly object _gate = new(); // "Chìa khóa"
private bool _busy = false;
private string? _busyLabel = null;
public bool Submit(string label, Func<CancellationToken, Task> work)
{
bool kick;
lock (_gate) // Chỉ 1 thread vào block này cùng lúc
{
if (_busy && _queue.Count >= _maxQueued) return false;
_queue.Enqueue(new Pending(label, work));
kick = !_busy;
Snapshot(); // Cập nhật public properties trong lock
}
// Ra ngoài lock mới gọi event (tránh deadlock)
OnChanged?.Invoke();
if (kick) RunNext();
return true;
}
}
```
### Giải pháp 2: Snapshot Pattern
Vấn đề với `lock`: không thể `await` bên trong lock (sẽ gây deadlock).
`DeviceCommandQueue` dùng **Snapshot Pattern** — copy dữ liệu ra public properties bên trong lock, rồi đọc public properties bên ngoài lock:
```csharp
// Public properties — đọc an toàn từ bất kỳ thread nào
public bool IsBusy { get; private set; }
public string? BusyLabel { get; private set; }
public int QueuedCount { get; private set; }
public string? LastError { get; private set; }
// Private fields — chỉ đọc/ghi trong lock
private bool _busy = false;
private string? _busyLabel = null;
// Gọi bên trong lock — snapshot mutable fields ra public properties
private void Snapshot()
{
IsBusy = _busy; // Atomic write trên x64
BusyLabel = _busyLabel;
QueuedCount = _queue.Count;
// ...
}
```
> **Tại sao không dùng lock ở chỗ đọc?** Vì .NET đảm bảo đọc reference và bool trên x64 là atomic — không cần lock khi chỉ đọc. Nhưng ghi phải trong lock để đảm bảo consistency.
### Giải pháp 3: `Interlocked` — Atomic operation
```csharp
// VdaStatePoller.cs — TriggerRefresh thread-safe
public void TriggerRefresh()
{
// Interlocked.Exchange: đổi _delayCts thành cái mới, trả về cái cũ
// Atomic — không thể bị gián đoạn giữa chừng
var old = Interlocked.Exchange(ref _delayCts, new CancellationTokenSource());
old.Cancel();
}
```
### `RobotState` — lock khi update, không lock khi đọc
```csharp
public class RobotState
{
private readonly object _lock = new();
public void UpdateVda(bool online, StateMsg? stateMsg, ...)
{
bool changed;
lock (_lock) // Lock khi ghi — đảm bảo consistent update
{
changed = IsOnline_Vda != online || ...;
IsOnline_Vda = online;
StateMsg = stateMsg;
// ...
}
// Fire event ngoài lock — event handlers có thể làm bất cứ thứ gì
if (changed) OnUpdated?.Invoke();
}
// Đọc không cần lock — mỗi property là computed từ một field (atomic read)
public double X_Vda => StateMsg?.AgvPosition?.X ?? 0;
public bool IsOnline_Vda { get; private set; }
}
```
---
## 10. IHostedService — Background task chạy suốt vòng đời app
### Vấn đề
Robot di chuyển liên tục. Cần một background task **poll trạng thái** từ thiết bị mỗi 300ms — không phải khi có request HTTP.
### IHostedService là gì
`IHostedService` là interface để đăng ký background task với ASP.NET Core. Framework tự gọi `StartAsync` khi app khởi động, `StopAsync` khi shutdown.
```csharp
// Lab505/Infrastructure/State/VdaStatePoller.cs
public class VdaStatePoller(IApiService api, RobotState imrState, RobotState amrState,
int periodMs = 300, INotificationService? notif = null)
: IHostedService, IDisposable, IStatePollTrigger
{
private CancellationTokenSource? _cts;
private Task? _loopTask;
// Framework gọi khi app khởi động
public Task StartAsync(CancellationToken cancellationToken)
{
_cts = new CancellationTokenSource();
_loopTask = Task.Run(() => Loop(_cts.Token)); // Chạy loop trong background
return Task.CompletedTask; // Trả về ngay — không chờ loop kết thúc
}
// Framework gọi khi app shutdown
public Task StopAsync(CancellationToken cancellationToken)
{
_cts?.Cancel(); // Signal loop dừng
return Task.CompletedTask;
}
// Vòng lặp chính — chạy mãi đến khi bị cancel
private async Task Loop(CancellationToken stopToken)
{
while (!stopToken.IsCancellationRequested)
{
await Task.WhenAll(
UpdateOne("IMR", imrState, stopToken),
UpdateOne("AMR2WS", amrState, stopToken));
await Task.Delay(300, ...);
}
}
}
```
Đăng ký trong Program.cs:
```csharp
builder.Services.AddHostedService<VdaStatePoller>();
```
### Tất cả background services trong dự án
```
App startup
├── OpcUaHostedService → Kết nối & duy trì OPC UA (auto-reconnect)
├── OpcStatePoller → Poll IMR/Dobot từ OPC UA mỗi 200ms
├── VdaStatePoller → Poll IMR/AMR từ VDA5050 mỗi 300ms
├── ConveyorStatePoller → Poll Conveyor từ Modbus mỗi 200ms
├── AsrsStatePoller → Poll ASRS từ Modbus mỗi 200ms
└── StatePushService → Lắng nghe state change → push SignalR về browser
```
---
## 11. Extension Methods — Tổ chức code theo nhóm
### Vấn đề
`Program.cs` cần đăng ký hàng trăm API endpoint. Nếu viết hết vào một file:
```csharp
// Program.cs — 1000 dòng endpoint
app.MapGet("/api/imr/status", ...);
app.MapPost("/api/imr/move", ...);
app.MapGet("/api/amr/status", ...);
// ... 50 endpoint nữa
```
→ File khổng lồ, khó tìm, khó bảo trì.
### Extension Methods là gì
**Extension method** cho phép "thêm" method vào class đã tồn tại mà không cần sửa class đó:
```csharp
// Định nghĩa extension method
public static class StringExtensions
{
// "this string s" → method này thuộc về kiểu string
public static bool IsNullOrEmpty(this string s)
{
return string.IsNullOrEmpty(s);
}
}
// Sử dụng — giống như method của string
string name = "John";
bool empty = name.IsNullOrEmpty(); // Gọi như method bình thường
```
### Dự án dùng Extension Methods để tổ chức API
```csharp
// Program.cs — chỉ gọi, không có code chi tiết
app.MapImrApi();
app.MapAmrApi();
app.MapLockApi();
app.MapWorkflowApi();
app.MapShareApi();
```
```csharp
// Presentation/Api/ImrApiExtensions.cs — code chi tiết ở đây
public static class ImrApiExtensions
{
public static void MapImrApi(this WebApplication app) // Extension của WebApplication
{
// Tất cả IMR endpoint ở trong file này
app.MapGet("/api/imr/status", GetStatus)
.RequireAuthorization();
app.MapPost("/api/imr/vda/move-to-abb", MoveToAbb)
.RequireAuthorization();
}
static async Task<IResult> GetStatus(
HttpContext ctx, UserContextResolver resolver)
{
var context = resolver.Resolve(ctx);
return Results.Ok(context.ImrState);
}
static async Task<IResult> MoveToAbb(
HttpContext ctx, UserContextResolver resolver)
{
var context = resolver.Resolve(ctx);
// Guard check nằm trong driver
await context.Imr.MoveToAbb();
return Results.Ok();
}
}
```
**Kết quả:** Mỗi nhóm thiết bị có file riêng, dễ tìm, dễ mở rộng.
---
## 12. Guard Pattern — Kiểm tra điều kiện trước khi thực thi
### Vấn đề
Robot không thể Load hàng khi đang di chuyển. Nếu không kiểm tra:
```csharp
// Không tốt — gửi lệnh Load khi robot đang di chuyển → phần cứng báo lỗi
public Task Load(CancellationToken t = default)
{
return CallSimple("Load", t); // Gửi thẳng, không kiểm tra
}
```
→ Phần cứng báo lỗi khó hiểu, hoặc tệ hơn: gây hỏng cơ cấu cơ khí.
### Guard Pattern
**Guard** kiểm tra điều kiện tiên quyết, ném exception rõ ràng nếu không thỏa mãn:
```csharp
// ImrCommandGuard.cs
public class ImrCommandGuard(RobotState imrState, SystemCondition condition)
{
public void RequireCanLoad()
{
if (!imrState.IsOnline_Vda)
throw new InvalidOperationException("IMR offline, không thể Load");
if (!condition.ImrAtC1 && !condition.ImrAtABB)
throw new InvalidOperationException(
$"IMR đang ở {condition.ImrPosition}, phải ở C1 hoặc ABB mới Load được");
if (condition.ImrCarrying)
throw new InvalidOperationException("IMR đang mang hàng, Load thêm không được");
}
public void RequireCanMoveToABB()
{
if (!imrState.IsOnline_Vda)
throw new InvalidOperationException("IMR offline");
if (imrState.NewBaseRequest == false)
throw new InvalidOperationException("IMR đang bận (NBR=false)");
}
}
```
Driver gọi guard trước khi gửi lệnh:
```csharp
// ImrVdaDriver.cs
public Task MoveToAbb(CancellationToken t = default)
{
_guard.RequireCanMoveToABB(); // Kiểm tra trước
return DockToStation("Abb", t); // Chỉ gửi nếu guard pass
}
public override Task Load_Vda(CancellationToken t = default)
{
_guard.RequireCanLoad(); // Kiểm tra trước
return CallSimple("Load", t);
}
```
**Lợi ích:**
- Exception message rõ ràng ("IMR đang ở giữa đường, phải ở C1 mới Load")
- Guard tái sử dụng được — nhiều chỗ gọi Load đều qua cùng một guard
- Tách biệt validation logic ra khỏi execution logic
---
## 13. Strategy Pattern — Đổi hành vi lúc runtime
### UserContextResolver — Core của Real/Sim switching
Đây là điểm quan trọng nhất trong kiến trúc dự án. Cùng một code API, nhưng tùy theo user mà gọi vào hardware thật hay simulation.
```csharp
// Lab505/Application/Services/UserContextResolver.cs
public sealed class UserContextResolver
{
private readonly RealDriverContext _real; // Singleton — hardware thật
private readonly UserSimPool _simPool; // Pool sim sessions per-user
private readonly AuthDbContext _db;
private readonly ShareApiModeService _shareMode;
public IDriverContext Resolve(HttpContext ctx)
{
bool canUseReal = ctx.User.FindFirstValue("CanUseReal") == "true";
var uid = GetUid(ctx); // null nếu là API Key user
// API Key user: ShareApiModeService quyết định real/sim
if (uid is null)
return (canUseReal && _shareMode.UseReal) ? _real : _simPool.GetOrCreate(-1);
// Browser user: đọc preference từ DB
bool useReal = canUseReal && (_db.UserPrefs.Find(uid.Value)?.UseReal == true);
return useReal ? _real : _simPool.GetOrCreate(uid.Value);
}
}
```
Mỗi API endpoint gọi `resolver.Resolve(ctx)` → nhận đúng context:
```csharp
static async Task<IResult> MoveToAbb(HttpContext ctx, UserContextResolver resolver)
{
var context = resolver.Resolve(ctx); // Real hoặc Sim?
await context.Imr.MoveToAbb(); // Gọi đúng driver
return Results.Ok();
}
```
### UserSimPool — Tạo session riêng mỗi user
```csharp
// UserSimPool — Singleton quản lý các Sim session
public class UserSimPool
{
private readonly ConcurrentDictionary<int, SimDriverContext> _sessions = new();
public SimDriverContext GetOrCreate(int userId)
{
// Lấy nếu có, tạo mới nếu chưa có
return _sessions.GetOrAdd(userId, id => CreateNewSession(id));
}
}
```
**Kết quả:** 30 sinh viên, mỗi người có `SimDriverContext` riêng — robot ảo của người này không ảnh hưởng người kia.
---
## 14. Options Pattern — Đọc config từ appsettings.json
### Vấn đề
IP, port của thiết bị có thể thay đổi tùy môi trường (lab A, lab B, production). Không thể hardcode trong code.
### appsettings.json
```json
{
"Infrastructure": {
"Vda5050": {
"BaseUrl": "https://192.168.111.21:7223/"
},
"OpcUa": {
"Clients": [
{ "Name": "IMR", "EndpointUrl": "opc.tcp://192.168.111.168:4840" }
]
},
"Modbus": {
"Endpoints": [
{ "Name": "PLC1", "IpAddress": "192.168.111.201", "Port": 502 }
]
}
},
"Workflow": {
"NbrTimeoutMs": 600000,
"CoilTimeoutMs": 5000
}
}
```
### Options Pattern
```csharp
// Định nghĩa class tương ứng với JSON
public class WorkflowOptions
{
public int NbrTimeoutMs { get; set; } = 600000;
public int CoilTimeoutMs { get; set; } = 5000;
}
// Đăng ký trong Program.cs
builder.Services.Configure<WorkflowOptions>(
builder.Configuration.GetSection("Workflow"));
// Sử dụng trong class cần config
public class FlowService(IOptions<WorkflowOptions> opts)
{
private readonly WorkflowOptions _opts = opts.Value;
public async Task WaitForCoil(CancellationToken ct)
{
var timeout = TimeSpan.FromMilliseconds(_opts.CoilTimeoutMs);
// Dùng timeout từ config, không hardcode
}
}
```
**Lợi ích:** Đổi IP thiết bị → chỉ sửa `appsettings.json`, không cần rebuild code.
### Cấu hình timeout Workflow
| Key | Mặc định | Áp dụng cho |
|-----|---------|------------|
| `NbrTimeoutMs` | 600000 (10 phút) | Chờ robot đến đúng vị trí |
| `PositionTimeoutMs` | 600000 (10 phút) | Chờ OPC UA xác nhận vị trí |
| `ActionTimeoutMs` | 120000 (2 phút) | Chờ Load/Unload/PickUp hoàn thành |
| `CoilTimeoutMs` | 5000 (5 giây) | Chờ Modbus coil phản hồi |
| `DobotHomeDelayMs` | 3000 (3 giây) | Chờ Dobot ổn định sau GoHome |
---
## 15. TaskCompletionSource — Chờ sự kiện không cần polling
### Vấn đề
Workflow cần chờ robot đến đúng vị trí trước khi gửi lệnh tiếp theo. Cách đơn giản nhất là **polling**:
```csharp
// Polling — KHÔNG TỐT
while (!condition.ImrAtABB)
{
await Task.Delay(500); // Hỏi lại mỗi 500ms
}
// Vấn đề: lãng phí CPU, phản ứng chậm (lag tối đa 500ms),
// và có race condition (check xong thì state lại đổi)
```
### TaskCompletionSource — Chờ bằng sự kiện
`TaskCompletionSource<T>` là một Task mà **bạn tự quyết định khi nào nó hoàn thành**. Thay vì polling, ta subscribe vào event — khi event fire thì task complete.
Đây là code thật trong `SystemCondition.WaitUntil`:
```csharp
// Lab505/Application/Condition/SystemCondition.cs
public async Task<bool> WaitUntil(
Func<SystemCondition, bool> condition,
int timeoutMs = 1_200_000,
CancellationToken ct = default)
{
// Fast path: điều kiện đã đúng rồi → trả về ngay
if (condition(this)) return true;
// Tạo TaskCompletionSource — một Task "thủ công"
var tcs = new TaskCompletionSource<bool>();
// Tạo timer tự hủy sau timeoutMs
using var timer = new CancellationTokenSource(timeoutMs);
// Handler sẽ được gọi mỗi khi bất kỳ thiết bị nào thay đổi
void handler()
{
if (condition(this))
tcs.TrySetResult(true); // → Task complete với kết quả true
}
// Đăng ký lắng nghe — từ đây mỗi khi thiết bị thay đổi, handler chạy
OnChanged += handler;
try
{
// Re-check ngay sau khi đăng ký — tránh race condition:
// (state có thể đã đổi giữa lúc check lần đầu và lúc subscribe)
if (condition(this)) return true;
// Đăng ký thêm 2 "nguồn hoàn thành":
// - ct bị cancel → tcs.TrySetCanceled → Task throw OperationCanceledException
// - timer hết hạn → tcs.TrySetResult(false) → Task trả về false (timeout)
using (ct.Register(() => tcs.TrySetCanceled(ct)))
using (timer.Token.Register(() => tcs.TrySetResult(false)))
return await tcs.Task; // Chờ ở đây — không tốn CPU
}
finally
{
OnChanged -= handler; // Quan trọng: hủy đăng ký để tránh memory leak
}
}
```
### Cách dùng trong workflow
```csharp
// FlowService — sạch, không có polling loop nào
public async Task Phase6_ImrToABB(CancellationToken ct)
{
await _ctx.Imr.MoveToAbb(ct);
// Chờ IMR đến ABB — không polling, chờ bằng event
// Trả về false nếu 10 phút mà chưa đến → workflow ném TimeoutException
await _ctx.SystemCondition.Require(
c => c.ImrReadyAtABB,
"IMR không đến được ABB trong 10 phút",
timeoutMs: 600_000,
ct: ct);
await _ctx.Dobot.PickUp(ct);
}
```
### Chuỗi event kết nối mọi thứ
```
OpcStatePoller poll OPC UA (200ms)
→ imrState.UpdateOpc(x, y, ...)
→ imrState.OnUpdated?.Invoke()
→ SystemCondition.Fire() ← imrState.OnUpdated += Fire (trong constructor)
→ SystemCondition.OnChanged?.Invoke()
→ WaitUntil handler() chạy
→ condition(this) → true
→ tcs.TrySetResult(true)
→ await tcs.Task hoàn thành
→ Workflow tiếp tục
```
> **Điểm mấu chốt:** `SystemCondition` subscribe vào **tất cả** thiết bị (IMR, AMR, Conveyor) trong constructor. Bất kỳ thứ gì thay đổi → `OnChanged` fire → `WaitUntil` kiểm tra điều kiện → nếu đúng thì xong.
---
## 16. record — Kiểu dữ liệu bất biến hiện đại
### Class thông thường vs record
C# có từ khóa `record` (từ C# 9) để định nghĩa kiểu dữ liệu **chỉ chứa dữ liệu**, không có logic:
```csharp
// Class thông thường — cần viết nhiều
public class FlowStepOld
{
public string Name { get; init; }
public Func<SystemCondition, bool> Precondition { get; init; }
public Func<CancellationToken, Task> Execute { get; init; }
public FlowStepOld(string name, Func<SystemCondition, bool> pre,
Func<CancellationToken, Task> exec)
{
Name = name; Precondition = pre; Execute = exec;
}
}
// record — viết một dòng, tự sinh constructor + Equals + ToString
public record FlowStep(
string Name,
Func<SystemCondition, bool> Precondition,
Func<CancellationToken, Task> Execute,
Func<SystemCondition, bool>? Done = null // optional, mặc định null
);
```
```csharp
// Lab505/Application/Condition/FlowStep.cs — code thật
public record FlowStep(
string Name,
Func<SystemCondition, bool> Precondition,
Func<CancellationToken, Task> Execute,
Func<SystemCondition, bool>? Done = null
);
```
### Dùng FlowStep trong workflow
`FlowStep` là **khai báo** một bước workflow — nói *cái gì cần làm*, không phải *làm ngay*:
```csharp
// Khai báo step — chưa chạy gì
var step = new FlowStep(
Name: "IMR đến ABB",
Precondition: c => c.ImrReady, // Điều kiện tiên quyết
Execute: ct => _imr.MoveToAbb(ct), // Lệnh cần chạy
Done: c => c.ImrReadyAtABB // Điều kiện hoàn thành
);
// StepRunner chạy step này
await runner.Run(step, cancellationToken);
// → Chờ ImrReady (WaitUntil)
// → Gọi MoveToAbb()
// → Chờ ImrReadyAtABB (WaitUntil)
```
### record trong DTOs
Dự án dùng record rộng rãi cho các DTO (Data Transfer Object):
```csharp
// Shared/ImrStatusDto.cs — DTO gửi từ server về browser
public record ImrStatusDto(
double X_Opc, double Y_Opc, double Theta_Opc,
string NavStatus, string DobotStatus,
double X_Vda, double Y_Vda,
bool IsOnline, string[] Errors
);
// API response
public record OperationAccepted(string OperationId);
public record MoveStraightRequest(double Distance, double Velocity);
```
> **Khi nào dùng record?** Khi object chỉ là "túi dữ liệu" — không có state thay đổi, không có logic phức tạp. DTOs, request/response models, các bước workflow.
---
## 17. Func\<\> và Action\<\> — Delegate như tham số
### Delegate là gì
**Delegate** là kiểu dữ liệu đại diện cho một **hàm**. Bạn có thể truyền hàm vào hàm khác như truyền số hay string.
`Func<T, TResult>` — hàm nhận T, trả về TResult:
```csharp
Func<int, bool> isPositive = n => n > 0; // Lambda
Func<string, int> strLength = s => s.Length;
bool result = isPositive(5); // true
```
`Action<T>` — hàm nhận T, không trả về gì:
```csharp
Action<string> log = msg => Console.WriteLine(msg);
log("Hello"); // In ra "Hello"
```
`Func<CancellationToken, Task>` — hàm async (dùng nhiều trong dự án):
```csharp
Func<CancellationToken, Task> moveImr = ct => _imr.MoveToAbb(ct);
await moveImr(cancellationToken); // Gọi hàm
```
### Tại sao FlowStep dùng Func<>
`FlowStep` lưu **công thức** (delegate), không lưu **kết quả**. Điều này cho phép `StepRunner` quyết định *khi nào* gọi:
```csharp
public record FlowStep(
string Name,
Func<SystemCondition, bool> Precondition, // "Khi nào được phép chạy"
Func<CancellationToken, Task> Execute, // "Chạy cái gì"
Func<SystemCondition, bool>? Done = null // "Biết xong khi nào"
);
// StepRunner gọi Precondition nhiều lần (polling trong WaitUntil)
// nhưng chỉ gọi Execute một lần
public async Task Run(FlowStep step, CancellationToken ct)
{
await sys.WaitUntil(step.Precondition, _preconditionMs, ct); // Gọi nhiều lần
await step.Execute(ct); // Gọi 1 lần
if (step.Done != null)
await sys.WaitUntil(step.Done, _completionMs, ct); // Gọi nhiều lần
}
```
### LINQ — Truy vấn collection với Func<>
**LINQ** (Language Integrated Query) dùng Func<> để lọc/sắp xếp/biến đổi collection:
```csharp
// AuthService.cs — code thật
public List<AppUser> GetManageable(UserRole requestorRole) =>
[.. db.Users
.Where(u => (int)u.Role < (int)requestorRole) // Func<AppUser, bool>
.OrderBy(u => u.Status) // Func<AppUser, UserStatus>
.ThenByDescending(u => u.Created)]; // Func<AppUser, DateTime>
// Đọc như văn xuôi:
// "Lấy tất cả user, lọc những người có Role thấp hơn requestor,
// sắp xếp theo Status tăng dần, rồi theo Created giảm dần"
```
LINQ trong DeviceCommandQueue:
```csharp
// Lấy tất cả key trong dict mà không có trong currentIds
foreach (var key in lastActions.Keys
.Where(k => !currentIds.Contains(k)) // lọc
.ToList()) // materialize (quan trọng khi xóa)
{
lastActions.Remove(key);
}
```
LINQ trong StepRunner:
```csharp
// Tạo danh sách Task từ danh sách branches
var tasks = branches
.Select(branch => RunBranch(branch, linked)) // Biến mỗi branch thành Task
.ToList();
await Task.WhenAll(tasks);
```
> **Các LINQ method hay dùng:**
> - `Where(condition)` — lọc
> - `Select(transform)` — biến đổi mỗi phần tử
> - `OrderBy/OrderByDescending` — sắp xếp
> - `FirstOrDefault(condition)` — lấy phần tử đầu tiên thỏa điều kiện, null nếu không có
> - `Any(condition)` — có phần tử nào thỏa điều kiện không?
> - `ToList()` — convert IEnumerable về List (thực thi query)
---
## 18. Bảo mật mật khẩu — PBKDF2 và Constant-time Compare
### Tại sao không lưu mật khẩu thẳng
```csharp
// KHÔNG BAO GIỜ làm thế này
user.Password = "mypassword"; // Nếu DB bị leak → mọi mật khẩu bị lộ
```
### Hash + Salt
**Hash** — biến đổi một chiều: `"mypassword"` → `"a8f5f167..."`. Không thể ngược lại.
**Salt** — chuỗi random thêm vào trước khi hash: tránh tấn công rainbow table (bảng tra cứu hash có sẵn).
```csharp
// Lab505/Application/Services/AuthService.cs — code thật
public static string HashPassword(string password)
{
// Tạo 16 bytes ngẫu nhiên (salt) — mỗi lần hash ra salt khác nhau
byte[] salt = RandomNumberGenerator.GetBytes(16);
// PBKDF2-SHA256: hash password + salt, lặp 100.000 lần → rất chậm để brute-force
byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
Encoding.UTF8.GetBytes(password),
salt,
iterations: 100_000,
HashAlgorithmName.SHA256,
outputLength: 32);
// Lưu "salt:hash" dưới dạng Base64
return $"{Convert.ToBase64String(salt)}:{Convert.ToBase64String(hash)}";
}
public static bool VerifyPassword(string password, string storedHash)
{
var parts = storedHash.Split(':');
if (parts.Length != 2) return false;
byte[] salt = Convert.FromBase64String(parts[0]);
byte[] expect = Convert.FromBase64String(parts[1]);
// Hash lại password với salt cũ
byte[] actual = Rfc2898DeriveBytes.Pbkdf2(
Encoding.UTF8.GetBytes(password), salt, 100_000, HashAlgorithmName.SHA256, 32);
// So sánh theo thời gian cố định — tránh Timing Attack
return CryptographicOperations.FixedTimeEquals(actual, expect);
}
```
### Tại sao `FixedTimeEquals` thay vì `==`
```csharp
// Không dùng == để so sánh hash
actual == expect // Nguy hiểm!
// Tại sao? So sánh thông thường dừng ngay khi gặp byte đầu tiên khác nhau
// → Kẻ tấn công đo thời gian response → đoán được bao nhiêu byte đã khớp
// → "Timing Attack"
// FixedTimeEquals luôn so sánh đủ N bytes, bất kể khớp ở đâu → thời gian giống nhau
CryptographicOperations.FixedTimeEquals(actual, expect); // An toàn
```
---
## 19. SemaphoreSlim — lock dùng được với async
### Vấn đề với `lock` thông thường
`lock` không cho phép `await` bên trong:
```csharp
private readonly object _gate = new();
public async Task GetOrCreateAsync(int userId)
{
lock (_gate)
{
await SomeAsyncWork(); // LỖI BIÊN DỊCH — không thể await trong lock
}
}
```
Lý do: `lock` gắn với thread. Khi `await` nhả thread về pool, `lock` không còn ý nghĩa — thread khác có thể lấy lock đó.
### SemaphoreSlim — Giải pháp
`SemaphoreSlim(1, 1)` là semaphore chỉ cho phép **1 thread vào cùng lúc** — tương đương `lock` nhưng hoạt động với `async/await`:
```csharp
// Lab505/Application/Services/UserSimPool.cs
public sealed class UserSimPool
{
private readonly SemaphoreSlim _createLock = new(1, 1);
// Tham số (1, 1): initialCount=1 (có thể vào ngay), maxCount=1 (tối đa 1 thread)
public UserSimSession GetOrCreate(int userId)
{
if (_sessions.TryGetValue(userId, out var existing)) return existing; // Fast path
_createLock.Wait(); // Blocking — chờ đến khi được phép vào (sync version)
try
{
// Double-check sau khi lấy lock — thread khác có thể đã tạo trong lúc chờ
if (_sessions.TryGetValue(userId, out existing)) return existing;
var session = CreateNewSession(userId);
_sessions[userId] = session;
return session;
}
finally
{
_createLock.Release(); // PHẢI release trong finally — dù có exception
}
}
public async Task RemoveAsync(int userId)
{
if (_sessions.TryRemove(userId, out var session))
{
await session.StopAsync(...); // async — không thể dùng lock thường
await _createLock.WaitAsync(); // Async wait — không block thread
try
{
_freeIndices.Add(session.Index);
}
finally
{
_createLock.Release();
}
}
}
}
```
### So sánh
| | `lock` | `SemaphoreSlim(1,1)` |
|---|--------|----------------------|
| Dùng với `await` | ❌ Không | ✅ Có (`WaitAsync()`) |
| Cú pháp | Ngắn gọn | Dài hơn, cần `try/finally` |
| `finally` bắt buộc | Không (tự release) | **Có — nếu quên Release, app treo** |
| Dùng khi nào | Code sync | Code async |
### Pattern Double-Check Lock
```csharp
// Kiểm tra trước khi lấy lock (fast path — không cần lock cho đa số trường hợp)
if (_sessions.TryGetValue(userId, out var existing)) return existing;
_createLock.Wait();
try
{
// Kiểm tra LẠI sau khi có lock — vì thread khác có thể đã tạo trong lúc chờ
if (_sessions.TryGetValue(userId, out existing)) return existing;
// Giờ mới an toàn để tạo mới
var session = CreateNewSession(userId);
_sessions[userId] = session;
return session;
}
finally { _createLock.Release(); }
```
> **Quy tắc nhớ:** Thấy `await` → dùng `SemaphoreSlim`. Không có `await` → dùng `lock`.
---
## 20. IDisposable — Dọn dẹp tài nguyên, tránh memory leak
### Event subscription gây memory leak
Khi subscribe vào event (`+=`), subscriber bị giữ reference bởi publisher. Nếu không unsubscribe (`-=`), object không bao giờ bị GC thu hồi dù không còn dùng:
```csharp
// Publisher — RobotState sống mãi (Singleton)
public class RobotState
{
public event Action? OnUpdated;
}
// Subscriber — SystemCondition được tạo mới mỗi user session
public class SystemCondition
{
public SystemCondition(RobotState imr, RobotState amr, ...)
{
imr.OnUpdated += Fire; // RobotState giờ giữ reference đến SystemCondition
amr.OnUpdated += Fire;
}
// Nếu không unsubscribe → SystemCondition không bao giờ bị GC thu hồi
// → Memory leak — mỗi user session tạo 1 leak
}
```
### IDisposable — Hợp đồng dọn dẹp
`IDisposable` là interface với một method duy nhất: `Dispose()`. Convention: `Dispose()` là nơi dọn dẹp tài nguyên — unsubscribe event, đóng kết nối, giải phóng file...
```csharp
// Lab505/Application/Condition/SystemCondition.cs
public class SystemCondition : IDisposable
{
// Lưu delegate để unsubscribe ĐÚNG instance — quan trọng!
private readonly Action<bool> _uaConnectHandler;
public SystemCondition(RobotState imr, RobotState amr, ConveyorState conveyor, OpcUaClient ua)
{
_uaConnectHandler = _ => Fire(); // Lưu lại để dùng khi Dispose
imr.OnUpdated += Fire;
amr.OnUpdated += Fire;
conveyor.OnStateChanged += Fire;
ua.ConnectChanged += _uaConnectHandler;
}
public void Dispose()
{
// Unsubscribe đúng delegate — tránh để ghost subscription
Imr.OnUpdated -= Fire;
Amr.OnUpdated -= Fire;
Conveyor.OnStateChanged -= Fire;
_ua.ConnectChanged -= _uaConnectHandler;
}
}
```
### `using` — Tự động gọi Dispose
```csharp
// Cách 1: using statement (cũ hơn)
using (var condition = new SystemCondition(...))
{
await DoWork(condition);
} // → Dispose() tự gọi khi ra khỏi block, dù exception hay không
// Cách 2: using declaration (C# 8+, dùng nhiều trong dự án)
using var condition = new SystemCondition(...);
await DoWork(condition);
// → Dispose() gọi khi ra khỏi scope của method
// Cách 3: trong WaitUntil — unregister callback
using (ct.Register(() => tcs.TrySetCanceled(ct)))
using (timer.Token.Register(() => tcs.TrySetResult(false)))
return await tcs.Task;
// → Cả 2 registration được dispose khi Task hoàn thành
```
### Tại sao phải lưu delegate vào field
```csharp
// KHÔNG hoạt động — lambda tạo instance mới mỗi lần
ua.ConnectChanged += _ => Fire(); // Subscribe với instance A
ua.ConnectChanged -= _ => Fire(); // Unsubscribe với instance B (khác!) → không có tác dụng
// ĐÚNG — lưu vào field để unsubscribe đúng instance
private readonly Action<bool> _uaConnectHandler = _ => Fire();
ua.ConnectChanged += _uaConnectHandler; // Instance A
ua.ConnectChanged -= _uaConnectHandler; // Cũng instance A → hoạt động đúng
```
---
## 21. Claims — Định danh và quyền hạn trong mỗi request
### Claims là gì
Sau khi đăng nhập, ASP.NET Core lưu thông tin user vào **Claims** — các cặp key/value gắn với HTTP context. Mỗi request đến, middleware xác thực đọc cookie/header → điền Claims → code đọc Claims để biết ai đang gọi và có quyền gì.
```csharp
// Các claim được gắn khi login thành công
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) // "1"
new Claim(ClaimTypes.Name, user.Username) // "john"
new Claim(ClaimTypes.Role, user.Role.ToString())// "Operator"
new Claim("CanUseReal", "true") // Custom claim
new Claim("CanWorkflow", "true") // Custom claim
```
### Đọc Claims trong code
```csharp
// UserContextResolver.cs — đọc claim để quyết định Real hay Sim
public IDriverContext Resolve(HttpContext ctx)
{
// FindFirstValue trả về string hoặc null nếu không có claim đó
bool canUseReal = ctx.User.FindFirstValue("CanUseReal") == "true";
// ClaimTypes.NameIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
var uidStr = ctx.User.FindFirstValue(ClaimTypes.NameIdentifier);
int? uid = int.TryParse(uidStr, out var id) ? id : null;
// uid == null → API Key user (NameIdentifier là string, không phải int)
bool useReal = canUseReal && (_db.UserPrefs.Find(uid.Value)?.UseReal == true);
return useReal ? _real : _simPool.GetOrCreate(uid.Value);
}
```
### ApiKeyAuthHandler — Tạo Claims từ API Key
Khi request dùng API Key thay vì cookie, `ApiKeyAuthHandler` lookup key trong config và tạo Claims tương đương:
```csharp
// Lab505/Infrastructure/Auth/ApiKeyAuthHandler.cs
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Đọc header
if (!Request.Headers.TryGetValue("X-Api-Key", out var keyValues))
return Task.FromResult(AuthenticateResult.NoResult()); // Không có header → bỏ qua
var key = keyValues.ToString();
var entries = config.GetSection("ApiKeys").Get<Dictionary<string, ApiKeyEntry>>() ?? [];
if (!entries.TryGetValue(key, out var entry))
return Task.FromResult(AuthenticateResult.Fail("Invalid API key")); // Key sai → 401
// Tạo Claims từ DB user (nếu linked) hoặc từ config
var claims = new List<Claim>();
if (entry.LinkedUsername is not null)
{
// Lấy scope để query DB từ trong Singleton handler
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AuthDbContext>();
var user = db.Users.FirstOrDefault(u => u.Username == entry.LinkedUsername);
claims.Add(new(ClaimTypes.NameIdentifier, user.Id.ToString())); // int uid
claims.Add(new(ClaimTypes.Role, user.Role.ToString()));
if (user.CanUseReal) claims.Add(new("CanUseReal", "true"));
if (user.CanWorkflow) claims.Add(new("CanWorkflow", "true"));
}
// Đóng gói Claims → Principal → Ticket → Xác thực thành công
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
```
### IServiceScopeFactory — Truy cập Scoped service từ Singleton
`ApiKeyAuthHandler` là Singleton (tạo một lần). `AuthDbContext` là Scoped (tạo mỗi request). Singleton **không được inject Scoped trực tiếp** — sẽ dùng instance cũ mãi.
Giải pháp: inject `IServiceScopeFactory`, tạo scope thủ công khi cần:
```csharp
// Singleton handler
public class ApiKeyAuthHandler(IServiceScopeFactory scopeFactory, ...)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Tạo scope thủ công → scope sống trong block using
using var scope = scopeFactory.CreateScope();
// Lấy Scoped service từ scope vừa tạo
var db = scope.ServiceProvider.GetRequiredService<AuthDbContext>();
var user = db.Users.FirstOrDefault(...); // Query DB an toàn
// scope bị dispose khi ra khỏi using → DbContext được cleanup
}
}
```
> **Quy tắc:** Singleton cần Scoped service → không inject trực tiếp → dùng `IServiceScopeFactory` tạo scope thủ công.
### Phân quyền endpoint bằng Claims
```csharp
// Chỉ cho phép user có role Admin hoặc Manager
app.MapGet("/admin/users", GetAllUsers)
.RequireAuthorization(policy => policy.RequireRole("Admin", "Manager"));
// Chỉ cho phép user có claim CanUseReal
app.MapPost("/api/imr/move", MoveImr)
.RequireAuthorization(policy => policy.RequireClaim("CanUseReal", "true"));
```
---
## 25. Cài đặt & Chạy
### Yêu cầu
- [.NET 10 SDK](https://dotnet.microsoft.com/download)
- (Tùy chọn) Kết nối mạng `192.168.111.x` nếu có phần cứng thật
### Chạy Simulation (không cần phần cứng)
```bash
# Terminal 1 — Simulator (giả lập thiết bị)
cd Lab505.Sim
dotnet run
# Terminal 2 — Server chính
cd Lab505
dotnet run
```
Truy cập: `http://localhost:7000`
### Tài khoản mặc định
| Username | Password | Role | Ghi chú |
|----------|----------|------|---------|
| `dev` | `robotics` | Admin | Tài khoản dev |
| `t3api` | `robotics` | Operator | Tài khoản API Key (dùng `X-Api-Key: 2024XYZ789ABCDEF1234`) |
### Cấu hình IP thiết bị
Sửa `Lab505/appsettings.json` nếu thiết bị ở IP khác:
```json
{
"Infrastructure": {
"Vda5050": { "BaseUrl": "https://192.168.111.21:7223/" },
"OpcUa": {
"Clients": [
{ "Name": "IMR", "EndpointUrl": "opc.tcp://192.168.111.168:4840" }
]
},
"Modbus": {
"Endpoints": [
{ "Name": "PLC1", "IpAddress": "192.168.111.201", "Port": 502 },
{ "Name": "PLC2", "IpAddress": "192.168.111.200", "Port": 502 },
{ "Name": "ASRS_PLC", "IpAddress": "192.168.111.203", "Port": 502 }
]
}
}
}
```
### Cấu trúc thư mục
```
Lab505/ ← Server chính
├── Domain/Entities/ ← Model cốt lõi (RobotState, AppUser, DeviceGroup...)
├── Infrastructure/
│ ├── Drivers/ ← Driver giao tiếp thiết bị
│ ├── Protocols/ ← OPC UA client, Modbus pool, VDA5050 HTTP
│ └── State/ ← Pollers (OpcStatePoller, VdaStatePoller)
├── Application/
│ ├── Services/ ← DeviceGroupLock, UserContextResolver, CommandQueue...
│ ├── Contexts/ ← IDriverContext, RealDriverContext, SimDriverContext
│ └── Flow/ ← FlowService (workflow 9 pha)
├── Presentation/Api/ ← Extension methods đăng ký endpoint
└── Program.cs ← DI, middleware, startup
Lab505.Sim/ ← Simulators (thiết bị ảo)
Lab505.Shared/ ← DTOs dùng chung server + client
Lab505.Client/ ← Blazor WebAssembly frontend
Lab505.Script/ ← Roslyn script engine
```
---
## 22. Roslyn Script Engine — Compile và chạy C# lúc runtime
### Vấn đề
Workflow tự động được hard-code trong server. Muốn thêm chu trình mới → phải sửa code → rebuild → deploy lại. Với phòng lab có nhiều bài thực hành khác nhau, điều này rất bất tiện.
### Giải pháp: Roslyn
**Roslyn** là trình biên dịch C# open-source của Microsoft. Nó có thể được nhúng vào ứng dụng để **compile và chạy C# code do user nhập vào** — không cần rebuild server.
Luồng hoàn chỉnh:
```
User gõ C# code vào Monaco Editor trên browser
↓
POST /api/script/run { code: "await IMR.GoTo(\"Abb\"); ..." }
↓
ScriptEngine.ExecuteAsync(code, globals: flowContext, token)
↓
Roslyn compile code trong memory → chạy ngay
↓
Output stream về browser qua SignalR (real-time)
```
### ScriptEngine — code thật
```csharp
// Lab505.Script/ScriptEngine.cs
public class ScriptEngine
{
private readonly ScriptOptions _baseOptions;
public ScriptEngine(IHubContext<ScriptHub> hub, ...)
{
// Khai báo các namespace mà script user có thể dùng không cần viết using
_baseOptions = ScriptOptions.Default
.WithImports([
"System",
"System.Threading",
"System.Threading.Tasks",
"Lab505.Script.Facades", // IImrFacade, IAmrFacade...
"Lab505.Shared",
])
.WithReferences([
typeof(Task).Assembly,
typeof(ScriptEngine).Assembly,
]);
}
public async Task<string> ExecuteAsync(
string code,
object? globals = null, // Object mà script có thể truy cập trực tiếp
CancellationToken token = default,
string? userId = null)
{
// Tạo script object — chưa chạy, chỉ compile
var script = CSharpScript.Create(
code,
options: _baseOptions,
globalsType: globals?.GetType() // Script "nhìn thấy" các field/property của globals
);
try
{
// Chạy script, truyền globals và cancellation token
ScriptState<object>? state = await script.RunAsync(globals, token);
return state?.ReturnValue?.ToString() ?? "";
}
catch (CompilationErrorException ex)
{
// Lỗi cú pháp C# → hiện cho user biết, không crash server
foreach (var diagnostic in ex.Diagnostics)
writer.WriteLine("❌ " + diagnostic);
return "";
}
}
}
```
### FlowContext — "Môi trường" của script
`FlowContext` là object được inject làm **globals** — mọi field `public` của nó đều truy cập được trực tiếp trong script mà không cần prefix:
```csharp
// Lab505.Script/FlowContext.cs
public class FlowContext
{
public required IImrFacade IMR { get; set; } // → script gọi: await IMR.GoTo("Abb")
public required IAmrFacade AMR { get; set; } // → await AMR.GoTo("Cap1")
public required IConveyorFacade Conveyor { get; set; } // → await Conveyor.C1Out(true)
public required IAsrsFacade ASRS { get; set; } // → await ASRS.Pick(...)
public required IDobotFacade Dobot { get; set; } // → await Dobot.PickUp()
public required ICondition State { get; set; } // → await State.WaitUntil(...)
public required TextWriter Log { get; set; } // → Log.WriteLine("msg")
public CancellationToken Token { get; set; } // → Emergency stop
}
```
### `required` keyword (C# 11)
`required` bắt buộc field đó **phải được khởi tạo** khi tạo object — tại compile time, không phải runtime:
```csharp
// Không có required — có thể quên set, chỉ biết lúc runtime (NullReferenceException)
var ctx = new FlowContext(); // Không lỗi compile dù chưa set gì
ctx.IMR.GoTo("Abb"); // Crash runtime: NullReferenceException
// Có required — lỗi ngay lúc compile nếu quên
var ctx = new FlowContext(); // LỖI COMPILE: IMR, AMR, ... phải được khởi tạo
var ctx = new FlowContext // ✅ Đúng — bắt buộc dùng object initializer
{
IMR = imrFacade,
AMR = amrFacade,
Conveyor = conveyorFacade,
// ... nếu thiếu field nào → lỗi compile ngay
};
```
### Script user viết — ví dụ thực tế
```csharp
// User gõ vào Monaco Editor — đây là C# thật, được Roslyn compile
// FlowContext được inject → IMR, AMR, Log... dùng trực tiếp
Log.WriteLine("Bắt đầu chu trình...");
await IMR.GoTo("Abb");
await State.WaitUntil(c => c.ImrReadyAtABB, timeoutMs: 60_000, Token);
await Dobot.GoHome(Token);
await Dobot.PickUp(Token);
await AMR.GoTo("Cap2");
Log.WriteLine("Hoàn thành!");
```
Mỗi dòng `Log.WriteLine(...)` được stream về browser **ngay lập tức** qua `RealtimeWriter` → SignalR → UI cập nhật theo thời gian thực trong khi script đang chạy.
### Tại sao không dùng script file có sẵn?
Roslyn cho phép **mỗi sinh viên viết và chạy workflow riêng** của mình mà không ảnh hưởng người khác — vì `FlowContext` của mỗi user trỏ vào `SimDriverContext` riêng (hoặc `RealDriverContext` nếu được phép). Toàn bộ isolation đến từ kiến trúc đã xây ở các mục trước.
---
## 23. Generics \<T\> và out parameter — Hai pattern thấy ở mọi nơi
### Generics `<T>` — Viết code một lần, dùng nhiều kiểu
#### Vấn đề không có generics
```csharp
// Không tốt — phải viết riêng cho từng kiểu
public List<AppUser> GetUsers() { ... }
public List<SavedScript> GetScripts() { ... }
public List<UserPref> GetPrefs() { ... }
// → Code y hệt nhau, chỉ khác kiểu trả về
```
#### Giải pháp: Generic method
`<T>` là **placeholder cho kiểu dữ liệu** — giống biến nhưng cho kiểu:
```csharp
// Viết một lần, T được thay thế khi gọi
public List<T> GetAll<T>() where T : class
{
return db.Set<T>().ToList(); // db.Set<AppUser>(), db.Set<SavedScript>()...
}
// Gọi:
var users = GetAll<AppUser>(); // T = AppUser
var scripts = GetAll<SavedScript>(); // T = SavedScript
```
#### Generics xuất hiện ở đâu trong dự án
```csharp
// TaskCompletionSource<bool> — Task hoàn thành với kết quả bool
var tcs = new TaskCompletionSource<bool>();
tcs.TrySetResult(true); // bool
bool result = await tcs.Task;
// IOptions<WorkflowOptions> — inject config strongly-typed
public FlowService(IOptions<WorkflowOptions> opts)
{
int timeout = opts.Value.NbrTimeoutMs; // Không cần cast, không sợ typo
}
// IHubContext<StateHub> — inject SignalR hub cụ thể
public class StatePushService(IHubContext<StateHub> hub)
{
await hub.Clients.All.SendAsync("ImrStateUpdated", dto);
}
// DbSet<AppUser> — EF Core table typed
public DbSet<AppUser> Users => Set<AppUser>();
// RobotResult<T> — response wrapper cho VDA5050 API
public class RobotResult<T> : RobotResult
{
public T? Data { get; set; }
}
var res = await api.GetState("IMR", ct); // RobotResult<VdaRobotState>
var x = res.Data?.AgvPosition?.X; // Truy cập typed, không cần cast
```
#### Generic constraints — Thu hẹp T được phép
`where T : ...` giới hạn T phải thỏa mãn điều kiện:
```csharp
// Lab505/Infrastructure/Protocols/Vda5050/ApiService.cs
private async Task<T> Execute<T>(CancellationToken token, Func<Task<T>> body)
where T : RobotResult, new()
// ^^^^^^^^^^^^ ^^^^
// T phải kế thừa RobotResult T phải có constructor không tham số
{
token.ThrowIfCancellationRequested();
try
{
return await body();
}
catch (HttpRequestException ex)
{
// Vì T : new() → có thể tạo T() không biết T là gì
// Vì T : RobotResult → biết T có property IsSuccess, Message
return new T { IsSuccess = false, Message = $"Network error: {ex.Message}" };
}
}
// Dùng:
Execute<RobotResult<VdaRobotState>>(token, async () => { ... });
Execute<RobotResult>(token, async () => { ... });
// → Cùng một method, hai kiểu trả về khác nhau, error handling giống nhau
```
Các constraint phổ biến:
| Constraint | Ý nghĩa |
|-----------|---------|
| `where T : class` | T phải là reference type (không phải `int`, `bool`) |
| `where T : SomeBase` | T phải kế thừa SomeBase |
| `where T : ISomeInterface` | T phải implement interface đó |
| `where T : new()` | T phải có constructor không tham số |
| `where T : class, new()` | Kết hợp nhiều constraint |
---
### `out` parameter — Trả về nhiều giá trị
#### Vấn đề
Method chỉ trả được một giá trị. Nhưng đôi khi cần trả cả kết quả lẫn thông báo lỗi:
```csharp
// Cách không tốt — exception cho flow bình thường
public int Parse(string s)
{
if (!int.TryParse(s, out int n)) throw new Exception("Not a number");
return n;
}
// → Exception quá nặng cho case "user nhập sai"
```
#### `out` — Tham số đầu ra
```csharp
// bool trả về: thành công hay không
// out T result: giá trị nếu thành công
public static bool TryConnect(string ip, int port, byte unitId, out ModbusTcpClient? client)
{
var tcp = new ModbusTcpClient(ip, port, unitId);
if (tcp.Connect())
{
client = tcp; // Gán vào out — bắt buộc phải gán trong mọi code path
return true;
}
else
{
client = null; // Bắt buộc gán, dù là null
return false;
}
}
// Gọi:
if (ModbusTcpClient.TryConnect("192.168.111.201", 502, 1, out var client))
{
client.ReadCoils(...); // client chắc chắn không null ở đây
}
// Nếu false → client = null, không dùng
```
#### `out var` — Khai báo biến ngay tại chỗ dùng
Cú pháp hiện đại — không cần khai báo biến trước:
```csharp
// Cũ — khai báo trước
ModbusTcpClient? client;
bool ok = TryConnect(ip, port, id, out client);
// Mới — khai báo ngay tại chỗ (dùng trong toàn bộ dự án)
bool ok = TryConnect(ip, port, id, out ModbusTcpClient? client);
// hoặc dùng var để compiler tự suy kiểu:
bool ok = TryConnect(ip, port, id, out var client);
```
#### `out` xuất hiện ở đâu trong dự án
```csharp
// UserContextResolver.cs — tách int từ string claim
var s = ctx.User.FindFirstValue(ClaimTypes.NameIdentifier);
int? uid = int.TryParse(s, out var id) ? id : null;
// UserSimPool.cs — lấy và xóa từ ConcurrentDictionary
if (_sessions.TryRemove(userId, out var session))
{
await session.StopAsync(...); // session chắc chắn có giá trị
}
// ApiKeyAuthHandler.cs — lookup dictionary
if (!entries.TryGetValue(key, out var entry))
return AuthenticateResult.Fail("Invalid API key");
// entry có giá trị nếu vào được bên trong if
// Nhiều nơi khác: TryGetValue, TryDequeue, TryPeek...
```
#### Pattern TryXxx — Convention của .NET
Mọi method theo pattern `bool TryXxx(args, out T result)` đều có nghĩa:
- Trả `true` + `result` có giá trị → thành công
- Trả `false` + `result` là `null`/default → thất bại, không throw exception
Pattern này giúp tránh exception cho các case bình thường (user nhập sai, key không tồn tại...).
---
## 24. Tổng kết — Bản đồ các pattern
```
Khi gửi lệnh từ browser:
Browser → HTTP Request
↓
API Endpoint (Minimal API + Extension Method)
↓
UserContextResolver.Resolve(ctx) ← Strategy Pattern
↓
IDriverContext ←──────────────────── Interface
/ \
RealDriverContext SimDriverContext ← Polymorphism
|
ImrVdaDriver ←──────────────────────── kế thừa VdaDriverBase (Abstract Class)
|
Guard.RequireX() ←──────────────────── Guard Pattern
|
await Api.PostAsync() ←────────────── async/await
| (CancellationToken) ←───────── Cancellation
|
[thiết bị vật lý / simulator]
State cập nhật:
VdaStatePoller (IHostedService) ←─────── Background Service
|
state.UpdateVda() ←─────────────────── Thread-safe (lock)
|
OnUpdated?.Invoke() ←──────────────── Event
|
StatePushService nhận
|
SignalR → Browser ←──────────────────── Real-time push
```
---
*Xem [POSTMAN_API_GUIDE.md](POSTMAN_API_GUIDE.md) để biết cách test API.*
*Cập nhật lần cuối: tháng 3/2026.*