Compare commits
3
Commits
8824a81758
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe23e1c64a | ||
|
|
14f5e32262 | ||
|
|
ffc210f827 |
@@ -68,10 +68,10 @@ python tools/win_screenshot.py TfsExcelImporter\bin\Release\net48\TfsExcelImport
|
||||
界面按 4 步排:顶部状态条常驻显示服务器/项目/类型与连接状态,四张卡片一次只展开一张(展开一张会把其它收成一行摘要),预览表格永远占满剩余高度。
|
||||
|
||||
1. **步骤 1 连接**:填 URL、项目、工作项类型与账号密码(认证固定 NTLM,用户名可写 `user` 或 `DOMAIN\user`),点「测试连接」——右上状态灯变绿即连通。
|
||||
2. **步骤 2 选数据**:点「加载迭代列表」选目标迭代(也可手填完整路径);点「导出 Excel 模板」拿默认模板,或「浏览...」选已有 `.xlsx`。需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项);勾「跳过已存在标题」按「项目/类型/迭代 + 标题」去重。字段校验**不可绕过**,不合法时日志会直接告诉你改哪一列。
|
||||
2. **步骤 2 选数据**:点「加载迭代列表」选目标迭代(也可手填完整路径);**Area 路径同样在这一步填,且为必填**(新导入的工作项都写到该 Area,留空会导致团队视图看不到,所以导入前会被拦下),点「加载 Area 列表」可从服务器拉真实 Area 树,也可手填完整路径;点「导出 Excel 模板」拿默认模板,或「浏览...」选已有 `.xlsx`。需要挂父项时填「父 PBI Id」(默认全部挂同一个;Excel 里加 `PBI Id` 列可逐行指定不同父项),点「加载 PBI 列表」可拉出该迭代下的 Product Backlog Item(下拉显示「#Id 标题 · 状态」,选中自动回填纯 Id),也可直接手输 Id。字段校验**不可绕过**,不合法时日志会直接告诉你改哪一列。
|
||||
3. **步骤 3 预览核对**:选完文件自动读表,表格里逐行核对;缺迭代/文件路径无效时红字直接标在对应输入框下方,不再弹框。
|
||||
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 显示缩放换算;**改了显示缩放比例要重启程序**才生效。
|
||||
|
||||
@@ -107,11 +107,11 @@ copy TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe dist\
|
||||
| --- | --- |
|
||||
| `TfsUrl` / `Project` / `WorkItemType` | 目标集合、项目、工作项类型(`Task` 或 `Product Backlog Item`) |
|
||||
| `IterationPath` | 可只写 `2026年Sprint\2026年Sprint10`,程序自动补项目名前缀 |
|
||||
| `AreaPath` | 区域路径;界面「高级工具」栏也可改 |
|
||||
| `AreaPath` | 区域路径;导入必填,界面上与迭代同在第 2 步卡片(可点「加载 Area 列表」从 TFS 分类树拉取),值直接写进 `System.AreaPath` |
|
||||
| `Username` / `Password` | 认证固定 NTLM,用户名可写 `user` 或 `DOMAIN\user` |
|
||||
| `FinancialProjectRef` / `CompletedRef` / `LogDateRef` / `OriginalEstimateRef` | 自定义字段引用名;留空则按显示名在服务器字段表里查(支持前缀模糊匹配,如 `Completed` → `Completed Work`) |
|
||||
| `ParentPbiId` | 所有 Task 默认挂接的父 PBI Id;Excel 每行 `PBI Id` 列可覆盖 |
|
||||
| `SkipExistingTitles` | 同项目/同类型/同迭代下按标题去重 |
|
||||
| `ParentPbiId` | 所有 Task 默认挂接的父 PBI Id(界面上可从「加载 PBI 列表」里挑,落库只存纯数字);Excel 每行 `PBI Id` 列可覆盖 |
|
||||
| `SkipExistingTitles` | 同项目/同类型/同迭代下按标题去重;**默认不勾选**,需要去重时手动勾 |
|
||||
| `DefaultState` | Excel `State` 列留空时的默认值 |
|
||||
| `LastExcelPath` | 上次选中的数据文件,界面回填用 |
|
||||
|
||||
@@ -145,6 +145,7 @@ copy TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe dist\
|
||||
|
||||
- **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` 置空强制直连,界面不提供代理开关(本机若只能经代理上网,程序会直连失败)。
|
||||
- **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,需另加列或改回写日期。
|
||||
- **字段校验不可绕过**:OM 14.x 没有 `SaveFlags.BypassRules`,旧界面上那个 `bypassRules` 勾选从未真正生效,已移除。校验失败时日志与 report CSV 直接给出「字段(原因) → 怎么改」,列表字段还会列出允许值,按提示改 Excel 对应列后重跑即可。
|
||||
@@ -153,4 +154,4 @@ copy TfsExcelImporter\bin\Release\net48\TfsExcelImporter.exe dist\
|
||||
|
||||
## 验证
|
||||
|
||||
桌面版改完,先用只含几行的 Excel 跑一次小批量导入(先删服务器已有同标题项或勾「跳过已存在标题」),再在积压工作页展开父项确认子任务可见;改动涉及界面布局或图标时,跑 `python tools/win_screenshot.py` 抓图核对。确认无误后再跑全量。
|
||||
桌面版改完,先用只含几行的 Excel 跑一次小批量导入(先删服务器已有同标题项或勾操作条上「跳过已存在标题」),再在积压工作页展开父项确认子任务可见;改动涉及界面布局或图标时,跑 `python tools/win_screenshot.py` 抓图核对。确认无误后再跑全量。
|
||||
|
||||
@@ -62,7 +62,8 @@ namespace TfsExcelImporter
|
||||
// 旧版本有 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; } = true;
|
||||
// 默认不勾选:首次导入时希望先看到真实冲突/报错,而不是被静默跳过
|
||||
public bool SkipExistingTitles { get; set; } = false;
|
||||
public string DefaultState { get; set; } = "To Do";
|
||||
|
||||
// 自定义字段引用名;留空则按 DisplayName 自动解析
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace TfsExcelImporter
|
||||
{
|
||||
/// <summary>
|
||||
/// 输入框空态占位文字(cue banner)。net48 的 TextBox 没有 PlaceholderText,
|
||||
/// 用原生 EM_SETCUEBANNER 实现;ComboBox(DropDown)要发给它内嵌的 Edit 子窗口,
|
||||
/// 直接发给组合框本体无效。文字只在输入框为空时显示,与 Web 表单 placeholder 手感一致。
|
||||
/// </summary>
|
||||
internal static class CueBanner
|
||||
{
|
||||
private const int EM_SETCUEBANNER = 0x1501;
|
||||
private const uint GW_CHILD = 5;
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, string lParam);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetWindow(IntPtr hWnd, uint cmd);
|
||||
|
||||
/// <summary>设置占位文字。控件句柄可能尚未创建,挂 HandleCreated 兜底;
|
||||
/// wParam=1 让占位文字在聚焦时也显示(有真实输入后自然消失)。</summary>
|
||||
public static void Set(Control c, string text)
|
||||
{
|
||||
if (c == null || string.IsNullOrEmpty(text)) return;
|
||||
Action apply = () => Send(c, text);
|
||||
if (c.IsHandleCreated) apply();
|
||||
c.HandleCreated += (s, e) => apply();
|
||||
}
|
||||
|
||||
private static void Send(Control c, string text)
|
||||
{
|
||||
IntPtr target = c.Handle;
|
||||
if (c is ComboBox)
|
||||
{
|
||||
// DropDown 组合框的内嵌 Edit 子窗口:cue banner 只认它
|
||||
target = GetWindow(c.Handle, GW_CHILD);
|
||||
if (target == IntPtr.Zero) return;
|
||||
}
|
||||
SendMessage(target, EM_SETCUEBANNER, (IntPtr)1, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,35 +46,129 @@ 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))
|
||||
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
|
||||
{
|
||||
File.Copy(src, path, true);
|
||||
return;
|
||||
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; }
|
||||
}
|
||||
|
||||
// --------------------------------------------------------- 读取数据
|
||||
|
||||
/// <summary>读取 Excel(或同格式 CSV 由用户另存为 xlsx)数据行,跳过空标题行。</summary>
|
||||
|
||||
+314
-46
@@ -37,17 +37,26 @@ namespace TfsExcelImporter
|
||||
{
|
||||
_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 += 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,
|
||||
_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();
|
||||
|
||||
FormClosing += (s, e) => { try { SaveUiToConfig(); } catch { } };
|
||||
@@ -69,9 +78,9 @@ namespace TfsExcelImporter
|
||||
_txtPwd.Text = _cfg.Password;
|
||||
_cmbIteration.Text = _cfg.IterationPath;
|
||||
_txtExcel.Text = _cfg.LastExcelPath;
|
||||
_txtAreaPath.Text = _cfg.AreaPath;
|
||||
_cmbArea.Text = _cfg.AreaPath;
|
||||
_chkSkip.Checked = _cfg.SkipExistingTitles;
|
||||
_txtParentPbi.Text = _cfg.ParentPbiId;
|
||||
_cmbParent.Text = _cfg.ParentPbiId;
|
||||
}
|
||||
|
||||
private void SaveUiToConfig()
|
||||
@@ -83,9 +92,9 @@ namespace TfsExcelImporter
|
||||
_cfg.Password = _txtPwd.Text;
|
||||
_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.ParentPbiId = _txtParentPbi.Text.Trim();
|
||||
_cfg.ParentPbiId = NormalizePbiText(_cmbParent.Text);
|
||||
_cfg.Save();
|
||||
}
|
||||
|
||||
@@ -154,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))
|
||||
@@ -165,7 +190,7 @@ namespace TfsExcelImporter
|
||||
return;
|
||||
}
|
||||
SetBusy(true);
|
||||
SetConnection("读取迭代中…", ChipKind.Info);
|
||||
SetConnection($"读取 {what} 列表中…", ChipKind.Info);
|
||||
try
|
||||
{
|
||||
using (var client = new TfsClient(_cfg))
|
||||
@@ -182,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
|
||||
{
|
||||
@@ -221,6 +226,137 @@ 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 async void BrowseExcel()
|
||||
{
|
||||
@@ -241,17 +377,32 @@ namespace TfsExcelImporter
|
||||
|
||||
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();
|
||||
await PreviewDataAsync();
|
||||
}
|
||||
@@ -263,6 +414,99 @@ namespace TfsExcelImporter
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 线程再更新表格。
|
||||
@@ -305,9 +549,15 @@ 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
|
||||
{
|
||||
@@ -327,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,
|
||||
@@ -349,7 +598,7 @@ namespace TfsExcelImporter
|
||||
: $"Area 修正完成,共 {r.Item1} 条";
|
||||
_lblStatus.Text = summary;
|
||||
Log(summary);
|
||||
ShowError(_errArea, _fArea, _cardAdv, "");
|
||||
ShowError(_errArea, _fArea, _cardData, "");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -376,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,
|
||||
@@ -420,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))
|
||||
{
|
||||
@@ -447,6 +713,7 @@ namespace TfsExcelImporter
|
||||
}
|
||||
|
||||
ShowError(_errIteration, _fIteration, _cardData, "");
|
||||
ShowError(_errArea, _fArea, _cardData, "");
|
||||
ShowError(_errExcel, _fExcel, _cardData, "");
|
||||
SetRunBadge(BadgeKind.Active);
|
||||
SetBusy(true);
|
||||
@@ -479,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;
|
||||
@@ -508,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()));
|
||||
|
||||
|
||||
+193
-90
@@ -21,11 +21,12 @@ namespace TfsExcelImporter
|
||||
private TextBox _txtPwd = new TextBox { UseSystemPasswordChar = true };
|
||||
|
||||
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();
|
||||
|
||||
@@ -67,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
|
||||
@@ -114,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();
|
||||
|
||||
@@ -168,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);
|
||||
}
|
||||
|
||||
@@ -189,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
|
||||
{
|
||||
@@ -199,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 });
|
||||
@@ -220,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);
|
||||
}
|
||||
|
||||
@@ -243,12 +255,11 @@ namespace TfsExcelImporter
|
||||
_fUser = NewField(_txtUser, 150, false);
|
||||
_fPwd = NewField(_txtPwd, 150, true);
|
||||
|
||||
// 空态占位提示(cue banner):只在该输入框没填内容时显示
|
||||
CueBanner.Set(_txtUrl, "如 http://server:8080/tfs/DefaultCollection");
|
||||
CueBanner.Set(_txtProject, "如 Tools_Dev");
|
||||
CueBanner.Set(_txtType, "如 Task");
|
||||
CueBanner.Set(_txtUser, "留空用当前 Windows 身份");
|
||||
CueBanner.Set(_txtPwd, "域账号密码(同上可选)");
|
||||
// 空态占位提示(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);
|
||||
|
||||
@@ -316,51 +327,79 @@ namespace TfsExcelImporter
|
||||
int x = M;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
_connRowCaptions[i].SetBounds(x, _connRowY, lblW[i], Theme.FieldH);
|
||||
Theme.Place(_connRowCaptions[i], x, _connRowY, lblW[i], Theme.FieldH);
|
||||
x += lblW[i] + lblGap;
|
||||
_connRowFields[i].SetBounds(x, _connRowY, boxW, Theme.FieldH);
|
||||
Theme.Place(_connRowFields[i], x, _connRowY, boxW, Theme.FieldH);
|
||||
x += boxW + gap;
|
||||
}
|
||||
_btnTest.SetBounds(x - gap + G, _connRowY, _btnTest.Width, Theme.BtnH);
|
||||
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);
|
||||
|
||||
CueBanner.Set(_cmbIteration, "选择或手填完整迭代路径,如 Tools_Dev\\Sprint 1");
|
||||
CueBanner.Set(_txtExcel, "选择 .xlsx 文件,或点右侧「浏览…」");
|
||||
CueBanner.Set(_txtParentPbi, "如 219975");
|
||||
_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("跳过已存在标题", "");
|
||||
// 行尾两个按钮宽度取齐(取两者较宽的一个):右缘本来就都由 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,
|
||||
new Hint("Task 默认挂到该 backlog item;Excel 里加 PBI Id 列可逐行覆盖"));
|
||||
// 勾选项不再贴着标签起头:整体右移到上面三行输入框的左缘(跳过标签列)。
|
||||
// 只有「去重」这一个开关;字段校验不可绕过(OM 14.x 无 BypassRules),失败时由
|
||||
// TfsClient 输出可操作的修复提示。
|
||||
y = Row(_cardData, y, 32, _fParent.Left - M, _chkSkip);
|
||||
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;
|
||||
@@ -409,6 +448,10 @@ namespace TfsExcelImporter
|
||||
// 148 已够图标+文字(实际量出约 130),省下的宽度留给右侧状态文字与进度条
|
||||
_btnImport = NewButton("开始导入 TFS", BtnKind.Primary, IconKind.ArrowUp, 148);
|
||||
// 主/次按钮同高(层级靠主色表达,不再用 38px 拔高),避免操作条里两个按钮大小不齐
|
||||
|
||||
// 去重开关紧贴主按钮右侧:它是「开始导入」这一个动作的开关(一次导入只在开始时读一次),
|
||||
// 挂在按钮旁边才不会被误读成某个字段的属性。
|
||||
_chkSkip = NewCheck("跳过已存在标题", "");
|
||||
_pbar = new ProgressTrack
|
||||
{
|
||||
Minimum = 0,
|
||||
@@ -432,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);
|
||||
@@ -446,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>
|
||||
@@ -520,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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -538,17 +597,16 @@ namespace TfsExcelImporter
|
||||
{
|
||||
_cardAdv = MakeCard(0, "高级工具", true, Theme.Px(36));
|
||||
_cardAdv.ShowBadge = false;
|
||||
_fArea = NewField(_txtAreaPath, 420, true);
|
||||
CueBanner.Set(_txtAreaPath, "如 Tools_Dev\\导入工具,留空则沿用工作项现有 Area");
|
||||
// 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,
|
||||
new Hint("改 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 / 补挂父项");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 摆放助手
|
||||
@@ -557,8 +615,15 @@ 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>
|
||||
@@ -600,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;
|
||||
@@ -753,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;
|
||||
|
||||
// 预览卡吃剩余高度;空间不足时先让日志收成一行
|
||||
@@ -777,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)
|
||||
@@ -792,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);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- 状态呈现
|
||||
@@ -890,16 +986,14 @@ namespace TfsExcelImporter
|
||||
_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>
|
||||
@@ -960,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;
|
||||
}
|
||||
}
|
||||
@@ -981,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);
|
||||
|
||||
+123
-12
@@ -88,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(() =>
|
||||
{
|
||||
@@ -101,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)
|
||||
{
|
||||
@@ -120,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();
|
||||
@@ -149,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>
|
||||
|
||||
+269
-11
@@ -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,11 +673,15 @@ 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,
|
||||
Invalid ? Theme.Danger : Theme.Ink2,
|
||||
TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding
|
||||
| TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
|
||||
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);
|
||||
|
||||
if (Collapsible)
|
||||
{
|
||||
@@ -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,10 +3,10 @@
|
||||
"Project": "Tools_Dev",
|
||||
"WorkItemType": "Task",
|
||||
"IterationPath": "",
|
||||
"AreaPath": "Tools_Dev\\DataTechnologies",
|
||||
"AreaPath": "",
|
||||
"Username": "",
|
||||
"Password": "",
|
||||
"SkipExistingTitles": true,
|
||||
"SkipExistingTitles": false,
|
||||
"DefaultState": "To Do",
|
||||
"FinancialProjectRef": "",
|
||||
"CompletedRef": "",
|
||||
|
||||
Reference in New Issue
Block a user