Compare commits

...
6 Commits
Author SHA1 Message Date
chenshoulin fe23e1c64a feat: 增加父 PBI 列表加载功能与界面优化
- 更新 README.md,明确父 PBI Id 的选择方式,增加加载 PBI 列表的功能,提升用户在导入时的便利性。
- 在 MainForm.cs 中添加加载 PBI 列表的按钮,优化父项选择逻辑,确保用户能够方便地选择合适的父项。
- 修改 MainFormUi.cs,将父 PBI Id 输入框替换为下拉框,支持从列表中选择,提升用户体验。
- 在 TfsClient.cs 中实现获取父项候选的逻辑,确保用户能够根据项目和迭代路径获取相关的工作项信息。
- 调整界面布局,确保父 PBI 选择与其他输入项一致,提升整体视觉效果。
2026-11-02 13:07:58 +08:00
chenshoulin 14f5e32262 feat: 增强数据导入功能与用户界面优化
- 更新 README.md,强调 Area 路径为必填项,并增加加载 Area 列表的功能,确保用户在导入时不会遗漏必要信息。
- 修改 Config.cs 和 config.json,调整 SkipExistingTitles 默认值为 false,以便用户首次导入时能看到真实冲突和报错。
- 在 MainForm.cs 中添加加载 Area 列表的按钮,优化用户交互体验。
- 更新 ExcelService.cs,增强模板导出逻辑,确保用户能够更方便地使用自定义模板。
- 调整界面布局,确保 Area 路径与迭代路径的选择更加直观,提升整体用户体验。
2026-11-02 10:40:52 +08:00
chenshoulin ffc210f827 refactor: 移除 CueBanner 类及相关按钮,优化界面布局
- 删除 CueBanner.cs 文件,移除输入框的占位提示功能。
- 更新 MainForm.cs 和 MainFormUi.cs,删除与 Browse 按钮相关的代码,简化用户界面。
- 调整控件布局以提升整体用户体验,确保界面更加简洁。
2026-11-01 23:15:15 +08:00
chenshoulin 8824a81758 feat: 实现密码加密存储与异步数据预览功能
- 在 Config.cs 中添加 DPAPI 加密支持,确保密码安全存储,兼容旧版配置。
- 更新 MainForm.cs,重构数据预览逻辑为异步方法,提升用户体验,避免界面冻结。
- 修改相关方法以支持异步操作,确保在处理大文件时界面响应流畅。
- 更新项目文件以引用 System.Security,支持加密功能。
2026-11-01 21:57:53 +08:00
chenshoulin 8a6f9d55bc refactor: 移除不再使用的配置文件与代码,优化用户界面
- 删除 config.json 和 requirements.txt 文件,移除 Python 版相关代码,简化项目结构。
- 更新 README.md,调整工具说明,强调仅保留 C# WinForms 版本。
- 在 MainForm.cs 中添加输入框的占位提示,提升用户体验。
- 更新 .gitignore,添加 debug.log 文件以记录运行时日志。
- 移除与 Python 版相关的示例 CSV 文件,确保数据源一致性。
2026-11-01 21:44:31 +08:00
chenshoulin d055b415fa feat: 增强便携版支持与配置管理
- 更新 .gitignore 文件,添加便携版分发目录和 Fody 生成的配置文件。
- 修改 README.md,详细说明便携版的构建与分发流程,强调单文件分发的优势。
- 在 Config.cs 中实现便携配置管理,优先使用 exe 同目录的 config.json,提升用户体验。
- 更新 ExcelService.cs,优化默认模板的导出逻辑,支持现场替换模板文件。
- 在 MainForm.cs 中加载应用图标,提升界面一致性。
- 调整 Program.cs,确保在单文件分发时正确加载 native DLL。
2026-11-01 20:17:56 +08:00
24 changed files with 2260 additions and 831 deletions
+9
View File
@@ -4,6 +4,12 @@ obj/
*.user *.user
*.suo *.suo
# 便携版分发目录(dotnet build 后把单文件 exe 拷进来)
dist/
# Fody(Costura)构建时自动生成
TfsExcelImporter/FodyWeavers.xsd
# Python # Python
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
@@ -23,3 +29,6 @@ data/work_items.csv
Thumbs.db Thumbs.db
Desktop.ini Desktop.ini
.DS_Store .DS_Store
# 运行时日志(WebView2/crashpad 报错输出)
debug.log
+64 -57
View File
@@ -12,30 +12,30 @@ TFS 2013 工作项批量导入工具集,用于把 Excel/CSV 里的工时台账
| 迭代 | `2026年Sprint\2026年Sprint10` | | 迭代 | `2026年Sprint\2026年Sprint10` |
| 认证 | 域账号 NTLM(内网直连,不走代理) | | 认证 | 域账号 NTLM(内网直连,不走代理) |
## 两套工具,先用哪个 ## 工具一览
| | [TfsExcelImporter](TfsExcelImporter)(C# WinForms) | [tfs_import.py](tfs_import.py)(Python CLI) | 仓库只有一套工具:[TfsExcelImporter](TfsExcelImporter)(C# WinForms 桌面版),数据源为 `.xlsx`(默认模板随程序发布),图形界面预览后导入。
| --- | --- | --- |
| 通信协议 | TFS Client OM(VS/Team Explorer 同款内部 SOAP) | REST `/_apis/wit/*` |
| 适用 | **本环境可用**。该 TFS 2013 实例只有 `/_apis/projects` 通,`wit/fields`、`wit/classificationnodes`、`wit/wiql` 全部 404 | 服务器开放了 wit REST 路由时使用 |
| 数据源 | `.xlsx`(默认模板随程序发布) | `data/work_items.csv`(GBK/UTF-8 均可,需自备) |
| 界面 | 图形界面,预览后导入 | 命令行,`--dry-run` 先校验 |
Python 版在本环境会因 REST 路由 404 而失败,保留用于其它 TFS 实例或接口可用时的批量脚本化导入。 通信走 TFS Client OM(VS/Team Explorer 同款内部 SOAP):该 TFS 2013 实例只有 `/_apis/projects` 通,`wit/fields`、`wit/classificationnodes`、`wit/wiql` 全部 404,REST 路线走不通。原先另有一套 Python CLI(REST `/_apis/wit/*`)实现,因上述限制无法在本环境工作,已移除。
## 目录结构 ## 目录结构
``` ```
TFSImport/ TFSImport/
├── tfs_import.py # Python 命令行导入器(REST)
├── config.json # Python 版配置
├── requirements.txt # requests / requests-ntlm
├── data/ ├── data/
│ └── work_items.example.csv # 列结构与示例行(UTF-8 BOM);真实台账不入库 │ └── work_items.csv # 本地工时台账(含人员/项目,不入库)
├── templates/ ├── templates/
│ └── TFS导入模板.xlsx # 默认模板:csproj 随构建拷到 exe 目录,「导出Excel模板」原样复制它 │ └── TFS导入模板.xlsx # 默认模板:构建时嵌入 exe,「导出Excel模板」原样导出
└── TfsExcelImporter/ # C# WinForms 桌面版(主用) ├── tools/
│ ├── make_icon.py # 生成 app.ico(9 个尺寸帧,纯标准库 SDF 栅格化 + 手写 PNG/ICO)
│ ├── pe_icon.py # 解析 exe 的 PE 图标资源,导出某帧 PNG(换图标后核对用)
│ └── win_screenshot.py # 冒烟截图:拉起 exe、PrintWindow 抓窗、导出标题栏图标(ctypes)
└── TfsExcelImporter/ # C# WinForms 桌面版
├── TfsExcelImporter.csproj # net48 + ClosedXML + TFS ExtendedClient 14.* ├── TfsExcelImporter.csproj # net48 + ClosedXML + TFS ExtendedClient 14.*
├── FodyWeavers.xml # Costura 单文件打包配置(便携版)
├── NativeLibraryLoader.cs # 释放并预加载内嵌的 TFS native DLL
├── AppIcon.cs # 从内嵌 app.ico 取 Form.Icon(窗口/任务栏)
├── app.ico # 应用图标(16~256 共 9 档,tools/make_icon.py 生成)
├── MainForm.cs # 导入 / 修 Area / 补挂父项流程 ├── MainForm.cs # 导入 / 修 Area / 补挂父项流程
├── MainFormUi.cs # 界面外壳:步骤卡片布局、手风琴折叠、状态呈现 ├── MainFormUi.cs # 界面外壳:步骤卡片布局、手风琴折叠、状态呈现
├── Theme.cs # 设计 token(颜色/字号/间距/缩放)与自绘控件 ├── Theme.cs # 设计 token(颜色/字号/间距/缩放)与自绘控件
@@ -48,7 +48,7 @@ TFSImport/
## 快速开始 ## 快速开始
### C# 桌面版(主用) ### 桌面版
```powershell ```powershell
dotnet build TfsExcelImporter.sln -c Release dotnet build TfsExcelImporter.sln -c Release
@@ -56,49 +56,68 @@ dotnet build TfsExcelImporter.sln -c Release
TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe
``` ```
「导出Excel模板」复制的是 exe 同目录的 `TFS导入模板.xlsx`(构建时自动拷过去);单独分发 exe 时要带上这个文件,否则该按钮会报「未找到默认模板文件」。 「导出Excel模板」优先用 exe 同目录的 `TFS导入模板.xlsx`(现场可替换),没有则从 exe 内嵌资源导出——**分发时只带一个 exe 就够,不用再附带模板文件**。
应用图标是 `TfsExcelImporter/app.ico`(蓝色渐变圆角底 + 白色上升箭头),csproj 里 `ApplicationIcon` 写进 exe 的 Win32 图标资源,同时以托管资源再嵌一份给 `Form.Icon` 用(多尺寸帧,高 DPI 下不糊)。要改设计就改 `tools/make_icon.py` 后重跑,覆盖 `app.ico` 再编译:
```powershell
python tools/make_icon.py # 重新生成 app.ico,并出预览图 tools/icon_preview.png
python tools/win_screenshot.py TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe tools\_win.png
```
界面按 4 步排:顶部状态条常驻显示服务器/项目/类型与连接状态,四张卡片一次只展开一张(展开一张会把其它收成一行摘要),预览表格永远占满剩余高度。 界面按 4 步排:顶部状态条常驻显示服务器/项目/类型与连接状态,四张卡片一次只展开一张(展开一张会把其它收成一行摘要),预览表格永远占满剩余高度。
1. **步骤 1 连接**:填 URL、项目、工作项类型、认证方式与域账号,点「测试连接」——右上状态灯变绿即连通;内网保持「使用系统代理」**不勾选**。 1. **步骤 1 连接**:填 URL、项目、工作项类型与账号密码(认证固定 NTLM,用户名可写 `user` 或 `DOMAIN\user`),点「测试连接」——右上状态灯变绿即连通。
2. **步骤 2 选数据**:点「加载迭代列表」选目标迭代(也可手填完整路径);点「导出 Excel 模板」拿默认模板,或「浏览...」选已有 `.xlsx`。需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项)。 2. **步骤 2 选数据**:点「加载迭代列表」选目标迭代(也可手填完整路径);**Area 路径同样在这一步填,且为必填**(新导入的工作项都写到该 Area,留空会导致团队视图看不到,所以导入前会被拦下),点「加载 Area 列表」可从服务器拉真实 Area 树,也可手填完整路径;点「导出 Excel 模板」拿默认模板,或「浏览...」选已有 `.xlsx`。需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项),点「加载 PBI 列表」可拉出该迭代下的 Product Backlog Item(下拉显示「#Id 标题 · 状态」,选中自动回填纯 Id),也可直接手输 Id。字段校验**不可绕过**,不合法时日志会直接告诉你改哪一列。
3. **步骤 3 预览核对**:选完文件自动读表,表格里逐行核对;缺迭代/文件路径无效时红字直接标在对应输入框下方,不再弹框。 3. **步骤 3 预览核对**:选完文件自动读表,表格里逐行核对;缺迭代/文件路径无效时红字直接标在对应输入框下方,不再弹框。
4. **步骤 4 导入**:底部操作条点「开始导入 TFS」,进度条 + `n/m` + 成功/跳过/失败三个计数实时更新,日志抽屉逐行输出 `OK/SKIP/FAIL` 与工作项 ID;跑完点「打开报告 CSV」看逐行结果。 4. **步骤 4 导入**:底部操作条点「开始导入 TFS」,进度条 + `n/m` + 成功/跳过/失败三个计数实时更新,日志抽屉逐行输出 `OK/SKIP/FAIL` 与工作项 ID;跑完点「打开报告 CSV」看逐行结果。主按钮右侧的「跳过已存在标题」(默认不勾)是去重开关,按「项目/类型/迭代 + 标题」判重——它只作用于导入这一个动作,勾上后立即生效于下一次导入;导入跑起来后该勾选框会置灰(开关在一次导入开始时只读一次)。
5. 历史数据 Area 不对、或漏挂父项时,展开底部「高级工具」用「按迭代修 Area」「补挂父项」批量纠正;Area 路径也在这一栏里填(以前只能手改 config.json)。 5. 历史数据 Area 不对、或漏挂父项时,展开底部「高级工具」用「按迭代修 Area」「补挂父项」批量纠正;两者都按第 2 步的「目标迭代 / Area 路径」筛选已有工作项。
桌面版按 System DPI 感知实现,界面尺寸随 Windows 显示缩放换算;**改了显示缩放比例要重启程序**才生效。 桌面版按 System DPI 感知实现,界面尺寸随 Windows 显示缩放换算;**改了显示缩放比例要重启程序**才生效。
### Python 版 ### 便携版(单 exe,免安装)
构建产物只有一个文件:`TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe`(约 9.3 MB)。依赖和资源全部内嵌:
| 内容 | 打包方式 |
| --- | --- |
| 58 个托管 DLL(ClosedXML / OpenXml / TFS Client OM …) | `Costura.Fody` 内嵌,运行时经 `AssemblyResolve` 从内存加载,不落盘 |
| `Microsoft.WITDataStore32/64.dll`(纯 win32,TFS OM 用) | 独立内嵌,启动时按进程位数释放到 `%TEMP%\TfsExcelImporter\native\{内容hash}` 并 `LoadLibrary` 预加载 |
| 默认模板 `TFS导入模板.xlsx` | 内嵌资源,「导出Excel模板」时释放;exe 同目录放同名文件则优先用它 |
| `config.json` | 首次保存时写到 exe 同目录(便携);目录只读时回退 `%AppData%\TfsExcelImporter\config.json` |
分发:
```powershell ```powershell
pip install -r requirements.txt mkdir dist
python tfs_import.py --dry-run # 只校验数据与字段映射,不写入 copy TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe dist\
python tfs_import.py --list-fields # 列出服务器全部字段(显示名/引用名)
python tfs_import.py # 正式导入
python tfs_import.py --link-existing # 已导入的项补挂父链接(不新建)
python tfs_import.py --skip-existing-titles # 跳过服务器已有的同标题项
python tfs_import.py --input other.csv --limit 5
``` ```
每次运行在 `data/import_report_<时间戳>.csv` 生成逐行结果报告(行号 / Title / 结果 / WorkItemId / 错误)。 把 `dist\TfsExcelImporter.exe` 拷到任意目录双击即用。想连配置一起带走,就把 exe 同目录的 `config.json` 一起拷。
前提:目标机需有 .NET Framework 4.8(Win10 1903+ / Win11 系统自带,一般无需额外安装)。`FodyWeavers.xml` 是 Costura 的打包配置,删掉它或用 `-p:FodyDisable=true` 构建即回到「exe + 一堆 DLL」的普通输出。
## 配置说明 ## 配置说明
配置的语义、留空字段如何解析见 [tfs_import.py:49](tfs_import.py#L49) 与 [Config.cs](TfsExcelImporter/Config.cs),关键字段: 桌面版的配置落在 exe 同目录的 `config.json`(界面改动后自动写回);exe 目录不可写时回退到 `%AppData%\TfsExcelImporter\config.json`。
配置的语义、留空字段如何解析见 [Config.cs](TfsExcelImporter/Config.cs),关键字段:
| 键 | 说明 | | 键 | 说明 |
| --- | --- | | --- | --- |
| `tfs_url` / `project` / `work_item_type` | 目标集合、项目、工作项类型(`Task` 或 `Product Backlog Item`) | | `TfsUrl` / `Project` / `WorkItemType` | 目标集合、项目、工作项类型(`Task` 或 `Product Backlog Item`) |
| `iteration_path` | 可只写 `2026年Sprint\2026年Sprint10`,程序自动补项目名前缀 | | `IterationPath` | 可只写 `2026年Sprint\2026年Sprint10`,程序自动补项目名前缀 |
| `auth.mode` | `ntlm`(域账号,典型)/ `basic` / `default`(当前 Windows 凭据,仅桌面版) | | `AreaPath` | 区域路径;导入必填,界面上与迭代同在第 2 步卡片(可点「加载 Area 列表」从 TFS 分类树拉取),值直接写进 `System.AreaPath` |
| `field_refs` | 语义名 → 字段引用名;自定义字段留空时按 `resolve_fields_by_display_name` 的显示名在服务器字段表里查(支持前缀模糊匹配,如 `Completed` → `Completed Work`) | | `Username` / `Password` | 认证固定 NTLM,用户名可写 `user` 或 `DOMAIN\user` |
| `parent_title` / `parent_id` | 父工作项,二选一;按标题匹配不到会直接报错并提示改用 `parent_id` | | `FinancialProjectRef` / `CompletedRef` / `LogDateRef` / `OriginalEstimateRef` | 自定义字段引用名;留空则按显示名在服务器字段表里查(支持前缀模糊匹配,如 `Completed` → `Completed Work`) |
| `bypass_rules` | 是否请求绕过字段校验规则;桌面版走 Client OM(14.x 无 `SaveFlags.BypassRules`),实际由服务器规则决定 | | `ParentPbiId` | 所有 Task 默认挂接的父 PBI Id(界面上可从「加载 PBI 列表」里挑,落库只存纯数字);Excel 每行 `PBI Id` 列可覆盖 |
| `skip_existing_titles` | 同项目/同类型/同迭代下按标题去重 | | `SkipExistingTitles` | 同项目/同类型/同迭代下按标题去重;**默认不勾选**,需要去重时手动勾 |
| `DefaultState` | Excel `State` 列留空时的默认值 |
| `LastExcelPath` | 上次选中的数据文件,界面回填用 |
> 配置里含明文密码,请勿提交到共享仓库;`config.json` 保持空值,凭据本地填写。 > 配置里含明文密码,请勿提交到共享仓库;`config.json` 保持空值,凭据本地填写。
## Excel / CSV 列 ## Excel 列
桌面版 Excel 模板 = 仓库里的 `templates\TFS导入模板.xlsx`,界面「导出Excel模板」直接复制它: 桌面版 Excel 模板 = 仓库里的 `templates\TFS导入模板.xlsx`,界面「导出Excel模板」直接复制它:
@@ -114,37 +133,25 @@ python tfs_import.py --input other.csv --limit 5
系统日期列(`Created Date` / `Closed Date`)已从模板移除:`System.CreatedDate` 由服务器按导入时间填写,`Microsoft.VSTS.Common.ClosedDate` 不再写入、保持为空。 系统日期列(`Created Date` / `Closed Date`)已从模板移除:`System.CreatedDate` 由服务器按导入时间填写,`Microsoft.VSTS.Common.ClosedDate` 不再写入、保持为空。
Python 版仍读 `data/work_items.example.csv` 的旧列(含 `CreatedDate`、`ClosedDate`、`Notes`),未随模板调整。 真实台账含人员与项目信息,不入库,放在 `data\work_items.csv`(已在 `.gitignore` 里)。
真实台账含人员与项目信息,不入库;本地准备数据文件:
```powershell
copy data\work_items.example.csv data\work_items.csv # Python 版默认读这个路径,已在 .gitignore 里
```
- 表头按名匹配,顺序不限,`AssignedTo` / `Assigned To` 等价;缺列按模板顺序兜底,但该列已被别的表头占用时不套用位置(旧版模板文件不会串列)。 - 表头按名匹配,顺序不限,`AssignedTo` / `Assigned To` 等价;缺列按模板顺序兜底,但该列已被别的表头占用时不套用位置(旧版模板文件不会串列)。
- 空 `Title` 的行直接跳过;`State` 为空时用 `default_state`;未识别的列(如 `Group`)忽略。 - 空 `Title` 的行直接跳过;`State` 为空时用 `DefaultState`;未识别的列(如 `Group`)忽略。
- 日期支持 `yyyy-MM-dd[ / ][ HH:mm[:ss]]` 等格式,Excel 日期序列号(如 `46300`)会被还原成日期。 - 日期支持 `yyyy-MM-dd[ / ][ HH:mm[:ss]]` 等格式,Excel 日期序列号(如 `46300`)会被还原成日期。
- CSV 从 Excel 另存时注意编码,脚本按 `utf-8-sig` → `gbk` 依次尝试。
## 环境坑点 ## 环境坑点
这些是实测结论,改代码前先看: 这些是实测结论,改代码前先看:
- **wit REST 路由全 404**:TFS 2013 RTM/低 Update 不带 `/_apis/wit/*`,`Classification.asmx?WSDL` 也被禁 → 桌面版整体走 Client OM(NuGet `Microsoft.TeamFoundationServer.ExtendedClient` 钉 `14.*`,对应 VS2015 客户端代际;15.x 不兼容 TFS 2013)。 - **wit REST 路由全 404**:TFS 2013 RTM/低 Update 不带 `/_apis/wit/*`,`Classification.asmx?WSDL` 也被禁 → 桌面版整体走 Client OM(NuGet `Microsoft.TeamFoundationServer.ExtendedClient` 钉 `14.*`,对应 VS2015 客户端代际;15.x 不兼容 TFS 2013)。
- **502 Bad Gateway**:TFS OM 内部用 `HttpWebRequest`,默认跟随 IE 系统代理,代理会拦内网 TFS。桌面版默认把 `WebRequest.DefaultWebProxy` 置空直连;确实要走代理时勾「使用系统代理」并带上 Windows 凭据过代理认证。 - **502 Bad Gateway**:TFS OM 内部用 `HttpWebRequest`,默认跟随 IE 系统代理,代理会拦内网 TFS。桌面版固定把 `WebRequest.DefaultWebProxy` 置空强制直连,界面不提供代理开关(本机若只能经代理上网,程序会直连失败)。
- **Area 与迭代同源**:两者都是 `ICommonStructureService` 的分类树(Area = `ProjectModelHierarchy`,迭代 = `ProjectLifecycle`),`GetNodesXml` 深度展开后取每个节点的 `Path`,再由 `NormalizeNodePath` 去掉项目名前缀与 `Area`/`Iteration` 根段、拼回 `项目\子...`。项目根 Area 归一化后为空会被过滤,所以下拉里只有子区域;列表拉不到时手填完整路径一样可用。`TF30063` 是「服务器拒绝当前身份」(填步骤 1 的账号密码),与 DNS/代理导致的连不上是两码事,界面已分开提示。
- **TF400276 / 关闭状态只读**:改已关闭工作项的 Area 会被拒;`FixAreaAsync` 走「重新打开 → 改 Area → 还原状态」的状态循环,中途失败回滚状态。 - **TF400276 / 关闭状态只读**:改已关闭工作项的 Area 会被拒;`FixAreaAsync` 走「重新打开 → 改 Area → 还原状态」的状态循环,中途失败回滚状态。
- **`System.CreatedDate` 写不进去**:OM 14.x 没有 `SaveFlags.BypassRules`(15.x 才加),该字段服务器托管;`Microsoft.VSTS.Common.ClosedDate` 在 `State=Done` 时按普通字段可尝试写入。模板已去掉日期列,所以导入不再走这条路——若某模板要求 `Done` 必填 Closed Date,需另加列或改回写日期。 - **`System.CreatedDate` 写不进去**:OM 14.x 没有 `SaveFlags.BypassRules`(15.x 才加),该字段服务器托管;`Microsoft.VSTS.Common.ClosedDate` 在 `State=Done` 时按普通字段可尝试写入。模板已去掉日期列,所以导入不再走这条路——若某模板要求 `Done` 必填 Closed Date,需另加列或改回写日期。
- **孤立 Task 在积压工作页不可见**:TFS 2013 的 backlog/任务板按「父项 → 子任务」组织,没挂父链接的 Task 只能在查询里看到,所以导入必须带 `parent_title`/`parent_id`。 - **字段校验不可绕过**:OM 14.x 没有 `SaveFlags.BypassRules`,旧界面上那个 `bypassRules` 勾选从未真正生效,已移除。校验失败时日志与 report CSV 直接给出「字段(原因) → 怎么改」,列表字段还会列出允许值,按提示改 Excel 对应列后重跑即可。
- **孤立 Task 在积压工作页不可见**:TFS 2013 的 backlog/任务板按「父项 → 子任务」组织,没挂父链接的 Task 只能在查询里看到,所以导入必须带父项(界面填父 PBI Id,或 Excel 里加 `PBI Id` 列)。
- **DNS 解析失败 / 超时**:多为 VPN 或网络断开,不是代码问题;桌面版会对这类异常附加排查提示。 - **DNS 解析失败 / 超时**:多为 VPN 或网络断开,不是代码问题;桌面版会对这类异常附加排查提示。
## 验证 ## 验证
改动 Python 版后至少跑: 桌面版改完,先用只含几行的 Excel 跑一次小批量导入(先删服务器已有同标题项或勾操作条上「跳过已存在标题」),再在积压工作页展开父项确认子任务可见;改动涉及界面布局或图标时,跑 `python tools/win_screenshot.py` 抓图核对。确认无误后再跑全量。
```powershell
python -m py_compile tfs_import.py
python tfs_import.py --dry-run
```
桌面版改完跑一次 `--limit` 级别的小批量导入(先删服务器已有同标题项或开启跳过),并在积压工作页展开父项确认子任务可见。
+46
View File
@@ -0,0 +1,46 @@
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace TfsExcelImporter
{
/// <summary>
/// 应用图标。exe 的 Win32 图标资源由 csproj 的 ApplicationIcon 提供,
/// 这里负责窗口标题栏/任务栏用的 Form.Icon:从内嵌的 app.ico(9 个尺寸帧)
/// 直接构造,系统按 DPI 取 16/32/48;取不到再退回提取 exe 自身图标。
/// </summary>
internal static class AppIcon
{
private static Icon _cached;
private static bool _tried;
public static Icon Load()
{
if (_tried) return _cached;
_tried = true;
try
{
using (Stream s = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("app.ico"))
{
if (s != null) _cached = new Icon(s);
}
}
catch
{
// 内嵌 ICO 解析失败(例如只认 BMP 帧的极端情况):忽略,走下面的兜底
_cached = null;
}
if (_cached == null)
{
try { _cached = Icon.ExtractAssociatedIcon(Application.ExecutablePath); }
catch { }
}
return _cached;
}
}
}
+98 -11
View File
@@ -1,5 +1,7 @@
using System; using System;
using System.IO; using System.IO;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace TfsExcelImporter namespace TfsExcelImporter
@@ -18,18 +20,50 @@ namespace TfsExcelImporter
// 可选:区域路径 // 可选:区域路径
public string AreaPath { get; set; } = ""; public string AreaPath { get; set; } = "";
// ntlm | basic | default(当前 Windows 凭据) // 认证固定 NTLM:用户名可写 user,也可写 DOMAIN\user
public string AuthMode { get; set; } = "ntlm";
public string Username { get; set; } = ""; public string Username { get; set; } = "";
// 明文密码只存在于内存(UI 回显需要);落盘一律走 DPAPI 加密的 PasswordEnc。
// [JsonIgnore] 防止明文随 SerializeObject 写进 config.json。
[JsonIgnore]
public string Password { get; set; } = ""; public string Password { get; set; } = "";
public string Domain { get; set; } = "";
// 是否走 IE 系统代理。内网 TFS 请保持 false(直连); // 兼容旧版明文键:反序列化时承接旧 config.json 的 "Password",下次 Save 自动转为加密存储。
// 代理/网关常对 HttpClient 请求返回 502(浏览器例外名单直连,.NET 不一定继承) // getter 恒返 null,序列化不再输出明文键。
public bool UseSystemProxy { get; set; } = false; [JsonProperty("Password", NullValueHandling = NullValueHandling.Ignore)]
private string LegacyPassword { get { return null; } set { if (!string.IsNullOrEmpty(value)) Password = value; } }
public bool BypassRules { get; set; } = true; // DPAPI(CurrentUser) 加密后的密码,Base64;同机同用户可解,拷到别的机器/账户需重输。
public bool SkipExistingTitles { get; set; } = true; [JsonProperty("PasswordEnc", NullValueHandling = NullValueHandling.Ignore)]
private string PasswordEnc { get; set; } = "";
// ------------------------------------------------------------- DPAPI
private static string Protect(string plain)
{
var bytes = ProtectedData.Protect(Encoding.UTF8.GetBytes(plain), null, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(bytes);
}
/// <summary>解密失败返回 null(不抛异常,让调用方回退到空密码)。</summary>
private static string TryUnprotect(string cipher)
{
try
{
var bytes = ProtectedData.Unprotect(Convert.FromBase64String(cipher), null, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(bytes);
}
catch
{
return null;
}
}
// 旧版本有 BypassRules 开关,已移除:TFS 2013 对应的 Client OM 14.x 没有 SaveFlags.BypassRules
// (15.x 才加,而 15.x 不兼容 TFS 2013),勾选从未生效。旧 config.json 里的残留键由
// Newtonsoft 按默认 MissingMemberHandling.Ignore 忽略,不需要手工清理。
// 默认不勾选:首次导入时希望先看到真实冲突/报错,而不是被静默跳过
public bool SkipExistingTitles { get; set; } = false;
public string DefaultState { get; set; } = "To Do"; public string DefaultState { get; set; } = "To Do";
// 自定义字段引用名;留空则按 DisplayName 自动解析 // 自定义字段引用名;留空则按 DisplayName 自动解析
@@ -44,11 +78,39 @@ namespace TfsExcelImporter
// 父 Product Backlog Item:所有 Task 默认挂接的 PBI Id(如 219975);Excel 每行 PBI Id 列可覆盖 // 父 Product Backlog Item:所有 Task 默认挂接的 PBI Id(如 219975);Excel 每行 PBI Id 列可覆盖
public string ParentPbiId { get; set; } = ""; public string ParentPbiId { get; set; } = "";
private static string ConfigPath // 便携优先:配置写在 exe 同目录(拷走 exe 即可带走配置);
// exe 目录只读(如放在 Program Files)时回退到 %AppData%\TfsExcelImporter。
private static string PortableConfigPath
{ {
get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"); } get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"); }
} }
private static string RoamingConfigPath
{
get
{
return Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"TfsExcelImporter", "config.json");
}
}
private static string ConfigPath
{
get
{
if (File.Exists(PortableConfigPath)) return PortableConfigPath;
if (File.Exists(RoamingConfigPath)) return RoamingConfigPath;
return PortableConfigPath;
}
}
/// <summary>当前实际使用的配置文件路径(界面提示用)。</summary>
public static string ConfigLocation
{
get { return ConfigPath; }
}
public static AppConfig Load() public static AppConfig Load()
{ {
try try
@@ -56,7 +118,16 @@ namespace TfsExcelImporter
if (File.Exists(ConfigPath)) if (File.Exists(ConfigPath))
{ {
var cfg = JsonConvert.DeserializeObject<AppConfig>(File.ReadAllText(ConfigPath)); var cfg = JsonConvert.DeserializeObject<AppConfig>(File.ReadAllText(ConfigPath));
if (cfg != null) return cfg; if (cfg != null)
{
// 加密值优先于旧明文键;解密失败(换机/换账户/文件被改)留空,用户重输即可
if (!string.IsNullOrEmpty(cfg.PasswordEnc))
{
var plain = TryUnprotect(cfg.PasswordEnc);
if (plain != null) cfg.Password = plain;
}
return cfg;
}
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -68,14 +139,30 @@ namespace TfsExcelImporter
public void Save() public void Save()
{ {
// 落盘前把内存中的明文加密;Password 本身带 [JsonIgnore] 不会写出
PasswordEnc = string.IsNullOrEmpty(Password) ? "" : Protect(Password);
var json = JsonConvert.SerializeObject(this, Formatting.Indented);
try try
{ {
File.WriteAllText(ConfigPath, JsonConvert.SerializeObject(this, Formatting.Indented)); File.WriteAllText(ConfigPath, json);
return;
} }
catch (Exception ex) catch (Exception ex)
{ {
System.Diagnostics.Debug.WriteLine("写入 config.json 失败: " + ex.Message); System.Diagnostics.Debug.WriteLine("写入 config.json 失败: " + ex.Message);
} }
// exe 目录不可写(只读介质 / Program Files)时落到用户配置目录
try
{
var fallback = RoamingConfigPath;
Directory.CreateDirectory(Path.GetDirectoryName(fallback));
File.WriteAllText(fallback, json);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("写入用户配置目录失败: " + ex.Message);
}
} }
} }
} }
+123 -7
View File
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Data; using System.Data;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Security.Cryptography;
using ClosedXML.Excel; using ClosedXML.Excel;
namespace TfsExcelImporter namespace TfsExcelImporter
@@ -22,7 +23,8 @@ namespace TfsExcelImporter
/// <summary> /// <summary>
/// Excel 读取与默认模板。模板内容(列宽、示例行、样式)只在 /// Excel 读取与默认模板。模板内容(列宽、示例行、样式)只在
/// templates\TFS导入模板.xlsx 里维护,随构建复制到 exe 目录后原样导出。 /// templates\TFS导入模板.xlsx 里维护,构建时作为嵌入资源打进 exe;
/// 若 exe 同目录存在同名文件则优先用它(现场可替换模板而不用重编译)。
/// 列: Title | State | Assigned To | FinancialProject | Completed | LogDate | PBI Id | Description /// 列: Title | State | Assigned To | FinancialProject | Completed | LogDate | PBI Id | Description
/// </summary> /// </summary>
public static class ExcelService public static class ExcelService
@@ -44,13 +46,127 @@ namespace TfsExcelImporter
// --------------------------------------------------------- 默认模板 // --------------------------------------------------------- 默认模板
/// <summary>把随程序发布的默认模板原样复制到目标路径。</summary> /// <summary>exe 同目录的模板路径(现场可替换,存在时优先于内嵌模板)。</summary>
public static void CopyTemplate(string path) public static string LocalTemplatePath
{ {
var src = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TemplateFileName); get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TemplateFileName); }
if (!File.Exists(src)) }
throw new FileNotFoundException("未找到默认模板文件: " + src, src);
File.Copy(src, path, true); /// <summary>
/// exe 同目录的模板是否还是构建时那份(与内嵌模板内容一致)。
/// 现场替换过、或被填过数据都算"不一致",导出前应由调用方确认来源。
/// </summary>
public static bool LocalTemplateIsBuiltIn()
{
var local = LocalTemplatePath;
if (!File.Exists(local)) return true;
try
{
var embed = ReadEmbeddedTemplate();
return embed != null && SameDigest(embed, File.ReadAllBytes(local));
}
catch { return false; }
}
/// <summary>
/// 把默认模板原样写到目标路径,返回模板来源描述(用于日志)。
/// 优先用 exe 同目录的同名文件(现场可替换),forceEmbedded 或该文件不存在时用内嵌资源。
///
/// 模板源只有这两个确定来源,绝不按"相近文件名"去猜;目标就是调用方选定的那一个路径。
/// 写出后再比对一次内容,避免"报成功但文件不是模板"这类静默错。
/// </summary>
public static string CopyTemplate(string path, bool forceEmbedded = false)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException("导出路径为空", nameof(path));
var dst = Path.GetFullPath(path);
var src = LocalTemplatePath;
if (!forceEmbedded && File.Exists(src))
{
var srcFull = Path.GetFullPath(src);
// 目标就是源本身:File.Copy 会抛"源和目标是同一个文件",先给出可读提示
if (string.Equals(srcFull, dst, StringComparison.OrdinalIgnoreCase))
throw new IOException(
"导出路径与模板源文件相同(" + srcFull + "),请换一个文件名或目录。");
File.Copy(srcFull, dst, true);
AssertSameContent(srcFull, dst);
return "exe 同目录 " + TemplateFileName;
}
var embed = ReadEmbeddedTemplate();
if (embed == null)
throw new FileNotFoundException(
"未找到默认模板:exe 内嵌资源与同目录 " + TemplateFileName + " 均缺失", src);
// 先写临时文件再替换:中途失败不会把目标位置已有的文件写坏
var tmp = dst + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
File.WriteAllBytes(tmp, embed);
File.Copy(tmp, dst, true);
AssertSameContent(tmp, dst);
}
finally
{
try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
}
return "exe 内嵌模板";
}
private static byte[] ReadEmbeddedTemplate()
{
var asm = typeof(ExcelService).Assembly;
// 嵌入名取决于 Link 名:默认 <RootNamespace>.<文件名>
var name = asm.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(TemplateFileName, StringComparison.OrdinalIgnoreCase));
if (name == null) return null;
using (var input = asm.GetManifestResourceStream(name))
{
if (input == null) return null;
using (var buffer = new MemoryStream())
{
input.CopyTo(buffer);
return buffer.ToArray();
}
}
}
/// <summary>写出后比对内容,避免"导出成功但文件是旧的/被别的数据占了"这类静默错。</summary>
private static void AssertSameContent(string expected, string actual)
{
var a = new FileInfo(expected);
var b = new FileInfo(actual);
if (!b.Exists || b.Length != a.Length || !SameDigest(expected, actual))
throw new IOException("模板写出后校验不一致,目标文件内容与模板不同:" + actual);
}
private static bool SameDigest(string x, string y)
{
return SameDigest(File.ReadAllBytes(x), File.ReadAllBytes(y));
}
private static bool SameDigest(byte[] x, byte[] y)
{
if (x == null || y == null || x.Length != y.Length) return false;
using (var sha = SHA256.Create())
{
byte[] hx = sha.ComputeHash(x);
byte[] hy = sha.ComputeHash(y);
for (int i = 0; i < hx.Length; i++)
if (hx[i] != hy[i]) return false;
return true;
}
}
/// <summary>数据行数(Title 非空);文件被占用/损坏时返回 -1,调用方据此区分"读不出"与"空表"。</summary>
public static int CountDataRows(string path)
{
try { return ReadRows(path).Count; }
catch { return -1; }
} }
// --------------------------------------------------------- 读取数据 // --------------------------------------------------------- 读取数据
+3
View File
@@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
</Weavers>
+339 -86
View File
@@ -23,6 +23,7 @@ namespace TfsExcelImporter
using (var g = Graphics.FromHwnd(IntPtr.Zero)) using (var g = Graphics.FromHwnd(IntPtr.Zero))
Theme.Scale = g.DpiX / 96f; Theme.Scale = g.DpiX / 96f;
_cfg = AppConfig.Load(); _cfg = AppConfig.Load();
Icon = AppIcon.Load();
BuildUi(); BuildUi();
LoadConfigToUi(); LoadConfigToUi();
WireEvents(); WireEvents();
@@ -34,23 +35,29 @@ namespace TfsExcelImporter
private void WireEvents() private void WireEvents()
{ {
_cmbAuth.SelectedIndexChanged += (s, e) => { UpdateAuthUi(); OnFieldChanged(); };
_btnTest.Click += async (s, e) => await TestConnectionAsync(); _btnTest.Click += async (s, e) => await TestConnectionAsync();
_btnLoadIterations.Click += async (s, e) => await LoadIterationsAsync(); _btnLoadIterations.Click += async (s, e) => await LoadIterationsAsync();
_btnBrowse.Click += (s, e) => BrowseExcel(); _btnLoadAreas.Click += async (s, e) => await LoadAreasAsync();
_btnLoadPbi.Click += async (s, e) => await LoadBacklogAsync();
_btnTemplate.Click += (s, e) => ExportTemplate(); _btnTemplate.Click += (s, e) => ExportTemplate();
_btnPreview.Click += (s, e) => PreviewData(); _btnPreview.Click += async (s, e) => await PreviewDataAsync();
_btnImport.Click += async (s, e) => await ImportAsync(); _btnImport.Click += async (s, e) => await ImportAsync();
_btnFixArea.Click += async (s, e) => await FixAreaAsync(); _btnFixArea.Click += async (s, e) => await FixAreaAsync();
_btnLinkParent.Click += async (s, e) => await LinkParentAsync(); _btnLinkParent.Click += async (s, e) => await LinkParentAsync();
foreach (var tb in new[] { _txtUrl, _txtProject, _txtType, _txtUser, _txtPwd, _txtDomain, foreach (var tb in new[] { _txtUrl, _txtProject, _txtType, _txtUser, _txtPwd, _txtExcel })
_txtExcel, _txtParentPbi, _txtAreaPath })
tb.TextChanged += (s, e) => OnFieldChanged(); tb.TextChanged += (s, e) => OnFieldChanged();
_cmbIteration.TextChanged += (s, e) => OnFieldChanged(); _cmbIteration.TextChanged += (s, e) => OnFieldChanged();
_cmbArea.TextChanged += (s, e) => OnFieldChanged();
_cmbParent.TextChanged += (s, e) => OnFieldChanged();
// 从列表里挑的是「#219975 标题 · 状态」这种展示文本,落库/导入得是纯 Id。
// 两个事件都挂:鼠标点选主要走 SelectionChangeCommitted(下拉关闭时),
// 键盘上下选择/程序置位只有 SelectedIndexChanged,重复选同一项则只有前者。
_cmbParent.SelectedIndexChanged += (s, e) => CommitPbiSelection();
_cmbParent.SelectionChangeCommitted += (s, e) => CommitPbiSelection();
// 下拉收起时再兜一次:无论键盘还是鼠标选完,这里一定能拿到最终选中项
_cmbParent.DropDownClosed += (s, e) => CommitPbiSelection();
_chkSkip.CheckedChanged += (s, e) => OnFieldChanged(); _chkSkip.CheckedChanged += (s, e) => OnFieldChanged();
_chkBypass.CheckedChanged += (s, e) => OnFieldChanged();
_chkProxy.CheckedChanged += (s, e) => OnFieldChanged();
FormClosing += (s, e) => { try { SaveUiToConfig(); } catch { } }; FormClosing += (s, e) => { try { SaveUiToConfig(); } catch { } };
} }
@@ -61,37 +68,19 @@ namespace TfsExcelImporter
RefreshSummaries(); RefreshSummaries();
} }
// ------------------------------------------------------------- 认证区联动
private void UpdateAuthUi()
{
bool needCreds = _cmbAuth.SelectedItem != null && _cmbAuth.SelectedItem.ToString() != "default";
_txtUser.Enabled = needCreds;
_txtPwd.Enabled = needCreds;
_txtDomain.Enabled = needCreds;
_fUser.Invalid = false;
_fPwd.Invalid = false;
_fDomain.Invalid = false;
}
// ------------------------------------------------------------- 配置互转 // ------------------------------------------------------------- 配置互转
private void LoadConfigToUi() private void LoadConfigToUi()
{ {
_txtUrl.Text = _cfg.TfsUrl; _txtUrl.Text = _cfg.TfsUrl;
_txtProject.Text = _cfg.Project; _txtProject.Text = _cfg.Project;
_txtType.Text = _cfg.WorkItemType; _txtType.Text = _cfg.WorkItemType;
_cmbAuth.SelectedItem = _cfg.AuthMode;
if (_cmbAuth.SelectedItem == null) _cmbAuth.SelectedItem = "ntlm";
_txtUser.Text = _cfg.Username; _txtUser.Text = _cfg.Username;
_txtPwd.Text = _cfg.Password; _txtPwd.Text = _cfg.Password;
_txtDomain.Text = _cfg.Domain;
_chkProxy.Checked = _cfg.UseSystemProxy;
_cmbIteration.Text = _cfg.IterationPath; _cmbIteration.Text = _cfg.IterationPath;
_txtExcel.Text = _cfg.LastExcelPath; _txtExcel.Text = _cfg.LastExcelPath;
_txtAreaPath.Text = _cfg.AreaPath; _cmbArea.Text = _cfg.AreaPath;
_chkSkip.Checked = _cfg.SkipExistingTitles; _chkSkip.Checked = _cfg.SkipExistingTitles;
_chkBypass.Checked = _cfg.BypassRules; _cmbParent.Text = _cfg.ParentPbiId;
_txtParentPbi.Text = _cfg.ParentPbiId;
UpdateAuthUi();
} }
private void SaveUiToConfig() private void SaveUiToConfig()
@@ -99,17 +88,13 @@ namespace TfsExcelImporter
_cfg.TfsUrl = _txtUrl.Text.Trim(); _cfg.TfsUrl = _txtUrl.Text.Trim();
_cfg.Project = _txtProject.Text.Trim(); _cfg.Project = _txtProject.Text.Trim();
_cfg.WorkItemType = _txtType.Text.Trim(); _cfg.WorkItemType = _txtType.Text.Trim();
_cfg.AuthMode = _cmbAuth.SelectedItem != null ? _cmbAuth.SelectedItem.ToString() : "ntlm";
_cfg.Username = _txtUser.Text.Trim(); _cfg.Username = _txtUser.Text.Trim();
_cfg.Password = _txtPwd.Text; _cfg.Password = _txtPwd.Text;
_cfg.Domain = _txtDomain.Text.Trim();
_cfg.UseSystemProxy = _chkProxy.Checked;
_cfg.IterationPath = _cmbIteration.Text.Trim(); _cfg.IterationPath = _cmbIteration.Text.Trim();
_cfg.LastExcelPath = _txtExcel.Text.Trim(); _cfg.LastExcelPath = _txtExcel.Text.Trim();
_cfg.AreaPath = _txtAreaPath.Text.Trim(); _cfg.AreaPath = _cmbArea.Text.Trim();
_cfg.SkipExistingTitles = _chkSkip.Checked; _cfg.SkipExistingTitles = _chkSkip.Checked;
_cfg.BypassRules = _chkBypass.Checked; _cfg.ParentPbiId = NormalizePbiText(_cmbParent.Text);
_cfg.ParentPbiId = _txtParentPbi.Text.Trim();
_cfg.Save(); _cfg.Save();
} }
@@ -167,7 +152,7 @@ namespace TfsExcelImporter
SetConnection("连接失败", ChipKind.Danger); SetConnection("连接失败", ChipKind.Danger);
SetBadgeOf(_cardConn, BadgeKind.Warn); SetBadgeOf(_cardConn, BadgeKind.Warn);
Log("连接失败: " + FirstLine(ex.Message)); Log("连接失败: " + FirstLine(ex.Message));
Log("排查: 内网请确认「使用系统代理」保持关闭;DNS 失败多为 VPN 或未连内网。"); Log("排查: 程序固定直连(不走本机系统代理);DNS 失败多为 VPN 或未连内网。");
_cardConn.Expanded = true; _cardConn.Expanded = true;
_cardConn.ApplyHeight(); _cardConn.ApplyHeight();
Relayout(); Relayout();
@@ -178,8 +163,24 @@ namespace TfsExcelImporter
} }
} }
// ------------------------------------------------------------- 迭代加载 // ------------------------------------------------------------- 迭代 / Area 列表
// 两者都是 TFS 分类结构(ICommonStructureService),取数、填表、报错完全同构,
// 只有「结构根节点」「是否自动选第一条」不同,所以共用一套加载流程。
private async Task LoadIterationsAsync() private async Task LoadIterationsAsync()
{
await LoadPathListAsync("迭代", c => c.GetIterationPathsAsync(_cfg.Project, Log),
_cmbIteration, _fIteration, _errIteration, true);
}
private async Task LoadAreasAsync()
{
// Area 不自动选第一条:选错区域会静默写到别人的团队视图下,让用户自己挑更安全
await LoadPathListAsync("Area", c => c.GetAreaPathsAsync(_cfg.Project, Log),
_cmbArea, _fArea, _errArea, false);
}
private async Task LoadPathListAsync(string what, Func<TfsClient, Task<List<string>>> fetch,
ComboBox combo, InputField field, Label err, bool selectFirstWhenNoMatch)
{ {
SaveUiToConfig(); SaveUiToConfig();
if (string.IsNullOrWhiteSpace(_cfg.TfsUrl)) if (string.IsNullOrWhiteSpace(_cfg.TfsUrl))
@@ -189,7 +190,7 @@ namespace TfsExcelImporter
return; return;
} }
SetBusy(true); SetBusy(true);
SetConnection("读取迭代中…", ChipKind.Info); SetConnection($"读取 {what} 列表中…", ChipKind.Info);
try try
{ {
using (var client = new TfsClient(_cfg)) using (var client = new TfsClient(_cfg))
@@ -206,37 +207,17 @@ namespace TfsExcelImporter
{ {
Log("警告: 字段元数据获取失败,导入可能受影响: " + FirstLine(ex.Message)); Log("警告: 字段元数据获取失败,导入可能受影响: " + FirstLine(ex.Message));
} }
var paths = await client.GetIterationPathsAsync(_cfg.Project, Log); var paths = await fetch(client);
var keep = _cmbIteration.Text; FillPathCombo(combo, paths, selectFirstWhenNoMatch);
_cmbIteration.Items.Clear(); Log($"已加载 {combo.Items.Count} 条 {what} 路径");
foreach (var p in paths) _cmbIteration.Items.Add(p);
if (_cmbIteration.Items.Count > 0)
{
int match = -1;
for (int i = 0; i < _cmbIteration.Items.Count; i++)
{
if (string.Equals(_cmbIteration.Items[i].ToString(), keep, StringComparison.OrdinalIgnoreCase)
|| string.Equals(_cmbIteration.Items[i].ToString(), _cfg.IterationPath, StringComparison.OrdinalIgnoreCase))
{
match = i;
break;
}
}
_cmbIteration.SelectedIndex = match >= 0 ? match : 0;
}
Log($"已加载 {_cmbIteration.Items.Count} 个迭代路径");
SetConnection("已连接", ChipKind.Ok); SetConnection("已连接", ChipKind.Ok);
SetBadgeOf(_cardConn, BadgeKind.Done); SetBadgeOf(_cardConn, BadgeKind.Done);
ShowError(_errIteration, _fIteration, _cardData, ""); ShowError(err, field, _cardData, "");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
SetConnection("连接失败", ChipKind.Danger); ReportTfsFailure(ex, what, field, err);
SetBadgeOf(_cardConn, BadgeKind.Warn);
ShowError(_errIteration, _fIteration, _cardData, "迭代列表加载失败,可手填完整路径");
Log("加载迭代失败: " + FirstLine(ex.Message));
Log("排查: 内网请确认「使用系统代理」保持关闭;DNS 失败多为 VPN 或未连内网。");
} }
finally finally
{ {
@@ -245,8 +226,139 @@ namespace TfsExcelImporter
} }
} }
// ------------------------------------------------------------- 父 PBI 列表
private async Task LoadBacklogAsync()
{
SaveUiToConfig();
if (string.IsNullOrWhiteSpace(_cfg.TfsUrl))
{
Append("请先填写服务器 URL", LogLevel.Warn);
OpenDetail(_cardConn);
return;
}
SetBusy(true);
SetConnection("读取 PBI 列表中…", ChipKind.Info);
try
{
using (var client = new TfsClient(_cfg))
{
Log("测试连接...");
Log(await client.TestConnectionAsync());
var items = await client.GetBacklogItemsAsync(_cfg.Project, _cfg.IterationPath, Log);
// 下拉项是「#219975 标题 · 状态」,但字段本身只存纯 Id:
// Items.Clear 会连带清空 Text,所以先存后回填,刷新列表不丢已填的 Id。
var keep = _cmbParent.Text;
_cmbParent.Items.Clear();
foreach (var it in items) _cmbParent.Items.Add(it);
_cmbParent.Text = keep;
Log($"已加载 {items.Count} 条候选父项(从列表选中后会自动回填 Id)");
if (items.Count == 0) Log("提示: 没有可选父项,可直接手填 Id,或先确认项目/迭代是否正确");
SetConnection("已连接", ChipKind.Ok);
SetBadgeOf(_cardConn, BadgeKind.Done);
ShowError(_errParent, _fParent, _cardData, "");
}
}
catch (Exception ex)
{
ReportTfsFailure(ex, "父 PBI", _fParent, _errParent);
}
finally
{
SetBusy(false);
OnFieldChanged();
}
}
/// <summary>
/// 列表项是「#219975 标题 · State」这种展示文本,字段要的是纯数字 Id:
/// 选中后立刻把 Text 归位成 Id,避免展示串被写进 System.Parent 或落进 config。
/// 用 SelectedIndexChanged 而不是 SelectionChangeCommitted——后者只在「下拉关闭」时才发,
/// 键盘/程序触发的选中收不到;这里以「# 开头」判定是不是列表回填,手输纯 Id 不受影响。
/// 回填 Text 会让 SelectedIndex 变 -1 再触发一次,此时文本已是数字,直接 return 不会递归。
/// </summary>
private void CommitPbiSelection()
{
int idx = _cmbParent.SelectedIndex;
if (idx < 0 || idx >= _cmbParent.Items.Count) return; // 回填后 SelectedIndex 会变 -1,这条路用于收敛
var item = _cmbParent.Items[idx] as TfsClient.WorkItemBrief;
if (item == null) return;
var id = item.Id.ToString();
if (string.Equals(_cmbParent.Text, id, StringComparison.Ordinal)) return;
_cmbParent.Text = id;
_cmbParent.SelectionStart = id.Length;
Log($"父 PBI 已选: #{item.Id} {item.Title}");
}
/// <summary>
/// 把「#219975 标题 · State」洗成纯 Id 再落库。
/// 选中事件负责即时回填,这里是最后一道保险:事件万一没触发(比如某些自绘交互),
/// 写进 config / 传给 TFS 的仍是干净 Id,不会出现「挂不上父项却看不出原因」。
/// </summary>
private static string NormalizePbiText(string text)
{
if (string.IsNullOrWhiteSpace(text)) return "";
text = text.Trim();
if (text[0] != '#') return text;
int i = 1;
while (i < text.Length && text[i] >= '0' && text[i] <= '9') i++;
return i > 1 ? text.Substring(1, i - 1) : text;
}
/// <summary>
/// 连接类失败的统一呈现:TF30063(服务器拒绝当前身份)与网络不通是两回事,
/// 前者该去填账号密码,后者才查 VPN/代理,提示分开写才能真正指引到动作。
/// </summary>
private void ReportTfsFailure(Exception ex, string what, InputField field, Label err)
{
var msg = FirstLine(ex.Message);
if (msg.IndexOf("TF30063", StringComparison.OrdinalIgnoreCase) >= 0)
{
SetConnection("认证失败", ChipKind.Danger);
SetBadgeOf(_cardConn, BadgeKind.Warn);
ShowError(err, field, _cardData, "认证失败:请在步骤 1 填写可访问该项目的用户名/密码");
Log($"加载 {what} 失败: 未授权(TF30063),当前 Windows 身份无权访问该项目");
Log("排查: 用户名可写 user 或 DOMAIN\\user;程序固定走 NTLM 直连。");
}
else
{
SetConnection("连接失败", ChipKind.Danger);
SetBadgeOf(_cardConn, BadgeKind.Warn);
ShowError(err, field, _cardData, $"{what} 列表加载失败,可手动填写");
Log($"加载 {what} 失败: " + msg);
Log("排查: 程序固定直连(不走本机系统代理);DNS 失败多为 VPN 或未连内网。");
}
}
/// <summary>
/// 填充路径下拉:先保留当前手填/已选内容,刷新列表不冲掉用户的选择。
/// Items.Clear 会把 DropDown 样式的 Text 一并清空,所以要在清空前取值、匹配后回填。
/// </summary>
private static void FillPathCombo(ComboBox combo, List<string> paths, bool selectFirstWhenNoMatch)
{
var keep = combo.Text;
combo.Items.Clear();
foreach (var p in paths) combo.Items.Add(p);
if (combo.Items.Count == 0)
{
combo.Text = keep;
return;
}
int match = -1;
for (int i = 0; i < combo.Items.Count; i++)
{
if (string.Equals(combo.Items[i].ToString(), keep, StringComparison.OrdinalIgnoreCase))
{
match = i;
break;
}
}
if (match >= 0) combo.SelectedIndex = match;
else if (selectFirstWhenNoMatch) combo.SelectedIndex = 0;
else combo.Text = keep;
}
// ------------------------------------------------------------- Excel // ------------------------------------------------------------- Excel
private void BrowseExcel() private async void BrowseExcel()
{ {
using (var dlg = new OpenFileDialog()) using (var dlg = new OpenFileDialog())
{ {
@@ -259,25 +371,40 @@ namespace TfsExcelImporter
if (dlg.ShowDialog(this) != DialogResult.OK) return; if (dlg.ShowDialog(this) != DialogResult.OK) return;
_txtExcel.Text = dlg.FileName; _txtExcel.Text = dlg.FileName;
SaveUiToConfig(); SaveUiToConfig();
PreviewData(); await PreviewDataAsync();
} }
} }
private void ExportTemplate() private async void ExportTemplate()
{ {
var startDir = ExportStartDirectory();
using (var dlg = new SaveFileDialog()) using (var dlg = new SaveFileDialog())
{ {
dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx"; dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx";
dlg.FileName = ExcelService.TemplateFileName;
dlg.Title = "导出默认模板"; dlg.Title = "导出默认模板";
dlg.DefaultExt = "xlsx";
dlg.AddExtension = true;
// 关掉系统自带的"是否替换",换成能看清目标文件是什么的确认框(见 ConfirmOverwriteTemplate)
dlg.OverwritePrompt = false;
dlg.InitialDirectory = startDir;
// 关键:FileName 给完整路径。只给文件名时对话框会沿用系统"上次目录",
// 那个目录里往往躺着 TFS导入模板11.xlsx 这类近似名,容易选错/覆盖到已有数据表
dlg.FileName = Path.Combine(startDir, ExcelService.TemplateFileName);
if (dlg.ShowDialog(this) != DialogResult.OK) return; if (dlg.ShowDialog(this) != DialogResult.OK) return;
var path = dlg.FileName;
try try
{ {
ExcelService.CopyTemplate(dlg.FileName); if (!ConfirmOverwriteTemplate(path)) return;
Log("模板已导出: " + dlg.FileName);
_txtExcel.Text = dlg.FileName; bool embeddedOnly;
if (!ConfirmTemplateSource(out embeddedOnly)) return;
var srcDesc = ExcelService.CopyTemplate(path, embeddedOnly);
Log("模板已导出(来源:" + srcDesc + "): " + path);
_txtExcel.Text = path;
SaveUiToConfig(); SaveUiToConfig();
PreviewData(); await PreviewDataAsync();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -287,7 +414,103 @@ namespace TfsExcelImporter
} }
} }
private void PreviewData() /// <summary>
/// 导出对话框起始目录:优先当前 Excel 所在目录,其次桌面。
/// 显式给目录,避免对话框落到"系统记住的上次目录"而出乎意料。
/// </summary>
private string ExportStartDirectory()
{
var last = _txtExcel.Text.Trim();
if (!string.IsNullOrEmpty(last))
{
try
{
var dir = Path.GetDirectoryName(last);
if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) return dir;
}
catch { }
}
try
{
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
if (!string.IsNullOrEmpty(desktop) && Directory.Exists(desktop)) return desktop;
}
catch { }
return AppDomain.CurrentDomain.BaseDirectory;
}
/// <summary>
/// 覆盖确认。系统默认提示只问"是否替换",看不出目标文件其实是用户已有的数据表,
/// 这里把路径、大小、修改时间和已有数据行数都摆出来,避免把导入数据当模板覆盖掉。
/// </summary>
private bool ConfirmOverwriteTemplate(string path)
{
FileInfo fi;
try { fi = new FileInfo(path); }
catch { return true; }
if (!fi.Exists) return true;
// 大文件数行会卡住界面:超过 20MB 就只报大小/时间,不数行
int rows = fi.Length <= 20 * 1024 * 1024 ? ExcelService.CountDataRows(path) : 0;
var sb = new StringBuilder();
sb.AppendLine("目标位置已存在文件,继续将用空白模板覆盖它:");
sb.AppendLine(path);
sb.AppendLine();
sb.AppendLine("大小 " + FormatSize(fi.Length) + " · 修改时间 " + fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm"));
if (rows > 0)
sb.AppendLine("该文件已有 " + rows + " 行数据,覆盖后无法恢复!");
else if (rows < 0)
sb.AppendLine("该文件读不出内容(可能正被 Excel 打开,或不是 Excel 文件)。");
return MessageBox.Show(this, sb.ToString(), "确认覆盖已有文件",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK;
}
private static string FormatSize(long bytes)
{
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return (bytes / 1024.0).ToString("0.#") + " KB";
return (bytes / 1024.0 / 1024.0).ToString("0.#") + " MB";
}
/// <summary>
/// 导出前确认模板来源。exe 同目录的 TFS导入模板.xlsx 一旦被现场替换、或被填过数据,
/// 导出结果就不再是空白模板——用户会看到"导出的模板里带着别的数据"。
/// 这里把选择权交出来:内置空白模板 / 仍用该文件 / 不导出。
/// </summary>
private bool ConfirmTemplateSource(out bool embeddedOnly)
{
embeddedOnly = false;
var local = ExcelService.LocalTemplatePath;
if (!File.Exists(local) || ExcelService.LocalTemplateIsBuiltIn()) return true;
int rows = ExcelService.CountDataRows(local);
var sb = new StringBuilder();
sb.AppendLine("exe 同目录的模板文件与内置模板不一致:");
sb.AppendLine(local);
sb.AppendLine();
if (rows > 0)
sb.AppendLine("它当前有 " + rows + " 行内容,用它导出的模板会带上这些行。");
else if (rows < 0)
sb.AppendLine("它读不出数据(可能正被 Excel 打开,或不是模板文件)。");
else
sb.AppendLine("它已被替换为自定义模板。");
sb.AppendLine();
sb.AppendLine("是(Y):改用内置空白模板");
sb.AppendLine("否(N):仍用这个文件");
sb.AppendLine("取消:不导出");
var r = MessageBox.Show(this, sb.ToString(), "模板来源确认",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
if (r == DialogResult.Cancel) return false;
embeddedOnly = r == DialogResult.Yes;
return true;
}
// ------------------------------------------------------------- 预览
// ClosedXML 全量载入工作簿,大文件在 UI 线程读会冻结界面——放 Task.Run,
// 读期间 SetBusy 防止重复点击;await 后自动回到 UI 线程再更新表格。
private async Task PreviewDataAsync()
{ {
var path = _txtExcel.Text.Trim(); var path = _txtExcel.Text.Trim();
if (string.IsNullOrEmpty(path) || !File.Exists(path)) if (string.IsNullOrEmpty(path) || !File.Exists(path))
@@ -296,9 +519,10 @@ namespace TfsExcelImporter
Append("预览未执行:Excel 文件不存在", LogLevel.Warn); Append("预览未执行:Excel 文件不存在", LogLevel.Warn);
return; return;
} }
SetBusy(true);
try try
{ {
_rows = ExcelService.ReadRows(path); _rows = await Task.Run(() => ExcelService.ReadRows(path));
_grid.DataSource = null; _grid.DataSource = null;
_grid.DataSource = _rows.Select((r, i) => new _grid.DataSource = _rows.Select((r, i) => new
{ {
@@ -306,7 +530,7 @@ namespace TfsExcelImporter
标题 = r.Title, 标题 = r.Title,
状态 = r.State, 状态 = r.State,
指派 = r.AssignedTo, 指派 = r.AssignedTo,
财务项目 = r.FinancialProject, 项目 = r.FinancialProject,
完成量 = r.Completed, 完成量 = r.Completed,
日期 = r.LogDate, 日期 = r.LogDate,
父PBI = r.PbiId, 父PBI = r.PbiId,
@@ -325,9 +549,19 @@ namespace TfsExcelImporter
} }
catch (Exception ex) catch (Exception ex)
{ {
// 读取失败必须清掉上一次的数据,否则表格会继续显示旧文件的行,
// 看起来就像"刚导出的文件里装的是别的文件的数据"
_rows = new List<WorkItemRow>();
_grid.DataSource = null;
_lblStatus.Text = "读取失败";
Log("读取 Excel 失败: " + FirstLine(ex.Message)); Log("读取 Excel 失败: " + FirstLine(ex.Message));
ShowError(_errExcel, _fExcel, _cardData, "读取失败:" + FirstLine(ex.Message)); ShowError(_errExcel, _fExcel, _cardData, "读取失败:" + FirstLine(ex.Message));
UpdateEmptyState(); UpdateEmptyState();
RefreshSummaries();
}
finally
{
SetBusy(false);
} }
} }
@@ -343,9 +577,8 @@ namespace TfsExcelImporter
} }
if (string.IsNullOrWhiteSpace(_cfg.AreaPath)) if (string.IsNullOrWhiteSpace(_cfg.AreaPath))
{ {
ShowError(_errArea, _fArea, _cardAdv, "请填写 Area 路径,例如 Tools_Dev\\DataTechnologies"); ShowError(_errArea, _fArea, _cardData, "请填写 Area 路径,例如 Tools_Dev\\DataTechnologies");
OpenDetail(_cardAdv); _cmbArea.Focus();
_txtAreaPath.Focus();
return; return;
} }
var confirm = MessageBox.Show(this, var confirm = MessageBox.Show(this,
@@ -365,7 +598,7 @@ namespace TfsExcelImporter
: $"Area 修正完成,共 {r.Item1} 条"; : $"Area 修正完成,共 {r.Item1} 条";
_lblStatus.Text = summary; _lblStatus.Text = summary;
Log(summary); Log(summary);
ShowError(_errArea, _fArea, _cardAdv, ""); ShowError(_errArea, _fArea, _cardData, "");
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -392,7 +625,7 @@ namespace TfsExcelImporter
if (!int.TryParse(_cfg.ParentPbiId, out parentId)) if (!int.TryParse(_cfg.ParentPbiId, out parentId))
{ {
ShowError(_errParent, _fParent, _cardData, "父 PBI Id 需为纯数字,例如 219975"); ShowError(_errParent, _fParent, _cardData, "父 PBI Id 需为纯数字,例如 219975");
_txtParentPbi.Focus(); _cmbParent.Focus();
return; return;
} }
var confirm = MessageBox.Show(this, var confirm = MessageBox.Show(this,
@@ -436,6 +669,23 @@ namespace TfsExcelImporter
Append("导入取消:目标迭代未选", LogLevel.Warn); Append("导入取消:目标迭代未选", LogLevel.Warn);
return; return;
} }
// Area 必填:不写 AreaPath 的工作项落在项目根区域,团队视图里看不到(历史坑)
if (string.IsNullOrWhiteSpace(_cfg.AreaPath))
{
ShowError(_errArea, _fArea, _cardData, "请填写 Area 路径,例如 Tools_Dev\\DataTechnologies");
Append("导入取消:Area 路径未填", LogLevel.Warn);
_cmbArea.Focus();
return;
}
// 父 PBI 是可选字段,但一旦填了就必须是纯数字:非数字会在挂接时被静默当成「不挂父项」,
// 导入"成功"却少了层级,比直接报错更难发现。
if (!string.IsNullOrWhiteSpace(_cfg.ParentPbiId) && !int.TryParse(_cfg.ParentPbiId, out _))
{
ShowError(_errParent, _fParent, _cardData, "父 PBI Id 需为纯数字,可点右侧「加载 PBI 列表」选择");
Append("导入取消:父 PBI Id 不是数字", LogLevel.Warn);
_cmbParent.Focus();
return;
}
var path = _txtExcel.Text.Trim(); var path = _txtExcel.Text.Trim();
if (string.IsNullOrEmpty(path) || !File.Exists(path)) if (string.IsNullOrEmpty(path) || !File.Exists(path))
{ {
@@ -445,13 +695,15 @@ namespace TfsExcelImporter
} }
if (_rows.Count == 0) if (_rows.Count == 0)
{ {
try { _rows = ExcelService.ReadRows(path); } SetBusy(true);
try { _rows = await Task.Run(() => ExcelService.ReadRows(path)); }
catch (Exception ex) catch (Exception ex)
{ {
ShowError(_errExcel, _fExcel, _cardData, "读取失败:" + FirstLine(ex.Message)); ShowError(_errExcel, _fExcel, _cardData, "读取失败:" + FirstLine(ex.Message));
Log("读取 Excel 失败: " + FirstLine(ex.Message)); Log("读取 Excel 失败: " + FirstLine(ex.Message));
return; return;
} }
finally { SetBusy(false); }
} }
if (_rows.Count == 0) if (_rows.Count == 0)
{ {
@@ -461,6 +713,7 @@ namespace TfsExcelImporter
} }
ShowError(_errIteration, _fIteration, _cardData, ""); ShowError(_errIteration, _fIteration, _cardData, "");
ShowError(_errArea, _fArea, _cardData, "");
ShowError(_errExcel, _fExcel, _cardData, ""); ShowError(_errExcel, _fExcel, _cardData, "");
SetRunBadge(BadgeKind.Active); SetRunBadge(BadgeKind.Active);
SetBusy(true); SetBusy(true);
@@ -493,6 +746,7 @@ namespace TfsExcelImporter
var logRef = TfsClient.ResolveRef(fieldMap, "LogDate", _cfg.LogDateRef); var logRef = TfsClient.ResolveRef(fieldMap, "LogDate", _cfg.LogDateRef);
var origEstRef = TfsClient.ResolveRef(fieldMap, "Original Estimate", _cfg.OriginalEstimateRef); var origEstRef = TfsClient.ResolveRef(fieldMap, "Original Estimate", _cfg.OriginalEstimateRef);
Log($"字段: FinancialProject->{finRef ?? "(未找到)"} Completed->{compRef ?? "(未找到)"} LogDate->{logRef ?? "(未找到)"} OriginalEstimate->{origEstRef ?? "(未找到)"}"); Log($"字段: FinancialProject->{finRef ?? "(未找到)"} Completed->{compRef ?? "(未找到)"} LogDate->{logRef ?? "(未找到)"} OriginalEstimate->{origEstRef ?? "(未找到)"}");
Log($"目标: 迭代 {_cfg.IterationPath} Area {_cfg.AreaPath}");
Log($"父PBI: '{(string.IsNullOrWhiteSpace(_cfg.ParentPbiId) ? "(未填)" : _cfg.ParentPbiId)}'——Excel 每行可用 PBI Id 列覆盖"); Log($"父PBI: '{(string.IsNullOrWhiteSpace(_cfg.ParentPbiId) ? "(未填)" : _cfg.ParentPbiId)}'——Excel 每行可用 PBI Id 列覆盖");
HashSet<string> existing = null; HashSet<string> existing = null;
@@ -522,12 +776,12 @@ namespace TfsExcelImporter
new KeyValuePair<string, object>(titleRef, row.Title), new KeyValuePair<string, object>(titleRef, row.Title),
new KeyValuePair<string, object>(stateRef, new KeyValuePair<string, object>(stateRef,
string.IsNullOrWhiteSpace(row.State) ? _cfg.DefaultState : row.State.Trim()), string.IsNullOrWhiteSpace(row.State) ? _cfg.DefaultState : row.State.Trim()),
new KeyValuePair<string, object>(iterationRef, _cfg.IterationPath) new KeyValuePair<string, object>(iterationRef, _cfg.IterationPath),
// Area 已在导入前校验为必填:每行都显式写入,不再依赖服务器默认区域
new KeyValuePair<string, object>(areaRef, _cfg.AreaPath.Trim())
}; };
if (!string.IsNullOrWhiteSpace(row.AssignedTo)) if (!string.IsNullOrWhiteSpace(row.AssignedTo))
fields.Add(new KeyValuePair<string, object>(assignedRef, row.AssignedTo.Trim())); fields.Add(new KeyValuePair<string, object>(assignedRef, row.AssignedTo.Trim()));
if (!string.IsNullOrWhiteSpace(_cfg.AreaPath))
fields.Add(new KeyValuePair<string, object>(areaRef, _cfg.AreaPath.Trim()));
if (!string.IsNullOrWhiteSpace(row.FinancialProject) && finRef != null) if (!string.IsNullOrWhiteSpace(row.FinancialProject) && finRef != null)
fields.Add(new KeyValuePair<string, object>(finRef, row.FinancialProject.Trim())); fields.Add(new KeyValuePair<string, object>(finRef, row.FinancialProject.Trim()));
@@ -550,7 +804,7 @@ namespace TfsExcelImporter
var pbiText = !string.IsNullOrWhiteSpace(row.PbiId) ? row.PbiId.Trim() : _cfg.ParentPbiId; var pbiText = !string.IsNullOrWhiteSpace(row.PbiId) ? row.PbiId.Trim() : _cfg.ParentPbiId;
int? parentPbi = int.TryParse(pbiText, out var pbiNum) ? pbiNum : (int?)null; int? parentPbi = int.TryParse(pbiText, out var pbiNum) ? pbiNum : (int?)null;
var id = await client.CreateWorkItemAsync(_cfg.Project, _cfg.WorkItemType, fields, _chkBypass.Checked, parentPbi); var id = await client.CreateWorkItemAsync(_cfg.Project, _cfg.WorkItemType, fields, parentPbi);
ok++; ok++;
report.AppendLine($"{line},\"{row.Title}\",OK,{id},"); report.AppendLine($"{line},\"{row.Title}\",OK,{id},");
Log($"[{i + 1}/{_rows.Count}] OK #{id} {row.Title}"); Log($"[{i + 1}/{_rows.Count}] OK #{id} {row.Title}");
@@ -573,7 +827,7 @@ namespace TfsExcelImporter
SetConnection("连接失败", ChipKind.Danger); SetConnection("连接失败", ChipKind.Danger);
SetRunBadge(BadgeKind.Warn); SetRunBadge(BadgeKind.Warn);
Log("导入中断: " + FirstLine(ex.Message)); Log("导入中断: " + FirstLine(ex.Message));
Log("排查: 内网请确认「使用系统代理」保持关闭;DNS 失败多为 VPN 或未连内网。"); Log("排查: 程序固定直连(不走本机系统代理);DNS 失败多为 VPN 或未连内网。");
} }
finally finally
{ {
@@ -588,10 +842,9 @@ namespace TfsExcelImporter
} }
catch (Exception ex) { Log("写报告失败: " + FirstLine(ex.Message)); } catch (Exception ex) { Log("写报告失败: " + FirstLine(ex.Message)); }
_pbar.Value = _pbar.Maximum; _pbar.Value = _pbar.Maximum;
// 成功/跳过/失败的分布已在右侧三个胶囊里,这里只补胶囊没有的「总数」,明细仍写日志
_lblStatus.Text = $"完成 {ok + skip + fail}/{_rows.Count}"; _lblStatus.Text = $"完成 {ok + skip + fail}/{_rows.Count}";
var summary = $"汇总: 成功 {ok} / 跳过 {skip} / 失败 {fail}"; Log($"汇总: 成功 {ok} / 跳过 {skip} / 失败 {fail}");
_lblStatus.Text = summary;
Log(summary);
SetChips(ok, skip, fail, false); SetChips(ok, skip, fail, false);
RefreshSummaries(); RefreshSummaries();
if (fail == 0 && ok > 0) OpenDetail(_cardLog); if (fail == 0 && ok > 0) OpenDetail(_cardLog);
+312 -97
View File
@@ -17,21 +17,18 @@ namespace TfsExcelImporter
private TextBox _txtUrl = new TextBox(); private TextBox _txtUrl = new TextBox();
private TextBox _txtProject = new TextBox(); private TextBox _txtProject = new TextBox();
private TextBox _txtType = new TextBox(); private TextBox _txtType = new TextBox();
private ComboBox _cmbAuth = new ComboBox();
private TextBox _txtUser = new TextBox(); private TextBox _txtUser = new TextBox();
private TextBox _txtPwd = new TextBox { UseSystemPasswordChar = true }; private TextBox _txtPwd = new TextBox { UseSystemPasswordChar = true };
private TextBox _txtDomain = new TextBox();
private CheckBox _chkProxy = new CheckBox();
private ComboBox _cmbIteration = new ComboBox(); private ComboBox _cmbIteration = new ComboBox();
private ComboBox _cmbArea = new ComboBox();
private TextBox _txtExcel = new TextBox(); private TextBox _txtExcel = new TextBox();
private TextBox _txtParentPbi = new TextBox(); private ComboBox _cmbParent = new ComboBox();
private TextBox _txtAreaPath = new TextBox();
private Button _btnLoadIterations = new Button(); private Button _btnLoadIterations = new Button();
private Button _btnBrowse = new Button(); private Button _btnLoadAreas = new Button();
private Button _btnLoadPbi = new Button();
private Button _btnTemplate = new Button(); private Button _btnTemplate = new Button();
private CheckBox _chkSkip = new CheckBox(); private CheckBox _chkSkip = new CheckBox();
private CheckBox _chkBypass = new CheckBox();
private DataGridView _grid = new DataGridView(); private DataGridView _grid = new DataGridView();
private Button _btnPreview = new Button(); private Button _btnPreview = new Button();
@@ -52,9 +49,12 @@ namespace TfsExcelImporter
private Card _cardConn, _cardData, _cardPreview, _cardLog, _cardAdv; private Card _cardConn, _cardData, _cardPreview, _cardLog, _cardAdv;
private Surface _actionBar; private Surface _actionBar;
private StepBadge _badgeRun; private StepBadge _badgeRun;
private InputField _fUrl, _fProject, _fType, _fAuth, _fUser, _fPwd, _fDomain, private InputField _fUrl, _fProject, _fType, _fUser, _fPwd,
_fIteration, _fExcel, _fParent, _fArea; _fIteration, _fExcel, _fParent, _fArea;
private Label _errIteration, _errExcel, _errParent, _errArea; private Label _errIteration, _errExcel, _errParent, _errArea;
private Label[] _connRowCaptions; // 第 1 步第二行的标签(重排时要跟着一起摆)
private InputField[] _connRowFields; // 同排的四个输入框
private int _connRowY;
private EmptyState _lblEmpty; private EmptyState _lblEmpty;
private StatusChip _chipConn, _chipOk, _chipSkip, _chipFail; private StatusChip _chipConn, _chipOk, _chipSkip, _chipFail;
@@ -68,6 +68,8 @@ namespace TfsExcelImporter
private static int G { get { return Theme.Px(8); } } private static int G { get { return Theme.Px(8); } }
private static int LogBodyH { get { return Theme.Px(150); } } private static int LogBodyH { get { return Theme.Px(150); } }
private string _lastReportPath = ""; private string _lastReportPath = "";
/// <summary>上一次真正执行 Relayout 的客户区尺寸:尺寸没变就不重排(还原/激活时 WM_SIZE 会重发一次)。</summary>
private Size _laidOutSize;
/// <summary>需要在窗口拉宽时跟着变宽的控件。</summary> /// <summary>需要在窗口拉宽时跟着变宽的控件。</summary>
private class Stretch private class Stretch
@@ -115,7 +117,15 @@ namespace TfsExcelImporter
Controls.Add(_cardLog); Controls.Add(_cardLog);
Controls.Add(_cardAdv); Controls.Add(_cardAdv);
Resize += (s, e) => Relayout(); Resize += (s, e) =>
{
// 最小化会收到 WM_SIZE(SIZE_MINIMIZED) 加一个假尺寸(实测 237x39),还原时尺寸又回到原值:
// 这两次重排都白干——最小化那次把 80 多个控件重摆到 237x39 上,还原那次再摆回去,
// 而还原时窗口已经可见,UI 线程却卡在重排里(实测 123ms)不出像素,屏幕上就是一片黑。
if (WindowState == FormWindowState.Minimized) return;
if (ClientSize == _laidOutSize) return;
Relayout();
};
_uiReady = true; _uiReady = true;
Relayout(); Relayout();
@@ -169,17 +179,18 @@ namespace TfsExcelImporter
private void BuildRibbon() private void BuildRibbon()
{ {
// 设计方案:连接信息栏与步骤卡片同一套白卡视觉,「灰标签 + 深值」分组,不再用淡蓝底
_ribbon = new Surface _ribbon = new Surface
{ {
LineColor = Theme.PrimarySoftBorder, LineColor = Theme.Border,
FaceColor = Theme.PrimarySoft, FaceColor = Theme.Card,
Height = Theme.Px(44) Height = Theme.Px(44)
}; };
AddRibbonGroup("服务器", true); AddRibbonGroup("服务器", true);
AddRibbonGroup("项目", true); AddRibbonGroup("项目", true);
AddRibbonGroup("工作项", false); AddRibbonGroup("工作项", false);
_chipConn = new StatusChip { BackColor = Theme.PrimarySoft }; _chipConn = new StatusChip { BackColor = Theme.Card };
_ribbon.Controls.Add(_chipConn); _ribbon.Controls.Add(_chipConn);
} }
@@ -190,9 +201,9 @@ namespace TfsExcelImporter
{ {
Text = caption, Text = caption,
Font = Theme.Caption, Font = Theme.Caption,
ForeColor = Theme.Ink2, ForeColor = Theme.Ink3,
AutoSize = true, AutoSize = true,
BackColor = Theme.PrimarySoft BackColor = Theme.Card
}; };
var val = new Label var val = new Label
{ {
@@ -200,14 +211,14 @@ namespace TfsExcelImporter
Font = Theme.BodyBold, Font = Theme.BodyBold,
ForeColor = Theme.Ink, ForeColor = Theme.Ink,
AutoSize = true, AutoSize = true,
BackColor = Theme.PrimarySoft BackColor = Theme.Card
}; };
_ribbon.Controls.Add(cap); _ribbon.Controls.Add(cap);
_ribbon.Controls.Add(val); _ribbon.Controls.Add(val);
Panel sep = null; Panel sep = null;
if (withSeparator) if (withSeparator)
{ {
sep = new Panel { BackColor = Color.FromArgb(0xC2, 0xD3, 0xEF) }; sep = new Panel { BackColor = Theme.Border };
_ribbon.Controls.Add(sep); _ribbon.Controls.Add(sep);
} }
_ribItems.Add(new RibGroup { Cap = cap, Val = val, Sep = sep }); _ribItems.Add(new RibGroup { Cap = cap, Val = val, Sep = sep });
@@ -221,15 +232,15 @@ namespace TfsExcelImporter
var cap = group.Cap; var cap = group.Cap;
var val = group.Val; var val = group.Val;
var sep = group.Sep; var sep = group.Sep;
cap.SetBounds(x, (_ribbon.Height - cap.PreferredHeight) / 2, cap.PreferredWidth, cap.PreferredHeight); Theme.Place(cap, x, (_ribbon.Height - cap.PreferredHeight) / 2, cap.PreferredWidth, cap.PreferredHeight);
x += cap.Width + Theme.Px(6); x += cap.Width + Theme.Px(6);
val.SetBounds(x, (_ribbon.Height - val.PreferredHeight) / 2, val.PreferredWidth, val.PreferredHeight); Theme.Place(val, x, (_ribbon.Height - val.PreferredHeight) / 2, val.PreferredWidth, val.PreferredHeight);
x += val.Width + Theme.Px(12); x += val.Width + Theme.Px(12);
if (sep == null) continue; if (sep == null) continue;
sep.SetBounds(x - Theme.Px(8), (_ribbon.Height - Theme.Px(16)) / 2, 1, Theme.Px(16)); Theme.Place(sep, x - Theme.Px(8), (_ribbon.Height - Theme.Px(16)) / 2, 1, Theme.Px(16));
x += Theme.Px(5); x += Theme.Px(5);
} }
_chipConn.SetBounds(_ribbon.Width - _chipConn.Width - Theme.Px(12), Theme.Place(_chipConn, _ribbon.Width - _chipConn.Width - Theme.Px(12),
(_ribbon.Height - _chipConn.Height) / 2, _chipConn.Width, _chipConn.Height); (_ribbon.Height - _chipConn.Height) / 2, _chipConn.Width, _chipConn.Height);
} }
@@ -237,65 +248,158 @@ namespace TfsExcelImporter
private void BuildCardConn() private void BuildCardConn()
{ {
_cardConn = MakeCard(1, "连接 TFS 服务器", true, Theme.Px(44)); _cardConn = MakeCard(1, "连接 TFS 服务器", true, Theme.Px(44));
_cmbAuth.DropDownStyle = ComboBoxStyle.DropDownList;
_cmbAuth.Items.AddRange(new object[] { "ntlm", "basic", "default" });
_fUrl = NewField(_txtUrl, 620, true); _fUrl = NewField(_txtUrl, 620, true);
_fProject = NewField(_txtProject, 150, false); _fProject = NewField(_txtProject, 150, false);
_fType = NewField(_txtType, 180, false); _fType = NewField(_txtType, 150, false);
_fAuth = NewField(_cmbAuth, 170, false); _fUser = NewField(_txtUser, 150, false);
_fDomain = NewField(_txtDomain, 150, false); _fPwd = NewField(_txtPwd, 150, true);
_fUser = NewField(_txtUser, 180, false);
_fPwd = NewField(_txtPwd, 200, true); // 空态占位提示(cue banner):只在该输入框没填内容时显示。
// 用户/密码不设提示:这两格只有 150 设计px 宽,长句必被裁断,留空即可用当前 Windows 身份。
_fUrl.SetCue("如 http://server:8080/tfs/DefaultCollection");
_fProject.SetCue("如 Tools_Dev");
_fType.SetCue("如 Task");
_btnTest = NewButton("测试连接", BtnKind.Secondary, IconKind.Bolt, 130); _btnTest = NewButton("测试连接", BtnKind.Secondary, IconKind.Bolt, 130);
_chkProxy = NewCheck("使用系统代理", "内网 TFS 请保持关闭,勾选后常被代理拦成 502");
int y = _cardConn.HeaderH + Theme.S12; int y = _cardConn.HeaderH + Theme.S12;
// 三行表单共用一条字段左缘:标签列宽取各行最大值,同列字段宽度归一 y = Row(_cardConn, y, 42, new Lbl("服务器 URL", MaxLabelWidth("服务器 URL")), _fUrl);
int w1 = MaxLabelWidth("服务器 URL", "团队项目", "域");
int w2 = MaxLabelWidth("工作项类型", "用户");
int w3 = MaxLabelWidth("认证方式", "密码");
y = Row(_cardConn, y, 42, new Lbl("服务器 URL", w1), _fUrl);
Track(_fUrl, _cardConn, M, 0); Track(_fUrl, _cardConn, M, 0);
y = Row(_cardConn, y, 42, new Lbl("团队项目", w1), _fProject,
new Lbl("工作项类型", w2), _fType, new Lbl("认证方式", w3), _fAuth); // 第二行:项目 / 类型 / 用户 / 密码 + 测试连接同排,四个输入框等宽、整行铺满卡片内容区。
y = Row(_cardConn, y, 42, new Lbl("域", w1), _fDomain, // 标签自建并留引用——窗口变宽时要连标签一起重摆,Row() 建完就丢引用做不到。
new Lbl("用户", w2), _fUser, new Lbl("密码", w3), _fPwd, G, _btnTest); _connRowY = y;
y = Row(_cardConn, y, 26, _chkProxy); var captions = new[] { "团队项目", "工作项类型", "用户", "密码" };
_connRowCaptions = new Label[captions.Length];
_connRowFields = new[] { _fProject, _fType, _fUser, _fPwd };
for (int i = 0; i < captions.Length; i++)
{
// 标签宽度由布局按各自文字量给(不死板地共用一条定宽列):四个标签字数不同
// (2~5 字),共用定宽列会让「用户」「密码」和自己的输入框之间空出一大截。
var lbl = new Label
{
Text = captions[i],
Font = Theme.Body,
ForeColor = Theme.Ink2,
AutoSize = false, // 宽度每次重排时按文字量给
TextAlign = ContentAlignment.MiddleRight, // 文字右缘贴住输入框
BackColor = Theme.Card
};
_cardConn.Controls.Add(lbl);
_connRowCaptions[i] = lbl;
_connRowFields[i].AccessibleName = captions[i];
_cardConn.Controls.Add(_connRowFields[i]);
}
_cardConn.Controls.Add(_btnTest);
_layoutExtras.Add(LayoutConnRow);
y = _connRowY + Theme.Px(42);
_cardConn.BodyH = y - _cardConn.HeaderH + Theme.S8; _cardConn.BodyH = y - _cardConn.HeaderH + Theme.S8;
} }
/// <summary>
/// 第 1 步第二行排布:四个输入框同宽,整行(含「测试连接」)刚好铺满卡片内容区。
/// 每个标签只占自己文字的宽度,于是「文字 → 输入框」恒为 6px、「输入框 → 下一个标签」
/// 恒为 S12,四组间距完全一致;省下的宽度全给输入框,输入框因此比按定宽标签列算的更宽。
/// 每次重排按当期卡片宽度重算,缩放/拉伸下都不溢出、不留白。
/// </summary>
private void LayoutConnRow()
{
if (_connRowFields == null || _connRowCaptions == null) return;
int gap = Theme.S12; // 组与组之间
int lblGap = Theme.Px(6); // 标签文字 → 输入框(全行同一个值)
int n = _connRowFields.Length;
int avail = _cardConn.Width - M * 2;
// 每个标签只占自己文字宽度(+2px 防末字被裁),省下的宽度全部喂给输入框,
// 这样「文字→输入框」和「输入框→下一个标签」两处间距在四组上都是同一个值。
var lblW = new int[n];
int textSum = 0;
for (int i = 0; i < n; i++)
{
lblW[i] = Theme.TextWidth(_connRowCaptions[i].Text, Theme.Body) + Theme.Px(2);
textSum += lblW[i];
}
int boxW = (avail - textSum - n * lblGap - (n - 1) * gap - G - _btnTest.Width) / n;
boxW = Math.Max(Theme.Px(96), boxW);
int x = M;
for (int i = 0; i < n; i++)
{
Theme.Place(_connRowCaptions[i], x, _connRowY, lblW[i], Theme.FieldH);
x += lblW[i] + lblGap;
Theme.Place(_connRowFields[i], x, _connRowY, boxW, Theme.FieldH);
x += boxW + gap;
}
Theme.Place(_btnTest, x - gap + G, _connRowY, _btnTest.Width, Theme.BtnH);
}
// --- 步骤 2:迭代与数据源 --- // --- 步骤 2:迭代与数据源 ---
private void BuildCardData() private void BuildCardData()
{ {
_cardData = MakeCard(2, "选择迭代与数据源", true, Theme.Px(44)); _cardData = MakeCard(2, "选择迭代与数据源", true, Theme.Px(44));
_cardData.SummaryDots = true; // 头部摘要按「圆点 + 短语」分段,五项状态一眼可辨
_cmbIteration.DropDownStyle = ComboBoxStyle.DropDown; // 允许手填完整路径 _cmbIteration.DropDownStyle = ComboBoxStyle.DropDown; // 允许手填完整路径
_cmbArea.DropDownStyle = ComboBoxStyle.DropDown; // 同上:列表拿不到时仍能手填
_cmbParent.DropDownStyle = ComboBoxStyle.DropDown; // 可直接输 Id,也可从列表挑
// 不做自定义 DropDownWidth:字段已和迭代同宽,下拉面板跟着控件宽走,
// 形态与「目标迭代」完全一致,也不再有宽度写死后与实际布局对不上的问题。
_fIteration = NewField(_cmbIteration, 500, false); _fIteration = NewField(_cmbIteration, 500, false);
_fArea = NewField(_cmbArea, 500, true);
_fExcel = NewField(_txtExcel, 500, true); _fExcel = NewField(_txtExcel, 500, true);
_fParent = NewField(_txtParentPbi, 150, true); _fParent = NewField(_cmbParent, 500, true);
_fIteration.SetCue("选择或手填完整迭代路径,如 Tools_Dev\\Sprint 1");
// Area 现在是必填:留空会导致团队视图看不到新导入的工作项,所以提示里直接给写法
_fArea.SetCue("选择或手填完整 Area 路径,如 Tools_Dev\\DataTechnologies");
_fExcel.SetCue("选择 .xlsx 文件,或点右侧文件夹图标浏览");
// 行尾不再放说明文字,规则并进 cue:字段宽度与迭代一致后,这里放得下完整提示
_fParent.SetCue("选择或手填父 PBI Id,如 219975;Excel 里加 PBI Id 列可逐行覆盖");
_btnLoadIterations = NewButton("加载迭代列表", BtnKind.Secondary, IconKind.Fetch, 130); _btnLoadIterations = NewButton("加载迭代列表", BtnKind.Secondary, IconKind.Fetch, 130);
_btnBrowse = NewButton("浏览…", BtnKind.Secondary, IconKind.Folder, 92); _btnLoadAreas = NewButton("加载 Area 列表", BtnKind.Secondary, IconKind.Fetch, 130);
_btnLoadPbi = NewButton("加载 PBI 列表", BtnKind.Secondary, IconKind.Fetch, 130);
_btnTemplate = NewButton("导出 Excel 模板", BtnKind.Secondary, IconKind.Doc, 142); _btnTemplate = NewButton("导出 Excel 模板", BtnKind.Secondary, IconKind.Doc, 142);
_chkSkip = NewCheck("跳过已存在标题", ""); // 行尾两个按钮宽度取齐(取两者较宽的一个):右缘本来就都由 AnchorRight 贴在 M 上,
_chkBypass = NewCheck("bypassRules(绕过字段校验规则)", ""); // 宽度一致后左缘也落在同一条竖线上,两个按钮才成为一列;同时两行 Track 给右侧留的
// 宽度变成同一个值,上面两个输入框的右边框才对得齐。
int wBtn = Math.Max(_btnLoadIterations.Width, _btnTemplate.Width);
_btnLoadIterations.Width = wBtn;
_btnLoadAreas.Width = wBtn;
_btnLoadPbi.Width = wBtn;
_btnTemplate.Width = wBtn;
// 三行字段对齐同一条左缘:标签列宽取最大值 // 四行字段对齐同一条左缘:标签列宽取最大值;必填项的红色 * 也留进列宽里,
int wLbl = MaxLabelWidth("目标迭代", "Excel 文件", "父 PBI Id"); // 否则带 * 的行会把输入框往右推,四行左缘就不再是一条竖线。
int wLbl = MaxLabelWidth("目标迭代", "Area 路径", "Excel 文件", "父 PBI Id")
+ Theme.Px(2) + Theme.TextWidth("*", Theme.Body);
int y = _cardData.HeaderH + Theme.S12; int y = _cardData.HeaderH + Theme.S12;
y = Row(_cardData, y, 52, new Lbl("目标迭代", wLbl), _fIteration); y = Row(_cardData, y, 52, new Lbl("目标迭代", wLbl, true), _fIteration);
AnchorRight(_btnLoadIterations, _cardData, M, _fIteration.Top); AnchorRight(_btnLoadIterations, _cardData, M, _fIteration.Top);
Track(_fIteration, _cardData, _btnLoadIterations.Width + G + M, 0); Track(_fIteration, _cardData, wBtn + G + M, 0);
y = Row(_cardData, y, 52, new Lbl("Excel 文件", wLbl), _fExcel); // Area 与迭代同属「写到哪儿」:紧贴迭代下方,值直接落进 System.AreaPath。
// 行尾同样挂一个列表按钮:Area 树往往比迭代树深得多,手打路径最容易写错。
y = Row(_cardData, y, 52, new Lbl("Area 路径", wLbl, true), _fArea);
AnchorRight(_btnLoadAreas, _cardData, M, _fArea.Top);
Track(_fArea, _cardData, wBtn + G + M, 0);
y = Row(_cardData, y, 52, new Lbl("Excel 文件", wLbl, true), _fExcel);
// 设计方案:行内操作(浏览)并入输入框尾部图标,行尾只留右对齐成一列的操作按钮
_fExcel.AddSuffix(IconKind.Folder, BrowseExcel);
AnchorRight(_btnTemplate, _cardData, M, _fExcel.Top); AnchorRight(_btnTemplate, _cardData, M, _fExcel.Top);
AnchorRight(_btnBrowse, _cardData, _btnTemplate.Width + G + M, _fExcel.Top); Track(_fExcel, _cardData, wBtn + G + M, 0);
Track(_fExcel, _cardData, _btnTemplate.Width + _btnBrowse.Width + G * 2 + M, 0); // 父项行结构与上面三行完全一致:字段吃满宽度 + 行尾按钮右对齐。
y = Row(_cardData, y, 42, new Lbl("父 PBI Id", wLbl), _fParent, "Task 默认挂到该 backlog item;Excel 里加 PBI Id 列可逐行覆盖"); // Id 本身不可读,列出来才敢确认挂的是哪条。
y = Row(_cardData, y, 24, _chkSkip, 2 * G, _chkBypass); y = Row(_cardData, y, 52, new Lbl("父 PBI Id", wLbl), _fParent);
AnchorRight(_btnLoadPbi, _cardData, M, _fParent.Top);
Track(_fParent, _cardData, wBtn + G + M, 0);
// 「跳过已存在标题」不在这张卡片里:它是「开始导入」这个动作的开关,已挪到步骤 4 操作条
// 紧贴主按钮(卡片收起后只看得到一行摘要,勾没勾都看不见,容易被当成「没勾」)。
// 字段校验不可绕过(OM 14.x 无 BypassRules),失败时由 TfsClient 输出可操作的修复提示。
_errIteration = AddErrorUnder(_cardData, _fIteration); _errIteration = AddErrorUnder(_cardData, _fIteration);
_errArea = AddErrorUnder(_cardData, _fArea);
_errExcel = AddErrorUnder(_cardData, _fExcel); _errExcel = AddErrorUnder(_cardData, _fExcel);
_errParent = AddErrorUnder(_cardData, _fParent); _errParent = AddErrorUnder(_cardData, _fParent);
_cardData.BodyH = y - _cardData.HeaderH + Theme.S8; _cardData.BodyH = y - _cardData.HeaderH + Theme.S8;
@@ -341,8 +445,13 @@ namespace TfsExcelImporter
// 透明背景会让父容器改画自己的 BackColor(灰),这里直接给成操作条的白 // 透明背景会让父容器改画自己的 BackColor(灰),这里直接给成操作条的白
_badgeRun = new StepBadge { BackColor = Theme.Card }; _badgeRun = new StepBadge { BackColor = Theme.Card };
_btnPreview = NewButton("预览数据", BtnKind.Secondary, IconKind.Table, 120); _btnPreview = NewButton("预览数据", BtnKind.Secondary, IconKind.Table, 120);
_btnImport = NewButton("开始导入 TFS", BtnKind.Primary, IconKind.ArrowUp, 176); // 148 已够图标+文字(实际量出约 130),省下的宽度留给右侧状态文字与进度条
_btnImport = NewButton("开始导入 TFS", BtnKind.Primary, IconKind.ArrowUp, 148);
// 主/次按钮同高(层级靠主色表达,不再用 38px 拔高),避免操作条里两个按钮大小不齐 // 主/次按钮同高(层级靠主色表达,不再用 38px 拔高),避免操作条里两个按钮大小不齐
// 去重开关紧贴主按钮右侧:它是「开始导入」这一个动作的开关(一次导入只在开始时读一次),
// 挂在按钮旁边才不会被误读成某个字段的属性。
_chkSkip = NewCheck("跳过已存在标题", "");
_pbar = new ProgressTrack _pbar = new ProgressTrack
{ {
Minimum = 0, Minimum = 0,
@@ -366,6 +475,7 @@ namespace TfsExcelImporter
_actionBar.Controls.Add(_badgeRun); _actionBar.Controls.Add(_badgeRun);
_actionBar.Controls.Add(_btnPreview); _actionBar.Controls.Add(_btnPreview);
_actionBar.Controls.Add(_btnImport); _actionBar.Controls.Add(_btnImport);
_actionBar.Controls.Add(_chkSkip);
_actionBar.Controls.Add(_pbar); _actionBar.Controls.Add(_pbar);
_actionBar.Controls.Add(_chipOk); _actionBar.Controls.Add(_chipOk);
_actionBar.Controls.Add(_chipSkip); _actionBar.Controls.Add(_chipSkip);
@@ -380,21 +490,58 @@ namespace TfsExcelImporter
{ {
int badge = Theme.Px(22); int badge = Theme.Px(22);
int cy = (_actionBar.Height - badge) / 2; int cy = (_actionBar.Height - badge) / 2;
_badgeRun.SetBounds(M + Theme.Px(2), cy, badge, badge); Theme.Place(_badgeRun, M + Theme.Px(2), cy, badge, badge);
_badgeRun.Set(4, _runBadge); _badgeRun.Set(4, _runBadge);
_btnPreview.SetBounds(M + Theme.Px(42), (_actionBar.Height - _btnPreview.Height) / 2, Theme.Place(_btnPreview, M + Theme.Px(42), (_actionBar.Height - _btnPreview.Height) / 2,
_btnPreview.Width, _btnPreview.Height); _btnPreview.Width, _btnPreview.Height);
_btnImport.SetBounds(_btnPreview.Right + G, (_actionBar.Height - _btnImport.Height) / 2, Theme.Place(_btnImport, _btnPreview.Right + G, (_actionBar.Height - _btnImport.Height) / 2,
_btnImport.Width, _btnImport.Height); _btnImport.Width, _btnImport.Height);
_chipFail.SetBounds(_actionBar.Width - _chipFail.Width - M - Theme.Px(2), cy, _chipFail.Width, _chipFail.Height); // 去重开关:与两个按钮同一条中线,纵向按勾选框自身高度居中
_chipSkip.SetBounds(_chipFail.Left - G - _chipSkip.Width, cy, _chipSkip.Width, _chipSkip.Height); int chkW, chkH;
_chipOk.SetBounds(_chipSkip.Left - G - _chipOk.Width, cy, _chipOk.Width, _chipOk.Height); CheckBoxSize(_chkSkip, Theme.Body, out chkW, out chkH);
int statW = Theme.Px(160); Theme.Place(_chkSkip, _btnImport.Right + Theme.S16, (_actionBar.Height - chkH) / 2, chkW, chkH);
_lblStatus.SetBounds(_chipOk.Left - statW - G, 0, statW, _actionBar.Height);
int left = _btnImport.Right + Theme.S16; Theme.Place(_chipFail, _actionBar.Width - _chipFail.Width - M - Theme.Px(2), cy, _chipFail.Width, _chipFail.Height);
Theme.Place(_chipSkip, _chipFail.Left - G - _chipSkip.Width, cy, _chipSkip.Width, _chipSkip.Height);
Theme.Place(_chipOk, _chipSkip.Left - G - _chipOk.Width, cy, _chipOk.Width, _chipOk.Height);
// 进度条至少要 120px 才像一条进度条(再窄就只是一段杂线):先按最长常规文案给状态文字留宽,
// 宽度不够时再收窄状态文字(下限 120)——长文案本来就靠省略尾巴兜底,关键是别把进度条挤没。
int left = _chkSkip.Right + Theme.S16;
int statRoom = _chipOk.Left - G - left - Theme.Px(120) - G;
int statW = Math.Min(StatusLabelWidth(), Math.Max(Theme.Px(120), statRoom));
int statH = Theme.Caption.Height + Theme.Px(4);
Theme.Place(_lblStatus, _chipOk.Left - G - statW, (_actionBar.Height - statH) / 2, statW, statH);
int barW = Math.Max(Theme.Px(40), _lblStatus.Left - G - left); int barW = Math.Max(Theme.Px(40), _lblStatus.Left - G - left);
_pbar.SetBounds(left, (_actionBar.Height - _pbar.Height) / 2, barW, _pbar.Height); Theme.Place(_pbar, left, (_actionBar.Height - _pbar.Height) / 2, barW, _pbar.Height);
}
/// <summary>
/// net48 的 CheckBox 没有 PreferredWidth/Height 的稳定值:宽度自己量(文字 + 勾选框),
/// 高度取原生 PreferredHeight 并留 18px 下限,调用方据此按中线精确居中。
/// </summary>
private static void CheckBoxSize(CheckBox chk, Font font, out int width, out int height)
{
var pref = chk.GetPreferredSize(Size.Empty);
height = Math.Max(Theme.Px(18), pref.Height);
width = Math.Max(Theme.TextWidth(chk.Text, font) + Theme.Px(22), pref.Width);
}
/// <summary>
/// 操作条右侧状态文字的最大显示宽度:取各操作最长文案的实测宽度(160~280 之间夹取),
/// 保证常规状态既不折行、也不省略尾部计数。更长的文案(如「Area 修正完成…(详见日志)」)
/// 只省略尾巴——它们的数字在开头,不受影响。
/// </summary>
private static int StatusLabelWidth()
{
string[] samples =
{
"完成 999/999", // 导入结束:只报总数,分布交给右侧胶囊
"补挂完成: 挂接 99 / 已有父跳过 99 / 失败 0" // 补挂父项:最长的一条常规状态
};
int w = 0;
foreach (var s in samples) w = Math.Max(w, Theme.TextWidth(s, Theme.Caption));
return Math.Min(Theme.Px(280), Math.Max(Theme.Px(160), w + Theme.Px(8)));
} }
// --- 日志抽屉 --- // --- 日志抽屉 ---
@@ -434,16 +581,14 @@ namespace TfsExcelImporter
int x = _cardLog.Width - Theme.Px(12) - Theme.Px(30); // 让开折叠箭头 int x = _cardLog.Width - Theme.Px(12) - Theme.Px(30); // 让开折叠箭头
// 头部所有元素共用一条中线:按钮和勾选框都按 cy - 高度/2 摆,文字才齐平 // 头部所有元素共用一条中线:按钮和勾选框都按 cy - 高度/2 摆,文字才齐平
int cy = _cardLog.HeaderH / 2; int cy = _cardLog.HeaderH / 2;
_btnOpenReport.SetBounds(x - _btnOpenReport.Width, cy - _btnOpenReport.Height / 2, Theme.Place(_btnOpenReport, x - _btnOpenReport.Width, cy - _btnOpenReport.Height / 2,
_btnOpenReport.Width, _btnOpenReport.Height); _btnOpenReport.Width, _btnOpenReport.Height);
_btnClearLog.SetBounds(_btnOpenReport.Left - G - _btnClearLog.Width, cy - _btnClearLog.Height / 2, Theme.Place(_btnClearLog, _btnOpenReport.Left - G - _btnClearLog.Width, cy - _btnClearLog.Height / 2,
_btnClearLog.Width, _btnClearLog.Height); _btnClearLog.Width, _btnClearLog.Height);
// net48 的 CheckBox 没有 PreferredWidth,只能自己量文字宽度(外加勾选框); // net48 的 CheckBox 没有 PreferredWidth:宽高都由 CheckBoxSize 量出来,整体压在中线上
// 高度取原生 PreferredHeight,整体压在中线上 int chkW, chkH;
var pref = _chkAutoScroll.GetPreferredSize(Size.Empty); CheckBoxSize(_chkAutoScroll, Theme.Caption, out chkW, out chkH);
int chkH = Math.Max(Theme.Px(18), pref.Height); Theme.Place(_chkAutoScroll, _btnClearLog.Left - chkW - G, cy - chkH / 2, chkW, chkH);
int chkW = Math.Max(Theme.TextWidth(_chkAutoScroll.Text, Theme.Caption) + Theme.Px(22), pref.Width);
_chkAutoScroll.SetBounds(_btnClearLog.Left - chkW - G, cy - chkH / 2, chkW, chkH);
}); });
} }
@@ -452,15 +597,16 @@ namespace TfsExcelImporter
{ {
_cardAdv = MakeCard(0, "高级工具", true, Theme.Px(36)); _cardAdv = MakeCard(0, "高级工具", true, Theme.Px(36));
_cardAdv.ShowBadge = false; _cardAdv.ShowBadge = false;
_fArea = NewField(_txtAreaPath, 420, true); // Area 输入框已上移到第 2 步(必填),这里只剩两个批量修正动作,
// 两者都按第 2 步填的「目标迭代 / Area 路径」筛选已有工作项。
_btnFixArea = NewButton("按迭代修 Area", BtnKind.Secondary, IconKind.Wrench, 158); _btnFixArea = NewButton("按迭代修 Area", BtnKind.Secondary, IconKind.Wrench, 158);
_btnLinkParent = NewButton("补挂父项", BtnKind.Secondary, IconKind.Tree, 120); _btnLinkParent = NewButton("补挂父项", BtnKind.Secondary, IconKind.Tree, 120);
int y = _cardAdv.HeaderH + Theme.S12; int y = _cardAdv.HeaderH + Theme.S12;
y = Row(_cardAdv, y, 52, "Area 路径", _fArea, "改 Area 与补挂父项都按上面的「目标迭代」筛选已有工作项"); y = Row(_cardAdv, y, 34, _btnFixArea, G, _btnLinkParent, G,
y = Row(_cardAdv, y, 34, _btnFixArea, G, _btnLinkParent, G, "已关闭的工作项会被临时重新打开,完成后自动还原状态"); new Hint("Area 取第 2 步的「Area 路径」,按「目标迭代」筛选;已关闭的工作项会临时重新打开,完成后自动还原状态"));
_errArea = AddErrorUnder(_cardAdv, _fArea);
_cardAdv.BodyH = y - _cardAdv.HeaderH + Theme.S8; _cardAdv.BodyH = y - _cardAdv.HeaderH + Theme.S8;
_cardAdv.SetSummary("按迭代批量修 Area / 补挂父项");
} }
// ------------------------------------------------------------- 摆放助手 // ------------------------------------------------------------- 摆放助手
@@ -469,8 +615,23 @@ namespace TfsExcelImporter
{ {
public readonly string Text; public readonly string Text;
public readonly int MinWidth; // 运行时像素(构建时已含缩放) public readonly int MinWidth; // 运行时像素(构建时已含缩放)
/// <summary>必填项:标签后补一个红色 *,且列宽里预留它的位置。</summary>
public readonly bool Required;
public Lbl(string text, int minWidth) { Text = text; MinWidth = minWidth; } public Lbl(string text, int minWidth, bool required = false)
{
Text = text;
MinWidth = minWidth;
Required = required;
}
}
/// <summary>紧跟在字段后面的灰色说明(Caption 字号 + Ink3):非标签、不参与标签列宽计算。</summary>
private class Hint
{
public readonly string Text;
public Hint(string text) { Text = text; }
} }
/// <summary>一组标签文字的最大实测宽度,用作对齐列宽。</summary> /// <summary>一组标签文字的最大实测宽度,用作对齐列宽。</summary>
@@ -504,6 +665,21 @@ namespace TfsExcelImporter
}; };
lbl.SetBounds(x, y + (Theme.FieldH - lbl.PreferredHeight) / 2, lbl.PreferredWidth, lbl.PreferredHeight); lbl.SetBounds(x, y + (Theme.FieldH - lbl.PreferredHeight) / 2, lbl.PreferredWidth, lbl.PreferredHeight);
card.Controls.Add(lbl); card.Controls.Add(lbl);
if (spec != null && spec.Required)
{
// 红色 * 紧跟标签右缘:颜色是这套界面里唯一的「必填」色板(与错误提示同色)
var star = new Label
{
Text = "*",
Font = Theme.Body,
ForeColor = Theme.Danger,
AutoSize = true,
BackColor = Theme.Card
};
star.SetBounds(x + lbl.PreferredWidth + Theme.Px(1),
y + (Theme.FieldH - star.PreferredHeight) / 2, star.PreferredWidth, star.PreferredHeight);
card.Controls.Add(star);
}
x += Math.Max(lbl.PreferredWidth, spec != null ? spec.MinWidth : 0) + Theme.Px(6); x += Math.Max(lbl.PreferredWidth, spec != null ? spec.MinWidth : 0) + Theme.Px(6);
lastLabel = label; lastLabel = label;
continue; continue;
@@ -511,6 +687,23 @@ namespace TfsExcelImporter
if (item is int) { x += (int)item; continue; } if (item is int) { x += (int)item; continue; }
var hint = item as Hint;
if (hint != null)
{
var hl = new Label
{
Text = hint.Text,
Font = Theme.Caption,
ForeColor = Theme.Ink3,
AutoSize = true,
BackColor = Theme.Card
};
hl.SetBounds(x, y + (Theme.FieldH - hl.PreferredHeight) / 2, hl.PreferredWidth, hl.PreferredHeight);
card.Controls.Add(hl);
x += hl.Width + Theme.S12;
continue;
}
var c = item as Control; var c = item as Control;
if (c == null) continue; if (c == null) continue;
int top = y + Math.Max(0, (Theme.FieldH - c.Height) / 2); int top = y + Math.Max(0, (Theme.FieldH - c.Height) / 2);
@@ -640,22 +833,22 @@ namespace TfsExcelImporter
{ {
int cw = Math.Max(Theme.Px(320), ClientSize.Width - M * 2); int cw = Math.Max(Theme.Px(320), ClientSize.Width - M * 2);
_ribbon.SetBounds(M, M, cw, _ribbon.Height); Theme.Place(_ribbon, M, M, cw, _ribbon.Height);
int y = _ribbon.Bottom + G; int y = _ribbon.Bottom + G;
foreach (var card in new[] { _cardConn, _cardData }) foreach (var card in new[] { _cardConn, _cardData })
{ {
card.SetBounds(M, y, cw, card.Height); Theme.Place(card, M, y, cw, card.Height);
y = card.Bottom + G; y = card.Bottom + G;
} }
// 从底部往上排 // 从底部往上排
int by = ClientSize.Height - M; int by = ClientSize.Height - M;
_cardAdv.SetBounds(M, by - _cardAdv.Height, cw, _cardAdv.Height); Theme.Place(_cardAdv, M, by - _cardAdv.Height, cw, _cardAdv.Height);
by = _cardAdv.Top - G; by = _cardAdv.Top - G;
_cardLog.SetBounds(M, by - _cardLog.Height, cw, _cardLog.Height); Theme.Place(_cardLog, M, by - _cardLog.Height, cw, _cardLog.Height);
by = _cardLog.Top - G; by = _cardLog.Top - G;
_actionBar.SetBounds(M, by - _actionBar.Height, cw, _actionBar.Height); Theme.Place(_actionBar, M, by - _actionBar.Height, cw, _actionBar.Height);
by = _actionBar.Top - G; by = _actionBar.Top - G;
// 预览卡吃剩余高度;空间不足时先让日志收成一行 // 预览卡吃剩余高度;空间不足时先让日志收成一行
@@ -664,14 +857,14 @@ namespace TfsExcelImporter
_cardLog.Expanded = false; _cardLog.Expanded = false;
_cardLog.ApplyHeight(); _cardLog.ApplyHeight();
by = ClientSize.Height - M; by = ClientSize.Height - M;
_cardAdv.SetBounds(M, by - _cardAdv.Height, cw, _cardAdv.Height); Theme.Place(_cardAdv, M, by - _cardAdv.Height, cw, _cardAdv.Height);
by = _cardAdv.Top - G; by = _cardAdv.Top - G;
_cardLog.SetBounds(M, by - _cardLog.Height, cw, _cardLog.Height); Theme.Place(_cardLog, M, by - _cardLog.Height, cw, _cardLog.Height);
by = _cardLog.Top - G; by = _cardLog.Top - G;
_actionBar.SetBounds(M, by - _actionBar.Height, cw, _actionBar.Height); Theme.Place(_actionBar, M, by - _actionBar.Height, cw, _actionBar.Height);
by = _actionBar.Top - G; by = _actionBar.Top - G;
} }
_cardPreview.SetBounds(M, y, cw, Math.Max(Theme.Px(120), by - G - y)); Theme.Place(_cardPreview, M, y, cw, Math.Max(Theme.Px(120), by - G - y));
_cardPreview.BodyH = _cardPreview.Height - _cardPreview.HeaderH; _cardPreview.BodyH = _cardPreview.Height - _cardPreview.HeaderH;
foreach (var st in _stretches) foreach (var st in _stretches)
@@ -679,18 +872,34 @@ namespace TfsExcelImporter
if (st.C == null || st.Owner == null) continue; if (st.C == null || st.Owner == null) continue;
int w = Math.Max(Theme.Px(60), st.Owner.Width - st.X - st.Right); int w = Math.Max(Theme.Px(60), st.Owner.Width - st.X - st.Right);
int h = st.FillHeight ? Math.Max(Theme.Px(20), st.Owner.Height - st.Y - st.Bottom) : st.C.Height; int h = st.FillHeight ? Math.Max(Theme.Px(20), st.Owner.Height - st.Y - st.Bottom) : st.C.Height;
st.C.SetBounds(st.X, st.Y, w, h); Theme.Place(st.C, st.X, st.Y, w, h);
} }
foreach (var ra in _rightAnchors) foreach (var ra in _rightAnchors)
{ {
if (ra.C == null || ra.Owner == null) continue; if (ra.C == null || ra.Owner == null) continue;
ra.C.SetBounds(ra.Owner.Width - ra.FromRight - ra.C.Width, ra.Y, ra.C.Width, ra.C.Height); Theme.Place(ra.C, ra.Owner.Width - ra.FromRight - ra.C.Width, ra.Y, ra.C.Width, ra.C.Height);
} }
LayoutRibbon(); LayoutRibbon();
foreach (var act in _layoutExtras) act(); foreach (var act in _layoutExtras) act();
_cardConn.Invalidate(); _cardConn.Invalidate();
_cardData.Invalidate(); _cardData.Invalidate();
_laidOutSize = ClientSize;
}
/// <summary>
/// 自绘界面平时不擦背景(AllPaintingInWmPaint + 双缓冲),窗口被重新暴露时那块像素是系统给的黑色。
/// 还原/切前台时完整首帧要一百多毫秒,这段时间就是用户看到的「黑屏一闪」;
/// 这里在 WM_ERASEBKGND 上用 GDI 直接把客户区铺成面色,黑底一秒都不露,完整首帧随后补上细节。
/// </summary>
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0014 && Theme.FastErase(m.HWnd, m.WParam, BackColor))
{
m.Result = (IntPtr)1;
return;
}
base.WndProc(ref m);
} }
// ------------------------------------------------------------- 状态呈现 // ------------------------------------------------------------- 状态呈现
@@ -772,22 +981,19 @@ namespace TfsExcelImporter
{ {
ShortHost(_txtUrl.Text.Trim()), ShortHost(_txtUrl.Text.Trim()),
_txtProject.Text.Trim(), _txtProject.Text.Trim(),
_txtType.Text.Trim(), _txtType.Text.Trim()
_cmbAuth.SelectedItem != null ? _cmbAuth.SelectedItem.ToString() : "ntlm"
})); }));
_cardData.SetSummary(string.Join(" · ", new[] _cardData.SetSummary(string.Join(" · ", new[]
{ {
string.IsNullOrEmpty(iter) ? "迭代未选" : iter, string.IsNullOrEmpty(iter) ? "迭代未选" : iter,
string.IsNullOrWhiteSpace(_cmbArea.Text) ? "Area 未填" : "Area " + _cmbArea.Text.Trim(),
string.IsNullOrEmpty(fileName) ? "未选 Excel" : fileName, string.IsNullOrEmpty(fileName) ? "未选 Excel" : fileName,
_rows.Count > 0 ? _rows.Count + " 行" : "未预览", _rows.Count > 0 ? _rows.Count + " 行" : "未预览",
string.IsNullOrWhiteSpace(_txtParentPbi.Text) ? "父 PBI 未填" : "父 PBI #" + _txtParentPbi.Text.Trim() string.IsNullOrWhiteSpace(_cmbParent.Text) ? "父 PBI 未填" : "父 PBI #" + _cmbParent.Text.Trim()
})); }));
_cardPreview.SetSummary(_rows.Count > 0 _cardPreview.SetSummary(_rows.Count > 0
? "共 " + _rows.Count + " 行,可直接开始导入" ? "共 " + _rows.Count + " 行,可直接开始导入"
: "选择 Excel 后在这里核对将要写入的内容"); : "选择 Excel 后在这里核对将要写入的内容");
_cardAdv.SetSummary(string.IsNullOrWhiteSpace(_txtAreaPath.Text)
? "Area 未设置"
: "Area " + _txtAreaPath.Text.Trim());
} }
/// <summary>第 4 步徽标:待办 / 进行中 / 完成 / 有失败。</summary> /// <summary>第 4 步徽标:待办 / 进行中 / 完成 / 有失败。</summary>
@@ -848,9 +1054,13 @@ namespace TfsExcelImporter
_btnPreview.Enabled = !busy; _btnPreview.Enabled = !busy;
_btnTest.Enabled = !busy; _btnTest.Enabled = !busy;
_btnLoadIterations.Enabled = !busy; _btnLoadIterations.Enabled = !busy;
_btnLoadAreas.Enabled = !busy;
_btnLoadPbi.Enabled = !busy;
_btnFixArea.Enabled = !busy; _btnFixArea.Enabled = !busy;
_btnLinkParent.Enabled = !busy; _btnLinkParent.Enabled = !busy;
_btnBrowse.Enabled = !busy; // 去重开关在导入开始时只读一次:跑起来再改会误导(看着改了,本轮其实不生效),直接置灰
_chkSkip.Enabled = !busy;
_fExcel.SetSuffixEnabled(!busy); // 「浏览」已并入输入框尾部,随忙等一起禁用
_btnTemplate.Enabled = !busy; _btnTemplate.Enabled = !busy;
} }
} }
@@ -869,16 +1079,21 @@ namespace TfsExcelImporter
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
var g = e.Graphics; var g = e.Graphics;
int icon = Theme.Px(40); int well = Theme.Px(48); // 圆形浅灰图标底:裸图标太轻,兜一层「底座」才有空状态的分量
int icon = Theme.Px(22);
int textH = Theme.Px(18); int textH = Theme.Px(18);
int blockH = icon + Theme.Px(10) + textH; int blockH = well + Theme.Px(12) + textH;
int top = Math.Max(Theme.Px(4), (Height - blockH) / 2); int top = Math.Max(Theme.Px(4), (Height - blockH) / 2);
int wellX = (Width - well) / 2;
var old = g.SmoothingMode; var old = g.SmoothingMode;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Icons.Draw(g, IconKind.Table, new Rectangle((Width - icon) / 2, top, icon, icon), Theme.Ink3); using (var b = new SolidBrush(Theme.Disabled))
g.FillEllipse(b, wellX, top, well, well);
Icons.Draw(g, IconKind.Table,
new Rectangle(wellX + (well - icon) / 2, top + (well - icon) / 2, icon, icon), Theme.Ink3);
g.SmoothingMode = old; g.SmoothingMode = old;
TextRenderer.DrawText(g, Text, Theme.Body, TextRenderer.DrawText(g, Text, Theme.Body,
new Rectangle(Theme.Px(16), top + icon + Theme.Px(10), Width - Theme.Px(32), textH), new Rectangle(Theme.Px(16), top + well + Theme.Px(12), Width - Theme.Px(32), textH),
Theme.Ink3, Theme.Ink3,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis); | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
+83
View File
@@ -0,0 +1,83 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace TfsExcelImporter
{
/// <summary>
/// TFS Client OM 除托管程序集外还依赖两个纯 win32 DLL
/// (Microsoft.WITDataStore32/64.dll)。托管程序集由 Costura 内嵌并从内存加载,
/// native DLL 只能落盘后 LoadLibrary,所以单文件分发时:
/// 启动阶段把内嵌的 native DLL 释放到 %TEMP%\TfsExcelImporter\native\{内容hash},
/// 再 LoadLibrary 预加载 —— 之后 TFS 内部的 DllImport 会直接命中已加载模块。
/// 目录名带 DLL 内容 hash,升级后不会残留旧版本。
/// exe 同目录存在同名 DLL(开发机 bin 目录、绿色解压版)时不做任何处理。
/// </summary>
internal static class NativeLibraryLoader
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LoadLibraryW")]
private static extern IntPtr LoadLibrary(string path);
public static void EnsureLoaded()
{
var fileName = Environment.Is64BitProcess
? "Microsoft.WITDataStore64.dll"
: "Microsoft.WITDataStore32.dll";
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName)))
return;
try
{
var asm = typeof(NativeLibraryLoader).Assembly;
var resourceName = "native." + fileName;
using (var stream = asm.GetManifestResourceStream(resourceName))
{
if (stream == null)
{
Debug.WriteLine("未找到内嵌 native 资源: " + resourceName);
return;
}
byte[] bytes;
using (var buffer = new MemoryStream())
{
stream.CopyTo(buffer);
bytes = buffer.ToArray();
}
var target = Path.Combine(NativeDir(bytes), fileName);
Directory.CreateDirectory(Path.GetDirectoryName(target));
if (!File.Exists(target))
{
try { File.WriteAllBytes(target, bytes); }
catch (IOException)
{
// 同 hash 目录已被另一实例写住,内容等价,直接用
if (!File.Exists(target)) throw;
}
}
if (LoadLibrary(target) == IntPtr.Zero)
Debug.WriteLine("LoadLibrary 失败(" + Marshal.GetLastWin32Error() + "): " + target);
}
}
catch (Exception ex)
{
// 释放失败不阻断启动:TFS 连接时会自行报 DllNotFound,提示仍是可读的
Debug.WriteLine("释放 native DLL 失败: " + ex.Message);
}
}
private static string NativeDir(byte[] bytes)
{
byte[] hash;
using (var sha = SHA256.Create())
hash = sha.ComputeHash(bytes);
var stamp = BitConverter.ToString(hash, 0, 4).Replace("-", "");
return Path.Combine(Path.GetTempPath(), "TfsExcelImporter", "native", stamp);
}
}
}
+3
View File
@@ -8,6 +8,9 @@ namespace TfsExcelImporter
[STAThread] [STAThread]
private static void Main() private static void Main()
{ {
// 单文件分发时 native DLL 从内嵌资源释放并预加载(TFS Client OM 需要)
NativeLibraryLoader.EnsureLoaded();
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm()); Application.Run(new MainForm());
+205 -40
View File
@@ -23,31 +23,18 @@ namespace TfsExcelImporter
public TfsClient(AppConfig cfg) public TfsClient(AppConfig cfg)
{ {
ICredentials cred; // 认证固定 NTLM:用户名可写 user(用当前登录域),也可写 DOMAIN\user 显式指定域。
var mode = (cfg.AuthMode ?? "ntlm").ToLowerInvariant(); var user = (cfg.Username ?? "").Trim();
if (mode == "default") var pwd = cfg.Password ?? "";
{ var sep = user.IndexOf('\\');
cred = CredentialCache.DefaultCredentials; ICredentials cred = sep > 0
} ? new NetworkCredential(user.Substring(sep + 1), pwd, user.Substring(0, sep))
else : new NetworkCredential(user, pwd);
{
var user = string.IsNullOrEmpty(cfg.Domain) ? cfg.Username : cfg.Domain + "\\" + cfg.Username;
cred = new NetworkCredential(user, cfg.Password ?? "");
}
_tpc = new TfsTeamProjectCollection(new Uri(cfg.TfsUrl), cred); _tpc = new TfsTeamProjectCollection(new Uri(cfg.TfsUrl), cred);
// TFS OM 内部用 HttpWebRequest 传输,默认跟随 IE 系统代理——实测代理会拦内网 TFS 返回 502。 // TFS OM 内部用 HttpWebRequest 传输,默认跟随 IE 系统代理——实测代理会拦内网 TFS 返回 502。
// 默认直连;勾选"使用系统代理"时保留系统代理并带 Windows 凭据过代理认证。 // 因此固定直连:把 DefaultWebProxy 置空,不读取本机系统代理设置。
if (!cfg.UseSystemProxy) WebRequest.DefaultWebProxy = new WebProxy();
{
WebRequest.DefaultWebProxy = new WebProxy(); // 空 WebProxy = 不走代理,直连
}
else
{
var p = WebRequest.DefaultWebProxy ?? new WebProxy();
p.Credentials = CredentialCache.DefaultCredentials;
WebRequest.DefaultWebProxy = p;
}
} }
/// <summary>WorkItemStore 惰性初始化(首次调用会下载字段/类型元数据,耗时数秒属正常)。</summary> /// <summary>WorkItemStore 惰性初始化(首次调用会下载字段/类型元数据,耗时数秒属正常)。</summary>
@@ -101,10 +88,30 @@ namespace TfsExcelImporter
return null; return null;
} }
// ------------------------------------------------------------- 迭代 // ------------------------------------------------------------- 迭代 / Area
/// <summary>取项目下全部迭代完整路径(Tools_Dev\2026年Sprint\2026年Sprint10 形式),按路径排序。</summary> /// <summary>取项目下全部迭代完整路径(Tools_Dev\2026年Sprint\2026年Sprint10 形式),按路径排序。</summary>
public async Task<List<string>> GetIterationPathsAsync(string project, Action<string> log = null) public Task<List<string>> GetIterationPathsAsync(string project, Action<string> log = null)
{
return GetClassificationPathsAsync(project, "ProjectLifecycle", "Iteration", "迭代", log);
}
/// <summary>
/// 取项目下全部 Area 完整路径(Tools_Dev\DataTechnologies 形式),按路径排序。
/// Area 与迭代同属分类结构(ICommonStructureService),只是根节点不同:
/// TFS 2013 里 Area 的 StructureType 固定为 ProjectModelHierarchy,迭代是 ProjectLifecycle。
/// </summary>
public Task<List<string>> GetAreaPathsAsync(string project, Action<string> log = null)
{
return GetClassificationPathsAsync(project, "ProjectModelHierarchy", "Area", "Area", log);
}
/// <summary>
/// 通用分类树抓取:按 StructureType 挑根节点(拿不到就用名字模糊匹配兜底),
/// GetNodesXml 深度展开整棵树,再取每个节点的 Path 属性。迭代与 Area 共用这一条通道。
/// </summary>
private async Task<List<string>> GetClassificationPathsAsync(string project, string structureType,
string nameHint, string label, Action<string> log)
{ {
var list = await Task.Run(() => var list = await Task.Run(() =>
{ {
@@ -114,13 +121,13 @@ namespace TfsExcelImporter
throw new InvalidOperationException("项目不存在或无权访问: " + project); throw new InvalidOperationException("项目不存在或无权访问: " + project);
var structures = css.ListStructures(proj.Uri); var structures = css.ListStructures(proj.Uri);
var iterations = structures.FirstOrDefault(n => n.StructureType == "ProjectLifecycle") var root = structures.FirstOrDefault(n => string.Equals(n.StructureType, structureType, StringComparison.OrdinalIgnoreCase))
?? structures.FirstOrDefault(n => (n.Name ?? "").IndexOf("Iteration", StringComparison.OrdinalIgnoreCase) >= 0); ?? structures.FirstOrDefault(n => (n.Name ?? "").IndexOf(nameHint, StringComparison.OrdinalIgnoreCase) >= 0);
if (iterations == null) if (root == null)
throw new InvalidOperationException("未找到 Iterations(ProjectLifecycle) 结构"); throw new InvalidOperationException($"未找到 {label} 结构(StructureType={structureType})");
// GetNodesXml 深度展开全树;Node 元素的 Path 属性为分类节点路径 // 深度展开全树;Node 元素的 Path 属性为分类节点路径
var tree = css.GetNodesXml(new[] { iterations.Uri }, true); var tree = css.GetNodesXml(new[] { root.Uri }, true);
var raw = new List<string>(); var raw = new List<string>();
if (tree != null) if (tree != null)
{ {
@@ -133,20 +140,20 @@ namespace TfsExcelImporter
return raw; return raw;
}); });
var result = list.Select(p => NormalizeIterationPath(p, project)) var result = list.Select(p => NormalizeNodePath(p, project))
.Where(p => p != null) .Where(p => p != null)
.Distinct(StringComparer.OrdinalIgnoreCase) .Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase) .OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
.ToList(); .ToList();
log?.Invoke($"迭代列表来源: TFS OM ICommonStructureService({result.Count} 个)"); log?.Invoke($"{label}列表来源: TFS OM ICommonStructureService({result.Count} 个)");
return result; return result;
} }
/// <summary> /// <summary>
/// 节点路径归一化为工作项 IterationPath(项目\子...)。 /// 分类节点路径归一化为工作项字段值(项目\子...),迭代与 Area 共用。
/// 兼容:含/不含项目名前缀、含/不含结构根段(Iteration/Iterations/Area/Areas)。 /// 兼容:含/不含项目名前缀、含/不含结构根段(Iteration/Iterations/Area/Areas)。
/// </summary> /// </summary>
private static string NormalizeIterationPath(string nodePath, string project) private static string NormalizeNodePath(string nodePath, string project)
{ {
if (string.IsNullOrWhiteSpace(nodePath)) return null; if (string.IsNullOrWhiteSpace(nodePath)) return null;
var segs = nodePath.Split('\\').Select(s => s.Trim()).Where(s => s.Length > 0).ToList(); var segs = nodePath.Split('\\').Select(s => s.Trim()).Where(s => s.Length > 0).ToList();
@@ -162,6 +169,97 @@ namespace TfsExcelImporter
return project + "\\" + string.Join("\\", segs); return project + "\\" + string.Join("\\", segs);
} }
// ------------------------------------------------------------- 父项(backlog item)
/// <summary>下拉用的轻量工作项快照:只要 Id / 标题 / 类型 / 状态 / 迭代。</summary>
public class WorkItemBrief
{
public int Id;
public string Title;
public string Type;
public string State;
public string IterationPath;
/// <summary>
/// 列表里给人看的文本:Id 打头,后面是标题;状态只在「非 New」时追加。
/// 新建未审批的 PBI 全是 New,逐条显示纯属噪音——真正要看的是 Done/Closed 这类
/// 挂上去也展不开的父项,让异常状态自己显形就够了。
/// </summary>
public override string ToString()
{
var tail = string.IsNullOrWhiteSpace(State)
|| string.Equals(State, "New", StringComparison.OrdinalIgnoreCase)
? "" : " · " + State;
return "#" + Id + " " + (Title ?? "") + tail;
}
}
/// <summary>
/// 查可当父项用的工作项(默认 Product Backlog Item)。
/// 先按目标迭代过滤;该迭代下一条都没有时放宽到全项目——迭代里还没建 PBI 是常态,
/// 直接返回空列表会让人以为「接口没通」。
/// </summary>
public async Task<List<WorkItemBrief>> GetBacklogItemsAsync(string project, string iterationPath,
Action<string> log = null)
{
var scoped = await QueryWorkItemsAsync(project, iterationPath, "Product Backlog Item");
if (scoped.Count > 0)
{
log?.Invoke($"父项候选: 迭代「{iterationPath}」下的 Product Backlog Item {scoped.Count} 条");
return scoped;
}
log?.Invoke("父项候选: 该迭代下没有 Product Backlog Item,放宽到全项目");
var all = await QueryWorkItemsAsync(project, null, "Product Backlog Item");
if (all.Count > 0)
{
log?.Invoke($"父项候选: 全项目 Product Backlog Item {all.Count} 条");
return all;
}
// 非敏捷模板(CMMI/Scrum 的老项目)没有 PBI 类型:退化为「除 Task 外的所有工作项」
var fallback = await QueryWorkItemsAsync(project, iterationPath, null, excludeType: "Task");
log?.Invoke($"父项候选: 未找到 Product Backlog Item,退回「非 Task 工作项」{fallback.Count} 条");
return fallback;
}
/// <summary>
/// WIQL 取工作项快照。workItemType 为空时按 excludeType 反向过滤(排除导入类型本身)。
/// iterationPath 为空时不限迭代。
/// </summary>
private async Task<List<WorkItemBrief>> QueryWorkItemsAsync(string project, string iterationPath,
string workItemType, string excludeType = null)
{
return await Task.Run(() =>
{
var wiql = new StringBuilder(
"SELECT [System.Id], [System.Title], [System.WorkItemType], [System.State], [System.IterationPath] " +
"FROM WorkItems WHERE ");
wiql.Append($"[System.TeamProject] = '{EscapeWiql(project)}'");
if (!string.IsNullOrWhiteSpace(iterationPath))
wiql.Append($" AND [System.IterationPath] = '{EscapeWiql(iterationPath)}'");
if (!string.IsNullOrWhiteSpace(workItemType))
wiql.Append($" AND [System.WorkItemType] = '{EscapeWiql(workItemType)}'");
else if (!string.IsNullOrWhiteSpace(excludeType))
wiql.Append($" AND [System.WorkItemType] <> '{EscapeWiql(excludeType)}'");
wiql.Append(" ORDER BY [System.Id]");
var list = new List<WorkItemBrief>();
foreach (WorkItem wi in Store.Query(wiql.ToString()))
{
list.Add(new WorkItemBrief
{
Id = wi.Id,
Title = wi.Title,
Type = Convert.ToString(wi.Fields["System.WorkItemType"].Value),
State = Convert.ToString(wi.Fields["System.State"].Value),
IterationPath = Convert.ToString(wi.Fields["System.IterationPath"].Value)
});
}
return list;
});
}
// ------------------------------------------------------------- 查重 // ------------------------------------------------------------- 查重
/// <summary>查询指定迭代下同类型工作项的标题集合。</summary> /// <summary>查询指定迭代下同类型工作项的标题集合。</summary>
@@ -187,14 +285,16 @@ namespace TfsExcelImporter
/// <summary> /// <summary>
/// 创建工作项(OM Save)。返回新工作项 ID。 /// 创建工作项(OM Save)。返回新工作项 ID。
/// 说明:OM 14.x 的 SaveFlags 无 BypassRules(15.x 才加入,且 15.x 不兼容 TFS 2013)—— /// 说明:字段校验不可绕过——OM 14.x 的 SaveFlags 无 BypassRules(15.x 才加入,且 15.x 不兼容 TFS 2013),
/// 因此校验失败时直接把「哪个字段 / 什么原因 / 怎么改」写进异常(见 CheckInvalid),
/// 不做静默降级,避免产出违反模板规则的脏数据。
/// System.CreatedDate 为服务器管理的只读字段,无法写入(取导入时间); /// System.CreatedDate 为服务器管理的只读字段,无法写入(取导入时间);
/// Microsoft.VSTS.Common.ClosedDate 在 State=Done 时按普通规则通常可写:尝试写入, /// Microsoft.VSTS.Common.ClosedDate 在 State=Done 时按普通规则通常可写:尝试写入,
/// 校验或保存失败则清空该字段降级为普通保存(保证行导入成功)。 /// 校验或保存失败则清空该字段降级为普通保存(保证行导入成功)。
/// parentPbiId 非空时,通过 System.LinkTypes.Hierarchy(Reverse=Parent) 挂接到该 PBI。 /// parentPbiId 非空时,通过 System.LinkTypes.Hierarchy(Reverse=Parent) 挂接到该 PBI。
/// </summary> /// </summary>
public async Task<int> CreateWorkItemAsync(string project, string workItemType, public async Task<int> CreateWorkItemAsync(string project, string workItemType,
List<KeyValuePair<string, object>> fields, bool bypassRules, int? parentPbiId = null) List<KeyValuePair<string, object>> fields, int? parentPbiId = null)
{ {
return await Task.Run(() => return await Task.Run(() =>
{ {
@@ -269,14 +369,77 @@ namespace TfsExcelImporter
return null; return null;
} }
/// <summary>
/// 把 wi.Validate() 的结果整理成「字段(原因) → 怎么改」的单行提示。
/// 单行是硬要求:这段文字会写进 import_report.csv,换行会破坏 CSV 的行结构。
/// </summary>
private static string CheckInvalid(WorkItem wi) private static string CheckInvalid(WorkItem wi)
{ {
var invalid = wi.Validate(); var invalid = wi.Validate();
if (invalid.Count == 0) return null; if (invalid.Count == 0) return null;
var names = new StringBuilder(); var sb = new StringBuilder();
foreach (Field f in invalid) foreach (Field f in invalid)
names.Append(f.Name).Append("(").Append(FieldStatusText(f)).Append("); "); {
return names.ToString(); if (sb.Length > 0) sb.Append(";");
sb.Append(f.Name).Append('(').Append(FieldStatusText(f)).Append(") → ")
.Append(FixHint(f));
}
return sb.ToString();
}
/// <summary>
/// 按字段状态给出修复动作:导入失败时用户拿到的应该是「补哪一列、改成什么」,
/// 而不是只有一句「字段校验失败」。注意校验无法绕过(OM 14.x 无 BypassRules)。
/// </summary>
private static string FixHint(Field f)
{
switch (f.Status.ToString())
{
case "InvalidEmpty":
case "InvalidNull":
return "必填但没值:Excel 补上这一列,并确认字段映射是否对上" + AllowedHint(f);
case "InvalidTooLong":
return "值超长:截断到上限内(TFS 字符串字段默认上限 255 字符)";
case "InvalidType":
return "类型不匹配,该字段是 " + FieldTypeText(f) + ":检查单元格里是文本还是数字/日期";
case "InvalidValue":
case "InvalidList":
return "值不在允许范围" + AllowedHint(f);
case "InvalidFormat":
return "格式不对:日期写 yyyy-MM-dd,数字不要带单位或千分位";
case "InvalidComputed":
return "计算字段不可写:把这一列从 Excel 去掉";
case "InvalidNotNew":
return "只在新建时可设置:不要对已存在工作项改这一列";
default:
return "按服务器返回的规则修正该字段的值";
}
}
/// <summary>列出字段的允许值(列表字段 InvalidList 的主因),最多展开 8 个。</summary>
private static string AllowedHint(Field f)
{
try
{
var vals = new List<string>();
int total = 0;
foreach (object v in f.AllowedValues)
{
total++;
if (vals.Count < 8) vals.Add(Convert.ToString(v));
}
if (vals.Count == 0) return "";
return "(允许值: " + string.Join(" / ", vals.ToArray())
+ (total > vals.Count ? " 等 " + total + " 项" : "") + ")";
}
catch { return ""; }
}
/// <summary>字段类型(String / Integer / DateTime ...),用于提示类型不匹配。</summary>
private static string FieldTypeText(Field f)
{
try { return f.FieldDefinition.FieldType.ToString(); }
catch { return "未知类型"; }
} }
/// <summary>把 FieldStatus 翻译为可读原因(用字符串匹配,避免不同 OM 版本枚举成员差异)。</summary> /// <summary>把 FieldStatus 翻译为可读原因(用字符串匹配,避免不同 OM 版本枚举成员差异)。</summary>
@@ -315,7 +478,9 @@ namespace TfsExcelImporter
{ {
return await Task.Run(() => return await Task.Run(() =>
{ {
var wiql = "SELECT [System.Id] FROM WorkItems WHERE " + // SELECT 必须带全循环里要读的字段:OM 对查询未包含的字段会逐条触发完整加载
// (每条一次服务器往返),只 SELECT Id 会让批量修 Area 退化成 N+1
var wiql = "SELECT [System.Id], [System.Title], [System.State], [System.AreaPath] FROM WorkItems WHERE " +
$"[System.TeamProject] = '{EscapeWiql(project)}' AND " + $"[System.TeamProject] = '{EscapeWiql(project)}' AND " +
$"[System.WorkItemType] = '{EscapeWiql(workItemType)}' AND " + $"[System.WorkItemType] = '{EscapeWiql(workItemType)}' AND " +
$"[System.IterationPath] = '{EscapeWiql(iterationPath)}' AND " + $"[System.IterationPath] = '{EscapeWiql(iterationPath)}' AND " +
+31 -4
View File
@@ -11,6 +11,10 @@
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<!-- System DPI 感知:界面像素尺寸按 Theme.Px() 换算,见 app.manifest --> <!-- System DPI 感知:界面像素尺寸按 Theme.Px() 换算,见 app.manifest -->
<ApplicationManifest>app.manifest</ApplicationManifest> <ApplicationManifest>app.manifest</ApplicationManifest>
<!-- exe 图标(资源管理器/任务栏/快捷方式)。多尺寸 ICO 由 tools/make_icon.py 生成 -->
<ApplicationIcon>app.ico</ApplicationIcon>
<!-- 便携单文件:Costura 把所有依赖 DLL 嵌入 exe,运行时自动解析 -->
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -22,16 +26,39 @@
<PackageReference Include="Microsoft.TeamFoundationServer.ExtendedClient" Version="14.*" /> <PackageReference Include="Microsoft.TeamFoundationServer.ExtendedClient" Version="14.*" />
<!-- 无需安装 VS 也可用 dotnet build 编译 net48 --> <!-- 无需安装 VS 也可用 dotnet build 编译 net48 -->
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" PrivateAssets="all" />
<!-- 单文件打包:把所有引用 DLL(含 native WITDataStore)嵌进 exe -->
<PackageReference Include="Fody" Version="6.8.2" PrivateAssets="all" />
<PackageReference Include="Costura.Fody" Version="5.7.0" PrivateAssets="all" />
</ItemGroup>
<!-- DPAPI(ProtectedData):config.json 密码加密 -->
<ItemGroup>
<Reference Include="System.Security" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="config.json"> <None Update="config.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<!-- 默认导入模板:随 exe 一起发布,「导出Excel模板」原样复制这份文件 --> <!--
<Content Include="..\templates\TFS导入模板.xlsx" Link="TFS导入模板.xlsx"> 图标同时以「托管资源」嵌一份:窗口标题栏/任务栏用 Form.Icon,
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> 从内嵌 ICO 取可以得到全部 9 个尺寸帧;若走 Icon.ExtractAssociatedIcon
</Content> 只能拿到系统默认那一档,高 DPI 下会糊。
-->
<EmbeddedResource Include="app.ico" LogicalName="app.ico" />
<!-- 默认导入模板:嵌入 exe,「导出Excel模板」时释放出来;exe 同目录存在同名文件时优先用它(便于现场替换模板) -->
<EmbeddedResource Include="..\templates\TFS导入模板.xlsx" Link="TFS导入模板.xlsx" />
<!--
TFS Client OM 的 native DLL(NuGet 包 lib\native\{amd64,x86})。
Costura 只嵌托管程序集,这两个是纯 win32 DLL,单独嵌入,
启动时由 NativeLibraryLoader 释放到临时目录并预加载。
-->
<EmbeddedResource Include="$(NuGetPackageRoot)microsoft.teamfoundationserver.extendedclient\*\lib\native\amd64\Microsoft.WITDataStore64.dll">
<LogicalName>native.Microsoft.WITDataStore64.dll</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="$(NuGetPackageRoot)microsoft.teamfoundationserver.extendedclient\*\lib\native\x86\Microsoft.WITDataStore32.dll">
<LogicalName>native.Microsoft.WITDataStore32.dll</LogicalName>
</EmbeddedResource>
</ItemGroup> </ItemGroup>
</Project> </Project>
+269 -11
View File
@@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
namespace TfsExcelImporter namespace TfsExcelImporter
@@ -149,10 +151,64 @@ namespace TfsExcelImporter
return Card; return Card;
} }
public static int TextWidth(string text, Font font) { private static readonly Dictionary<int, SolidBrush> _eraseBrushes = new Dictionary<int, SolidBrush>();
/// <summary>
/// WM_ERASEBKGND 的快速擦除:直接用 GDI 把客户区铺成底色,不经过双缓冲、不建 GraphicsPath。
/// 自绘控件为了不闪都不擦背景,代价是窗口被重新暴露(还原、切前台)时那块像素保持系统的黑色,
/// 要等完整首帧(实测整窗 100ms+)才盖掉——这就是「黑色界面闪现」的来源。
/// 这里先用一次 FillRect 换掉黑底:即使完整首帧还没来,用户看到的也只是和界面同色的浅底。
/// </summary>
public static bool FastErase(IntPtr hwnd, IntPtr hdc, Color color)
{
RECT rc;
if (color.A == 0 || !GetClientRect(hwnd, out rc) || rc.right <= 0 || rc.bottom <= 0) return false;
int key = color.ToArgb();
SolidBrush brush;
if (!_eraseBrushes.TryGetValue(key, out brush))
{
brush = new SolidBrush(color);
_eraseBrushes[key] = brush;
}
var g = Graphics.FromHdc(hdc);
try { g.FillRectangle(brush, 0, 0, rc.right, rc.bottom); }
finally { g.Dispose(); }
return true;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int left, top, right, bottom; }
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out RECT rc);
private static readonly Dictionary<string, int> _textWidths = new Dictionary<string, int>();
public static int TextWidth(string text, Font font)
{
if (string.IsNullOrEmpty(text)) return 0; if (string.IsNullOrEmpty(text)) return 0;
return TextRenderer.MeasureText(text, font, Size.Empty, // 排版会反复量同一批文案(拖拽缩放每帧都要全量量一遍),而 MeasureText 每次都要建 DC、选字体,
// 和查一次字典差两个数量级。字体是静态单例,键里带字体名/字号/字形就足以区分。
string key = font.Name + "|" + font.SizeInPoints.ToString("F1") + "|" + (int)font.Style + "|" + text;
int w;
if (_textWidths.TryGetValue(key, out w)) return w;
w = TextRenderer.MeasureText(text, font, Size.Empty,
TextFormatFlags.NoPadding | TextFormatFlags.SingleLine).Width; TextFormatFlags.NoPadding | TextFormatFlags.SingleLine).Width;
if (_textWidths.Count > 800) _textWidths.Clear(); // 日志摘要/路径是动态文案,别让它无限涨
_textWidths[key] = w;
return w;
}
/// <summary>
/// 位置尺寸都没变就不动。每次 SetBounds 都是一次 WM_WINDOWPOSCHANGED 加一次重绘,
/// 而重排里绝大多数控件其实待在原地——打字、状态刷新这类重排尤其如此,
/// 拦掉空转会把这些场景的 70~100ms 直接抹平。
/// </summary>
public static void Place(Control c, int x, int y, int w, int h)
{
var b = c.Bounds;
if (b.X == x && b.Y == y && b.Width == w && b.Height == h) return;
c.SetBounds(x, y, w, h);
} }
public static Color ChipInk(ChipKind kind) public static Color ChipInk(ChipKind kind)
@@ -393,6 +449,8 @@ namespace TfsExcelImporter
g.SmoothingMode = SmoothingMode.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias;
var r = new RectangleF(0.5f, 0.5f, Width - 1f, Height - 1f); var r = new RectangleF(0.5f, 0.5f, Width - 1f, Height - 1f);
using (var b = new SolidBrush(fill)) g.FillEllipse(b, r); using (var b = new SolidBrush(fill)) g.FillEllipse(b, r);
if (Kind == BadgeKind.Pending)
using (var p = new Pen(Theme.BorderStrong, Theme.Hair)) g.DrawEllipse(p, r);
g.SmoothingMode = old; g.SmoothingMode = old;
// 勾画在圆内缩 4px(14px 盒子 / 22px 圆),铺满整圆会贴边看着像被裁掉 // 勾画在圆内缩 4px(14px 盒子 / 22px 圆),铺满整圆会贴边看着像被裁掉
if (Kind == BadgeKind.Done) Icons.Draw(g, IconKind.Check, Icons.BadgeGlyph(ClientRectangle), ink); if (Kind == BadgeKind.Done) Icons.Draw(g, IconKind.Check, Icons.BadgeGlyph(ClientRectangle), ink);
@@ -423,6 +481,16 @@ namespace TfsExcelImporter
TabStop = false; TabStop = false;
} }
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0014 && Theme.FastErase(m.HWnd, m.WParam, BackColor))
{
m.Result = (IntPtr)1;
return;
}
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
Theme.FillPanel(e.Graphics, new Rectangle(0, 0, Width, Height), _face, LineColor, Theme.FillPanel(e.Graphics, new Rectangle(0, 0, Width, Height), _face, LineColor,
@@ -446,6 +514,8 @@ namespace TfsExcelImporter
public bool ShowBadge = true; public bool ShowBadge = true;
/// <summary>卡片头部右侧留给按钮的宽度,摘要文字不越过它。</summary> /// <summary>卡片头部右侧留给按钮的宽度,摘要文字不越过它。</summary>
public int HeaderReserve = 0; public int HeaderReserve = 0;
/// <summary>头部摘要按「圆点 + 短语」分段绘制(状态摘要样式);默认纯文本。</summary>
public bool SummaryDots = false;
public int HeaderH = 44; public int HeaderH = 44;
public int BodyH = 0; public int BodyH = 0;
public Action<bool> OnToggle; public Action<bool> OnToggle;
@@ -461,6 +531,17 @@ namespace TfsExcelImporter
HeaderH = Theme.Px(44); HeaderH = Theme.Px(44);
} }
// 卡片占了大半客户区,窗口重新暴露时它不擦背景就是一大片黑——和 MainForm 一样先铺面色。
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0014 && Theme.FastErase(m.HWnd, m.WParam, BackColor))
{
m.Result = (IntPtr)1;
return;
}
base.WndProc(ref m);
}
public Rectangle BodyRect { get { return new Rectangle(0, HeaderH, Width, BodyH); } } public Rectangle BodyRect { get { return new Rectangle(0, HeaderH, Width, BodyH); } }
private Rectangle HeaderRect { get { return new Rectangle(0, 0, Width, HeaderH); } } private Rectangle HeaderRect { get { return new Rectangle(0, 0, Width, HeaderH); } }
@@ -570,6 +651,10 @@ namespace TfsExcelImporter
var old = g.SmoothingMode; var old = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias;
using (var b = new SolidBrush(badgeFill)) g.FillEllipse(b, badge); using (var b = new SolidBrush(badgeFill)) g.FillEllipse(b, badge);
// 未激活徽章加一圈浅描边:纯灰底在白卡上存在感太弱,描边后与「激活/完成」的实心徽章同属一套语义
if (Badge == BadgeKind.Pending)
using (var p = new Pen(Theme.BorderStrong, Theme.Hair))
g.DrawEllipse(p, badge.X + 0.5f, badge.Y + 0.5f, badge.Width - 1f, badge.Height - 1f);
g.SmoothingMode = old; g.SmoothingMode = old;
if (Badge == BadgeKind.Done) Icons.Draw(g, IconKind.Check, Icons.BadgeGlyph(badge), badgeInk); if (Badge == BadgeKind.Done) Icons.Draw(g, IconKind.Check, Icons.BadgeGlyph(badge), badgeInk);
else else
@@ -588,11 +673,15 @@ namespace TfsExcelImporter
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis); | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
int sx = titleRect.Right + Theme.Px(12); int sx = titleRect.Right + Theme.Px(12);
var sumRect = new Rectangle(sx, 0, Math.Max(0, Width - chevW - sx - Theme.Px(12)), HeaderH); int sumW = Math.Max(0, Width - chevW - sx - Theme.Px(12));
TextRenderer.DrawText(g, Summary, Theme.Caption, sumRect, if (SummaryDots)
Invalid ? Theme.Danger : Theme.Ink2, DrawDotSummary(g, Summary, sx, sumW);
TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding else
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis); TextRenderer.DrawText(g, Summary, Theme.Caption,
new Rectangle(sx, 0, sumW, HeaderH),
Invalid ? Theme.Danger : Theme.Ink2,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
if (Collapsible) if (Collapsible)
{ {
@@ -605,6 +694,40 @@ namespace TfsExcelImporter
using (var p = new Pen(Theme.Border)) using (var p = new Pen(Theme.Border))
g.DrawLine(p, Theme.S16, HeaderH, Width - Theme.S16, HeaderH); g.DrawLine(p, Theme.S16, HeaderH, Width - Theme.S16, HeaderH);
} }
/// <summary>「圆点 + 短语」状态摘要:按 " · " 分段,每段一枚圆点;放不下的段整段省略。</summary>
private void DrawDotSummary(Graphics g, string summary, int x, int availW)
{
if (string.IsNullOrEmpty(summary) || availW <= 0) return;
var segments = summary.Split(new[] { " · " }, StringSplitOptions.None);
int dot = Theme.Px(6);
int dotGap = Theme.Px(6);
int segGap = Theme.Px(14);
int cursor = x;
int limit = x + availW;
foreach (var segment in segments)
{
if (cursor + dot + dotGap > limit) break;
var oldSmoothing = g.SmoothingMode;
g.SmoothingMode = SmoothingMode.AntiAlias;
using (var b = new SolidBrush(Invalid ? Theme.Danger : Theme.Ink3))
g.FillEllipse(b, cursor, (HeaderH - dot) / 2, dot, dot);
g.SmoothingMode = oldSmoothing;
cursor += dot + dotGap;
int remain = limit - cursor;
if (remain <= 0) break;
int tw = Theme.TextWidth(segment, Theme.Caption);
bool truncated = tw > remain;
var flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding
| TextFormatFlags.SingleLine;
if (truncated) flags |= TextFormatFlags.EndEllipsis;
TextRenderer.DrawText(g, segment, Theme.Caption,
new Rectangle(cursor, 0, Math.Min(tw + Theme.Px(2), remain), HeaderH),
Invalid ? Theme.Danger : Theme.Ink2, flags);
cursor += Math.Min(tw, remain) + segGap;
if (truncated) break;
}
}
} }
internal enum BtnKind { Secondary, Primary, Ghost } internal enum BtnKind { Secondary, Primary, Ghost }
@@ -831,14 +954,25 @@ namespace TfsExcelImporter
private bool _invalid; private bool _invalid;
private ComboBox _combo; private ComboBox _combo;
private Chevron _chevron; private Chevron _chevron;
private SuffixIcon _suffix;
private Control _content; // 主内容控件(TextBox/ComboBox),占位层据此判定显隐
private CueLabel _cue; // 自绘占位提示:原生 EM_SETCUEBANNER 控制不了颜色/字号/对齐
// 内容容器:整体内缩 2px 并按圆角 Region 裁剪——恰好让开聚焦态 2px 描边带, // 内容容器:整体内缩 2px 并按圆角 Region 裁剪——恰好让开聚焦态 2px 描边带,
// 否则白底会切掉描边的内半圈,只剩外圈 AA 残边(视觉上就是一圈毛刺)。 // 否则白底会切掉描边的内半圈,只剩外圈 AA 残边(视觉上就是一圈毛刺)。
// 子控件(尤其被挤出宿主藏箭头的 ComboBox)再怎么越界,也只会被裁在描边圈以内。 // 子控件(尤其被挤出宿主藏箭头的 ComboBox)再怎么越界,也只会被裁在描边圈以内。
private Panel _box; private Panel _box;
/// <summary>上一次 LayoutInner 时的宿主尺寸:尺寸没变就不用重摆子控件、更不用重建圆角 Region。</summary>
private Size _innerSize = new Size(-1, -1);
/// <summary>宿主右侧留给自绘箭头的区域,同时也是点击展开下拉的热区。</summary> /// <summary>宿主右侧留给自绘箭头的区域,同时也是点击展开下拉的热区。</summary>
private int ArrowZone { get { return Theme.Px(26); } } private int ArrowZone { get { return Theme.Px(26); } }
/// <summary>内容右侧的固定预留:组合框是箭头热区,文本框是尾部图标按钮(没有则 0)。</summary>
private int RightReserve
{
get { return _chevron != null ? ArrowZone : (_suffix != null ? Theme.Px(26) : 0); }
}
/// <summary>内容左缘相对 _box 的缩进。TextBox 就摆在 Px(7),组合框闭合态文字必须共用同一基准, /// <summary>内容左缘相对 _box 的缩进。TextBox 就摆在 Px(7),组合框闭合态文字必须共用同一基准,
/// 否则同一排的输入框文字会错开一条竖线。</summary> /// 否则同一排的输入框文字会错开一条竖线。</summary>
private static int TextInsetX { get { return Theme.Px(7); } } private static int TextInsetX { get { return Theme.Px(7); } }
@@ -896,16 +1030,56 @@ namespace TfsExcelImporter
_chevron.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) ToggleComboDropDown(); }; _chevron.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) ToggleComboDropDown(); };
_box.Controls.Add(_chevron); _box.Controls.Add(_chevron);
} }
_content = inner;
inner.BackColor = Theme.Card; inner.BackColor = Theme.Card;
inner.Font = mono ? Theme.Mono : Theme.Body; inner.Font = mono ? Theme.Mono : Theme.Body;
inner.ForeColor = Theme.Ink; inner.ForeColor = Theme.Ink;
_box.Controls.Add(inner); _box.Controls.Add(inner);
inner.Enter += (s, e) => Invalidate(); inner.Enter += (s, e) => Invalidate();
inner.Leave += (s, e) => Invalidate(); inner.Leave += (s, e) => Invalidate();
LayoutInner(); LayoutInner(true);
return inner; return inner;
} }
/// <summary>文本框尾部图标按钮(如 Excel 字段的「浏览」):点击执行回调,悬停着色提示可点。</summary>
public void AddSuffix(IconKind glyph, Action onClick)
{
if (_suffix != null) return;
_suffix = new SuffixIcon { Glyph = glyph };
_suffix.Click += (s, e) => { if (onClick != null) onClick(); };
_box.Controls.Add(_suffix);
LayoutInner(true);
}
/// <summary>忙等时独立禁用尾部按钮,不影响输入框本身的编辑。</summary>
public void SetSuffixEnabled(bool enabled)
{
if (_suffix != null) _suffix.Enabled = enabled;
}
/// <summary>
/// 自绘占位提示:比原生 EM_SETCUEBANNER 多出「浅灰、小字号、水平居中」三件事。
/// 鼠标经 HTTRANSPARENT 穿透到输入框,文字随内容输入即时显隐,与 Web placeholder 手感一致。
/// </summary>
public void SetCue(string text)
{
if (_cue == null)
{
_cue = new CueLabel();
_box.Controls.Add(_cue);
}
_cue.Text = text ?? "";
if (_content != null) _content.TextChanged += (s, e) => UpdateCueVisibility();
UpdateCueVisibility();
LayoutInner(true);
}
private void UpdateCueVisibility()
{
if (_cue != null && _content != null)
_cue.Visible = string.IsNullOrEmpty(_content.Text);
}
protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); LayoutInner(); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); LayoutInner(); }
private void DrawComboItem(object sender, DrawItemEventArgs e) private void DrawComboItem(object sender, DrawItemEventArgs e)
@@ -953,14 +1127,19 @@ namespace TfsExcelImporter
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis); | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
} }
private void LayoutInner() private void LayoutInner(bool force = false)
{ {
if (_box == null) return; // 构造中途触发 OnSizeChanged 时容器可能还没建好 if (_box == null) return; // 构造中途触发 OnSizeChanged 时容器可能还没建好
// 尺寸没变 → 子控件位置也不会变,直接跳过:这里一次要重摆 3~5 个真实子窗并重建 Region,
// 单次 3~4ms,重排里被反复调用的正是这种空转。
var hostSize = new Size(Width, Height);
if (!force && hostSize == _innerSize) return;
_innerSize = hostSize;
_box.SetBounds(2, 2, Width - 4, Height - 4); _box.SetBounds(2, 2, Width - 4, Height - 4);
SetBoxRegion(); SetBoxRegion();
foreach (Control c in _box.Controls) foreach (Control c in _box.Controls)
{ {
if (c is Chevron) continue; if (c is Chevron || c is SuffixIcon || c is CueLabel) continue;
var tb = c as TextBox; var tb = c as TextBox;
var cb = c as ComboBox; var cb = c as ComboBox;
if (cb != null) if (cb != null)
@@ -974,7 +1153,13 @@ namespace TfsExcelImporter
} }
int natural = tb != null ? tb.PreferredHeight : Theme.Px(19); int natural = tb != null ? tb.PreferredHeight : Theme.Px(19);
int th = Math.Min(Math.Max(natural, Theme.Px(18)), _box.Height - Theme.Px(4)); int th = Math.Min(Math.Max(natural, Theme.Px(18)), _box.Height - Theme.Px(4));
c.SetBounds(Theme.Px(7), Math.Max(Theme.Px(2), (_box.Height - th) / 2), _box.Width - Theme.Px(14), th); // Edit 自绘时把文字画在客户区上沿往下 Px(2) 处,而 PreferredHeight 底部还含着约
// Px(4) 的边框留白(BorderStyle=None 也不减)。直接按 PreferredHeight 居中,等于把
// 「上留白 2 + 文字 + 下留白 4」整体居中——文字就偏上 Px(2),肉眼一眼能看出来。
// 把这段底部留白的一半补回来,文字才落在框内视觉中线上(Consolas / 雅黑都适用)。
int textTopFix = tb != null ? Theme.Px(2) : 0;
c.SetBounds(Theme.Px(7), Math.Max(Theme.Px(2), (_box.Height - th) / 2) + textTopFix,
_box.Width - Theme.Px(14) - RightReserve, th);
} }
if (_chevron != null) if (_chevron != null)
{ {
@@ -982,6 +1167,21 @@ namespace TfsExcelImporter
_chevron.SetBounds(_box.Width - Theme.Px(7) - size, Theme.Px(2), size, _box.Height - Theme.Px(4)); _chevron.SetBounds(_box.Width - Theme.Px(7) - size, Theme.Px(2), size, _box.Height - Theme.Px(4));
_chevron.BringToFront(); // 后加的兄弟控件在底层,必须提到组合框上方才看得见 _chevron.BringToFront(); // 后加的兄弟控件在底层,必须提到组合框上方才看得见
} }
if (_suffix != null)
{
int size = Theme.Px(16);
_suffix.SetBounds(_box.Width - Theme.Px(8) - size, Theme.Px(2), size, _box.Height - Theme.Px(4));
}
if (_cue != null)
{
// 与内容文字同一缩进基准,宽度让开尾部箭头/图标区;文字左对齐(不再居中)。
// 起点就用 TextInsetX:实测(150% 截图)空态占位与已填内容的第一个墨迹列
// 相对左边框都在 +13px,多让或让少都会在「敲字瞬间」看到文字横跳。
_cue.SetBounds(TextInsetX, Theme.Px(2),
Math.Max(Theme.Px(24), _box.Width - TextInsetX - Theme.Px(7) - RightReserve),
_box.Height - Theme.Px(4));
_cue.BringToFront();
}
Invalidate(); Invalidate();
} }
@@ -1018,6 +1218,64 @@ namespace TfsExcelImporter
} }
} }
/// <summary>输入框尾部图标按钮:白底上悬停变主色,点击交给外部回调。</summary>
private sealed class SuffixIcon : Control
{
public IconKind Glyph = IconKind.None;
private bool _hover;
public SuffixIcon()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint
| ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw
| ControlStyles.SupportsTransparentBackColor, true);
BackColor = Theme.Card;
Cursor = Cursors.Hand;
TabStop = false;
}
protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); _hover = true; Invalidate(); }
protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _hover = false; Invalidate(); }
protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Invalidate(); }
protected override void OnPaint(PaintEventArgs e)
{
int size = Theme.Px(16);
Icons.Draw(e.Graphics, Glyph,
new Rectangle((Width - size) / 2, (Height - size) / 2, size, size),
_hover && Enabled ? Theme.Primary : Theme.Ink2);
}
}
/// <summary>占位提示层:小一号字号、置灰、左对齐并贴住真实文字的左缘;鼠标事件穿透,不挡输入框聚焦与编辑。</summary>
private sealed class CueLabel : Control
{
public CueLabel()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint
| ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
BackColor = Theme.Card;
TabStop = false;
}
protected override void WndProc(ref Message m)
{
const int WM_NCHITTEST = 0x84;
if (m.Msg == WM_NCHITTEST) { m.Result = (IntPtr)(-1); return; } // HTTRANSPARENT:点击穿透
base.WndProc(ref m);
}
protected override void OnPaint(PaintEventArgs e)
{
// 左对齐:占位文字必须从真实文字的起点起头,用户一敲字两个位置才不跳动。
// NoPadding 去掉 DrawText 自带的 2px 文字边距,起点完全由外层给的 x 决定。
TextRenderer.DrawText(e.Graphics, Text, Theme.Caption,
new Rectangle(0, 0, Width, Height), Theme.Ink3,
TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
}
}
protected override void OnMouseDown(MouseEventArgs e) protected override void OnMouseDown(MouseEventArgs e)
{ {
base.OnMouseDown(e); base.OnMouseDown(e);
Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

+2 -6
View File
@@ -3,14 +3,10 @@
"Project": "Tools_Dev", "Project": "Tools_Dev",
"WorkItemType": "Task", "WorkItemType": "Task",
"IterationPath": "", "IterationPath": "",
"AreaPath": "Tools_Dev\\DataTechnologies", "AreaPath": "",
"AuthMode": "ntlm",
"Username": "", "Username": "",
"Password": "", "Password": "",
"Domain": "", "SkipExistingTitles": false,
"UseSystemProxy": false,
"BypassRules": true,
"SkipExistingTitles": true,
"DefaultState": "To Do", "DefaultState": "To Do",
"FinancialProjectRef": "", "FinancialProjectRef": "",
"CompletedRef": "", "CompletedRef": "",
-36
View File
@@ -1,36 +0,0 @@
{
"tfs_url": "http://pdtfs01.dev.goldenstand.cn:8080/tfs/DefaultCollection",
"project": "Tools_Dev",
"team": "DataTechnologies",
"work_item_type": "Task",
"parent_title": "陈首林",
"parent_id": "",
"iteration_path": "2026年Sprint\\2026年Sprint10",
"area_path": "",
"auth": {
"mode": "ntlm",
"username": "chenshoulin",
"password": "Password72",
"domain": ""
},
"field_refs": {
"title": "System.Title",
"state": "System.State",
"assigned_to": "System.AssignedTo",
"financial_project": "",
"completed": "",
"log_date": "",
"created_date": "System.CreatedDate",
"closed_date": "Microsoft.VSTS.Common.ClosedDate",
"iteration_path": "System.IterationPath",
"area_path": "System.AreaPath"
},
"resolve_fields_by_display_name": {
"financial_project": "FinancialProject",
"completed": "Completed",
"log_date": "LogDate"
},
"bypass_rules": true,
"skip_existing_titles": true,
"default_state": "To Do"
}
-3
View File
@@ -1,3 +0,0 @@
Title,State,AssignedTo,FinancialProject,Completed,LogDate,CreatedDate,ClosedDate,PBI Id,Notes
20261012 - 示例:货载报告解析并上传凭证受托报告相关内容,To Do,张三,信托 - 上海信托,5,2026-10-12,2026-10-30 11:14,,,示例行,导入前请删除
20261009 示例:受托报告bug修复,Done,李四,信托 - 上海信托,8,2026-10-09,2026-10-10 18:20:00,2026-10-30 18:00:00,219975,PBI Id 列可逐行指定父项,留空则用配置里的 parent_title/parent_id
1 Title State AssignedTo FinancialProject Completed LogDate CreatedDate ClosedDate PBI Id Notes
2 20261012 - 示例:货载报告解析并上传凭证受托报告相关内容 To Do 张三 信托 - 上海信托 5 2026-10-12 2026-10-30 11:14 示例行,导入前请删除
3 20261009 示例:受托报告bug修复 Done 李四 信托 - 上海信托 8 2026-10-09 2026-10-10 18:20:00 2026-10-30 18:00:00 219975 PBI Id 列可逐行指定父项,留空则用配置里的 parent_title/parent_id
-4
View File
@@ -1,4 +0,0 @@
[1101/171941.143:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: 系统找不到指定的文件。 (0x2)
[1101/173900.093:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: 系统找不到指定的文件。 (0x2)
[1101/184906.941:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: 系统找不到指定的文件。 (0x2)
[1101/191310.883:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: 系统找不到指定的文件。 (0x2)
-2
View File
@@ -1,2 +0,0 @@
requests>=2.28
requests-ntlm>=1.2
-467
View File
@@ -1,467 +0,0 @@
#!/usr/bin/env python3
"""
TFS 2013 工作项批量导入工具
目标环境(来自截图):
服务器 : http://pdtfs01.dev.goldenstand.cn:8080/tfs/DefaultCollection
团队项目 : Tools_Dev
团队 : DataTechnologies
迭代路径 : 2026年Sprint\\2026年Sprint10 (URL: .../_backlogs/Iteration/2026%E5%B9%B4Sprint/2026%E5%B9%B4Sprint10)
数据源: data/work_items.csv(Title/State/AssignedTo/FinancialProject/Completed/LogDate/CreatedDate/ClosedDate)
字段映射: config.json -> field_refs;留空的自定义字段按显示名自动解析。
用法:
python tfs_import.py --dry-run # 只校验数据与字段,不写入
python tfs_import.py # 正式导入
python tfs_import.py --link-existing # 已导入的项补挂父链接(不新建)
python tfs_import.py --input other.csv # 指定数据文件
python tfs_import.py --skip-existing-titles # 跳过已存在同标题工作项
python tfs_import.py --list-fields # 列出服务器全部字段(显示名/引用名)
认证(config.json auth.mode):
ntlm : 域\\用户 + 密码(TFS 2013 典型配置)
basic : 服务器开了基本身份验证时使用
默认凭据: username 留空则尝试当前 Windows 凭据(仅 basic/ntlm 均需显式账号,TFS 2013 一般用 ntlm)
"""
from __future__ import annotations
import argparse
import csv
import json
import sys
import time
from datetime import datetime
from pathlib import Path
try:
import requests
except ImportError:
print("缺少依赖 requests,请先: pip install -r requirements.txt", file=sys.stderr)
sys.exit(2)
BASE_DIR = Path(__file__).resolve().parent
API_VER = "1.0"
DATE_FMT_IN = ["%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d", "%Y/%m/%d", "%Y-%m-%d %H:%M"]
# ---------------------------------------------------------------- 配置与数据
def load_config(path: Path) -> dict:
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def load_rows(path: Path) -> list[dict]:
# 依次尝试 utf-8-sig / gbk,兼容新旧 CSV 编码
rows: list[dict] | None = None
last_err: Exception | None = None
for enc in ("utf-8-sig", "gbk"):
try:
with path.open("r", encoding=enc, newline="") as f:
reader = csv.DictReader(f)
rows = [r for r in reader if (r.get("Title") or "").strip()]
break
except UnicodeDecodeError as e:
last_err = e
if rows is None:
raise SystemExit(f"无法读取 CSV {path}(utf-8/gbk 均失败): {last_err}")
return rows
def parse_dt(value: str) -> str | None:
"""把 CSV 里的时间统一成 TFS 接受的 ISO 格式;空值返回 None。"""
value = (value or "").strip()
if not value:
return None
for fmt in DATE_FMT_IN:
try:
return datetime.strptime(value, fmt).strftime("%Y-%m-%dT%H:%M:%S")
except ValueError:
continue
raise ValueError(f"无法解析时间: {value!r}")
# ---------------------------------------------------------------- HTTP 会话
def build_session(cfg: dict) -> requests.Session:
auth = cfg.get("auth", {})
mode = (auth.get("mode") or "ntlm").lower()
sess = requests.Session()
sess.verify = False
sess.headers.update({"Accept": "application/json"})
user = auth.get("username") or ""
pwd = auth.get("password") or ""
domain = auth.get("domain") or ""
if mode == "ntlm":
from requests_ntlm import HttpNtlmAuth
if not user or not pwd:
raise SystemExit("ntlm 模式需要 config.json 里配置 auth.username / auth.password")
login = f"{domain}\\{user}" if domain else user
sess.auth = HttpNtlmAuth(login, pwd)
elif mode == "basic":
if not user or not pwd:
raise SystemExit("basic 模式需要 config.json 里配置 auth.username / auth.password")
sess.auth = (f"{domain}\\{user}" if domain else user, pwd)
else:
raise SystemExit(f"未知 auth.mode: {mode}")
return sess
def tfs_send(sess: requests.Session, method: str, url: str, *, retries: int = 3,
**kwargs) -> requests.Response:
"""带退避重试的请求:502/503/504 网关错误或网络异常时最多重试 retries 次。"""
kwargs.setdefault("timeout", 60)
resp: requests.Response | None = None
for attempt in range(1, retries + 1):
try:
resp = sess.request(method, url, **kwargs)
except requests.RequestException as e:
if attempt == retries:
raise
wait = 3 * attempt
print(f"[重试] {method.upper()} {url} 网络异常: {e};{wait}s 后第 {attempt + 1} 次尝试")
time.sleep(wait)
continue
if resp.status_code in (502, 503, 504) and attempt < retries:
wait = 3 * attempt
print(f"[重试] {method.upper()} {url} -> {resp.status_code};{wait}s 后第 {attempt + 1} 次尝试")
time.sleep(wait)
continue
return resp
raise RuntimeError(f"请求重试 {retries} 次后仍失败: {method.upper()} {url}")
def tfs_get(sess: requests.Session, url: str, params: dict | None = None) -> dict:
resp = tfs_send(sess, "get", url, params=params)
if resp.status_code >= 400:
raise RuntimeError(f"GET {url} -> {resp.status_code}: {resp.text[:500]}")
return resp.json()
def tfs_wiql(sess: requests.Session, url: str, wiql: str) -> dict:
resp = tfs_send(sess, "post", url, params={"api-version": API_VER}, json={"query": wiql})
if resp.status_code >= 400:
raise RuntimeError(f"WIQL 查询失败 {resp.status_code}: {resp.text[:500]}")
return resp.json()
# ---------------------------------------------------------------- 字段解析
def resolve_fields(sess: requests.Session, base: str, cfg: dict) -> dict:
"""返回 {语义名: 引用名}。优先用 config.field_refs 显式值,其次按显示名查服务器字段表。"""
refs = dict(cfg.get("field_refs") or {})
by_display = cfg.get("resolve_fields_by_display_name") or {}
need_lookup = [k for k, v in by_display.items() if not refs.get(k)]
if not need_lookup:
return refs
data = tfs_get(sess, f"{base}/_apis/wit/fields", params={"api-version": API_VER})
catalog = data.get("value", [])
lower_map = {}
for f in catalog:
lower_map.setdefault(f.get("name", "").strip().lower(), f.get("referenceName"))
for key in need_lookup:
display = by_display.get(key) or key
ref = lower_map.get(display.strip().lower())
if not ref:
# 宽松匹配: 显示名以配置词开头(如 Completed -> Completed Work)
for f in catalog:
name = f.get("name", "").strip().lower()
if name.startswith(display.strip().lower()):
ref = f.get("referenceName")
print(f"[字段] {key}: {display!r} 模糊匹配到 {f.get('name')!r} -> {ref}")
break
if not ref:
avail = ", ".join(sorted({f.get("name", "") for f in catalog if f.get("name")}))[:800]
raise SystemExit(
f"字段 {key} 的显示名 {display!r} 在服务器上找不到,请在 config.json 的 "
f"field_refs 里显式配置引用名。\n服务器字段(截断): {avail}"
)
refs[key] = ref
print(f"[字段] {key}: {display!r} -> {ref}")
return refs
# ---------------------------------------------------------------- 重复检测
def existing_titles(sess: requests.Session, base: str, project: str, iteration: str,
type_name: str) -> set[str]:
wiql = (
"SELECT [System.Title] FROM WorkItems "
f"WHERE [System.TeamProject] = '{project}' "
f"AND [System.WorkItemType] = '{type_name}' "
f"AND [System.IterationPath] = '{iteration}'"
)
data = tfs_wiql(sess, f"{base}/{project}/_apis/wit/wiql", wiql)
ids = [w["id"] for w in data.get("workItems", [])]
titles: set[str] = set()
for i in range(0, len(ids), 50):
chunk = ids[i:i + 50]
data = tfs_get(
sess,
f"{base}/_apis/wit/workitems",
params={"ids": ",".join(map(str, chunk)), "fields": "System.Title", "api-version": API_VER},
)
for item in data.get("value", []):
titles.add(item.get("fields", {}).get("System.Title", ""))
return titles
# ---------------------------------------------------------------- 构造与提交
def build_patch(row: dict, refs: dict, cfg: dict, iteration_full: str, area: str) -> list[dict]:
ops: list[dict] = []
def add(ref: str | None, value):
if not ref or value is None or value == "":
return
ops.append({"op": "add", "path": f"/fields/{ref}", "value": value})
add(refs["title"], row["Title"].strip())
add(refs["state"], (row.get("State") or cfg.get("default_state") or "To Do").strip())
add(refs["assigned_to"], (row.get("AssignedTo") or "").strip())
add(refs["iteration_path"], iteration_full)
if area:
add(refs["area_path"], area)
add(refs.get("financial_project"), (row.get("FinancialProject") or "").strip())
completed = (row.get("Completed") or "").strip()
if completed:
add(refs.get("completed"), float(completed) if "." in completed else int(completed))
log_date = parse_dt(row.get("LogDate"))
if log_date:
add(refs.get("log_date"), log_date)
# CreatedDate / ClosedDate 是系统字段,常规接口不可写;bypassRules=true 时部分模板可写。
created = parse_dt(row.get("CreatedDate"))
if created:
add(refs.get("created_date"), created)
closed = parse_dt(row.get("ClosedDate"))
if closed:
add(refs.get("closed_date"), closed)
return ops
def create_work_item(sess: requests.Session, base: str, project: str, type_name: str,
ops: list[dict], bypass_rules: bool) -> dict:
url = f"{base}/{project}/_apis/wit/workitems/${requests.utils.quote(type_name)}"
params = {"api-version": API_VER}
if bypass_rules:
params["bypassRules"] = "true"
headers = {"Content-Type": "application/json-patch+json"}
resp = tfs_send(sess, "patch", url, params=params, headers=headers,
data=json.dumps(ops, ensure_ascii=False))
if resp.status_code >= 400:
raise RuntimeError(f"PATCH {url} -> {resp.status_code}: {resp.text[:800]}")
return resp.json()
# ---------------------------------------------------------------- 父项挂接
def query_work_item_ids(sess: requests.Session, base: str, project: str,
type_name: str, iteration: str) -> list[int]:
wiql = (
"SELECT [System.Id] FROM WorkItems "
f"WHERE [System.TeamProject] = '{project}' "
f"AND [System.WorkItemType] = '{type_name}' "
f"AND [System.IterationPath] = '{iteration}'"
)
data = tfs_wiql(sess, f"{base}/{project}/_apis/wit/wiql", wiql)
return [w["id"] for w in data.get("workItems", [])]
def find_parent_id(sess: requests.Session, base: str, project: str, cfg: dict) -> int | None:
"""解析父工作项:优先 config.parent_id,其次按 parent_title 全项目精确匹配标题。"""
pid = str(cfg.get("parent_id") or "").strip()
if pid:
return int(pid)
title = (cfg.get("parent_title") or "").strip()
if not title:
return None
safe_title = title.replace("'", "''")
wiql = (
"SELECT [System.Id] FROM WorkItems "
f"WHERE [System.TeamProject] = '{project}' "
f"AND [System.Title] = '{safe_title}' "
"AND [System.WorkItemType] <> 'Task'"
)
data = tfs_wiql(sess, f"{base}/{project}/_apis/wit/wiql", wiql)
items = data.get("workItems", [])
if not items:
raise SystemExit(
f"按标题找不到父工作项: {title!r}\n"
f"请把 config.json 的 parent_title 改成积压工作里已有的条目标题,"
f"或直接填 parent_id。"
)
if len(items) > 1:
print(f"[父项] 警告: 标题 {title!r} 匹配到 {len(items)} 条,取最新创建的一条")
# 取 CreatedDate 最大(最新)的一条
return max(int(w["id"]) for w in items)
def task_has_parent(item: dict) -> bool:
for rel in item.get("relations") or []:
if rel.get("rel") == "System.LinkTypes.Hierarchy-Reverse":
return True
return False
def link_parent(sess: requests.Session, base: str, task_id: int, parent_id: int) -> None:
ops = [{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Hierarchy-Reverse",
"url": f"{base}/_apis/wit/workitems/{parent_id}",
},
}]
url = f"{base}/_apis/wit/workitems/{task_id}"
resp = tfs_send(
sess, "patch", url,
params={"api-version": API_VER},
headers={"Content-Type": "application/json-patch+json"},
data=json.dumps(ops),
)
if resp.status_code >= 400:
raise RuntimeError(f"挂接 #{task_id} -> #{parent_id} 失败 {resp.status_code}: {resp.text[:500]}")
def link_existing_tasks(sess: requests.Session, base: str, project: str, cfg: dict,
iteration_full: str, parent_id: int) -> int:
"""把已导入的同类型/同迭代 Task 补挂到父项下;已有父的跳过。"""
type_name = cfg["work_item_type"]
ids = query_work_item_ids(sess, base, project, type_name, iteration_full)
print(f"[补挂] 找到 {type_name} {len(ids)} 条,父项 #{parent_id}")
linked = skipped = failed = 0
for tid in ids:
try:
data = tfs_get(sess, f"{base}/_apis/wit/workitems/{tid}", params={"api-version": API_VER})
if task_has_parent(data):
skipped += 1
continue
link_parent(sess, base, tid, parent_id)
linked += 1
print(f"[补挂] OK #{tid} -> #{parent_id}")
except Exception as e:
failed += 1
print(f"[补挂] FAIL #{tid} -> {e}")
print(f"[补挂] 汇总: 成功 {linked} / 已有父跳过 {skipped} / 失败 {failed}")
return 0 if not failed else 1
# ---------------------------------------------------------------- 主流程
def main() -> int:
ap = argparse.ArgumentParser(description="TFS 2013 工作项批量导入")
ap.add_argument("--config", default=str(BASE_DIR / "config.json"))
ap.add_argument("--input", default=str(BASE_DIR / "data" / "work_items.csv"))
ap.add_argument("--dry-run", action="store_true", help="只校验不写入")
ap.add_argument("--skip-existing-titles", action="store_true", help="跳过服务器已存在的同标题项")
ap.add_argument("--list-fields", action="store_true", help="列出服务器字段表后退出")
ap.add_argument("--link-existing", action="store_true",
help="把已导入的同类型/同迭代工作项补挂到父项下(不新建)")
ap.add_argument("--limit", type=int, default=0, help="只处理前 N 条(调试用)")
args = ap.parse_args()
cfg = load_config(Path(args.config))
base = cfg["tfs_url"].rstrip("/")
project = cfg["project"]
type_name = cfg["work_item_type"]
iteration_cfg = cfg.get("iteration_path") or ""
iteration_full = f"{project}\\{iteration_cfg}" if iteration_cfg and not iteration_cfg.startswith(project) else iteration_cfg
area = cfg.get("area_path") or ""
bypass_rules = bool(cfg.get("bypass_rules", True))
# --link-existing 不读数据文件,直接进补挂流程
if args.link_existing:
sess = build_session(cfg)
parent_id = find_parent_id(sess, base, project, cfg)
if not parent_id:
raise SystemExit("--link-existing 需要配置 parent_title 或 parent_id")
print(f"[父项] #{parent_id}")
print(f"[迭代] {iteration_full}")
return link_existing_tasks(sess, base, project, cfg, iteration_full, parent_id)
rows = load_rows(Path(args.input))
if args.limit:
rows = rows[: args.limit]
print(f"[数据] 共 {len(rows)} 行待导入: {args.input}")
sess = build_session(cfg)
if args.list_fields:
data = tfs_get(sess, f"{base}/_apis/wit/fields", params={"api-version": API_VER})
for f in sorted(data.get("value", []), key=lambda x: x.get("name", "")):
print(f"{f.get('referenceName', ''):<55} {f.get('name', '')}")
return 0
refs = resolve_fields(sess, base, cfg)
print(f"[迭代] {iteration_full}")
parent_id = find_parent_id(sess, base, project, cfg)
if parent_id:
print(f"[父项] #{parent_id}")
else:
print("[父项] 未配置 parent_title/parent_id,导入的项不挂父链接")
known: set[str] = set()
if args.skip_existing_titles or args.dry_run:
try:
known = existing_titles(sess, base, project, iteration_full, type_name)
print(f"[去重] 服务器同类型/同迭代已有 {len(known)} 条")
except Exception as e:
print(f"[去重] 查询失败(继续): {e}")
ok = fail = skipped = 0
report_path = BASE_DIR / "data" / f"import_report_{time.strftime('%Y%m%d_%H%M%S')}.csv"
with report_path.open("w", encoding="utf-8-sig", newline="") as rf:
writer = csv.writer(rf)
writer.writerow(["行号", "Title", "结果", "WorkItemId", "错误"])
for idx, row in enumerate(rows, 1):
title = row["Title"].strip()
try:
if args.skip_existing_titles and title in known:
skipped += 1
writer.writerow([idx, title, "SKIP", "", "标题已存在"])
print(f"[{idx}/{len(rows)}] SKIP {title}")
continue
ops = build_patch(row, refs, cfg, iteration_full, area)
if args.dry_run:
ok += 1
writer.writerow([idx, title, "DRY", "", json.dumps(ops, ensure_ascii=False)[:200]])
print(f"[{idx}/{len(rows)}] DRY {title} ({len(ops)} ops)")
continue
result = create_work_item(sess, base, project, type_name, ops, bypass_rules)
wid = result.get("id")
if parent_id and wid:
try:
link_parent(sess, base, int(wid), parent_id)
print(f"[挂接] #{wid} -> 父项 #{parent_id}")
except Exception as e:
print(f"[挂接] FAIL #{wid} -> {e}")
ok += 1
writer.writerow([idx, title, "OK", wid, ""])
print(f"[{idx}/{len(rows)}] OK #{wid} {title}")
except Exception as e:
fail += 1
writer.writerow([idx, title, "FAIL", "", str(e)[:500]])
print(f"[{idx}/{len(rows)}] FAIL {title} -> {e}")
print(f"\n[汇总] 成功 {ok} / 跳过 {skipped} / 失败 {fail};报告: {report_path}")
return 1 if fail else 0
if __name__ == "__main__":
sys.exit(main())
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

+305
View File
@@ -0,0 +1,305 @@
#!/usr/bin/env python3
"""生成 TfsExcelImporter 的应用图标(app.ico / 预览图)。
纯标准库实现(本机没有 Pillow / numpy):用有向距离场(SDF)解析求覆盖率做
抗锯齿,再手写 PNG / ICO 容器,不依赖任何第三方包。
设计:蓝色渐变圆角方块 + 白色线性「上升箭头」字形(导入语义,
方向与界面「开始导入」按钮的 ArrowUp 一致)。按尺寸分档:
- 大尺寸:加顶部高光与 1px 内描边(立体感)
- 小尺寸(<=24):关掉高光/内描边、加粗描边并略微放大字形,避免糊成一团
用法:
python tools/make_icon.py # 生成 app.ico + tools/icon_preview.png
python tools/make_icon.py --only-preview # 只出预览图
"""
import argparse
import math
import os
import struct
import zlib
# ----------------------------------------------------------------- 设计参数
SIZES = [16, 20, 24, 32, 40, 48, 64, 128, 256]
COLOR_TOP = (0x44, 0x8E, 0xFA) # 顶部亮蓝
COLOR_BOT = (0x18, 0x42, 0xC4) # 底部深蓝
WHITE = (255, 255, 255)
TILE_MARGIN = 0.045
TILE_RADIUS = 0.235
def style(size):
"""按尺寸分档的视觉参数。"""
if size <= 20:
return dict(stroke=0.150, gloss=0.00, rim=0.00, ring=True, grow=1.08)
if size <= 24:
return dict(stroke=0.138, gloss=0.00, rim=0.00, ring=True, grow=1.06)
if size <= 40:
return dict(stroke=0.118, gloss=0.09, rim=0.14, ring=False, grow=1.02)
return dict(stroke=0.100, gloss=0.10, rim=0.17, ring=False, grow=1.00)
# 字形骨架(归一化坐标,单位方格)。全部是圆头胶囊,端点已按描边半径内缩过,
# 这样描边加粗时外形不会溢出画布。
# 返回 (箭头胶囊组, 副元素胶囊组, 副元素描边系数);副元素为空表示只画箭头。
def glyph_capsules(stroke, variant="arrow"):
if variant == "arrow":
# 只有箭头:上下留白对称(0.14~0.85),比例比带盒子时更大更饱满
arrow = [
(0.500, 0.270, 0.500, 0.790),
(0.262, 0.418, 0.500, 0.196),
(0.500, 0.196, 0.738, 0.418),
]
return arrow, [], 1.0
shaft_end = 0.700 if variant == "tray" else 0.650
arrow = [
# 箭杆 + 箭头两撇(V 形,圆头在顶点自然并成箭头)
(0.500, 0.235, 0.500, shaft_end),
(0.330, 0.375, 0.500, 0.205),
(0.500, 0.205, 0.670, 0.375),
]
if variant == "slot":
# 单根加粗横条("槽/落点"),无竖壁,小尺寸更干净
return arrow, [(0.250, 0.780, 0.750, 0.780)], 1.30
# 托盘:底边 + 两侧竖壁;底边端点落在竖壁中心线上,角部由此自然圆接
return arrow, [
(0.300, 0.800, 0.700, 0.800),
(0.300, 0.640, 0.300, 0.800),
(0.700, 0.640, 0.700, 0.800),
], 1.0
# ----------------------------------------------------------------- SDF 基础
def sd_round_rect(x, y, cx, cy, hw, hh, r):
dx = abs(x - cx) - (hw - r)
dy = abs(y - cy) - (hh - r)
ox = dx if dx > 0.0 else 0.0
oy = dy if dy > 0.0 else 0.0
inner = dx if dx > dy else dy
if inner > 0.0:
inner = 0.0
return math.hypot(ox, oy) + inner - r
def sd_seg(x, y, ax, ay, bx, by):
pax, pay = x - ax, y - ay
bax, bay = bx - ax, by - ay
den = bax * bax + bay * bay
t = 0.0 if den == 0.0 else max(0.0, min(1.0, (pax * bax + pay * bay) / den))
return math.hypot(pax - bax * t, pay - bay * t)
def clamp01(v):
return 0.0 if v < 0.0 else (1.0 if v > 1.0 else v)
def cov(d, size):
"""距离场 -> 覆盖率(1px 过渡带)。"""
return clamp01(0.5 - d * size)
# ----------------------------------------------------------------- 单尺寸渲染
def render(size, variant="tray"):
st = style(size)
# 只有箭头时没有「托盘」当配重,线条要更粗一点才站得住
stroke = st["stroke"] + (0.016 if variant == "arrow" else 0.0)
grow = st["grow"]
arrow, tray, tray_w = glyph_capsules(stroke, variant)
gr = stroke / 2.0
# 大尺寸下托盘描边略细于箭头:用「粗细」而不是「透明度」做主次(透明度压在深蓝上会发灰)
tray_k = tray_w * (1.0 if size <= 32 else 0.94)
tray_tone = 1.0
hw = 0.5 - TILE_MARGIN
rad = TILE_RADIUS
inner_shrink = 1.0 / size # 内描边宽度 = 1px
buf = bytearray(size * size * 4)
span = 1.0 - 2.0 * TILE_MARGIN
for py in range(size):
v = (py + 0.5) / size
# 字形整体缩放:把坐标拉回以 0.5 为心
gv = 0.5 + (v - 0.5) / grow
row_off = py * size * 4
for px in range(size):
u = (px + 0.5) / size
a = cov(sd_round_rect(u, v, 0.5, 0.5, hw, hw, rad), size)
if a <= 0.0:
continue
# 渐变(略偏对角线,避免纯竖条的死板)
t = clamp01(((v - TILE_MARGIN) * 0.82 + (u - TILE_MARGIN) * 0.18) / span)
cr = COLOR_TOP[0] + (COLOR_BOT[0] - COLOR_TOP[0]) * t
cg = COLOR_TOP[1] + (COLOR_BOT[1] - COLOR_TOP[1]) * t
cb = COLOR_TOP[2] + (COLOR_BOT[2] - COLOR_TOP[2]) * t
# 顶部高光
if st["gloss"] > 0.0:
g = st["gloss"] * clamp01(1.0 - (v - TILE_MARGIN) / 0.38)
cr += (255.0 - cr) * g
cg += (255.0 - cg) * g
cb += (255.0 - cb) * g
# 1px 内描边(沿边缘的细亮线,让方块边界更挺)
if st["rim"] > 0.0:
d_in = sd_round_rect(u, v, 0.5, 0.5, hw - inner_shrink,
hw - inner_shrink, rad - inner_shrink)
band = a - cov(d_in, size)
if band > 0.0:
k = st["rim"] * band
cr += (255.0 - cr) * k
cg += (255.0 - cg) * k
cb += (255.0 - cb) * k
# 字形:托盘(略细)+ 箭头(主调)
gu = 0.5 + (u - 0.5) / grow
for group, tone, k in ((tray, tray_tone, tray_k), (arrow, 1.0, 1.0)):
d = 1e9
rg = gr * k
for (ax, ay, bx, by) in group:
dd = sd_seg(gu, gv, ax, ay, bx, by) - rg
if dd < d:
d = dd
ag = cov(d, size) * a * tone
if ag > 0.0:
cr += (WHITE[0] - cr) * ag
cg += (WHITE[1] - cg) * ag
cb += (WHITE[2] - cb) * ag
i = row_off + px * 4
buf[i] = int(cr + 0.5)
buf[i + 1] = int(cg + 0.5)
buf[i + 2] = int(cb + 0.5)
buf[i + 3] = int(a * 255.0 + 0.5)
return buf
# ----------------------------------------------------------------- PNG / ICO
def png_bytes(w, h, rgba):
raw = bytearray()
for y in range(h):
raw.append(0)
raw += rgba[y * w * 4:(y + 1) * w * 4]
def chunk(tag, data):
return (struct.pack(">I", len(data)) + tag + data
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr)
+ chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
def dib_bytes(w, h, rgba):
"""32bpp 自下而上的 BMP(ICO 里的 DIB,含 AND 掩码)。"""
xor = bytearray()
for y in range(h - 1, -1, -1):
for x in range(w):
i = (y * w + x) * 4
xor += bytes((rgba[i + 2], rgba[i + 1], rgba[i], rgba[i + 3]))
and_stride = ((w + 31) // 32) * 4
and_mask = bytes(and_stride * h)
hdr = struct.pack("<IiiHHIIiiII", 40, w, h * 2, 1, 32, 0,
len(xor) + len(and_mask), 0, 0, 0, 0)
return hdr + bytes(xor) + and_mask
def ico_bytes(frames):
n = len(frames)
out = [struct.pack("<HHH", 0, 1, n)]
offset = 6 + 16 * n
body = b""
for size, payload in frames:
b = 0 if size >= 256 else size
out.append(struct.pack("<BBBBHHII", b, b, 0, 0, 1, 32, len(payload),
offset + len(body)))
body += payload
return b"".join(out) + body
# ----------------------------------------------------------------- 预览拼版
def blit(dst, dw, dh, src, sw, sh, ox, oy, scale=1):
for y in range(sh * scale):
sy = y // scale
dy = oy + y
if dy >= dh:
break
for x in range(sw * scale):
sx = x // scale
dx = ox + x
if dx >= dw:
break
si = (sy * sw + sx) * 4
di = (dy * dw + dx) * 4
dst[di:di + 4] = src[si:si + 4]
def preview(renders, path):
pad = 10
big = renders[256]
strip = SIZES[:-1] # 16..128
zoom = 4
strip_w = sum(s * zoom + pad for s in strip)
w = max(256 + 2 * pad, strip_w + pad)
h = 256 + strip_w * 0 + 64 + 128 * zoom + 3 * pad
h = 256 + pad * 3 + 128 * zoom
canvas = bytearray(w * h * 4)
for i in range(w * h):
canvas[i * 4 + 0] = 0xF3
canvas[i * 4 + 1] = 0xF4
canvas[i * 4 + 2] = 0xF6
canvas[i * 4 + 3] = 0xFF
blit(canvas, w, h, big, 256, 256, pad, pad, 1)
x = pad
y = 256 + pad * 2
for s in strip:
blit(canvas, w, h, renders[s], s, s, x, y + (128 - s) * zoom, zoom)
x += s * zoom + pad
with open(path, "wb") as f:
f.write(png_bytes(w, h, canvas))
return w, h
# ----------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="TfsExcelImporter/app.ico")
ap.add_argument("--preview", default="tools/icon_preview.png")
ap.add_argument("--only-preview", action="store_true")
ap.add_argument("--variant", default="arrow", choices=["arrow", "tray", "slot"])
args = ap.parse_args()
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
out_ico = args.out if os.path.isabs(args.out) else os.path.join(root, args.out)
out_png = (args.preview if os.path.isabs(args.preview)
else os.path.join(root, args.preview))
if args.variant != "arrow":
base, ext = os.path.splitext(out_png)
out_png = "%s_%s%s" % (base, args.variant, ext)
renders = {}
for s in SIZES:
renders[s] = render(s, args.variant)
print("rendered %dx%d" % (s, s))
frames = [(s, png_bytes(s, s, renders[s]) if s >= 256
else dib_bytes(s, s, renders[s])) for s in SIZES]
if not args.only_preview:
with open(out_ico, "wb") as f:
f.write(ico_bytes(frames))
print("wrote %s (%d bytes)" % (out_ico, os.path.getsize(out_ico)))
with open(os.path.splitext(out_png)[0] + "_256.png", "wb") as f:
f.write(png_bytes(256, 256, renders[256]))
w, h = preview(renders, out_png)
print("wrote %s (%dx%d)" % (out_png, w, h))
if __name__ == "__main__":
main()
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""查 exe 里到底嵌了哪套图标(PE 资源解析),可导出最大帧为 PNG 核对。
用途:换图标后 Windows 仍显示旧图标时,先确认「exe 里是新图标」还是「外壳图标缓存没刷」。
python tools/pe_icon.py dist/TfsExcelImporter.exe [out_256.png]
"""
import struct
import sys
import zlib
def u16(d, o):
return struct.unpack_from("<H", d, o)[0]
def u32(d, o):
return struct.unpack_from("<I", d, o)[0]
def parse_resources(path):
d = open(path, "rb").read()
pe = u32(d, 0x3C)
if d[pe:pe + 4] != b"PE\0\0":
raise SystemExit("不是 PE 文件")
coff = pe + 4
nsec = u16(d, coff + 2)
opt_size = u16(d, coff + 16)
opt = coff + 20
magic = u16(d, opt)
dd = opt + (96 if magic == 0x10B else 112)
rsrc_rva = u32(d, dd + 2 * 8)
sec = opt + opt_size
sections = []
for i in range(nsec):
s = sec + 40 * i
vsize, vaddr, rawsize, rawptr = (u32(d, s + 8), u32(d, s + 12),
u32(d, s + 16), u32(d, s + 20))
sections.append((vaddr, vsize, rawptr, rawsize))
def rva2off(rva):
for vaddr, vsize, rawptr, rawsize in sections:
if vaddr <= rva < vaddr + max(vsize, rawsize):
return rva - vaddr + rawptr
raise ValueError("rva %#x 不在任何节里" % rva)
base = rva2off(rsrc_rva)
out = []
def walk(off, path_ids):
nnamed, nid = u16(d, base + off + 12), u16(d, base + off + 14)
for i in range(nnamed + nid):
e = base + off + 16 + 8 * i
name_id, off_to = u32(d, e), u32(d, e + 4)
if off_to & 0x80000000:
walk(off_to & 0x7FFFFFFF, path_ids + [name_id])
else:
de = base + off_to
rva, size = u32(d, de), u32(d, de + 4)
o = rva2off(rva)
out.append((path_ids + [name_id], d[o:o + size]))
walk(0, [])
return out
def png_write(path, w, h, rgba):
raw = bytearray()
for y in range(h):
raw.append(0)
raw += rgba[y * w * 4:(y + 1) * w * 4]
def chunk(tag, data):
return (struct.pack(">I", len(data)) + tag + data
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
with open(path, "wb") as f:
f.write(b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
def dib_to_rgba(payload):
bw, bh2 = struct.unpack_from("<ii", payload, 4)
h = bh2 // 2
px = payload[40:40 + bw * h * 4]
out = bytearray(bw * h * 4)
for y in range(h):
sy = h - 1 - y
for x in range(bw):
si = (sy * bw + x) * 4
di = (y * bw + x) * 4
out[di] = px[si + 2]
out[di + 1] = px[si + 1]
out[di + 2] = px[si]
out[di + 3] = px[si + 3]
return bw, h, out
def main():
exe = sys.argv[1]
out_png = sys.argv[2] if len(sys.argv) > 2 else None
res = parse_resources(exe)
groups = [(p, b) for p, b in res if p[0] == 14]
icons = {(p[1] if len(p) > 1 else 0): b for p, b in res if p[0] == 3}
print("%s: RT_GROUP_ICON=%d RT_ICON=%d" % (exe, len(groups), len(icons)))
if not groups:
print("!! exe 里没有图标资源(会用系统默认 exe 图标)")
return
for path_ids, b in groups:
cnt, = struct.unpack_from("<H", b, 4)
print(" group %s: %d 帧" % (path_ids, cnt))
frames = []
for i in range(cnt):
w, h, cc, resv, planes, bc, sz, idx = struct.unpack_from("<BBBBHHIH", b, 6 + 14 * i)
frames.append((w or 256, idx, sz))
print(" 尺寸:", [f[0] for f in frames])
if out_png:
for size, idx, sz in frames:
if size == 256:
payload = icons.get(idx)
if payload and payload[:8] == b"\x89PNG\r\n\x1a\n":
open(out_png, "wb").write(payload)
print(" 已导出 256 PNG 帧 ->", out_png)
return
for size, idx, sz in frames:
if size == 48:
w, h, rgba = dib_to_rgba(icons[idx])
png_write(out_png, w, h, rgba)
print(" 已导出 48 DIB 帧 ->", out_png)
return
if __name__ == "__main__":
main()
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""冒烟验证:直接拉起 Release exe,截取真实窗口(含标题栏图标),存 PNG。
用途:确认 ApplicationIcon 与 Form.Icon 都生效、且换图标后窗口能正常起来。
纯标准库 + ctypes,不依赖任何第三方包。
"""
import ctypes
import os
import struct
import subprocess
import sys
import time
import zlib
from ctypes import wintypes as wt
u32 = ctypes.WinDLL("user32", use_last_error=True)
g32 = ctypes.WinDLL("gdi32", use_last_error=True)
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
u32.PrintWindow.argtypes = [wt.HWND, wt.HDC, wt.UINT]
u32.GetWindowRect.argtypes = [wt.HWND, ctypes.POINTER(wt.RECT)]
u32.GetWindowDC.argtypes = [wt.HWND]
u32.GetWindowDC.restype = wt.HDC
u32.GetWindowTextW.argtypes = [wt.HWND, wt.LPWSTR, ctypes.c_int]
u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
u32.IsWindowVisible.argtypes = [wt.HWND]
u32.SendMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, wt.LPARAM]
u32.SendMessageW.restype = ctypes.c_void_p
g32.CreateCompatibleDC.argtypes = [wt.HDC]
g32.CreateCompatibleDC.restype = wt.HDC
g32.CreateCompatibleBitmap.argtypes = [wt.HDC, ctypes.c_int, ctypes.c_int]
g32.CreateCompatibleBitmap.restype = wt.HBITMAP
g32.SelectObject.argtypes = [wt.HDC, wt.HGDIOBJ]
g32.SelectObject.restype = wt.HGDIOBJ
g32.GetDIBits.argtypes = [wt.HDC, wt.HBITMAP, wt.UINT, wt.UINT, ctypes.c_void_p,
ctypes.c_void_p, wt.UINT]
u32.ReleaseDC.argtypes = [wt.HWND, wt.HDC]
u32.ReleaseDC.restype = ctypes.c_int
u32.GetDC.argtypes = [wt.HWND]
u32.GetDC.restype = wt.HDC
u32.FillRect.argtypes = [wt.HDC, ctypes.POINTER(wt.RECT), wt.HBRUSH]
g32.DeleteObject.argtypes = [wt.HGDIOBJ]
g32.DeleteObject.restype = wt.BOOL
g32.DeleteDC.argtypes = [wt.HDC]
g32.DeleteDC.restype = wt.BOOL
g32.CreateSolidBrush.argtypes = [wt.DWORD]
g32.CreateSolidBrush.restype = wt.HBRUSH
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [("biSize", wt.DWORD), ("biWidth", wt.LONG), ("biHeight", wt.LONG),
("biPlanes", wt.WORD), ("biBitCount", wt.WORD),
("biCompression", wt.DWORD), ("biSizeImage", wt.DWORD),
("biXPelsPerMeter", wt.LONG), ("biYPelsPerMeter", wt.LONG),
("biClrUsed", wt.DWORD), ("biClrImportant", wt.DWORD)]
def bgra_to_rgba(buf):
"""GetDIBits 给的是 BGRA,PNG 要 RGBA。"""
out = bytearray(buf)
for i in range(0, len(out), 4):
out[i], out[i + 2] = out[i + 2], out[i]
return bytes(out)
def png(path, w, h, rgba):
raw = bytearray()
for y in range(h):
raw.append(0)
raw += rgba[y * w * 4:(y + 1) * w * 4]
def chunk(tag, data):
return (struct.pack(">I", len(data)) + tag + data
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
with open(path, "wb") as f:
f.write(b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
def find_window(pid, timeout=25.0):
result = []
@ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM)
def cb(hwnd, _):
p = wt.DWORD()
u32.GetWindowThreadProcessId(hwnd, ctypes.byref(p))
if p.value != pid or not u32.IsWindowVisible(hwnd):
return True
n = u32.GetWindowTextLengthW(hwnd)
if n <= 0:
return True
buf = ctypes.create_unicode_buffer(n + 2)
u32.GetWindowTextW(hwnd, buf, n + 2)
result.append((hwnd, buf.value))
return False
end = time.time() + timeout
while time.time() < end:
u32.EnumWindows(cb, 0)
if result:
return result[0]
time.sleep(0.3)
return None
def grab(hwnd, path):
r = wt.RECT()
u32.GetWindowRect(hwnd, ctypes.byref(r))
w, h = r.right - r.left, r.bottom - r.top
if w <= 0 or h <= 0:
raise RuntimeError("window rect empty")
src = u32.GetWindowDC(hwnd)
mem = g32.CreateCompatibleDC(src)
bmp = g32.CreateCompatibleBitmap(src, w, h)
old = g32.SelectObject(mem, bmp)
ok = u32.PrintWindow(hwnd, mem, 2) # PW_RENDERFULLCONTENT
bi = BITMAPINFOHEADER()
bi.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bi.biWidth, bi.biHeight = w, -h
bi.biPlanes, bi.biBitCount, bi.biCompression = 1, 32, 0
buf = ctypes.create_string_buffer(w * h * 4)
lines = g32.GetDIBits(mem, bmp, 0, h, buf, ctypes.byref(bi), 0)
g32.SelectObject(mem, old)
g32.DeleteObject(bmp)
g32.DeleteDC(mem)
u32.ReleaseDC(hwnd, src)
rgba = bgra_to_rgba(buf.raw)
png(path, w, h, rgba)
return w, h, ok, lines, rgba
def crop_zoom(src_png_w, src_png_h, rgba, cw, ch, scale, path, ox=0, oy=0):
out_w, out_h = cw * scale, ch * scale
dst = bytearray(out_w * out_h * 4)
for y in range(out_h):
sy = oy + y // scale
for x in range(out_w):
sx = ox + x // scale
si = (sy * src_png_w + sx) * 4
di = (y * out_w + x) * 4
dst[di:di + 4] = rgba[si:si + 4]
png(path, out_w, out_h, dst)
def main():
# 必须声明 DPI 感知:否则 GetWindowRect 返回的是被系统虚拟化(/缩放比)的坐标,
# 抓出来的图只有窗口左上角一块,高 DPI 下右/下必被裁掉。
# Win10 起用 shcore 的 per-monitor 感知最可靠,老系统退回 user32.SetProcessDPIAware。
aware = False
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # PROCESS_PER_MONITOR_DPI_AWARE
aware = True
except Exception:
pass
if not aware:
try:
aware = bool(u32.SetProcessDPIAware())
except Exception:
pass
print("dpi aware:", aware)
exe = sys.argv[1]
out = sys.argv[2]
icon_dump = sys.argv[3] if len(sys.argv) > 3 else None
proc = subprocess.Popen([exe], cwd=os.path.dirname(exe))
try:
got = find_window(proc.pid)
if not got:
print("FAIL: 没找到窗口(可能是启动崩溃),进程存活 =", proc.poll() is None)
if proc.poll() is None:
proc.terminate()
return 1
hwnd, title = got
print("window title:", title)
# WM_GETICON=0x7F, ICON_BIG=1 / ICON_SMALL=0
big = u32.SendMessageW(hwnd, 0x7F, 1, 0)
small = u32.SendMessageW(hwnd, 0x7F, 0, 0)
print("WM_GETICON big=%#x small=%#x" % (big or 0, small or 0))
time.sleep(0.6)
w, h, ok, lines, pixels = grab(hwnd, out)
print("printed %dx%d ok=%s lines=%d -> %s" % (w, h, ok, lines, out))
# 标题栏局部放大 4 倍,专门看图标
crop_zoom(w, h, pixels, min(300, w), min(44, h), 4,
os.path.splitext(out)[0] + "_titlebar.png", 0, 0)
print("titlebar crop ->", os.path.splitext(out)[0] + "_titlebar.png")
if icon_dump and big:
u32.DrawIconEx.argtypes = [wt.HDC, ctypes.c_int, ctypes.c_int, wt.HICON,
ctypes.c_int, ctypes.c_int, wt.UINT,
wt.HBRUSH, wt.UINT]
src = u32.GetDC(None)
mem = g32.CreateCompatibleDC(src)
size = 32
bmp = g32.CreateCompatibleBitmap(src, size, size)
old = g32.SelectObject(mem, bmp)
# 白底,避免透明区域看不清
brush = g32.CreateSolidBrush(0x00FFFFFF)
rect = wt.RECT(0, 0, size, size)
u32.FillRect(mem, ctypes.byref(rect), brush)
u32.DrawIconEx(mem, 0, 0, big, size, size, 0, None, 3) # DI_NORMAL
bi = BITMAPINFOHEADER()
bi.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bi.biWidth, bi.biHeight = size, -size
bi.biPlanes, bi.biBitCount, bi.biCompression = 1, 32, 0
buf2 = ctypes.create_string_buffer(size * size * 4)
g32.GetDIBits(mem, bmp, 0, size, buf2, ctypes.byref(bi), 0)
g32.SelectObject(mem, old)
g32.DeleteObject(bmp)
g32.DeleteObject(brush)
g32.DeleteDC(mem)
u32.ReleaseDC(None, src)
png(icon_dump, size, size, bgra_to_rgba(buf2.raw))
print("icon dumped ->", icon_dump)
finally:
time.sleep(0.2)
if proc.poll() is None:
proc.terminate()
return 0
if __name__ == "__main__":
sys.exit(main())