# 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 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, 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 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 pattern integration - Environment variable overrides with optional prefix #### 4. Repository Pattern with EF Core - Generic `IRepository` 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: `enable` 4. Create `DependencyInjection` folder for service registration extensions 5. Add test project under `test/` with MSTest 6. Add to Sharp.sln: `dotnet sln add ` ### Working with Result - Use `Result.Try()` to wrap exception-prone code - Chain operations with `Map()` for transformations - Use `Bind()` for operations that return Result - Extract values with `GetOrDefault()`, `GetOrThrow()`, or `Match()` - Always handle both success and failure cases ### Using the Global container - Register singletons: `Global.RegisterSingleton(instance)` or `Global.RegisterSingleton(() => new T())` - Register transients: `Global.RegisterTransient(() => new T())` - Subscribe to changes: `Global.Subscribe(e => { /* handle change */ })` - Retrieve services: `Global.Get()` - 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.