Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/nogic1008/t4sample

How to Use T4 in .NET Core + VSCode
https://github.com/nogic1008/t4sample

code-generation csharp dotnet dotnet-core t4

Last synced: 5 days ago
JSON representation

How to Use T4 in .NET Core + VSCode

Awesome Lists containing this project

README

        

# T4Sample (How to Use T4 in .NET Core + VSCode)

[![License](https://img.shields.io/github/license/nogic1008/T4Sample)](LICENSE)

This is a sample to create a table Entity class using T4.

In Japanese, see also [.NET Core+VS CodeでもT4 テンプレートエンジンでコード生成したい!](https://qiita.com/nogic1008/items/2c4049d43a11e83df15b)

## Environments

- .NET Core 3.1 SDK
- For use ["default implementation of interfaces"](https://docs.microsoft.com/dotnet/csharp/tutorials/default-interface-members-versions).

- Visual Studio Code
- Required: [C# Extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp)
- Recommended: [T4 Support](https://marketplace.visualstudio.com/items?itemName=zbecknell.t4-support) to highlight T4 Documents.

## What is "T4"?

T4 means "Text Template Transformation Toolkit".
It is bundled to Visual Studio since 2008.

It is often used for automatic code generation such as table definition classes.

This sample uses [Mono.TextTemplating](https://github.com/mono/t4) which is a T4 implemented by Mono Project.

## Processes

### 1. Install .NET local tool

```console
# You should create manifest file before install local tool.
> dotnet new tool-manifest
# Install T4 tool in local
> dotnet tool install dotnet-t4
```

```json
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-t4": {
"version": "2.2.1",
"commands": [
"t4"
]
}
}
}
```

**Note: You should call `dotnet tool restore` command after cloned repo.**

### 2. Create Project

```console
> dotnet new console -n T4Sample -o ./src
```

### 3. Create Table and Column Entities

- [ColumnInfo.cs](./src/ColumnInfo.cs)
- [TableInfo.cs](./src/TableInfo.cs)

### 4. Install Mono.TextTemplating from NuGet

The program code generated by T4 file depends on this package.

```console
> dotnet add package Mono.TextTemplating --version 2.2.1
```

### 5. Add Task to Prebuild and Cleanup

#### Define Target Files

Define `TextTemplate` and `Genarated` using Glob.

```diff


+
+

```

#### Define Prebuild Task

Define Task to run `dotnet t4`.

- `%(TextTemplate.Identity)`
- T4 File Paths such as *foo/Template.tt*.
- `$(RootNameSpace)`
- Default Namespace.
If you changed the T4 class's namespace, set it exactly.
- `%(TextTemplate.Filename)`
- T4 File Name.

```diff

+
+
+
```

#### Define Cleanup Task

Define Task to delete `*.Generated.cs`.

```diff

+
+
+
```

### 6. Create T4 Interface and define implements

`TransFormText()`, Called by Program to use T4 Classes are defined in *\*.Generated.cs*.
But \*.Generated.cs is generated just before the build.
So calling `TransFormText()` will cause a compile error because there is no definition at before build time.

This sample avoids this by using the "default implementation of interfaces".

```csharp
using System;

namespace T4Sample
{
public interface ITextTemplate
{
string TransformText() => throw new NotImplementedException();
}
}
```

### 7. Create T4 Template File & Class

Note that T4 class should be defined with `partial` class.

- [TableEntityTemplate.tt](./src/TableEntityTemplate.tt)
- [TableEntityTemplate.cs](./src/TableEntityTemplate.cs)

### 8. Call T4 Class in Program.cs

Note that variable type should be an interface. **Don't** use `var` or `TableEntityTemplate`.

- [Program.cs](./src/Program.cs)

## Build & Run

### Build

```console
> dotnet build
```

`TableEntityTemplate.Generated.cs` is generated and the program is built including it.

### Run

`dotnet run` does not cause Beforebuild-Event, you should execute `dotnet build` first.

```console
> cd src
> dotnet run
```

### Result

```csharp
using System;
using System.Collections.Generic;

namespace MyNameSpace
{
///
/// Stores employee information.
///
public class StaffMaster
{
public int StaffId { get; }

public string StaffName { get; set; }

///
/// Home Address.
///
public string Address { get; set; }

public DateTime CreatedDate { get; set; }

public StaffMaster(
int staffId
)
{
StaffId = staffId;
}

public StaffMaster(
int staffId,
string staffName,
string address,
DateTime createdDate
)
{
StaffId = staffId;
StaffName = staffName;
Address = address;
CreatedDate = createdDate;
}
}
}
```

## References

- [T4 Templates at Build Time with Dotnet Core](https://notquitepure.info/2018/12/12/T4-Templates-at-Build-Time-With-Dotnet-Core/)
- [Mono/T4](https://github.com/mono/t4)