Sharp.Demo 模块已经整合了 Client 和 Server 的所有功能, 并采用了最佳实践(Quick Start API、标准 DI、Result<T> 模式等), 因此 Client 和 Server 模块已不再需要。 变更内容: - 从解决方案中移除 Client 和 Server 项目 - 更新 CLAUDE.md 文档(根目录和 src/Sharp/) - 更新项目结构说明,明确 Sharp.Demo 为综合演示应用 - 更新构建和运行命令,指向 Sharp.Demo - 更新依赖关系说明 Sharp.Demo 优势: - 使用 Quick Start API 简化配置 - 标准依赖注入(移除 Global 容器依赖) - Result<T> 模式演示 - IApplicationState 应用状态管理 - 完整的开发者工具集成(F10/F11/F12) - 交互式模块演示(17+ 功能点) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
227 lines
8.7 KiB
Markdown
227 lines
8.7 KiB
Markdown
# CLAUDE.md
|
||
|
||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||
|
||
## Project Overview
|
||
|
||
Sharp-Basic is a modular C# .NET 8 framework for building enterprise applications with reusable components. It provides a comprehensive toolkit with emphasis on:
|
||
- **Modularity**: Independent, reusable libraries that can be used selectively
|
||
- **Desktop Applications**: WPF-based UI toolkit with MVVM infrastructure
|
||
- **Industrial IoT**: PLC integration (Siemens) and serial port communication
|
||
- **Configuration as Code**: Multi-format (JSON/XML/INI/TOML) with hot-reload
|
||
- **Functional Programming**: Result<T> pattern for railway-oriented error handling
|
||
|
||
**Language**: All comments and documentation are in Chinese (中文).
|
||
|
||
## Build Commands
|
||
|
||
### Build the entire solution
|
||
```bash
|
||
cd src/Sharp
|
||
dotnet build Sharp.sln
|
||
```
|
||
|
||
### Build specific project
|
||
```bash
|
||
cd src/Sharp
|
||
dotnet build Sharp.Demo/Sharp.Demo.csproj # WPF demo application (最佳实践示例)
|
||
dotnet build Common/Common.csproj # Core utilities
|
||
dotnet build Config/Config.csproj # Configuration management
|
||
```
|
||
|
||
### Run tests
|
||
```bash
|
||
cd src/Sharp
|
||
dotnet test Sharp.sln # All tests
|
||
dotnet test ../../test/Common.Test # Specific test project
|
||
```
|
||
|
||
### Run the Sharp.Demo application
|
||
```bash
|
||
cd src/Sharp
|
||
dotnet run --project Sharp.Demo/Sharp.Demo.csproj
|
||
```
|
||
|
||
### Clean build artifacts
|
||
```bash
|
||
cd src/Sharp
|
||
dotnet clean Sharp.sln
|
||
```
|
||
|
||
## Architecture Overview
|
||
|
||
### Project Structure
|
||
|
||
```
|
||
src/Sharp/ # All source projects
|
||
├── Common/ # Core foundation (Result<T>, Global container, utilities, SystemConfig)
|
||
├── Config/ # Multi-format configuration with hot-reload
|
||
├── Wpf/ # WPF UI toolkit (MVVM, dialogs, converters) - NO UI library dependency
|
||
├── Wpf.HandyControl/ # HandyControl UI library integration (optional)
|
||
├── Wpf.DevTools/ # WPF Developer Tools (DevTools, LogViewer, Performance Monitor)
|
||
├── Data/ # EF Core wrapper with repository pattern
|
||
├── Log/ # Serilog-based structured logging
|
||
├── Cache/ # Memory cache (planned)
|
||
├── EventBus/ # Event pub/sub (planned)
|
||
├── NetClient/ # HTTP client with Polly resilience
|
||
├── NetServer/ # Lightweight HTTP server with middleware
|
||
├── Ports/ # Serial port abstraction (RS232/RS485)
|
||
├── Plc/ # PLC abstraction interface
|
||
├── Plc.Siemens/ # Siemens S7 PLC implementation (S7.NET+)
|
||
├── Process/ # Process execution
|
||
├── Python/ # Python script execution
|
||
└── Sharp.Demo/ # 综合演示应用(最佳实践示例,替代了 Client 和 Server)
|
||
|
||
test/ # MSTest test projects
|
||
├── Common.Test/
|
||
├── Config.Test/
|
||
├── Data.Test/
|
||
├── Log.Test/
|
||
├── NetClient.Test/
|
||
└── NetServer.Test/
|
||
|
||
appsettings.template.json # 完整的配置模板文件
|
||
```
|
||
|
||
### Key Architectural Patterns
|
||
|
||
#### 1. Result<T> Pattern (Railway-Oriented Programming)
|
||
- Eliminates exceptions as control flow
|
||
- Provides chainable operations: `Map`, `Bind`, `Match`, `Where`, `OnSuccess`, `OnFailure`
|
||
- Synchronous and async wrappers: `Result.Try()`, `Result.TryAsync()`
|
||
- Example usage:
|
||
```csharp
|
||
Result.Try(() => int.Parse(input))
|
||
.Map(x => x * 2)
|
||
.Where(v => v > 100, "Value too small")
|
||
.OnSuccess(v => Console.WriteLine(v))
|
||
.OnFailure((ex, msg) => logger.LogError(msg));
|
||
```
|
||
|
||
#### 2. Dependency Injection (Hybrid Approach)
|
||
- **Primary**: Microsoft.Extensions.DependencyInjection for standard DI
|
||
- **Fallback**: Global service locator (Common.Global) for legacy/convenience
|
||
- Services registered in `DependencyInjection` folders within each module
|
||
- Client app startup (App.xaml.cs) orchestrates all service registration
|
||
|
||
#### 3. Configuration Management
|
||
- Multi-source configuration builder supporting JSON/XML/INI/TOML
|
||
- Hot-reload with change notifications
|
||
- Strong typing with DataAnnotations validation
|
||
- IOptions<T> pattern integration
|
||
- Environment variable overrides with optional prefix
|
||
|
||
#### 4. Repository Pattern with EF Core
|
||
- Generic `IRepository<TEntity>` abstraction
|
||
- Built-in entity types: `Entity`, `AuditableEntity`, `ISoftDeletable`
|
||
- Auto-audit tracking (CreatedAt, CreatedBy, UpdatedAt, UpdatedBy)
|
||
- Multi-database support: SQL Server, SQLite, PostgreSQL, MySQL, In-Memory
|
||
|
||
#### 5. MVVM for WPF
|
||
- `ViewModelBase` with INotifyPropertyChanged and IsBusy tracking
|
||
- `RelayCommand` and `AsyncCommand` implementations
|
||
- Services: `IDialogService`, `IFileDialogService`, `IDispatcherService`
|
||
- Converters: BoolToVisibility, InverseBooleanConverter, EnumToDescriptionConverter
|
||
- Global exception handling for UI/Task/AppDomain exceptions
|
||
|
||
#### 6. Middleware Pattern
|
||
- Custom HTTP server (NetServer) with ASP.NET Core-style pipeline
|
||
- Middleware: Authentication, CORS, Rate Limiting, Caching, Logging, Exception Handling
|
||
- Attribute-based routing with `RouteAttribute`
|
||
- Custom `IMiddleware` interface for extensibility
|
||
|
||
## Module Dependencies
|
||
|
||
**Core Layer** (no external dependencies):
|
||
- Common → (no dependencies)
|
||
|
||
**Configuration Layer**:
|
||
- Config → Microsoft.Extensions.Configuration.*, Tomlyn (TOML support)
|
||
|
||
**Data Layer**:
|
||
- Data → EF Core, Common
|
||
- Repository → Data
|
||
|
||
**Network Layer**:
|
||
- NetClient → Polly, Microsoft.Extensions.Http, Common
|
||
- NetServer → Common, Log
|
||
|
||
**WPF Layer**:
|
||
- Wpf → HandyControl (optional UI controls)
|
||
- Client → Wpf, Config, NetClient, NetServer, Log, Plc.Siemens, Ports
|
||
|
||
**Industrial IoT**:
|
||
- Ports → (serial port communication)
|
||
- Plc → (abstraction only)
|
||
- Plc.Siemens → Plc, S7.NET+ library
|
||
|
||
**Logging**:
|
||
- Log → Serilog, Microsoft.Extensions.Logging
|
||
|
||
## Common Development Workflows
|
||
|
||
### Adding a new module/library
|
||
1. Create project under `src/Sharp/`
|
||
2. Target `net8.0` (or `net8.0-windows` for WPF)
|
||
3. Enable nullable reference types: `<Nullable>enable</Nullable>`
|
||
4. Create `DependencyInjection` folder for service registration extensions
|
||
5. Add test project under `test/` with MSTest
|
||
6. Add to Sharp.sln: `dotnet sln add <ProjectPath>`
|
||
|
||
### Working with Result<T>
|
||
- Use `Result.Try()` to wrap exception-prone code
|
||
- Chain operations with `Map()` for transformations
|
||
- Use `Bind()` for operations that return Result<T>
|
||
- Extract values with `GetOrDefault()`, `GetOrThrow()`, or `Match()`
|
||
- Always handle both success and failure cases
|
||
|
||
### Using the Global container
|
||
- Register singletons: `Global.RegisterSingleton<T>(instance)` or `Global.RegisterSingleton<T>(() => new T())`
|
||
- Register transients: `Global.RegisterTransient<T>(() => new T())`
|
||
- Subscribe to changes: `Global.Subscribe<T>(e => { /* handle change */ })`
|
||
- Retrieve services: `Global.Get<T>()`
|
||
- Prefer standard DI (IServiceCollection) for new code
|
||
|
||
### Configuration workflow
|
||
1. Add config files to project root (appsettings.json, etc.)
|
||
2. Create strongly-typed options class with DataAnnotations
|
||
3. Build ConfigManager in App.xaml.cs OnStartup
|
||
4. Register with DI: `services.AddSingleton(cfg)` and `services.AddSingleton(cfg.Configuration)`
|
||
5. Use hot-reload callbacks: `cfg.OnReload(() => { /* refresh */ })`
|
||
|
||
### WPF Client startup flow
|
||
The Client application (App.xaml.cs) orchestrates initialization:
|
||
1. Register global exception handlers (UI, Task, AppDomain)
|
||
2. Build ConfigManager from appsettings.json
|
||
3. Setup ServiceCollection and register all services
|
||
4. Create ServiceProvider
|
||
5. Show LoginWindow (modal)
|
||
6. On successful login, show MainWindow
|
||
|
||
### Working with PLC (Siemens)
|
||
- Interface: `IPLC` in Plc project
|
||
- Implementation: Plc.Siemens using S7.NET+ library
|
||
- Supports: S7-1200, S7-1500, S7-300, S7-400
|
||
- Register with DI: Add Siemens PLC service with connection options
|
||
- Methods: Read/Write memory areas, data blocks, etc.
|
||
|
||
### Serial Port Communication
|
||
- Service: `ISerialPortService` in Ports module
|
||
- Discovery: `SerialPortDiscovery` for auto-detection
|
||
- Event-based data reception: `DataReceivedEventArgs`
|
||
- Configured with: baud rate, parity, stop bits, data bits
|
||
|
||
## Code Style
|
||
|
||
- **Target Framework**: .NET 8 (net8.0 / net8.0-windows)
|
||
- **Nullable**: Enabled (`#nullable enable`)
|
||
- **Implicit Usings**: Enabled
|
||
- **Namespace Convention**: `Sharp.*` (Common will migrate to `Sharp.Common`)
|
||
- **Language**: All comments, docs, and strings in Chinese
|
||
- **Backwards Compatibility**: Maintain for minor versions; breaking changes only in major versions
|
||
- **Testing**: MSTest with parallel execution enabled
|
||
|
||
## License
|
||
|
||
GNU AGPLv3 - Network services that use this framework must open source modifications. Contact author for alternative commercial licensing.
|