65.9K
CodeProject 正在变化。 阅读更多。
Home

自动 Resx 注释检查与 MSBuild 集成

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2010年8月25日

CPOL

1分钟阅读

viewsIcon

15922

downloadIcon

183

确保您的 resx 文件包含每个条目的有效注释,并与 MSBuild 集成。

引言

应用程序国际化通常使用 resx 文件来存储需要翻译的各种字符串。此工具可帮助您确保 Visual Studio 项目中的 resx 文件为每个条目都正确填充了注释值。

以下是结果的截图。

msbuild-resx-comment-checking1.png

它是如何工作的?

此工具使用了 MSBuild 的两个命名空间

为了实现自定义 MSBuild 任务,您只需要创建一个扩展 Microsoft.Build.Utilities.Task 抽象类的类,并在 Execute 方法中实现任务逻辑。返回值将指示任务是成功还是失败。

在此工具中,我们只想为每个缺失的条目添加一个警告,因此我们将始终返回 true

using System;
using System.Collections;
using System.IO;
using System.Resources;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MSBuild.Tools.Tasks {

    public class ResXCommentCheck : Task {

        public override bool Execute() {
            foreach (string file in Directory.GetFiles(Environment.CurrentDirectory, 
                "*.resx", SearchOption.AllDirectories)) {
                using (ResXResourceReader reader = new ResXResourceReader(file)) {
                    reader.UseResXDataNodes = true;
                    foreach (DictionaryEntry entry in reader) {
                        ResXDataNode node = (ResXDataNode)entry.Value;
                        if (string.IsNullOrEmpty(node.Comment)) {
                            Log.LogWarning(
                                "{0} doesn't contain any comment for the key {1}.",
                                Path.GetFileName(file), node.Name);
                        }
                    }
                }
            }
            return true;
        }
    }
}

MSBuild 集成

MSBuild 集成需要在 Visual Studio 项目(.vbproj.csproj 文件)中通过 UsingTask 节点完成,该节点可帮助您通过其 taskname(即类 FullName)和位置加载特定任务。

  • AssemblyFile 属性表示本地引用
  • AssemblyName 属性表示全局程序集缓存
<Project ToolsVersion="4.0" DefaultTargets="Build" 
    xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="MSBuild.Tools.Tasks.ResXCommentCheck"  
    AssemblyFile="c:\MSBuild.Tools.Tasks.dll" />
</Project>

可以在 AfterBuild 目标中调用自定义任务。

<Target Name="AfterBuild">
    <UsingTask TaskName="MSBuild.Tools.Tasks.ResXCommentCheck" 
        AssemblyFile="C:\MSBuild.Tools.Tasks.dll" />
</Target>

关注点

这个工具是我第一次使用自定义 MSBuild 任务的经验。正如您所看到的,API 非常易于使用,并且它提供了许多可能性来帮助开发人员检查他们的代码。

历史

  • 2010 年 8 月 25 日:初始发布
© . All rights reserved.