Compare commits

..
8 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
chenshoulin afed57047a fix: 更新图标和按钮样式以提升用户界面一致性
- 在 MainFormUi.cs 中,将“加载迭代列表”按钮的图标更改为 Fetch,更新“补挂父项”按钮的图标为 Tree,以增强视觉一致性。
- 在 Theme.cs 中,新增 Fetch 和 Tree 图标类型,并优化现有图标的绘制逻辑,确保在不同尺寸下的清晰度。
- debug.log 文件中添加了新的错误记录,便于后续调试和问题追踪。
2026-11-01 19:34:17 +08:00
chenshoulin dbe8ff2c08 feat: 添加系统 DPI 感知支持与界面优化
- 新增 app.manifest 文件以实现系统 DPI 感知,确保界面在不同缩放设置下正常显示。
- 更新 MainForm.cs 和 Theme.cs,调整控件布局和样式以适应 DPI 变化。
- 修改 README.md,增加关于 DPI 感知的说明。
- 新增 MainFormUi.cs,负责界面布局与状态呈现,优化用户体验。
- 新增 debug.log 文件以记录错误信息,便于调试和问题追踪。
2026-11-01 18:47:41 +08:00
24 changed files with 4573 additions and 954 deletions
+9
View File
@@ -4,6 +4,12 @@ obj/
*.user
*.suo
# 便携版分发目录(dotnet build 后把单文件 exe 拷进来)
dist/
# Fody(Costura)构建时自动生成
TfsExcelImporter/FodyWeavers.xsd
# Python
__pycache__/
*.py[cod]
@@ -23,3 +29,6 @@ data/work_items.csv
Thumbs.db
Desktop.ini
.DS_Store
# 运行时日志(WebView2/crashpad 报错输出)
debug.log
+74 -63
View File
@@ -12,31 +12,34 @@ TFS 2013 工作项批量导入工具集,用于把 Excel/CSV 里的工时台账
| 迭代 | `2026年Sprint\2026年Sprint10` |
| 认证 | 域账号 NTLM(内网直连,不走代理) |
## 两套工具,先用哪个
## 工具一览
| | [TfsExcelImporter](TfsExcelImporter)(C# WinForms) | [tfs_import.py](tfs_import.py)(Python CLI) |
| --- | --- | --- |
| 通信协议 | 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` 先校验 |
仓库只有一套工具:[TfsExcelImporter](TfsExcelImporter)(C# WinForms 桌面版),数据源为 `.xlsx`(默认模板随程序发布),图形界面预览后导入。
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/
├── tfs_import.py # Python 命令行导入器(REST)
├── config.json # Python 版配置
├── requirements.txt # requests / requests-ntlm
├── data/
│ └── work_items.example.csv # 列结构与示例行(UTF-8 BOM);真实台账不入库
│ └── work_items.csv # 本地工时台账(含人员/项目,不入库)
├── templates/
│ └── TFS导入模板.xlsx # 默认模板:csproj 随构建拷到 exe 目录,「导出Excel模板」原样复制它
└── TfsExcelImporter/ # C# WinForms 桌面版(主用)
│ └── TFS导入模板.xlsx # 默认模板:构建时嵌入 exe,「导出Excel模板」原样导出
├── 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.*
├── MainForm.cs # 界面与导入/修 Area 流程
├── 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 / 补挂父项流程
├── MainFormUi.cs # 界面外壳:步骤卡片布局、手风琴折叠、状态呈现
├── Theme.cs # 设计 token(颜色/字号/间距/缩放)与自绘控件
├── app.manifest # System DPI 感知,像素尺寸按缩放换算
├── TfsClient.cs # TFS Client OM 封装
├── ExcelService.cs # 读 Excel、导出默认模板、时间/数值归一
├── Config.cs # exe 同目录 config.json 读写
@@ -45,7 +48,7 @@ TFSImport/
## 快速开始
### C# 桌面版(主用)
### 桌面版
```powershell
dotnet build TfsExcelImporter.sln -c Release
@@ -53,48 +56,68 @@ dotnet build TfsExcelImporter.sln -c Release
TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe
```
「导出Excel模板」复制的是 exe 同目录的 `TFS导入模板.xlsx`(构建时自动拷过去);单独分发 exe 时要带上这个文件,否则该按钮会报「未找到默认模板文件」。
「导出Excel模板」优先用 exe 同目录的 `TFS导入模板.xlsx`(现场可替换),没有则从 exe 内嵌资源导出——**分发时只带一个 exe 就够,不用再附带模板文件**。
操作流程:
1. 填「TFS 连接」区:URL、项目、工作项类型、认证方式与域账号;内网保持「使用系统代理」**不勾选**。
2. 点「加载迭代列表」,选择目标迭代。
3. 点「导出Excel模板」拿到默认模板,或「浏览...」选择已有 `.xlsx`;点「预览数据」核对。
4. 需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项)。
5. 点「开始导入 TFS」,日志区逐行输出 `OK/SKIP/FAIL` 与工作项 ID。
6. 历史数据 Area 不对时用「按迭代修Area」批量纠正。
### Python 版
应用图标是 `TfsExcelImporter/app.ico`(蓝色渐变圆角底 + 白色上升箭头),csproj 里 `ApplicationIcon` 写进 exe 的 Win32 图标资源,同时以托管资源再嵌一份给 `Form.Icon` 用(多尺寸帧,高 DPI 下不糊)。要改设计就改 `tools/make_icon.py` 后重跑,覆盖 `app.ico` 再编译:
```powershell
pip install -r requirements.txt
python tfs_import.py --dry-run # 只校验数据与字段映射,不写入
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
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
```
每次运行在 `data/import_report_<时间戳>.csv` 生成逐行结果报告(行号 / Title / 结果 / WorkItemId / 错误)。
界面按 4 步排:顶部状态条常驻显示服务器/项目/类型与连接状态,四张卡片一次只展开一张(展开一张会把其它收成一行摘要),预览表格永远占满剩余高度。
1. **步骤 1 连接**:填 URL、项目、工作项类型与账号密码(认证固定 NTLM,用户名可写 `user` 或 `DOMAIN\user`),点「测试连接」——右上状态灯变绿即连通。
2. **步骤 2 选数据**:点「加载迭代列表」选目标迭代(也可手填完整路径);**Area 路径同样在这一步填,且为必填**(新导入的工作项都写到该 Area,留空会导致团队视图看不到,所以导入前会被拦下),点「加载 Area 列表」可从服务器拉真实 Area 树,也可手填完整路径;点「导出 Excel 模板」拿默认模板,或「浏览...」选已有 `.xlsx`。需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项),点「加载 PBI 列表」可拉出该迭代下的 Product Backlog Item(下拉显示「#Id 标题 · 状态」,选中自动回填纯 Id),也可直接手输 Id。字段校验**不可绕过**,不合法时日志会直接告诉你改哪一列。
3. **步骤 3 预览核对**:选完文件自动读表,表格里逐行核对;缺迭代/文件路径无效时红字直接标在对应输入框下方,不再弹框。
4. **步骤 4 导入**:底部操作条点「开始导入 TFS」,进度条 + `n/m` + 成功/跳过/失败三个计数实时更新,日志抽屉逐行输出 `OK/SKIP/FAIL` 与工作项 ID;跑完点「打开报告 CSV」看逐行结果。主按钮右侧的「跳过已存在标题」(默认不勾)是去重开关,按「项目/类型/迭代 + 标题」判重——它只作用于导入这一个动作,勾上后立即生效于下一次导入;导入跑起来后该勾选框会置灰(开关在一次导入开始时只读一次)。
5. 历史数据 Area 不对、或漏挂父项时,展开底部「高级工具」用「按迭代修 Area」「补挂父项」批量纠正;两者都按第 2 步的「目标迭代 / Area 路径」筛选已有工作项。
桌面版按 System DPI 感知实现,界面尺寸随 Windows 显示缩放换算;**改了显示缩放比例要重启程序**才生效。
### 便携版(单 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
mkdir dist
copy TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe dist\
```
把 `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`) |
| `iteration_path` | 可只写 `2026年Sprint\2026年Sprint10`,程序自动补项目名前缀 |
| `auth.mode` | `ntlm`(域账号,典型)/ `basic` / `default`(当前 Windows 凭据,仅桌面版) |
| `field_refs` | 语义名 → 字段引用名;自定义字段留空时按 `resolve_fields_by_display_name` 的显示名在服务器字段表里查(支持前缀模糊匹配,如 `Completed` → `Completed Work`) |
| `parent_title` / `parent_id` | 父工作项,二选一;按标题匹配不到会直接报错并提示改用 `parent_id` |
| `bypass_rules` | 是否请求绕过字段校验规则;桌面版走 Client OM(14.x 无 `SaveFlags.BypassRules`),实际由服务器规则决定 |
| `skip_existing_titles` | 同项目/同类型/同迭代下按标题去重 |
| `TfsUrl` / `Project` / `WorkItemType` | 目标集合、项目、工作项类型(`Task` 或 `Product Backlog Item`) |
| `IterationPath` | 可只写 `2026年Sprint\2026年Sprint10`,程序自动补项目名前缀 |
| `AreaPath` | 区域路径;导入必填,界面上与迭代同在第 2 步卡片(可点「加载 Area 列表」从 TFS 分类树拉取),值直接写进 `System.AreaPath` |
| `Username` / `Password` | 认证固定 NTLM,用户名可写 `user` 或 `DOMAIN\user` |
| `FinancialProjectRef` / `CompletedRef` / `LogDateRef` / `OriginalEstimateRef` | 自定义字段引用名;留空则按显示名在服务器字段表里查(支持前缀模糊匹配,如 `Completed` → `Completed Work`) |
| `ParentPbiId` | 所有 Task 默认挂接的父 PBI Id(界面上可从「加载 PBI 列表」里挑,落库只存纯数字);Excel 每行 `PBI Id` 列可覆盖 |
| `SkipExistingTitles` | 同项目/同类型/同迭代下按标题去重;**默认不勾选**,需要去重时手动勾 |
| `DefaultState` | Excel `State` 列留空时的默认值 |
| `LastExcelPath` | 上次选中的数据文件,界面回填用 |
> 配置里含明文密码,请勿提交到共享仓库;`config.json` 保持空值,凭据本地填写。
## Excel / CSV 列
## Excel 列
桌面版 Excel 模板 = 仓库里的 `templates\TFS导入模板.xlsx`,界面「导出Excel模板」直接复制它:
@@ -110,37 +133,25 @@ python tfs_import.py --input other.csv --limit 5
系统日期列(`Created Date` / `Closed Date`)已从模板移除:`System.CreatedDate` 由服务器按导入时间填写,`Microsoft.VSTS.Common.ClosedDate` 不再写入、保持为空。
Python 版仍读 `data/work_items.example.csv` 的旧列(含 `CreatedDate`、`ClosedDate`、`Notes`),未随模板调整。
真实台账含人员与项目信息,不入库;本地准备数据文件:
```powershell
copy data\work_items.example.csv data\work_items.csv # Python 版默认读这个路径,已在 .gitignore 里
```
真实台账含人员与项目信息,不入库,放在 `data\work_items.csv`(已在 `.gitignore` 里)。
- 表头按名匹配,顺序不限,`AssignedTo` / `Assigned To` 等价;缺列按模板顺序兜底,但该列已被别的表头占用时不套用位置(旧版模板文件不会串列)。
- 空 `Title` 的行直接跳过;`State` 为空时用 `default_state`;未识别的列(如 `Group`)忽略。
- 空 `Title` 的行直接跳过;`State` 为空时用 `DefaultState`;未识别的列(如 `Group`)忽略。
- 日期支持 `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)。
- **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 → 还原状态」的状态循环,中途失败回滚状态。
- **`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 或网络断开,不是代码问题;桌面版会对这类异常附加排查提示。
## 验证
改动 Python 版后至少跑:
```powershell
python -m py_compile tfs_import.py
python tfs_import.py --dry-run
```
桌面版改完跑一次 `--limit` 级别的小批量导入(先删服务器已有同标题项或开启跳过),并在积压工作页展开父项确认子任务可见。
桌面版改完,先用只含几行的 Excel 跑一次小批量导入(先删服务器已有同标题项或勾操作条上「跳过已存在标题」),再在积压工作页展开父项确认子任务可见;改动涉及界面布局或图标时,跑 `python tools/win_screenshot.py` 抓图核对。确认无误后再跑全量。
+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.IO;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
namespace TfsExcelImporter
@@ -18,18 +20,50 @@ namespace TfsExcelImporter
// 可选:区域路径
public string AreaPath { get; set; } = "";
// ntlm | basic | default(当前 Windows 凭据)
public string AuthMode { get; set; } = "ntlm";
// 认证固定 NTLM:用户名可写 user,也可写 DOMAIN\user
public string Username { get; set; } = "";
// 明文密码只存在于内存(UI 回显需要);落盘一律走 DPAPI 加密的 PasswordEnc。
// [JsonIgnore] 防止明文随 SerializeObject 写进 config.json。
[JsonIgnore]
public string Password { get; set; } = "";
public string Domain { get; set; } = "";
// 是否走 IE 系统代理。内网 TFS 请保持 false(直连);
// 代理/网关常对 HttpClient 请求返回 502(浏览器例外名单直连,.NET 不一定继承)
public bool UseSystemProxy { get; set; } = false;
// 兼容旧版明文键:反序列化时承接旧 config.json 的 "Password",下次 Save 自动转为加密存储。
// getter 恒返 null,序列化不再输出明文键。
[JsonProperty("Password", NullValueHandling = NullValueHandling.Ignore)]
private string LegacyPassword { get { return null; } set { if (!string.IsNullOrEmpty(value)) Password = value; } }
public bool BypassRules { get; set; } = true;
public bool SkipExistingTitles { get; set; } = true;
// DPAPI(CurrentUser) 加密后的密码,Base64;同机同用户可解,拷到别的机器/账户需重输。
[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";
// 自定义字段引用名;留空则按 DisplayName 自动解析
@@ -44,11 +78,39 @@ namespace TfsExcelImporter
// 父 Product Backlog Item:所有 Task 默认挂接的 PBI Id(如 219975);Excel 每行 PBI Id 列可覆盖
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"); }
}
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()
{
try
@@ -56,7 +118,16 @@ namespace TfsExcelImporter
if (File.Exists(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)
@@ -68,14 +139,30 @@ namespace TfsExcelImporter
public void Save()
{
// 落盘前把内存中的明文加密;Password 本身带 [JsonIgnore] 不会写出
PasswordEnc = string.IsNullOrEmpty(Password) ? "" : Protect(Password);
var json = JsonConvert.SerializeObject(this, Formatting.Indented);
try
{
File.WriteAllText(ConfigPath, JsonConvert.SerializeObject(this, Formatting.Indented));
File.WriteAllText(ConfigPath, json);
return;
}
catch (Exception ex)
{
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.IO;
using System.Linq;
using System.Security.Cryptography;
using ClosedXML.Excel;
namespace TfsExcelImporter
@@ -22,7 +23,8 @@ namespace TfsExcelImporter
/// <summary>
/// Excel 读取与默认模板。模板内容(列宽、示例行、样式)只在
/// templates\TFS导入模板.xlsx 里维护,随构建复制到 exe 目录后原样导出。
/// templates\TFS导入模板.xlsx 里维护,构建时作为嵌入资源打进 exe;
/// 若 exe 同目录存在同名文件则优先用它(现场可替换模板而不用重编译)。
/// 列: Title | State | Assigned To | FinancialProject | Completed | LogDate | PBI Id | Description
/// </summary>
public static class ExcelService
@@ -44,13 +46,127 @@ namespace TfsExcelImporter
// --------------------------------------------------------- 默认模板
/// <summary>把随程序发布的默认模板原样复制到目标路径。</summary>
public static void CopyTemplate(string path)
/// <summary>exe 同目录的模板路径(现场可替换,存在时优先于内嵌模板)。</summary>
public static string LocalTemplatePath
{
var src = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TemplateFileName);
if (!File.Exists(src))
throw new FileNotFoundException("未找到默认模板文件: " + src, src);
File.Copy(src, path, true);
get { return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TemplateFileName); }
}
/// <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>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+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]
private static void Main()
{
// 单文件分发时 native DLL 从内嵌资源释放并预加载(TFS Client OM 需要)
NativeLibraryLoader.EnsureLoaded();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
+205 -40
View File
@@ -23,31 +23,18 @@ namespace TfsExcelImporter
public TfsClient(AppConfig cfg)
{
ICredentials cred;
var mode = (cfg.AuthMode ?? "ntlm").ToLowerInvariant();
if (mode == "default")
{
cred = CredentialCache.DefaultCredentials;
}
else
{
var user = string.IsNullOrEmpty(cfg.Domain) ? cfg.Username : cfg.Domain + "\\" + cfg.Username;
cred = new NetworkCredential(user, cfg.Password ?? "");
}
// 认证固定 NTLM:用户名可写 user(用当前登录域),也可写 DOMAIN\user 显式指定域。
var user = (cfg.Username ?? "").Trim();
var pwd = cfg.Password ?? "";
var sep = user.IndexOf('\\');
ICredentials cred = sep > 0
? new NetworkCredential(user.Substring(sep + 1), pwd, user.Substring(0, sep))
: new NetworkCredential(user, pwd);
_tpc = new TfsTeamProjectCollection(new Uri(cfg.TfsUrl), cred);
// TFS OM 内部用 HttpWebRequest 传输,默认跟随 IE 系统代理——实测代理会拦内网 TFS 返回 502。
// 默认直连;勾选"使用系统代理"时保留系统代理并带 Windows 凭据过代理认证。
if (!cfg.UseSystemProxy)
{
WebRequest.DefaultWebProxy = new WebProxy(); // 空 WebProxy = 不走代理,直连
}
else
{
var p = WebRequest.DefaultWebProxy ?? new WebProxy();
p.Credentials = CredentialCache.DefaultCredentials;
WebRequest.DefaultWebProxy = p;
}
// 因此固定直连:把 DefaultWebProxy 置空,不读取本机系统代理设置。
WebRequest.DefaultWebProxy = new WebProxy();
}
/// <summary>WorkItemStore 惰性初始化(首次调用会下载字段/类型元数据,耗时数秒属正常)。</summary>
@@ -101,10 +88,30 @@ namespace TfsExcelImporter
return null;
}
// ------------------------------------------------------------- 迭代
// ------------------------------------------------------------- 迭代 / Area
/// <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(() =>
{
@@ -114,13 +121,13 @@ namespace TfsExcelImporter
throw new InvalidOperationException("项目不存在或无权访问: " + project);
var structures = css.ListStructures(proj.Uri);
var iterations = structures.FirstOrDefault(n => n.StructureType == "ProjectLifecycle")
?? structures.FirstOrDefault(n => (n.Name ?? "").IndexOf("Iteration", StringComparison.OrdinalIgnoreCase) >= 0);
if (iterations == null)
throw new InvalidOperationException("未找到 Iterations(ProjectLifecycle) 结构");
var root = structures.FirstOrDefault(n => string.Equals(n.StructureType, structureType, StringComparison.OrdinalIgnoreCase))
?? structures.FirstOrDefault(n => (n.Name ?? "").IndexOf(nameHint, StringComparison.OrdinalIgnoreCase) >= 0);
if (root == null)
throw new InvalidOperationException($"未找到 {label} 结构(StructureType={structureType})");
// GetNodesXml 深度展开全树;Node 元素的 Path 属性为分类节点路径
var tree = css.GetNodesXml(new[] { iterations.Uri }, true);
// 深度展开全树;Node 元素的 Path 属性为分类节点路径
var tree = css.GetNodesXml(new[] { root.Uri }, true);
var raw = new List<string>();
if (tree != null)
{
@@ -133,20 +140,20 @@ namespace TfsExcelImporter
return raw;
});
var result = list.Select(p => NormalizeIterationPath(p, project))
var result = list.Select(p => NormalizeNodePath(p, project))
.Where(p => p != null)
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(p => p, StringComparer.OrdinalIgnoreCase)
.ToList();
log?.Invoke($"迭代列表来源: TFS OM ICommonStructureService({result.Count} 个)");
log?.Invoke($"{label}列表来源: TFS OM ICommonStructureService({result.Count} 个)");
return result;
}
/// <summary>
/// 节点路径归一化为工作项 IterationPath(项目\子...)。
/// 分类节点路径归一化为工作项字段值(项目\子...),迭代与 Area 共用。
/// 兼容:含/不含项目名前缀、含/不含结构根段(Iteration/Iterations/Area/Areas)。
/// </summary>
private static string NormalizeIterationPath(string nodePath, string project)
private static string NormalizeNodePath(string nodePath, string project)
{
if (string.IsNullOrWhiteSpace(nodePath)) return null;
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);
}
// ------------------------------------------------------------- 父项(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>
@@ -187,14 +285,16 @@ namespace TfsExcelImporter
/// <summary>
/// 创建工作项(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 为服务器管理的只读字段,无法写入(取导入时间);
/// Microsoft.VSTS.Common.ClosedDate 在 State=Done 时按普通规则通常可写:尝试写入,
/// 校验或保存失败则清空该字段降级为普通保存(保证行导入成功)。
/// parentPbiId 非空时,通过 System.LinkTypes.Hierarchy(Reverse=Parent) 挂接到该 PBI。
/// </summary>
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(() =>
{
@@ -269,14 +369,77 @@ namespace TfsExcelImporter
return null;
}
/// <summary>
/// 把 wi.Validate() 的结果整理成「字段(原因) → 怎么改」的单行提示。
/// 单行是硬要求:这段文字会写进 import_report.csv,换行会破坏 CSV 的行结构。
/// </summary>
private static string CheckInvalid(WorkItem wi)
{
var invalid = wi.Validate();
if (invalid.Count == 0) return null;
var names = new StringBuilder();
var sb = new StringBuilder();
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>
@@ -315,7 +478,9 @@ namespace TfsExcelImporter
{
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.WorkItemType] = '{EscapeWiql(workItemType)}' AND " +
$"[System.IterationPath] = '{EscapeWiql(iterationPath)}' AND " +
+33 -4
View File
@@ -9,6 +9,12 @@
<AssemblyTitle>TFS Excel 导入工具</AssemblyTitle>
<Product>TFS Excel 导入工具</Product>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<!-- System DPI 感知:界面像素尺寸按 Theme.Px() 换算,见 app.manifest -->
<ApplicationManifest>app.manifest</ApplicationManifest>
<!-- exe 图标(资源管理器/任务栏/快捷方式)。多尺寸 ICO 由 tools/make_icon.py 生成 -->
<ApplicationIcon>app.ico</ApplicationIcon>
<!-- 便携单文件:Costura 把所有依赖 DLL 嵌入 exe,运行时自动解析 -->
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup>
<ItemGroup>
@@ -20,16 +26,39 @@
<PackageReference Include="Microsoft.TeamFoundationServer.ExtendedClient" Version="14.*" />
<!-- 无需安装 VS 也可用 dotnet build 编译 net48 -->
<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>
<None Update="config.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<!-- 默认导入模板:随 exe 一起发布,「导出Excel模板」原样复制这份文件 -->
<Content Include="..\templates\TFS导入模板.xlsx" Link="TFS导入模板.xlsx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<!--
图标同时以「托管资源」嵌一份:窗口标题栏/任务栏用 Form.Icon,
从内嵌 ICO 取可以得到全部 9 个尺寸帧;若走 Icon.ExtractAssociatedIcon
只能拿到系统默认那一档,高 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>
</Project>
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="TfsExcelImporter.app"/>
<!--
System DPI 感知:进程启动时按系统缩放取一次 DPI,Theme.Px() 据此换算所有像素尺寸。
刻意不用 PerMonitorV2——本程序没有跨显示器迁移场景,而运行中改缩放需要重建整套控件树。
改了 Windows 显示缩放比例后需重启程序才会按新比例重排。
-->
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">System</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10/11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
</assembly>
+2 -6
View File
@@ -3,14 +3,10 @@
"Project": "Tools_Dev",
"WorkItemType": "Task",
"IterationPath": "",
"AreaPath": "Tools_Dev\\DataTechnologies",
"AuthMode": "ntlm",
"AreaPath": "",
"Username": "",
"Password": "",
"Domain": "",
"UseSystemProxy": false,
"BypassRules": true,
"SkipExistingTitles": true,
"SkipExistingTitles": false,
"DefaultState": "To Do",
"FinancialProjectRef": "",
"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
-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())