Compare commits
5
Commits
d055b415fa
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe23e1c64a | ||
|
|
14f5e32262 | ||
|
|
ffc210f827 | ||
|
|
8824a81758 | ||
|
|
8a6f9d55bc |
@@ -29,3 +29,6 @@ data/work_items.csv
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
.DS_Store
|
||||
|
||||
# 运行时日志(WebView2/crashpad 报错输出)
|
||||
debug.log
|
||||
|
||||
@@ -12,33 +12,25 @@ 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 # 默认模板:构建时嵌入 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/ # C# WinForms 桌面版
|
||||
├── TfsExcelImporter.csproj # net48 + ClosedXML + TFS ExtendedClient 14.*
|
||||
├── FodyWeavers.xml # Costura 单文件打包配置(便携版)
|
||||
├── NativeLibraryLoader.cs # 释放并预加载内嵌的 TFS native DLL
|
||||
@@ -56,7 +48,7 @@ TFSImport/
|
||||
|
||||
## 快速开始
|
||||
|
||||
### C# 桌面版(主用)
|
||||
### 桌面版
|
||||
|
||||
```powershell
|
||||
dotnet build TfsExcelImporter.sln -c Release
|
||||
@@ -75,11 +67,11 @@ python tools/win_screenshot.py TfsExcelImporter\bin\Release\net48\TfsExcelImport
|
||||
|
||||
界面按 4 步排:顶部状态条常驻显示服务器/项目/类型与连接状态,四张卡片一次只展开一张(展开一张会把其它收成一行摘要),预览表格永远占满剩余高度。
|
||||
|
||||
1. **步骤 1 连接**:填 URL、项目、工作项类型、认证方式与域账号,点「测试连接」——右上状态灯变绿即连通;内网保持「使用系统代理」**不勾选**。
|
||||
2. **步骤 2 选数据**:点「加载迭代列表」选目标迭代(也可手填完整路径);点「导出 Excel 模板」拿默认模板,或「浏览...」选已有 `.xlsx`。需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项)。
|
||||
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」「补挂父项」批量纠正;Area 路径也在这一栏里填(以前只能手改 config.json)。
|
||||
4. **步骤 4 导入**:底部操作条点「开始导入 TFS」,进度条 + `n/m` + 成功/跳过/失败三个计数实时更新,日志抽屉逐行输出 `OK/SKIP/FAIL` 与工作项 ID;跑完点「打开报告 CSV」看逐行结果。主按钮右侧的「跳过已存在标题」(默认不勾)是去重开关,按「项目/类型/迭代 + 标题」判重——它只作用于导入这一个动作,勾上后立即生效于下一次导入;导入跑起来后该勾选框会置灰(开关在一次导入开始时只读一次)。
|
||||
5. 历史数据 Area 不对、或漏挂父项时,展开底部「高级工具」用「按迭代修 Area」「补挂父项」批量纠正;两者都按第 2 步的「目标迭代 / Area 路径」筛选已有工作项。
|
||||
|
||||
桌面版按 System DPI 感知实现,界面尺寸随 Windows 显示缩放换算;**改了显示缩放比例要重启程序**才生效。
|
||||
|
||||
@@ -105,39 +97,27 @@ copy TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe dist\
|
||||
|
||||
前提:目标机需有 .NET Framework 4.8(Win10 1903+ / Win11 系统自带,一般无需额外安装)。`FodyWeavers.xml` 是 Costura 的打包配置,删掉它或用 `-p:FodyDisable=true` 构建即回到「exe + 一堆 DLL」的普通输出。
|
||||
|
||||
### Python 版
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
每次运行在 `data/import_report_<时间戳>.csv` 生成逐行结果报告(行号 / Title / 结果 / WorkItemId / 错误)。
|
||||
|
||||
## 配置说明
|
||||
|
||||
桌面版的配置落在 exe 同目录的 `config.json`(界面改动后自动写回);exe 目录不可写时回退到 `%AppData%\TfsExcelImporter\config.json`。
|
||||
|
||||
配置的语义、留空字段如何解析见 [tfs_import.py:49](tfs_import.py#L49) 与 [Config.cs](TfsExcelImporter/Config.cs),关键字段:
|
||||
配置的语义、留空字段如何解析见 [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模板」直接复制它:
|
||||
|
||||
@@ -153,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` 抓图核对。确认无误后再跑全量。
|
||||
|
||||
@@ -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 自动解析
|
||||
@@ -84,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)
|
||||
@@ -96,6 +139,8 @@ namespace TfsExcelImporter
|
||||
|
||||
public void Save()
|
||||
{
|
||||
// 落盘前把内存中的明文加密;Password 本身带 [JsonIgnore] 不会写出
|
||||
PasswordEnc = string.IsNullOrEmpty(Password) ? "" : Protect(Password);
|
||||
var json = JsonConvert.SerializeObject(this, Formatting.Indented);
|
||||
try
|
||||
{
|
||||
|
||||
@@ -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
|
||||
@@ -45,34 +46,128 @@ namespace TfsExcelImporter
|
||||
|
||||
// --------------------------------------------------------- 默认模板
|
||||
|
||||
/// <summary>
|
||||
/// 把默认模板原样复制到目标路径。优先用 exe 同目录的同名文件(可由现场替换),
|
||||
/// 没有则从 exe 内嵌资源释放——单文件便携分发时无需附带模板。
|
||||
/// </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))
|
||||
{
|
||||
File.Copy(src, path, true);
|
||||
return;
|
||||
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)
|
||||
throw new FileNotFoundException(
|
||||
"未找到默认模板:exe 内嵌资源与同目录 " + TemplateFileName + " 均缺失", src);
|
||||
if (name == null) return null;
|
||||
|
||||
using (var input = asm.GetManifestResourceStream(name))
|
||||
{
|
||||
if (input == null) throw new FileNotFoundException("无法读取内嵌模板资源: " + name, src);
|
||||
using (var output = File.Create(path))
|
||||
input.CopyTo(output);
|
||||
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; }
|
||||
}
|
||||
|
||||
// --------------------------------------------------------- 读取数据
|
||||
|
||||
|
||||
+335
-82
@@ -35,23 +35,29 @@ namespace TfsExcelImporter
|
||||
|
||||
private void WireEvents()
|
||||
{
|
||||
_cmbAuth.SelectedIndexChanged += (s, e) => { UpdateAuthUi(); OnFieldChanged(); };
|
||||
_btnTest.Click += async (s, e) => await TestConnectionAsync();
|
||||
_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();
|
||||
_btnPreview.Click += (s, e) => PreviewData();
|
||||
_btnPreview.Click += async (s, e) => await PreviewDataAsync();
|
||||
_btnImport.Click += async (s, e) => await ImportAsync();
|
||||
_btnFixArea.Click += async (s, e) => await FixAreaAsync();
|
||||
_btnLinkParent.Click += async (s, e) => await LinkParentAsync();
|
||||
|
||||
foreach (var tb in new[] { _txtUrl, _txtProject, _txtType, _txtUser, _txtPwd, _txtDomain,
|
||||
_txtExcel, _txtParentPbi, _txtAreaPath })
|
||||
foreach (var tb in new[] { _txtUrl, _txtProject, _txtType, _txtUser, _txtPwd, _txtExcel })
|
||||
tb.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();
|
||||
_chkBypass.CheckedChanged += (s, e) => OnFieldChanged();
|
||||
_chkProxy.CheckedChanged += (s, e) => OnFieldChanged();
|
||||
|
||||
FormClosing += (s, e) => { try { SaveUiToConfig(); } catch { } };
|
||||
}
|
||||
@@ -62,37 +68,19 @@ namespace TfsExcelImporter
|
||||
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()
|
||||
{
|
||||
_txtUrl.Text = _cfg.TfsUrl;
|
||||
_txtProject.Text = _cfg.Project;
|
||||
_txtType.Text = _cfg.WorkItemType;
|
||||
_cmbAuth.SelectedItem = _cfg.AuthMode;
|
||||
if (_cmbAuth.SelectedItem == null) _cmbAuth.SelectedItem = "ntlm";
|
||||
_txtUser.Text = _cfg.Username;
|
||||
_txtPwd.Text = _cfg.Password;
|
||||
_txtDomain.Text = _cfg.Domain;
|
||||
_chkProxy.Checked = _cfg.UseSystemProxy;
|
||||
_cmbIteration.Text = _cfg.IterationPath;
|
||||
_txtExcel.Text = _cfg.LastExcelPath;
|
||||
_txtAreaPath.Text = _cfg.AreaPath;
|
||||
_cmbArea.Text = _cfg.AreaPath;
|
||||
_chkSkip.Checked = _cfg.SkipExistingTitles;
|
||||
_chkBypass.Checked = _cfg.BypassRules;
|
||||
_txtParentPbi.Text = _cfg.ParentPbiId;
|
||||
UpdateAuthUi();
|
||||
_cmbParent.Text = _cfg.ParentPbiId;
|
||||
}
|
||||
|
||||
private void SaveUiToConfig()
|
||||
@@ -100,17 +88,13 @@ namespace TfsExcelImporter
|
||||
_cfg.TfsUrl = _txtUrl.Text.Trim();
|
||||
_cfg.Project = _txtProject.Text.Trim();
|
||||
_cfg.WorkItemType = _txtType.Text.Trim();
|
||||
_cfg.AuthMode = _cmbAuth.SelectedItem != null ? _cmbAuth.SelectedItem.ToString() : "ntlm";
|
||||
_cfg.Username = _txtUser.Text.Trim();
|
||||
_cfg.Password = _txtPwd.Text;
|
||||
_cfg.Domain = _txtDomain.Text.Trim();
|
||||
_cfg.UseSystemProxy = _chkProxy.Checked;
|
||||
_cfg.IterationPath = _cmbIteration.Text.Trim();
|
||||
_cfg.LastExcelPath = _txtExcel.Text.Trim();
|
||||
_cfg.AreaPath = _txtAreaPath.Text.Trim();
|
||||
_cfg.AreaPath = _cmbArea.Text.Trim();
|
||||
_cfg.SkipExistingTitles = _chkSkip.Checked;
|
||||
_cfg.BypassRules = _chkBypass.Checked;
|
||||
_cfg.ParentPbiId = _txtParentPbi.Text.Trim();
|
||||
_cfg.ParentPbiId = NormalizePbiText(_cmbParent.Text);
|
||||
_cfg.Save();
|
||||
}
|
||||
|
||||
@@ -168,7 +152,7 @@ namespace TfsExcelImporter
|
||||
SetConnection("连接失败", ChipKind.Danger);
|
||||
SetBadgeOf(_cardConn, BadgeKind.Warn);
|
||||
Log("连接失败: " + FirstLine(ex.Message));
|
||||
Log("排查: 内网请确认「使用系统代理」保持关闭;DNS 失败多为 VPN 或未连内网。");
|
||||
Log("排查: 程序固定直连(不走本机系统代理);DNS 失败多为 VPN 或未连内网。");
|
||||
_cardConn.Expanded = true;
|
||||
_cardConn.ApplyHeight();
|
||||
Relayout();
|
||||
@@ -179,8 +163,24 @@ namespace TfsExcelImporter
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 迭代加载
|
||||
// ------------------------------------------------------------- 迭代 / Area 列表
|
||||
// 两者都是 TFS 分类结构(ICommonStructureService),取数、填表、报错完全同构,
|
||||
// 只有「结构根节点」「是否自动选第一条」不同,所以共用一套加载流程。
|
||||
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();
|
||||
if (string.IsNullOrWhiteSpace(_cfg.TfsUrl))
|
||||
@@ -190,7 +190,7 @@ namespace TfsExcelImporter
|
||||
return;
|
||||
}
|
||||
SetBusy(true);
|
||||
SetConnection("读取迭代中…", ChipKind.Info);
|
||||
SetConnection($"读取 {what} 列表中…", ChipKind.Info);
|
||||
try
|
||||
{
|
||||
using (var client = new TfsClient(_cfg))
|
||||
@@ -207,37 +207,17 @@ namespace TfsExcelImporter
|
||||
{
|
||||
Log("警告: 字段元数据获取失败,导入可能受影响: " + FirstLine(ex.Message));
|
||||
}
|
||||
var paths = await client.GetIterationPathsAsync(_cfg.Project, Log);
|
||||
var keep = _cmbIteration.Text;
|
||||
_cmbIteration.Items.Clear();
|
||||
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} 个迭代路径");
|
||||
var paths = await fetch(client);
|
||||
FillPathCombo(combo, paths, selectFirstWhenNoMatch);
|
||||
Log($"已加载 {combo.Items.Count} 条 {what} 路径");
|
||||
SetConnection("已连接", ChipKind.Ok);
|
||||
SetBadgeOf(_cardConn, BadgeKind.Done);
|
||||
ShowError(_errIteration, _fIteration, _cardData, "");
|
||||
ShowError(err, field, _cardData, "");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
SetConnection("连接失败", ChipKind.Danger);
|
||||
SetBadgeOf(_cardConn, BadgeKind.Warn);
|
||||
ShowError(_errIteration, _fIteration, _cardData, "迭代列表加载失败,可手填完整路径");
|
||||
Log("加载迭代失败: " + FirstLine(ex.Message));
|
||||
Log("排查: 内网请确认「使用系统代理」保持关闭;DNS 失败多为 VPN 或未连内网。");
|
||||
ReportTfsFailure(ex, what, field, err);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -246,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
|
||||
private void BrowseExcel()
|
||||
private async void BrowseExcel()
|
||||
{
|
||||
using (var dlg = new OpenFileDialog())
|
||||
{
|
||||
@@ -260,25 +371,40 @@ namespace TfsExcelImporter
|
||||
if (dlg.ShowDialog(this) != DialogResult.OK) return;
|
||||
_txtExcel.Text = dlg.FileName;
|
||||
SaveUiToConfig();
|
||||
PreviewData();
|
||||
await PreviewDataAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private void ExportTemplate()
|
||||
private async void ExportTemplate()
|
||||
{
|
||||
var startDir = ExportStartDirectory();
|
||||
using (var dlg = new SaveFileDialog())
|
||||
{
|
||||
dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx";
|
||||
dlg.FileName = ExcelService.TemplateFileName;
|
||||
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;
|
||||
|
||||
var path = dlg.FileName;
|
||||
try
|
||||
{
|
||||
ExcelService.CopyTemplate(dlg.FileName);
|
||||
Log("模板已导出: " + dlg.FileName);
|
||||
_txtExcel.Text = dlg.FileName;
|
||||
if (!ConfirmOverwriteTemplate(path)) return;
|
||||
|
||||
bool embeddedOnly;
|
||||
if (!ConfirmTemplateSource(out embeddedOnly)) return;
|
||||
|
||||
var srcDesc = ExcelService.CopyTemplate(path, embeddedOnly);
|
||||
Log("模板已导出(来源:" + srcDesc + "): " + path);
|
||||
_txtExcel.Text = path;
|
||||
SaveUiToConfig();
|
||||
PreviewData();
|
||||
await PreviewDataAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -288,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();
|
||||
if (string.IsNullOrEmpty(path) || !File.Exists(path))
|
||||
@@ -297,9 +519,10 @@ namespace TfsExcelImporter
|
||||
Append("预览未执行:Excel 文件不存在", LogLevel.Warn);
|
||||
return;
|
||||
}
|
||||
SetBusy(true);
|
||||
try
|
||||
{
|
||||
_rows = ExcelService.ReadRows(path);
|
||||
_rows = await Task.Run(() => ExcelService.ReadRows(path));
|
||||
_grid.DataSource = null;
|
||||
_grid.DataSource = _rows.Select((r, i) => new
|
||||
{
|
||||
@@ -326,9 +549,19 @@ namespace TfsExcelImporter
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 读取失败必须清掉上一次的数据,否则表格会继续显示旧文件的行,
|
||||
// 看起来就像"刚导出的文件里装的是别的文件的数据"
|
||||
_rows = new List<WorkItemRow>();
|
||||
_grid.DataSource = null;
|
||||
_lblStatus.Text = "读取失败";
|
||||
Log("读取 Excel 失败: " + FirstLine(ex.Message));
|
||||
ShowError(_errExcel, _fExcel, _cardData, "读取失败:" + FirstLine(ex.Message));
|
||||
UpdateEmptyState();
|
||||
RefreshSummaries();
|
||||
}
|
||||
finally
|
||||
{
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,9 +577,8 @@ namespace TfsExcelImporter
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(_cfg.AreaPath))
|
||||
{
|
||||
ShowError(_errArea, _fArea, _cardAdv, "请填写 Area 路径,例如 Tools_Dev\\DataTechnologies");
|
||||
OpenDetail(_cardAdv);
|
||||
_txtAreaPath.Focus();
|
||||
ShowError(_errArea, _fArea, _cardData, "请填写 Area 路径,例如 Tools_Dev\\DataTechnologies");
|
||||
_cmbArea.Focus();
|
||||
return;
|
||||
}
|
||||
var confirm = MessageBox.Show(this,
|
||||
@@ -366,7 +598,7 @@ namespace TfsExcelImporter
|
||||
: $"Area 修正完成,共 {r.Item1} 条";
|
||||
_lblStatus.Text = summary;
|
||||
Log(summary);
|
||||
ShowError(_errArea, _fArea, _cardAdv, "");
|
||||
ShowError(_errArea, _fArea, _cardData, "");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -393,7 +625,7 @@ namespace TfsExcelImporter
|
||||
if (!int.TryParse(_cfg.ParentPbiId, out parentId))
|
||||
{
|
||||
ShowError(_errParent, _fParent, _cardData, "父 PBI Id 需为纯数字,例如 219975");
|
||||
_txtParentPbi.Focus();
|
||||
_cmbParent.Focus();
|
||||
return;
|
||||
}
|
||||
var confirm = MessageBox.Show(this,
|
||||
@@ -437,6 +669,23 @@ namespace TfsExcelImporter
|
||||
Append("导入取消:目标迭代未选", LogLevel.Warn);
|
||||
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();
|
||||
if (string.IsNullOrEmpty(path) || !File.Exists(path))
|
||||
{
|
||||
@@ -446,13 +695,15 @@ namespace TfsExcelImporter
|
||||
}
|
||||
if (_rows.Count == 0)
|
||||
{
|
||||
try { _rows = ExcelService.ReadRows(path); }
|
||||
SetBusy(true);
|
||||
try { _rows = await Task.Run(() => ExcelService.ReadRows(path)); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
ShowError(_errExcel, _fExcel, _cardData, "读取失败:" + FirstLine(ex.Message));
|
||||
Log("读取 Excel 失败: " + FirstLine(ex.Message));
|
||||
return;
|
||||
}
|
||||
finally { SetBusy(false); }
|
||||
}
|
||||
if (_rows.Count == 0)
|
||||
{
|
||||
@@ -462,6 +713,7 @@ namespace TfsExcelImporter
|
||||
}
|
||||
|
||||
ShowError(_errIteration, _fIteration, _cardData, "");
|
||||
ShowError(_errArea, _fArea, _cardData, "");
|
||||
ShowError(_errExcel, _fExcel, _cardData, "");
|
||||
SetRunBadge(BadgeKind.Active);
|
||||
SetBusy(true);
|
||||
@@ -494,6 +746,7 @@ namespace TfsExcelImporter
|
||||
var logRef = TfsClient.ResolveRef(fieldMap, "LogDate", _cfg.LogDateRef);
|
||||
var origEstRef = TfsClient.ResolveRef(fieldMap, "Original Estimate", _cfg.OriginalEstimateRef);
|
||||
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 列覆盖");
|
||||
|
||||
HashSet<string> existing = null;
|
||||
@@ -523,12 +776,12 @@ namespace TfsExcelImporter
|
||||
new KeyValuePair<string, object>(titleRef, row.Title),
|
||||
new KeyValuePair<string, object>(stateRef,
|
||||
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))
|
||||
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)
|
||||
fields.Add(new KeyValuePair<string, object>(finRef, row.FinancialProject.Trim()));
|
||||
|
||||
@@ -551,7 +804,7 @@ namespace TfsExcelImporter
|
||||
var pbiText = !string.IsNullOrWhiteSpace(row.PbiId) ? row.PbiId.Trim() : _cfg.ParentPbiId;
|
||||
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++;
|
||||
report.AppendLine($"{line},\"{row.Title}\",OK,{id},");
|
||||
Log($"[{i + 1}/{_rows.Count}] OK #{id} {row.Title}");
|
||||
@@ -574,7 +827,7 @@ namespace TfsExcelImporter
|
||||
SetConnection("连接失败", ChipKind.Danger);
|
||||
SetRunBadge(BadgeKind.Warn);
|
||||
Log("导入中断: " + FirstLine(ex.Message));
|
||||
Log("排查: 内网请确认「使用系统代理」保持关闭;DNS 失败多为 VPN 或未连内网。");
|
||||
Log("排查: 程序固定直连(不走本机系统代理);DNS 失败多为 VPN 或未连内网。");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
+292
-98
@@ -17,21 +17,18 @@ namespace TfsExcelImporter
|
||||
private TextBox _txtUrl = new TextBox();
|
||||
private TextBox _txtProject = new TextBox();
|
||||
private TextBox _txtType = new TextBox();
|
||||
private ComboBox _cmbAuth = new ComboBox();
|
||||
private TextBox _txtUser = new TextBox();
|
||||
private TextBox _txtPwd = new TextBox { UseSystemPasswordChar = true };
|
||||
private TextBox _txtDomain = new TextBox();
|
||||
private CheckBox _chkProxy = new CheckBox();
|
||||
|
||||
private ComboBox _cmbIteration = new ComboBox();
|
||||
private ComboBox _cmbArea = new ComboBox();
|
||||
private TextBox _txtExcel = new TextBox();
|
||||
private TextBox _txtParentPbi = new TextBox();
|
||||
private TextBox _txtAreaPath = new TextBox();
|
||||
private ComboBox _cmbParent = new ComboBox();
|
||||
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 CheckBox _chkSkip = new CheckBox();
|
||||
private CheckBox _chkBypass = new CheckBox();
|
||||
|
||||
private DataGridView _grid = new DataGridView();
|
||||
private Button _btnPreview = new Button();
|
||||
@@ -52,9 +49,12 @@ namespace TfsExcelImporter
|
||||
private Card _cardConn, _cardData, _cardPreview, _cardLog, _cardAdv;
|
||||
private Surface _actionBar;
|
||||
private StepBadge _badgeRun;
|
||||
private InputField _fUrl, _fProject, _fType, _fAuth, _fUser, _fPwd, _fDomain,
|
||||
private InputField _fUrl, _fProject, _fType, _fUser, _fPwd,
|
||||
_fIteration, _fExcel, _fParent, _fArea;
|
||||
private Label _errIteration, _errExcel, _errParent, _errArea;
|
||||
private Label[] _connRowCaptions; // 第 1 步第二行的标签(重排时要跟着一起摆)
|
||||
private InputField[] _connRowFields; // 同排的四个输入框
|
||||
private int _connRowY;
|
||||
private EmptyState _lblEmpty;
|
||||
private StatusChip _chipConn, _chipOk, _chipSkip, _chipFail;
|
||||
|
||||
@@ -68,6 +68,8 @@ namespace TfsExcelImporter
|
||||
private static int G { get { return Theme.Px(8); } }
|
||||
private static int LogBodyH { get { return Theme.Px(150); } }
|
||||
private string _lastReportPath = "";
|
||||
/// <summary>上一次真正执行 Relayout 的客户区尺寸:尺寸没变就不重排(还原/激活时 WM_SIZE 会重发一次)。</summary>
|
||||
private Size _laidOutSize;
|
||||
|
||||
/// <summary>需要在窗口拉宽时跟着变宽的控件。</summary>
|
||||
private class Stretch
|
||||
@@ -115,7 +117,15 @@ namespace TfsExcelImporter
|
||||
Controls.Add(_cardLog);
|
||||
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;
|
||||
Relayout();
|
||||
|
||||
@@ -169,17 +179,18 @@ namespace TfsExcelImporter
|
||||
|
||||
private void BuildRibbon()
|
||||
{
|
||||
// 设计方案:连接信息栏与步骤卡片同一套白卡视觉,「灰标签 + 深值」分组,不再用淡蓝底
|
||||
_ribbon = new Surface
|
||||
{
|
||||
LineColor = Theme.PrimarySoftBorder,
|
||||
FaceColor = Theme.PrimarySoft,
|
||||
LineColor = Theme.Border,
|
||||
FaceColor = Theme.Card,
|
||||
Height = Theme.Px(44)
|
||||
};
|
||||
AddRibbonGroup("服务器", true);
|
||||
AddRibbonGroup("项目", true);
|
||||
AddRibbonGroup("工作项", false);
|
||||
|
||||
_chipConn = new StatusChip { BackColor = Theme.PrimarySoft };
|
||||
_chipConn = new StatusChip { BackColor = Theme.Card };
|
||||
_ribbon.Controls.Add(_chipConn);
|
||||
}
|
||||
|
||||
@@ -190,9 +201,9 @@ namespace TfsExcelImporter
|
||||
{
|
||||
Text = caption,
|
||||
Font = Theme.Caption,
|
||||
ForeColor = Theme.Ink2,
|
||||
ForeColor = Theme.Ink3,
|
||||
AutoSize = true,
|
||||
BackColor = Theme.PrimarySoft
|
||||
BackColor = Theme.Card
|
||||
};
|
||||
var val = new Label
|
||||
{
|
||||
@@ -200,14 +211,14 @@ namespace TfsExcelImporter
|
||||
Font = Theme.BodyBold,
|
||||
ForeColor = Theme.Ink,
|
||||
AutoSize = true,
|
||||
BackColor = Theme.PrimarySoft
|
||||
BackColor = Theme.Card
|
||||
};
|
||||
_ribbon.Controls.Add(cap);
|
||||
_ribbon.Controls.Add(val);
|
||||
Panel sep = null;
|
||||
if (withSeparator)
|
||||
{
|
||||
sep = new Panel { BackColor = Color.FromArgb(0xC2, 0xD3, 0xEF) };
|
||||
sep = new Panel { BackColor = Theme.Border };
|
||||
_ribbon.Controls.Add(sep);
|
||||
}
|
||||
_ribItems.Add(new RibGroup { Cap = cap, Val = val, Sep = sep });
|
||||
@@ -221,15 +232,15 @@ namespace TfsExcelImporter
|
||||
var cap = group.Cap;
|
||||
var val = group.Val;
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
}
|
||||
_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);
|
||||
}
|
||||
|
||||
@@ -237,65 +248,158 @@ namespace TfsExcelImporter
|
||||
private void BuildCardConn()
|
||||
{
|
||||
_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);
|
||||
_fProject = NewField(_txtProject, 150, false);
|
||||
_fType = NewField(_txtType, 180, false);
|
||||
_fAuth = NewField(_cmbAuth, 170, false);
|
||||
_fDomain = NewField(_txtDomain, 150, false);
|
||||
_fUser = NewField(_txtUser, 180, false);
|
||||
_fPwd = NewField(_txtPwd, 200, true);
|
||||
_fType = NewField(_txtType, 150, false);
|
||||
_fUser = NewField(_txtUser, 150, false);
|
||||
_fPwd = NewField(_txtPwd, 150, 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);
|
||||
_chkProxy = NewCheck("使用系统代理", "内网 TFS 请保持关闭,勾选后常被代理拦成 502");
|
||||
|
||||
int y = _cardConn.HeaderH + Theme.S12;
|
||||
// 三行表单共用一条字段左缘:标签列宽取各行最大值,同列字段宽度归一
|
||||
int w1 = MaxLabelWidth("服务器 URL", "团队项目", "域");
|
||||
int w2 = MaxLabelWidth("工作项类型", "用户");
|
||||
int w3 = MaxLabelWidth("认证方式", "密码");
|
||||
y = Row(_cardConn, y, 42, new Lbl("服务器 URL", w1), _fUrl);
|
||||
y = Row(_cardConn, y, 42, new Lbl("服务器 URL", MaxLabelWidth("服务器 URL")), _fUrl);
|
||||
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,
|
||||
new Lbl("用户", w2), _fUser, new Lbl("密码", w3), _fPwd, G, _btnTest);
|
||||
y = Row(_cardConn, y, 26, _chkProxy);
|
||||
|
||||
// 第二行:项目 / 类型 / 用户 / 密码 + 测试连接同排,四个输入框等宽、整行铺满卡片内容区。
|
||||
// 标签自建并留引用——窗口变宽时要连标签一起重摆,Row() 建完就丢引用做不到。
|
||||
_connRowY = y;
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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:迭代与数据源 ---
|
||||
private void BuildCardData()
|
||||
{
|
||||
_cardData = MakeCard(2, "选择迭代与数据源", true, Theme.Px(44));
|
||||
_cardData.SummaryDots = true; // 头部摘要按「圆点 + 短语」分段,五项状态一眼可辨
|
||||
_cmbIteration.DropDownStyle = ComboBoxStyle.DropDown; // 允许手填完整路径
|
||||
_cmbArea.DropDownStyle = ComboBoxStyle.DropDown; // 同上:列表拿不到时仍能手填
|
||||
_cmbParent.DropDownStyle = ComboBoxStyle.DropDown; // 可直接输 Id,也可从列表挑
|
||||
// 不做自定义 DropDownWidth:字段已和迭代同宽,下拉面板跟着控件宽走,
|
||||
// 形态与「目标迭代」完全一致,也不再有宽度写死后与实际布局对不上的问题。
|
||||
|
||||
_fIteration = NewField(_cmbIteration, 500, false);
|
||||
_fArea = NewField(_cmbArea, 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);
|
||||
_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);
|
||||
_chkSkip = NewCheck("跳过已存在标题", "");
|
||||
_chkBypass = NewCheck("bypassRules(绕过字段校验规则)", "");
|
||||
// 行尾两个按钮宽度取齐(取两者较宽的一个):右缘本来就都由 AnchorRight 贴在 M 上,
|
||||
// 宽度一致后左缘也落在同一条竖线上,两个按钮才成为一列;同时两行 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;
|
||||
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);
|
||||
Track(_fIteration, _cardData, _btnLoadIterations.Width + G + M, 0);
|
||||
y = Row(_cardData, y, 52, new Lbl("Excel 文件", wLbl), _fExcel);
|
||||
Track(_fIteration, _cardData, wBtn + G + M, 0);
|
||||
// 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(_btnBrowse, _cardData, _btnTemplate.Width + G + M, _fExcel.Top);
|
||||
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 列可逐行覆盖");
|
||||
y = Row(_cardData, y, 24, _chkSkip, 2 * G, _chkBypass);
|
||||
Track(_fExcel, _cardData, wBtn + G + M, 0);
|
||||
// 父项行结构与上面三行完全一致:字段吃满宽度 + 行尾按钮右对齐。
|
||||
// Id 本身不可读,列出来才敢确认挂的是哪条。
|
||||
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);
|
||||
_errArea = AddErrorUnder(_cardData, _fArea);
|
||||
_errExcel = AddErrorUnder(_cardData, _fExcel);
|
||||
_errParent = AddErrorUnder(_cardData, _fParent);
|
||||
_cardData.BodyH = y - _cardData.HeaderH + Theme.S8;
|
||||
@@ -344,6 +448,10 @@ namespace TfsExcelImporter
|
||||
// 148 已够图标+文字(实际量出约 130),省下的宽度留给右侧状态文字与进度条
|
||||
_btnImport = NewButton("开始导入 TFS", BtnKind.Primary, IconKind.ArrowUp, 148);
|
||||
// 主/次按钮同高(层级靠主色表达,不再用 38px 拔高),避免操作条里两个按钮大小不齐
|
||||
|
||||
// 去重开关紧贴主按钮右侧:它是「开始导入」这一个动作的开关(一次导入只在开始时读一次),
|
||||
// 挂在按钮旁边才不会被误读成某个字段的属性。
|
||||
_chkSkip = NewCheck("跳过已存在标题", "");
|
||||
_pbar = new ProgressTrack
|
||||
{
|
||||
Minimum = 0,
|
||||
@@ -367,6 +475,7 @@ namespace TfsExcelImporter
|
||||
_actionBar.Controls.Add(_badgeRun);
|
||||
_actionBar.Controls.Add(_btnPreview);
|
||||
_actionBar.Controls.Add(_btnImport);
|
||||
_actionBar.Controls.Add(_chkSkip);
|
||||
_actionBar.Controls.Add(_pbar);
|
||||
_actionBar.Controls.Add(_chipOk);
|
||||
_actionBar.Controls.Add(_chipSkip);
|
||||
@@ -381,24 +490,41 @@ namespace TfsExcelImporter
|
||||
{
|
||||
int badge = Theme.Px(22);
|
||||
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);
|
||||
_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);
|
||||
_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);
|
||||
|
||||
_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);
|
||||
_chipOk.SetBounds(_chipSkip.Left - G - _chipOk.Width, cy, _chipOk.Width, _chipOk.Height);
|
||||
// 状态文字按最长常规文案实测给宽,且只给一行的高度:
|
||||
// 宽度够了不折行,万一更长的文案也只省略尾巴,不会把计数拆到第二行。
|
||||
int statW = StatusLabelWidth();
|
||||
// 去重开关:与两个按钮同一条中线,纵向按勾选框自身高度居中
|
||||
int chkW, chkH;
|
||||
CheckBoxSize(_chkSkip, Theme.Body, out chkW, out chkH);
|
||||
Theme.Place(_chkSkip, _btnImport.Right + Theme.S16, (_actionBar.Height - chkH) / 2, chkW, chkH);
|
||||
|
||||
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);
|
||||
_lblStatus.SetBounds(_chipOk.Left - statW - G, (_actionBar.Height - statH) / 2, statW, statH);
|
||||
int left = _btnImport.Right + Theme.S16;
|
||||
Theme.Place(_lblStatus, _chipOk.Left - G - statW, (_actionBar.Height - statH) / 2, statW, statH);
|
||||
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>
|
||||
@@ -455,16 +581,14 @@ namespace TfsExcelImporter
|
||||
int x = _cardLog.Width - Theme.Px(12) - Theme.Px(30); // 让开折叠箭头
|
||||
// 头部所有元素共用一条中线:按钮和勾选框都按 cy - 高度/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);
|
||||
_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);
|
||||
// net48 的 CheckBox 没有 PreferredWidth,只能自己量文字宽度(外加勾选框);
|
||||
// 高度取原生 PreferredHeight,整体压在中线上
|
||||
var pref = _chkAutoScroll.GetPreferredSize(Size.Empty);
|
||||
int chkH = Math.Max(Theme.Px(18), pref.Height);
|
||||
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);
|
||||
// net48 的 CheckBox 没有 PreferredWidth:宽高都由 CheckBoxSize 量出来,整体压在中线上
|
||||
int chkW, chkH;
|
||||
CheckBoxSize(_chkAutoScroll, Theme.Caption, out chkW, out chkH);
|
||||
Theme.Place(_chkAutoScroll, _btnClearLog.Left - chkW - G, cy - chkH / 2, chkW, chkH);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -473,15 +597,16 @@ namespace TfsExcelImporter
|
||||
{
|
||||
_cardAdv = MakeCard(0, "高级工具", true, Theme.Px(36));
|
||||
_cardAdv.ShowBadge = false;
|
||||
_fArea = NewField(_txtAreaPath, 420, true);
|
||||
// Area 输入框已上移到第 2 步(必填),这里只剩两个批量修正动作,
|
||||
// 两者都按第 2 步填的「目标迭代 / Area 路径」筛选已有工作项。
|
||||
_btnFixArea = NewButton("按迭代修 Area", BtnKind.Secondary, IconKind.Wrench, 158);
|
||||
_btnLinkParent = NewButton("补挂父项", BtnKind.Secondary, IconKind.Tree, 120);
|
||||
|
||||
int y = _cardAdv.HeaderH + Theme.S12;
|
||||
y = Row(_cardAdv, y, 52, "Area 路径", _fArea, "改 Area 与补挂父项都按上面的「目标迭代」筛选已有工作项");
|
||||
y = Row(_cardAdv, y, 34, _btnFixArea, G, _btnLinkParent, G, "已关闭的工作项会被临时重新打开,完成后自动还原状态");
|
||||
_errArea = AddErrorUnder(_cardAdv, _fArea);
|
||||
y = Row(_cardAdv, y, 34, _btnFixArea, G, _btnLinkParent, G,
|
||||
new Hint("Area 取第 2 步的「Area 路径」,按「目标迭代」筛选;已关闭的工作项会临时重新打开,完成后自动还原状态"));
|
||||
_cardAdv.BodyH = y - _cardAdv.HeaderH + Theme.S8;
|
||||
_cardAdv.SetSummary("按迭代批量修 Area / 补挂父项");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 摆放助手
|
||||
@@ -490,8 +615,23 @@ namespace TfsExcelImporter
|
||||
{
|
||||
public readonly string Text;
|
||||
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>
|
||||
@@ -525,6 +665,21 @@ namespace TfsExcelImporter
|
||||
};
|
||||
lbl.SetBounds(x, y + (Theme.FieldH - lbl.PreferredHeight) / 2, lbl.PreferredWidth, lbl.PreferredHeight);
|
||||
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);
|
||||
lastLabel = label;
|
||||
continue;
|
||||
@@ -532,6 +687,23 @@ namespace TfsExcelImporter
|
||||
|
||||
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;
|
||||
if (c == null) continue;
|
||||
int top = y + Math.Max(0, (Theme.FieldH - c.Height) / 2);
|
||||
@@ -661,22 +833,22 @@ namespace TfsExcelImporter
|
||||
{
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// 从底部往上排
|
||||
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;
|
||||
_cardLog.SetBounds(M, by - _cardLog.Height, cw, _cardLog.Height);
|
||||
Theme.Place(_cardLog, M, by - _cardLog.Height, cw, _cardLog.Height);
|
||||
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;
|
||||
|
||||
// 预览卡吃剩余高度;空间不足时先让日志收成一行
|
||||
@@ -685,14 +857,14 @@ namespace TfsExcelImporter
|
||||
_cardLog.Expanded = false;
|
||||
_cardLog.ApplyHeight();
|
||||
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;
|
||||
_cardLog.SetBounds(M, by - _cardLog.Height, cw, _cardLog.Height);
|
||||
Theme.Place(_cardLog, M, by - _cardLog.Height, cw, _cardLog.Height);
|
||||
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;
|
||||
}
|
||||
_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;
|
||||
|
||||
foreach (var st in _stretches)
|
||||
@@ -700,18 +872,34 @@ namespace TfsExcelImporter
|
||||
if (st.C == null || st.Owner == null) continue;
|
||||
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;
|
||||
st.C.SetBounds(st.X, st.Y, w, h);
|
||||
Theme.Place(st.C, st.X, st.Y, w, h);
|
||||
}
|
||||
foreach (var ra in _rightAnchors)
|
||||
{
|
||||
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();
|
||||
foreach (var act in _layoutExtras) act();
|
||||
|
||||
_cardConn.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);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 状态呈现
|
||||
@@ -793,22 +981,19 @@ namespace TfsExcelImporter
|
||||
{
|
||||
ShortHost(_txtUrl.Text.Trim()),
|
||||
_txtProject.Text.Trim(),
|
||||
_txtType.Text.Trim(),
|
||||
_cmbAuth.SelectedItem != null ? _cmbAuth.SelectedItem.ToString() : "ntlm"
|
||||
_txtType.Text.Trim()
|
||||
}));
|
||||
_cardData.SetSummary(string.Join(" · ", new[]
|
||||
{
|
||||
string.IsNullOrEmpty(iter) ? "迭代未选" : iter,
|
||||
string.IsNullOrWhiteSpace(_cmbArea.Text) ? "Area 未填" : "Area " + _cmbArea.Text.Trim(),
|
||||
string.IsNullOrEmpty(fileName) ? "未选 Excel" : fileName,
|
||||
_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
|
||||
? "共 " + _rows.Count + " 行,可直接开始导入"
|
||||
: "选择 Excel 后在这里核对将要写入的内容");
|
||||
_cardAdv.SetSummary(string.IsNullOrWhiteSpace(_txtAreaPath.Text)
|
||||
? "Area 未设置"
|
||||
: "Area " + _txtAreaPath.Text.Trim());
|
||||
}
|
||||
|
||||
/// <summary>第 4 步徽标:待办 / 进行中 / 完成 / 有失败。</summary>
|
||||
@@ -869,9 +1054,13 @@ namespace TfsExcelImporter
|
||||
_btnPreview.Enabled = !busy;
|
||||
_btnTest.Enabled = !busy;
|
||||
_btnLoadIterations.Enabled = !busy;
|
||||
_btnLoadAreas.Enabled = !busy;
|
||||
_btnLoadPbi.Enabled = !busy;
|
||||
_btnFixArea.Enabled = !busy;
|
||||
_btnLinkParent.Enabled = !busy;
|
||||
_btnBrowse.Enabled = !busy;
|
||||
// 去重开关在导入开始时只读一次:跑起来再改会误导(看着改了,本轮其实不生效),直接置灰
|
||||
_chkSkip.Enabled = !busy;
|
||||
_fExcel.SetSuffixEnabled(!busy); // 「浏览」已并入输入框尾部,随忙等一起禁用
|
||||
_btnTemplate.Enabled = !busy;
|
||||
}
|
||||
}
|
||||
@@ -890,16 +1079,21 @@ namespace TfsExcelImporter
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
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 blockH = icon + Theme.Px(10) + textH;
|
||||
int blockH = well + Theme.Px(12) + textH;
|
||||
int top = Math.Max(Theme.Px(4), (Height - blockH) / 2);
|
||||
int wellX = (Width - well) / 2;
|
||||
var old = g.SmoothingMode;
|
||||
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;
|
||||
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,
|
||||
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter
|
||||
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
|
||||
|
||||
+205
-40
@@ -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 " +
|
||||
|
||||
@@ -31,6 +31,11 @@
|
||||
<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>
|
||||
|
||||
+266
-8
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace TfsExcelImporter
|
||||
@@ -149,10 +151,64 @@ namespace TfsExcelImporter
|
||||
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;
|
||||
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;
|
||||
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)
|
||||
@@ -393,6 +449,8 @@ namespace TfsExcelImporter
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
var r = new RectangleF(0.5f, 0.5f, Width - 1f, Height - 1f);
|
||||
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;
|
||||
// 勾画在圆内缩 4px(14px 盒子 / 22px 圆),铺满整圆会贴边看着像被裁掉
|
||||
if (Kind == BadgeKind.Done) Icons.Draw(g, IconKind.Check, Icons.BadgeGlyph(ClientRectangle), ink);
|
||||
@@ -423,6 +481,16 @@ namespace TfsExcelImporter
|
||||
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)
|
||||
{
|
||||
Theme.FillPanel(e.Graphics, new Rectangle(0, 0, Width, Height), _face, LineColor,
|
||||
@@ -446,6 +514,8 @@ namespace TfsExcelImporter
|
||||
public bool ShowBadge = true;
|
||||
/// <summary>卡片头部右侧留给按钮的宽度,摘要文字不越过它。</summary>
|
||||
public int HeaderReserve = 0;
|
||||
/// <summary>头部摘要按「圆点 + 短语」分段绘制(状态摘要样式);默认纯文本。</summary>
|
||||
public bool SummaryDots = false;
|
||||
public int HeaderH = 44;
|
||||
public int BodyH = 0;
|
||||
public Action<bool> OnToggle;
|
||||
@@ -461,6 +531,17 @@ namespace TfsExcelImporter
|
||||
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); } }
|
||||
|
||||
private Rectangle HeaderRect { get { return new Rectangle(0, 0, Width, HeaderH); } }
|
||||
@@ -570,6 +651,10 @@ namespace TfsExcelImporter
|
||||
var old = g.SmoothingMode;
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
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;
|
||||
if (Badge == BadgeKind.Done) Icons.Draw(g, IconKind.Check, Icons.BadgeGlyph(badge), badgeInk);
|
||||
else
|
||||
@@ -588,8 +673,12 @@ namespace TfsExcelImporter
|
||||
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
|
||||
|
||||
int sx = titleRect.Right + Theme.Px(12);
|
||||
var sumRect = new Rectangle(sx, 0, Math.Max(0, Width - chevW - sx - Theme.Px(12)), HeaderH);
|
||||
TextRenderer.DrawText(g, Summary, Theme.Caption, sumRect,
|
||||
int sumW = Math.Max(0, Width - chevW - sx - Theme.Px(12));
|
||||
if (SummaryDots)
|
||||
DrawDotSummary(g, Summary, sx, sumW);
|
||||
else
|
||||
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);
|
||||
@@ -605,6 +694,40 @@ namespace TfsExcelImporter
|
||||
using (var p = new Pen(Theme.Border))
|
||||
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 }
|
||||
@@ -831,14 +954,25 @@ namespace TfsExcelImporter
|
||||
private bool _invalid;
|
||||
private ComboBox _combo;
|
||||
private Chevron _chevron;
|
||||
private SuffixIcon _suffix;
|
||||
private Control _content; // 主内容控件(TextBox/ComboBox),占位层据此判定显隐
|
||||
private CueLabel _cue; // 自绘占位提示:原生 EM_SETCUEBANNER 控制不了颜色/字号/对齐
|
||||
// 内容容器:整体内缩 2px 并按圆角 Region 裁剪——恰好让开聚焦态 2px 描边带,
|
||||
// 否则白底会切掉描边的内半圈,只剩外圈 AA 残边(视觉上就是一圈毛刺)。
|
||||
// 子控件(尤其被挤出宿主藏箭头的 ComboBox)再怎么越界,也只会被裁在描边圈以内。
|
||||
private Panel _box;
|
||||
/// <summary>上一次 LayoutInner 时的宿主尺寸:尺寸没变就不用重摆子控件、更不用重建圆角 Region。</summary>
|
||||
private Size _innerSize = new Size(-1, -1);
|
||||
|
||||
/// <summary>宿主右侧留给自绘箭头的区域,同时也是点击展开下拉的热区。</summary>
|
||||
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>
|
||||
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(); };
|
||||
_box.Controls.Add(_chevron);
|
||||
}
|
||||
_content = inner;
|
||||
inner.BackColor = Theme.Card;
|
||||
inner.Font = mono ? Theme.Mono : Theme.Body;
|
||||
inner.ForeColor = Theme.Ink;
|
||||
_box.Controls.Add(inner);
|
||||
inner.Enter += (s, e) => Invalidate();
|
||||
inner.Leave += (s, e) => Invalidate();
|
||||
LayoutInner();
|
||||
LayoutInner(true);
|
||||
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(); }
|
||||
|
||||
private void DrawComboItem(object sender, DrawItemEventArgs e)
|
||||
@@ -953,14 +1127,19 @@ namespace TfsExcelImporter
|
||||
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
|
||||
}
|
||||
|
||||
private void LayoutInner()
|
||||
private void LayoutInner(bool force = false)
|
||||
{
|
||||
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);
|
||||
SetBoxRegion();
|
||||
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 cb = c as ComboBox;
|
||||
if (cb != null)
|
||||
@@ -974,7 +1153,13 @@ namespace TfsExcelImporter
|
||||
}
|
||||
int natural = tb != null ? tb.PreferredHeight : Theme.Px(19);
|
||||
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)
|
||||
{
|
||||
@@ -982,6 +1167,21 @@ namespace TfsExcelImporter
|
||||
_chevron.SetBounds(_box.Width - Theme.Px(7) - size, Theme.Px(2), size, _box.Height - Theme.Px(4));
|
||||
_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();
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
base.OnMouseDown(e);
|
||||
|
||||
@@ -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
@@ -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"
|
||||
}
|
||||
@@ -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,6 +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)
|
||||
[1101/193634.522:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: 系统找不到指定的文件。 (0x2)
|
||||
[1101/195235.112:ERROR:third_party\crashpad\crashpad\util\win\registration_protocol_win.cc:108] CreateFile: 系统找不到指定的文件。 (0x2)
|
||||
@@ -1,2 +0,0 @@
|
||||
requests>=2.28
|
||||
requests-ntlm>=1.2
|
||||
-467
@@ -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())
|
||||
@@ -146,6 +146,22 @@ def crop_zoom(src_png_w, src_png_h, rgba, cw, ch, scale, path, ox=0, oy=0):
|
||||
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user