T4Toolbox 删除 GeneratedCodeAttribute

T4Toolbox remove GeneratedCodeAttribute

我有以下问题: [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.34230")]

对于 windows 8 和 windows 7,当我们生成文件时,我们有这个数字的不同版本 (4.0.30319.34230)。因此,即使我生成了新内容,文件内部也发生了变化,唯一发生变化的就是这个数字。

有没有办法不将此属性添加到生成的代码中,或者有解决方案使 Windows 8 和 Windows 7 具有相同的数字?

我在tt文件中用下面的代码解决了:

...
<#@ assembly name="$(SolutionDir)../res/ICSharpCode.NRefactory.dll" #>
<#@ assembly name="$(SolutionDir)../res/ICSharpCode.NRefactory.CSharp.dll" #>
<#@ import namespace="ICSharpCode.NRefactory.CSharp" #>
<#@ import namespace="System.CodeDom.Compiler" #>
... 

<#+
public class XsdSchemaTransformer : CSharpTemplate
{
    public void TransformSchemas(TransformationContext transformationContext)
    {
        ...
        foreach (string file in files)
        {
            ...
            string transformText = typesTemplate.Transform();
            transformText = ModifyGeneratedCodeAttributeXmlVersionNumber(transformText);
            typesTemplate.Context.Write(typesTemplate.Output, transformText);
        }
    }

    private string ModifyGeneratedCodeAttributeXmlVersionNumber(string source)
    {
        CSharpParser parser = new CSharpParser();
        SyntaxTree syntaxTree = parser.Parse(source);
        IEnumerable<TypeDeclaration> typeDeclarations = syntaxTree.Descendants.OfType<TypeDeclaration>();
        foreach (TypeDeclaration typeDeclaration in typeDeclarations)
        {
            AttributeSection generatedCodeAttributeSection = typeDeclaration.Attributes.FirstOrDefault(x => x.Attributes.FirstOrDefault(y => IsTypeOfGeneratedCodeAttribute(y.Type)) != null);
            if (generatedCodeAttributeSection != null)
            {
                ICSharpCode.NRefactory.CSharp.Attribute generatedCodeAttribute = generatedCodeAttributeSection.Attributes.FirstOrDefault(x => IsTypeOfGeneratedCodeAttribute(x.Type));
                PrimitiveExpression primitiveExpression = (PrimitiveExpression)generatedCodeAttribute.Arguments.ElementAt(1);
                string xmlVersionNumber = Convert.ToString(primitiveExpression.Value);
                string[] splittedVersionNumber = xmlVersionNumber.Split('.');
                string formatedXmlVersionNumber = string.Format("{0}.{1}", splittedVersionNumber[0], splittedVersionNumber[1]);
                generatedCodeAttribute.Arguments.Remove(primitiveExpression);
                generatedCodeAttribute.Arguments.Add(new PrimitiveExpression(formatedXmlVersionNumber));
            }
        }

        return syntaxTree.GetText();
    }

    private bool IsTypeOfGeneratedCodeAttribute(AstType type)
    {
        return type.ToString().Equals(typeof(GeneratedCodeAttribute).FullName);
    }
}
#>

NRefacotry on nuget

结果是:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0")]