### Run Locally Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录E_贡献指南.md Bash command to run the example project. ```bash # Run example project cd CubeDemo dotnet run ``` -------------------------------- ### NewLife.CubeVue Installation and Usage Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/前端对接指南.md Commands to clone the project, install dependencies, configure the backend address, and start the development server for the Vue frontend. ```bash # Clone the project git clone https://github.com/NewLifeX/NewLife.CubeVue.git # Install dependencies cd NewLife.CubeVue npm install # Configure backend address # Modify .env.development VITE_API_URL=http://localhost:5000 # Start development server npm run dev ``` -------------------------------- ### Local Development Source: https://github.com/newlifex/newlife.cube/blob/master/NewLife.Cube.React/web/README.md Commands for installing dependencies and starting the development server. ```bash # Install dependencies pnpm install # Start development server pnpm dev ``` -------------------------------- ### Installation Tutorial Source: https://github.com/newlifex/newlife.cube/blob/master/NewLife.Cube.Vue/web/README.md Steps to install and run the project. ```bash git clone https://github.com/NewLifeX/NewLife.Cube.Vue.git npm i npm run dev ``` -------------------------------- ### Development Commands Source: https://github.com/newlifex/newlife.cube/blob/master/NewLife.Cube.Shadcn/web/README.md Commands to install dependencies and start the development server. ```bash pnpm install pnpm dev ``` -------------------------------- ### Icon Configuration Examples Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Examples of configuring different types of icons for menus. ```csharp // Font Awesome icons [Menu("User Management", Icon = "fa-users")] // Bootstrap Icons [Menu("Settings", Icon = "bi-gear")] // Custom icon class [Menu("Home", Icon = "icon-home")] ``` -------------------------------- ### Detail Query Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/核心接口架构.md Example of a GET request for retrieving a single entity's details. ```http GET /{type}/Detail?id=123 ``` -------------------------------- ### Icon Consistency Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Example demonstrating consistent icon usage. ```csharp // Good practice: Same series of icons [Menu("User", Icon = "fa-user")] [Menu("Role", Icon = "fa-users")] [Menu("Permission", Icon = "fa-lock")] // Avoid: Chaotic icon styles [Menu("User", Icon = "fa-user")] [Menu("Role", Icon = "bi-people")] // Mixed icon libraries ``` -------------------------------- ### Minimal Example (.NET 8/9 Minimal Hosting) Source: https://github.com/newlifex/newlife.cube/blob/master/README.md A minimal C# code example demonstrating how to set up NewLife.Cube with .NET 8/9 Minimal Hosting. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddCube(); // 注册权限、菜单、实体控制器扫描 var app = builder.Build(); app.UseMetronic(app.Environment); // or UseAdminLTE / UseTabler ... app.UseCube(app.Environment); // 路由 & 静态资源 & 中间件 app.Run(); ``` -------------------------------- ### Complete Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/数据权限.md A full example demonstrating the Product entity with relevant fields and a ProductController that utilizes the DataPermissionAttribute. ```csharp // Product entity public partial class Product : Entity { public Int32 TenantId { get; set; } public Int32 DepartmentId { get; set; } public Int32 CreateUserId { get; set; } // ... other fields } // Product controller [DataPermission(TenantField = "TenantId", DepartmentField = "DepartmentId", CreatorField = "CreateUserId")] public class ProductController : EntityController { protected override IEnumerable Search(Pager p) { // Base class automatically adds data permission filter conditions return base.Search(p); } } ``` -------------------------------- ### appsettings.json Configuration Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/会话管理.md An example of how to configure session-related settings in the appsettings.json file. ```json { "CubeSetting": { "SessionTimeout": 0, "EnableUserOnline": 2, "RefreshUserPeriod": 600, "TokenCookie": true } } ``` -------------------------------- ### List Query Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/核心接口架构.md Example of a GET request for listing entities with pagination, sorting, and filtering. ```http GET /{type}?pageIndex=1&pageSize=20&sort=Id&desc=true&Q=关键字&dtStart=...&dtEnd=... ``` -------------------------------- ### Permission Calculation Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录B_API参考.md Examples demonstrating how to calculate permission flags. ```plaintext 查看 + 添加 + 修改 = 1 + 2 + 4 = 7 查看 + 添加 + 修改 + 删除 = 1 + 2 + 4 + 8 = 15 所有权限 = 255 ``` -------------------------------- ### Performance Optimization Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Example of optimizing menu retrieval using caching. ```csharp // Use cache to get menus var menus = Menu.FindAllWithCache(); // Avoid querying menus in a loop foreach (var item in list) { // Bad: Querying menu in each loop // var menu = Menu.FindByName(item.MenuName); // Good: Use a cache dictionary var menu = menuDict.GetValueOrDefault(item.MenuName); } ``` -------------------------------- ### Manually Install Playwright Browsers (First Use) Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/mvc/README.md Commands to install the Playwright CLI globally and then install the Chromium browser. ```bash dotnet tool install --global Microsoft.Playwright.CLI playwright install chromium ``` -------------------------------- ### Complete Model Design Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/自定义实体与模型.md An example demonstrating the design of entity, input, output, and list item models. ```csharp // Entity class (Data layer) public partial class Student : Entity { public Int32 Id { get; set; } public String Name { get; set; } public Int32 ClassId { get; set; } public DateTime Birthday { get; set; } public String Remark { get; set; } // Navigation property public Class Class => Extends.Get(nameof(Class), k => Class.FindById(ClassId)); } // Input model public class StudentInput : IModel { [Required(ErrorMessage = "姓名不能为空")] [StringLength(50, ErrorMessage = "姓名最长50个字符")] public String Name { get; set; } [Range(1, 100, ErrorMessage = "请选择班级")] public Int32 ClassId { get; set; } public DateTime? Birthday { get; set; } public String Remark { get; set; } public Object this[String name] { get => this.GetValue(name); set => this.SetValue(name, value); } } // Output model public class StudentOutput { public Int32 Id { get; set; } public String Name { get; set; } public Int32 ClassId { get; set; } public String ClassName { get; set; } public DateTime Birthday { get; set; } public Int32 Age { get; set; } } // List item model public class StudentListItem { public Int32 Id { get; set; } public String Name { get; set; } public String ClassName { get; set; } public Int32 Age { get; set; } } ``` -------------------------------- ### ICubeModel Usage Examples Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/自定义实体与模型.md Examples demonstrating the implementation of the ICubeModel interface for LoginModel and VerifyCodeModel. ```csharp /// 登录模型 public class LoginModel : ICubeModel { /// 用户名 public String Username { get; set; } /// 密码 public String Password { get; set; } /// 记住我 public Boolean Remember { get; set; } /// 挑战标识 public String ChallengeId { get; set; } } /// 验证码模型 public class VerifyCodeModel : ICubeModel { /// 账号(手机号/邮箱) public String Username { get; set; } /// 渠道(Sms/Mail) public String Channel { get; set; } /// 场景 public String Scene { get; set; } } ``` -------------------------------- ### Log Recording Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/控制器扩展.md Example of recording business logs after an insert operation. ```csharp protected override void OnInsert(Student entity) { base.OnInsert(entity); // 记录业务日志 LogProvider.Provider.WriteLog("Student", "Add", true, $"添加学生:{entity.Name},学号:{entity.StudentNo}"); } ``` -------------------------------- ### Get Menu Tree Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Examples of how to retrieve the menu tree for the current user, all menus, or submenus of a specified parent menu. ```csharp // Get the menu tree visible to the current user var menus = Menu.GetMyMenu(); // Get all menus var allMenus = Menu.FindAllWithCache(); // Get submenus under a specified parent menu var children = Menu.FindAllByParentId(parentId); ``` -------------------------------- ### Menu Tree (Necessary) Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/核心接口架构.md Example GET request to retrieve the menu tree for a specific module. ```http GET /Cube/MenuTree?module=Admin ``` -------------------------------- ### Implementation Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/自定义实体与模型.md StudentModel implements the IModel interface. ```csharp /// 学生模型 public class StudentModel : IModel { /// 编号 public Int32 Id { get; set; } /// 姓名 public String Name { get; set; } /// 班级编号 public Int32 ClassId { get; set; } /// 年龄 public Int32 Age { get; set; } /// 索引器实现 public Object this[String name] { get => this.GetValue(name); set => this.SetValue(name, value); } } ``` -------------------------------- ### SysConfigController Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/控制器扩展.md Example of a ConfigController for managing system settings. It automatically binds to SysConfig.Current. ```csharp /// 系统配置 [AdminArea] [DisplayName("系统配置")] public class SysConfigController : ConfigController { // 自动读取和保存 SysConfig.Current } ``` -------------------------------- ### Automatic Registration Rule Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Example demonstrating automatic menu registration for a controller within the Admin area. ```csharp // Example: Controllers in the Admin area namespace MyApp.Areas.Admin.Controllers { [Menu("Product Management", Order = 10)] public class ProductController : EntityController { // Automatically registered under the "Admin" parent menu // Menu Name: Product Management // Sort Order: 10 } } ``` -------------------------------- ### GitHub Actions Example for Running MVC E2E Tests Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/mvc/E2E测试规划.md An example of how to configure GitHub Actions to run the MVC E2E tests using the --ci parameter. ```yaml - name: Run MVC E2E Tests run: dotnet run Test/e2e-mvc.cs -- --ci ``` -------------------------------- ### System Information Controller Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/控制器扩展.md An example of a controller that displays system information, inheriting from ObjectController. ```csharp /// 系统信息 [AdminArea] [DisplayName("系统信息")] public class SysInfoController : ObjectController { protected override SystemInfo Value { get { return new SystemInfo { MachineName = Environment.MachineName, OSVersion = Environment.OSVersion.ToString(), ProcessorCount = Environment.ProcessorCount, WorkingSet = Environment.WorkingSet / 1024 / 1024, // ... }; } set { } // 只读,不支持修改 } } public class SystemInfo { [DisplayName("机器名")] public String MachineName { get; set; } [DisplayName("操作系统")] public String OSVersion { get; set; } [DisplayName("处理器数")] public Int32 ProcessorCount { get; set; } [DisplayName("内存占用(MB)")] public Int64 WorkingSet { get; set; } } ``` -------------------------------- ### TokenService Usage Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/服务扩展.md Example of how to use TokenService in an ApiController to obtain an access token. ```csharp public class ApiController : Controller { private readonly TokenService _tokenService; public ApiController(TokenService tokenService) { _tokenService = tokenService; } /// 获取访问令牌 [HttpPost] public ActionResult Token(String appId, String secret) { var app = _tokenService.Authorize(appId, secret, false, HttpContext.GetUserHost()); var tokenSecret = $"HS256:{app.Secret}"; var token = _tokenService.IssueToken(app.Name, tokenSecret, 7200); return Json(token); } } ``` -------------------------------- ### Registering FileStorageService Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/服务扩展.md C# code examples for registering the FileStorageService. ```csharp // 在 AddCube 中已自动注册 services.AddCubeFileStorage(); // 或自定义集群名 services.AddCubeFileStorage("MyCluster"); ``` -------------------------------- ### Add Entity Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/核心接口架构.md Example of a POST request for adding a new entity. ```http POST /{type} ``` -------------------------------- ### Memory Caching Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/性能优化.md Example of using IMemoryCache for caching. ```csharp // 使用 IMemoryCache private readonly IMemoryCache _cache; public StudentDto GetStudent(Int32 id) { var key = $"Student:{id}"; if (!_cache.TryGetValue(key, out StudentDto dto)) { var student = Student.FindById(id); dto = student?.ToDto(); _cache.Set(key, dto, TimeSpan.FromMinutes(5)); } return dto; } ``` -------------------------------- ### ArrayPool Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/性能优化.md Example of using ArrayPool to reduce GC pressure. ```csharp // ? 使用数组池减少 GC 压力 var buffer = ArrayPool.Shared.Rent(1024); try { var count = stream.Read(buffer, 0, buffer.Length); // 处理数据 } finally { ArrayPool.Shared.Return(buffer); } ``` -------------------------------- ### Example Assertion with Context Information Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/mvc/E2E测试规划.md An example of how to include contextual information in assertions for better debugging when tests fail. ```csharp // Example: Assert with context information Assert.True( await page.IsVisibleAsync(".table tbody tr"), $"[TC-MENU-001] User management list has no data rows." + $"Current URL: {page.Url}, " + $"Page title: {await page.TitleAsync()}" ); ``` -------------------------------- ### Configuring Menu Permissions Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Example of configuring access permissions for a menu item. ```csharp // Get the menu var menu = Menu.FindByName("Product Management"); // Set permission menu.Permission = "ProductController"; // Associate with controller // Configure role permissions var role = Role.FindByName("Administrator"); role.Set(menu.Id, PermissionFlags.All); // Grant all permissions role.Update(); ``` -------------------------------- ### Run Tests Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录E_贡献指南.md Bash commands to run all tests or tests for a specific project. ```bash # Run all tests dotnet test # Run specific project tests dotnet test XUnitTest ``` -------------------------------- ### Docker Environment Variables Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录A_配置参考.md Example of setting environment variables for a Docker service. ```yaml services: myapp: image: myapp:latest environment: - ConnectionStrings__Membership=Server=db;Database=MyApp;... - Cube__DisplayName=我的系统 - Cube__JwtSecret=my_jwt_secret ``` -------------------------------- ### Get Field Metadata API Request Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录B_API参考.md Example GET request to retrieve field metadata for a list view. ```http GET /School/Student/GetFields?kind=List ``` -------------------------------- ### Clone Repository Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录E_贡献指南.md Bash command to clone the Cube repository from GitHub. ```bash git clone https://github.com/你的用户名/NewLife.Cube.git cd NewLife.Cube ``` -------------------------------- ### Get Field Metadata API Response Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录B_API参考.md Example response containing field metadata for a student entity. ```json { "code": 0, "data": [ { "name": "Id", "displayName": "编号", "type": "Int32", "nullable": false, "primaryKey": true }, { "name": "Name", "displayName": "姓名", "type": "String", "length": 50, "nullable": false }, { "name": "ClassId", "displayName": "班级", "type": "Int32", "mapField": "ClassName", "mapUrl": "/School/Class?id={ClassId}" } ] } ``` -------------------------------- ### Command-line experience Source: https://github.com/newlifex/newlife.cube/blob/master/README.md Instructions for installing NewLife.Templates and creating a new Cube project using the .NET CLI. ```bash dotnet new install NewLife.Templates dotnet new cube --name CubeWeb dotnet new xcode --name Zero.Data cd CubeWeb dotnet build start http://localhost:6080 dotnet run ``` -------------------------------- ### List Query API Request Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录B_API参考.md Example GET request for paginated student list query with filters. ```http GET /School/Student?pageIndex=1&pageSize=20&classId=1&name=张 ``` -------------------------------- ### Service Implementation Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/项目架构建议.md Example implementation of the Student Service, demonstrating data retrieval and insertion. ```csharp /// 学生服务 public class StudentService : IStudentService { private readonly ITracer _tracer; public StudentService(ITracer tracer) { _tracer = tracer; } public PagedResult GetList(StudentQuery query) { using var span = _tracer?.NewSpan(nameof(GetList), query); var pager = new Pager { PageIndex = query.PageIndex, PageSize = query.PageSize, Sort = query.Sort, Desc = query.Desc }; var list = Student.Search(query.ClassId, query.Name, pager); return new PagedResult { Data = list.Select(e => e.ToDto()).ToList(), Total = pager.TotalCount }; } public Int32 Add(StudentInput input) { var entity = new Student(); entity.Copy(input); entity.Insert(); return entity.Id; } } ``` -------------------------------- ### VerifyCodeRecord Query Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/通知系统.md Example of how to get the channel list using VerifyCodeRecord. ```csharp // Get channel list var channels = VerifyCodeRecord.GetChannelList(); // Returns: { "Sms": "100", "Mail": "50" } ``` -------------------------------- ### Development Commands Source: https://github.com/newlifex/newlife.cube/blob/master/NewLife.Cube.Svelte/web/README.md Commands for installing dependencies, running the development server, and building the project. ```bash pnpm install pnpm dev # http://localhost:5186 pnpm build # Output to ../wwwroot ``` -------------------------------- ### StringBuilder Pool Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/性能优化.md Example of using a StringBuilder pool to get and return StringBuilders. ```csharp // ? 使用对象池获取 StringBuilder var sb = Pool.StringBuilder.Get(); try { sb.Append("Hello"); sb.Append(" "); sb.Append("World"); return sb.ToString(); } finally { Pool.StringBuilder.Put(sb); } // 或使用扩展方法 var sb = Pool.StringBuilder.Get(); sb.Append("Hello World"); var result = sb.Put(true); // 自动归还并返回字符串 ``` -------------------------------- ### Get Menu Tree API Response Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录B_API参考.md Example response for fetching the user's menu tree. ```json { "code": 0, "data": [ { "id": 1, "name": "系统管理", "displayName": "系统管理", "url": "/Admin", "icon": "fa fa-cogs", "sort": 100, "children": [ { "id": 2, "name": "用户管理", "displayName": "用户管理", "url": "/Admin/User", "icon": "fa fa-users", "sort": 1 } ] } ] } ``` -------------------------------- ### Get Statistics for List Footer Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/实体控制器.md Example of overriding the GetStatistics method to display statistical information at the bottom of the list. ```csharp protected override IDictionary GetStatistics(IEnumerable list) { var stats = new Dictionary { ["TotalCount"] = list.Count(), ["TotalPrice"] = list.Sum(e => e.Price), ["AvgPrice"] = list.Average(e => e.Price) }; return stats; } ``` -------------------------------- ### Environment Variable Configuration - Connection String Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录A_配置参考.md Example of setting connection strings via environment variables in bash. ```bash # 设置连接字符串 export ConnectionStrings__Membership="Server=localhost;Database=MyApp;..." ``` -------------------------------- ### Project Structure Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录E_贡献指南.md Directory structure of the NewLife.Cube project, outlining the organization of core libraries, skins, examples, tests, and documentation. ```text NewLife.Cube/ ├── NewLife.Cube/ # WebAPI version core library │ ├── Common/ # Common components │ ├── Controllers/ # Base controller class │ ├── Entity/ # Entity classes │ ├── Extensions/ # Extension methods │ ├── Filters/ # Filters │ ├── Services/ # Service classes │ └── NewLife.Cube.csproj │ ├── NewLife.CubeNC/ # MVC version core library │ ├── Areas/ # Areas │ ├── Controllers/ # Controllers │ ├── Views/ # Views │ └── NewLife.CubeNC.csproj │ ├── NewLife.Cube.AdminLTE/ # AdminLTE skin ├── NewLife.Cube.Metronic/ # Metronic skin ├── NewLife.Cube.LayuiAdmin/ # LayuiAdmin skin ├── NewLife.Cube.Tabler/ # Tabler skin │ ├── CubeDemo/ # WebAPI version example ├── CubeSSO/ # MVC version example (SSO server) │ ├── XUnitTest/ # Unit tests │ ├── Doc/ # Documentation directory │ └── NewLife.Cube.sln # Solution file ``` -------------------------------- ### ASP.NET Core Installation - Connection String Source: https://github.com/newlifex/newlife.cube/blob/master/README.md Setting up the 'Membership' connection string in appsettings.json for ASP.NET Core. ```json "ConnectionStrings": { "Membership": "Data Source=..\Data\Membership.db" } ``` -------------------------------- ### Custom Frontend Integration - Menu Acquisition Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/前端对接指南.md JavaScript code to fetch user menus from the API and an example of the expected menu structure. ```javascript // Get user menus const menuResult = await fetch('/api/user/menus', { headers: { 'Authorization': `Bearer ${localStorage.getItem('accessToken')}` } }); const { data: menus } = await menuResult.json(); // Menu structure // [ // { // "id": 1, // "name": "System Management", // "url": "/admin", // "icon": "fa-cog", // "children": [ // { "id": 2, "name": "User Management", "url": "/admin/user" }, // { "id": 3, "name": "Role Management", "url": "/admin/role" } // ] // } // ] ``` -------------------------------- ### Dictionary Query (Advanced) Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/核心接口架构.md Example GET request to query dictionary values for specified codes. ```http GET /Cube/Lookup?codes=enable,sex,role ``` -------------------------------- ### Example: Verifying Login Success Record in Log File Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/mvc/E2E测试规划.md Shows how to check the log file for a 'Login Success' record. ```csharp // Example: Verify that the log has a login success record var logContent = DatabaseHelper.ReadLatestLog(runDir); Assert.Contains("登录成功", logContent, $"[TC-AUTH-010] '登录成功' record not found in log file"); ``` -------------------------------- ### Custom Frontend Integration - Field Metadata Driven Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/前端对接指南.md JavaScript functions to get page metadata (settings and form/list/detail/search configurations) and to render a form based on the retrieved metadata. ```javascript // Get page metadata (includes setting + list/addForm/editForm/detail/search) async function getPageMeta(entity) { const result = await fetch(`/api/${entity}/getpage`, { headers: { 'Authorization': `Bearer ${localStorage.getItem('accessToken')}` } }); return await result.json(); } // Render form based on metadata function renderForm(fields, formData) { return fields.map(field => { const value = formData[field.name]; switch (field.type) { case 'String': if (field.dataSource) { return renderSelect(field, value); } if (field.length > 200) { return renderTextarea(field, value); } return renderInput(field, value); case 'Int32': case 'Int64': if (field.dataSource) { return renderSelect(field, value); } return renderNumber(field, value); case 'Boolean': return renderSwitch(field, value); case 'DateTime': return renderDatePicker(field, value); default: return renderInput(field, value); } }); } ``` -------------------------------- ### ASP.NET MVC Installation - Connection String Source: https://github.com/newlifex/newlife.cube/blob/master/README.md Setting up the 'Membership' connection string in Web.config for ASP.NET MVC. ```xml ``` -------------------------------- ### Registering Menus via Code Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/菜单系统.md Example of manually registering menus in code during application startup. ```csharp public class Startup { public void Configure(IApplicationBuilder app) { // Register menus RegisterMenus(); } private void RegisterMenus() { // Create parent menu var parent = Menu.FindByName("Business Management"); if (parent == null) { parent = new Menu { Name = "Business Management", DisplayName = "Business Management", Icon = "fa-briefcase", Sort = 100, Visible = true }; parent.Insert(); } // Create child menu var menu = Menu.FindByName("Product Management"); if (menu == null) { menu = new Menu { Name = "Product Management", DisplayName = "Product Management", ParentId = parent.Id, Url = "/Admin/Product", Icon = "fa-box", Sort = 10, Visible = true }; menu.Insert(); } } } ``` -------------------------------- ### Page Metadata (Advanced) Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/Api/核心接口架构.md Example GET request for page metadata, used for defining fields for lists, additions, edits, details, and searches. ```http GET /{type}/GetPage ``` -------------------------------- ### Multi-Project References Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/项目架构建议.md Example of project references in .csproj files for a multi-project architecture. ```xml ``` -------------------------------- ### Cron Expression Examples Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录C_实体参考.md Examples of cron expressions and their meanings. ```cron 秒 分 时 日 月 周 0 0 2 * * ? 每天凌晨2点 0 */5 * * * ? 每5分钟 0 0 8-18 * * ? 每天8点到18点整点 ``` -------------------------------- ### Environment Variable Configuration - Cube Settings Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录A_配置参考.md Example of setting Cube specific settings via environment variables in bash. ```bash # 设置魔方配置 export Cube__DisplayName="我的系统" export Cube__JwtSecret="my_jwt_secret" ``` -------------------------------- ### ASP.NET Core Installation - NuGet Reference Source: https://github.com/newlifex/newlife.cube/blob/master/README.md How to reference NewLife.Cube.Core in an ASP.NET Core project using NuGet. ```csharp Through *NuGet* reference `NewLife.Cube.Core`, or compile the latest [魔方 NewLife.CubeNC](http://github.com/NewLifeX/NewLife.Cube) source code yourself ``` -------------------------------- ### Build Command Source: https://github.com/newlifex/newlife.cube/blob/master/NewLife.Cube.Shadcn/web/README.md Command to build the project. Output is placed in ../wwwroot/ and embedded as static resources in the .NET assembly. ```bash pnpm build ``` -------------------------------- ### Login Redirection Configuration Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/自定义登录与启动页.md Configuration for default homepage and role-based redirection after login. ```csharp // 配置默认首页 public class CubeSetting { /// 登录后默认跳转页面 public String DefaultPage { get; set; } = "/Admin"; /// 根据角色跳转不同页面 public Dictionary RoleHomePage { get; set; } = new() { ["管理员"] = "/Admin/Index", ["编辑员"] = "/Admin/Content", ["财务"] = "/Admin/Finance" }; } // 登录成功后的跳转逻辑 public ActionResult Login(String username, String password, String returnUrl) { // ... 验证逻辑 // 确定跳转地址 var url = returnUrl; if (url.IsNullOrEmpty()) { var user = ManageProvider.User as User; var setting = CubeSetting.Current; url = setting.RoleHomePage.GetValueOrDefault(user.RoleName) ?? setting.DefaultPage; } return Json(new { code = 0, url }); } ``` -------------------------------- ### List Query API Response Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录B_API参考.md Example response for a paginated student list query. ```json { "code": 0, "data": [ { "id": 1, "name": "张三", "classId": 1, "className": "一年级一班", "score": 95.5, "status": 1, "createTime": "2024-01-15 10:30:00" } ], "page": { "pageIndex": 1, "pageSize": 20, "totalCount": 100 }, "stat": { "总人数": 100, "平均分": 85.5 } } ``` -------------------------------- ### ASP.NET MVC Installation - NuGet Reference Source: https://github.com/newlifex/newlife.cube/blob/master/README.md How to reference NewLife.Cube in an ASP.NET MVC project using NuGet. ```csharp Through *NuGet* reference `NewLife.Cube`, or compile the latest [魔方 NewLife.Cube](http://github.com/NewLifeX/NewLife.Cube) source code yourself ``` -------------------------------- ### UserService Usage Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/服务扩展.md Example of how to use UserService in an AccountController for login and sending verification codes. ```csharp public class AccountController : Controller { private readonly UserService _userService; public AccountController(UserService userService) { _userService = userService; } [HttpPost] public ActionResult Login([FromBody] LoginModel model) { var result = _userService.Login(model, HttpContext); return Json(result); } [HttpPost] public async Task SendCode([FromBody] VerifyCodeModel model) { var ip = HttpContext.GetUserHost(); var record = await _userService.SendVerifyCode(model, ip); return Json(new { success = true, expireTime = record.ExpireTime }); } } ``` -------------------------------- ### Entity Class Best Practice Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/项目架构建议.md Demonstrates the correct way for an entity class to provide data access methods and the incorrect way of including complex business logic. ```csharp // ? 正确:实体类提供数据访问方法 public partial class Student { public static IList Search(Int32 classId, String name, Pager p) { } public static Student FindById(Int32 id) => Find(_.Id == id); } // ? 避免:实体类包含复杂业务逻辑 public partial class Student { public void EnrollCourse(Course course) { } // 复杂业务逻辑应放在服务层 } ``` -------------------------------- ### DepartmentController Example Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/控制器扩展.md Example of an EntityTreeController for managing departments. It removes the 'Remark' field and filters by ParentID. ```csharp /// 部门管理 [AdminArea] [DisplayName("部门管理")] public class DepartmentController : EntityTreeController { static DepartmentController() { ListFields.RemoveField("Remark"); } /// 搜索数据集 protected override IEnumerable Search(Pager p) { var parentId = p["ParentID"].ToInt(-1); // 根据父节点筛选 if (parentId >= 0) return Department.FindAllChildsByParent(parentId); // 默认显示整棵树 return Department.Root.AllChilds; } } ``` -------------------------------- ### BuildFilePath 方法 Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/文件存储.md 该方法按照标准规则生成文件存储路径。 ```csharp public String BuildFilePath(String path = null) { var file = FilePath; if (FileName.IsNullOrEmpty() && !file.IsNullOrEmpty()) FileName = Path.GetFileName(file); // 自动补充扩展名 var ext = Extension; if (ext.IsNullOrEmpty() && !FileName.IsNullOrEmpty()) ext = Path.GetExtension(FileName); Extension = ext; // 构造标准路径 if (file.IsNullOrEmpty()) { if (Id == 0 || Category.IsNullOrEmpty()) return null; var time = UploadTime; if (time.Year < 2000) time = DateTime.Today; FilePath = file = $"{Category}\\{time:yyyyMMdd}\\{Id}{ext}"; } return file; } ``` -------------------------------- ### Program.cs Changes (v4.x to v5.x) Source: https://github.com/newlifex/newlife.cube/blob/master/Doc/附录D_版本历史.md Example showing the shift from Startup.cs pattern in v4.x to minimal API pattern in v5.x. ```csharp // v4.x (Startup.cs 模式) public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app) { } } // v5.x (最小 API 模式) var builder = WebApplication.CreateBuilder(args); builder.Services.AddCube(); var app = builder.Build(); app.UseCube(); app.Run(); ``` -------------------------------- ### Field and Interface Customization Example Source: https://github.com/newlifex/newlife.cube/blob/master/README.md A C# code example showing how to customize entity fields and behaviors within an EntityController. ```csharp public class AppController : EntityController { static AppController() { LogOnChange = true; // 修改日志 ListFields.RemoveField("Secret"); // 隐藏敏感列 var log = ListFields.AddListField("Log", "UpdateUserId"); log.DisplayName = "修改日志"; log.Url = "/Admin/Log?category=应用系统&linkId={ID}"; log.Target = "_blank"; } } ```