Joe
Joe

Reputation: 6806

Trouble using a T4 Template in a .NET Core project

I'm trying to use the approach described here to employ T4 Templates to automatically increment my build numbers in a .NET Core 3.1 project. Unfortunately it's not working. My generated assembly just has 1.0.0 as the version. I'm wondering if anyone can tell me what I'm doing wrong:

First I created my "Version.tt" file and wrote (copied) the T4 Template as described.

<#@ template language="C#" #>
// 
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
//

using System.Reflection;

[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0.<#= this.BuildNumber #>")]
[assembly: AssemblyInformationalVersion("2.0.0.<#= this.BuildNumber #>")]
<#+
    int BuildNumber    = (int)(DateTime.Now - new DateTime(2020,1,1)).TotalDays;
#>

Then I placed this file in the root folder and added it to my project as a link

enter image description here

But when I built and looked at the assembly properties from Windows Explorer, it just says it's "1.0.0". In VS the project, I took a look at the properties of the TT file and I see this:

enter image description here

I tried searching through the directories and I don't see any sort of output file for this. Is there some step I'm missing? Do I need to change one of these properties? I didn't see anything in "Build Action" that seemed to apply.

Upvotes: 1

Views: 1548

Answers (1)

Jazimov
Jazimov

Reputation: 13292

I ran through your example. Apologies--in your case you want the Build Action to be None.

enter image description here

What worked for me is this template (showing some example import statements, should your template needs become more robust...):

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text.RegularExpressions" #>
// Generated by a T4 template!
using System.Reflection;

[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0.<#= this.BuildNumber #>")]
[assembly: AssemblyInformationalVersion("2.0.0.<#= this.BuildNumber #>")]
<#+
    int BuildNumber    = (int)(DateTime.Now - new DateTime(2020,1,1)).TotalDays;
#>

Because you're trying to generate your own AssemblyInfo.cs file, I suggest placing this T4 template in the Properties folder of your project and deleting the existing AssemblyInfo.cs file that's there. As soon as you save the T4 template, it will get build and generate AssemblyInfo.cs immediately (if no errors occurred). I tested the above and it works.

Upvotes: 1

Related Questions