Configuration workbooks and preview sessions
On this page
AdminConfigurationWorkbookController imports and exports users, roles, menus and grants. The server validates the XLSX and freezes a candidate for paged review and confirmation. Preview does not write to the database.
See TExcel for file I/O and the validation and persistence example for custom data imports.
Choose the business command
Use these exact kind names. Each command has its own schema and authorization requirements.
kind | Data worksheets | Write behavior |
|---|---|---|
NewUsers | Users, UserRoles | Create local users and assign initial roles; import only, with no credential export |
UserProfiles | Users | Update existing usernames, display names, email and avatars, without changing passwords or login switches |
UserRoles | Users, UserRoles | Replace the complete role set of each user declared in the main sheet |
Roles | Roles | Add or update the basic details of non-system roles |
Menus | Menus, Buttons, MenuLocales | Save menus, buttons and menu translations under the normal editor and trusted-route rules |
RolePermissions | Roles, MenuPermissions, ButtonPermissions, ApiPermissions | Replace declared roles’ complete menu, button and API permission sets with version checks |
For example, declaring user 101 in UserRoles.Users with no corresponding detail rows clears that user’s roles. Users absent from the main sheet retain their assignments. Empty permission detail sets likewise clear the corresponding grants of a declared role. Absence from a detail sheet does not universally mean “leave unchanged.”
Workbook structure and fields
Every file requires Metadata and all data worksheets for its command. Retain complete headers even in empty detail sheets. Metadata has kind and version columns with exactly one data row: version text 1 and a kind matching the request. Guide is optional, and a hidden _TExcelEnums sheet is allowed. Duplicate names and other extra sheets are rejected.
The table lists stable field keys. Current exports can use the corresponding Chinese captions. Import binds the keys or their shared caption mapping; retain every column and do not substitute arbitrary aliases.
| Command / worksheet | Complete field keys |
|---|---|
NewUsers / Users | key, userName, displayName, email, initialPassword, isEnabled, passwordLoginEnabled, mustChangePassword |
NewUsers / UserRoles | userKey, roleId |
UserProfiles / Users | id, userName, displayName, email, avatarUrl |
UserRoles / Users | userId |
UserRoles / UserRoles | userId, roleId |
Roles / Roles | id, roleName, roleCode, description, isEnabled, sort |
Menus / Menus | key, id, parentKey, menuName, menuCode, module, path, menuType, componentKey, redirect, visible, keepAlive, openMode, externalUrl, icon, sort, isEnabled, isSystem, description, remark |
Menus / Buttons | id, menuKey, buttonName, buttonCode, sort, isEnabled |
Menus / MenuLocales | menuKey, locale, localizedName |
RolePermissions / Roles | roleId, expectedPermissionVersion |
RolePermissions / MenuPermissions | roleId, menuId |
RolePermissions / ButtonPermissions | roleId, buttonId |
RolePermissions / ApiPermissions | roleId, apiCode |
Store IDs as positive decimal integer text to preserve long identifiers in Excel. Only ID columns that permit creation may be blank, such as Roles.id, Menus.id and Buttons.id; 0 is not a creation marker. Use true / false for booleans and current enum names for enums. Numeric enums and localized yes/no words are unsupported. Formulas, error cells and numeric values beyond reliable precision produce diagnostics.
NewUsers.key and Menus.key identify objects within the file. Their relationship fields, including userKey, menuKey and parentKey, resolve those keys according to each relationship. Do not infer relationships from row positions. Initial passwords follow the normal password policy and are excluded from public differences and error echoes. Preserve the exported RolePermissions.expectedPermissionVersion. API codes must exist in the current host’s actual permission catalog; duplicate detection is case-insensitive.
Generate a minimal role file
Run this complete program in a .NET 10 console project with TExcel installed. It creates Roles.xlsx containing one new role. Valid structure still requires domain checks for permissions and unique role codes. Reimporting does not automatically turn creation into an update by roleCode; updating an existing role requires its id.
using TExcel;
using (var writer = Excel.CreateWriter("Roles.xlsx"))
{
writer.WriteSheet(new[] { new { kind = "Roles", version = "1" } }, "Metadata");
writer.WriteSheet(new[]
{
new { id = "", roleName = "Operators", roleCode = "OPS", description = "Import demo", isEnabled = "true", sort = "10" }
}, "Roles");
writer.Complete();
}
Console.WriteLine($"Sheets: {string.Join(", ", Excel.GetSheets("Roles.xlsx").Select(sheet => sheet.Name))}");
Console.WriteLine($"Role rows: {Excel.QueryAsDictionary("Roles.xlsx", sheetName: "Roles").Count()}");Expected output:
Sheets: Metadata, Roles
Role rows: 1For existing configuration, prefer an export from the current host to retain real IDs, versions and referenceable resources. The export input selects a command with kind, a selection with nonempty ids, a menu module with module, and an instruction language with language (default zh-CN). Both objects and relationship rows count toward the export budget; narrow the selection when it exceeds the limit.
HTTP transport contract
Every action uses POST under /api/adminconfigurationworkbookcontroller/, with the host’s normal authentication and administration realm context.
| Action | Request body | Successful response |
|---|---|---|
preview?kind=Roles&fileName=Roles.xlsx | Raw XLSX bytes; URL-encode the filename | Preview object inside the host’s unified result envelope |
read | Session JSON | Current change and diagnostic pages with full counts |
commit | The same session JSON | Commit stages and the current page |
release | The same session JSON | Result of releasing the owned candidate |
export | Export-condition JSON | XLSX bytes; this action uses SkipUnifyResult |
For upload, Content-Type can be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. Send file bytes directly, without JSON.stringify(File) or multipart encoding. The host request adapter must recognize File / Blob and serialize ordinary DTOs as JSON. The download adapter must distinguish successful files from JSON errors. See Vue integration for envelope decoding and error propagation.
Use this JSON for read, commit and release, replacing sessionId with the preview’s value and retaining its returned revision:
{
"kind": "Roles",
"sessionId": "<preview.sessionId>",
"revision": 1,
"page": 1,
"sheet": "",
"action": ""
}The candidate revision is fixed at 1; clients cannot edit the plan. A different file requires a new preview. Custom frontends use the HTTP APIs above.
Paging and complete error state
page is one-based. An empty sheet selects all sheets; action is empty or added, updated, unchanged. Changes filter by sheet and action; diagnostics filter only by sheet. Each page contains at most 50 changes and 50 diagnostics. The server normalizes the page number using the larger page count.
| Field | Meaning |
|---|---|
totalRows / filteredRows | All / filtered public object changes, rather than physical XLSX rows or all relationship rows |
addedCount / updatedCount / unchangedCount | Object action counts across the complete candidate |
retainedCount | Objects outside the file that are retained |
errorCount / filteredErrors | All collected / sheet-filtered diagnostics, including early-stop markers |
rows / diagnostics | Current pages, which do not represent the complete candidate or diagnostic set |
canApply | errorCount == 0 && totalRows > 0; eligibility to confirm the candidate |
databaseCommitted / published | Successful database commit / completed post-commit cache and audit stages |
Diagnostics use sheet, rowNumber, field and code. Confirmation uses complete counts. Paging limits response details; the server retains the full candidate.
Authorization and commit stages
The controller requires Auth.Me; the service also checks the actual command permissions:
| Command | Import permissions | Export permission |
|---|---|---|
NewUsers | User.AddUser; assignments also require User.SetRoles | Unsupported |
UserProfiles | User.UpdateUser | User.GetUsers |
UserRoles | User.SetRoles | User.GetUsers |
Roles | Role.AddRole for creation, Role.UpdateRole for updates; mixed candidates require both | Role.GetRoles |
Menus | Menu.SaveMenu; button creation / updates also require Button.AddButton / Button.UpdateButton | Menu.GetMenuTree |
RolePermissions | Role.SetPermissions | Role.GetRoleById |
Preview, paging and confirmation recheck the relevant permissions. After acquiring the administration mutation lock inside the commit transaction, the service rechecks permissions, target and reference facts, and the permission catalog. Relevant changes during preparation or after preview require a new preview. The actor comes from authenticated context, never from the workbook or a request-supplied user ID.
| Observed state | Host behavior |
|---|---|
canApply=false | Show diagnostics and preview a corrected file |
databaseCommitted=false | Successful commit has not been recorded; read the same session after a failed confirmation |
databaseCommitted=true, published=false | Data is saved; retain the session and retry the same commit to continue cache / audit work |
published=true | Database and publication stages completed; refresh normal queries and release the candidate |
| Timeout or disconnected confirmation | Read the original session before deciding; disconnection does not prove rollback |
Retrying commit on the same live session skips completed database writes and continues unfinished publication. release only releases the candidate; it cannot undo a transaction already started or data already committed.
Session lifetime and resource budgets
Candidates live in the current service instance’s process. Ownership includes realm, scope, tenant and stable user ID; normal token rotation does not change it. Sessions expire after 30 idle minutes, with successful retrieval renewing that period. Each service instance permits at most 32 sessions. A new preview of the same kind under the same ownership replaces its predecessor.
In a multi-instance deployment, route later requests to the instance holding the candidate, or implement a shared mechanism with the full lifecycle contract. Restart, expiry or replacement makes the old session unavailable. Session retries are not permanent cross-process idempotency keys. If a session is lost with an uncertain confirmation outcome, reconcile normal data and audit records before starting another import.
The current configuration implementation limits a file to 512 MiB, objects and relationships to 100,000 data rows combined, and a cell to 32,767 characters. Raw inspection separately limits scanning to 200,000 rows, 5,000,000 cells and 10,000 format diagnostics, followed by a stop marker when that diagnostic budget is exceeded. Archive budgets apply independently. These are current source limits; proxy and host upload limits can be smaller. Custom application imports should set their own budgets; see upload validation.
Source locations: TAdmin/src/TAdmin/Controllers/AdminConfigurationWorkbookController.cs, Services/Workbooks/AdminConfigurationWorkbookService.cs, Services/Workbooks/AdminConfigurationWorkbookCodec.cs and Services/Excel/ExcelImportSessions.cs.