Tag Archives: Visual Studio

Transform T4 templates as part of the build, and pass variables from the project

T4 (Text Template Transformation Toolkit) is a great tool to generate code at design time; you can, for instance, create POCO classes from database tables, generate repetitive code, etc. In Visual Studio, T4 files (.tt extension) are associated with the TextTemplatingFileGenerator custom tool, which transforms the template to generate an output file every time you save the template. But sometimes it’s not enough, and you want to ensure that the template’s output is regenerated before build. It’s pretty easy to set this up, but there are a few gotchas to be aware of.

Transforming templates at build time

If your project is a classic csproj or vbproj (i.e. not a .NET Core SDK-style project), things are actually quite simple and well documented on this page.

Unload your project, and open it in the editor. Add the following PropertyGroup near the beginning of the file:

    <!-- 15.0 is for VS2017, adjust if necessary -->
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
    <!-- This is what will cause the templates to be transformed when the project is built (default is false) -->
    <!-- Set to true to force overwriting of read-only output files, e.g. if they're not checked out (default is false) -->
    <!-- Set to false to transform files even if the output appears to be up-to-date (default is true)  -->

And add the following Import at the end, after the import of Microsoft.CSharp.targets or Microsoft.VisualBasic.targets:

<Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />

Reload your project, and you’re done. Building the project should now transform the templates and regenerate their output.

SDK-style projects

If you’re using the new project format that comes with the .NET Core SDK (sometimes informally called "SDK-style project"), the approach described above will need a small change to work. This is because the default targets file (Sdk.targets in the .NET Core SDK) is now imported implicitly at the very end of the project, so you can’t import the text templating targets after the default targets. This causes the BuildDependsOn variable, which is modified by the T4 targets, to be overwritten, so the TransformAll target doesn’t run before the Build target.

Fortunately, there’s a workaround: you can import the default targets file explicitly, and import the text templating targets after that:

<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
<Import Project="$(VSToolsPath)\TextTemplating\Microsoft.TextTemplating.targets" />

Note that it will cause a MSBuild warning in the build output (MSB4011) because Sdk.targets is imported twice; you can safely ignore this warning.

Passing MSBuild variables to templates

At some point, the code generation logic might become too complex to remain entirely in the T4 template file. You might want to extract some of it into a helper assembly, and reference this assembly from the template, like this:

<#@ assembly name="../CodeGenHelper/bin/Release/net462/CodeGenHelper.dll" #>

Of course, specifying the path like this isn’t very very convenient… For instance, if you’re currently in Debug configuration, the Release version of CodeGenHelper.dll might be out of date. Fortunately, Visual Studio’s TextTemplatingFileGenerator custom tool recognizes MSBuild variables from the project, so you can do this instead:

<#@ assembly name="$(SolutionDir)/CodeGenHelper/bin/$(Configuration)/net462/CodeGenHelper.dll" #>

The $(SolutionDir) and $(Configuration) variables will be expanded to their actual values. If you save the template, the template will be transformed using the CodeGenHelper.dll assembly. Nice!

However, there’s a catch… if you configured the project to transform templates on build as described above, the build will now fail, with an error like this:

System.IO.FileNotFoundException: Could not find a part of the path ‘C:\Path\To\The\Project\$(SolutionDir)\CodeGenHelper\bin\$(Configuration)\net462\CodeGenHelper.dll’.

Notice the $(SolutionDir) and $(Configuration) variables in the path? They were not expanded! This is because the MSBuild target that transforms the templates and the TextTemplatingFileGenerator custom tool don’t use the same text transformation engine. And unfortunately, the one used by MSBuild doesn’t recognize MSBuild properties out of the box… Ironic, isn’t it?

All is not lost, though. All you have to do is explicitly specify the variables you want to pass as T4 parameters. Edit your project file again, and create a new ItemGroup with the following items:

    <T4ParameterValues Include="SolutionDir">
    <T4ParameterValues Include="Configuration">

The Include attribute is the name of the parameter as it will be passed to the text transformation engine. The Value element is, well, the value. And the Visible element prevents the T4ParameterValues item from appearing under the project in the solution explorer.

With this change, the build should now successfully transform the templates again.

So, just keep in mind that the TextTemplatingFileGenerator custom tool and the MSBuild text transformation target have different mechanisms for passing variables:

  • TextTemplatingFileGenerator supports only MSBuild variables from the project
  • MSBuild supports only T4ParameterValues

So if you use variables in your template and you want to be able to transform it when you save the template in Visual Studio and when you build the project, the variables have to be defined both as MSBuild variables and as T4ParameterValues.

Common MSBuild properties and items with Directory.Build.props

To be honest, I never really liked MSBuild until recently. The project files generated by Visual Studio were a mess, most of their content was redundant, you had to unload the projects to edit them, it was poorly documented… But with the advent of .NET Core and the new "SDK-style" projects, it’s become much, much better.

MSBuild 15 introduced a pretty cool feature: implicit imports (I don’t know if it’s the official name, but I’ll use it anyway). Basically, you can create a file named Directory.Build.props anywhere in your repo, and it will be automatically imported by any project under the directory containing this file. This makes it very easy to share common properties and items across projects. This feature is described in details in this documentation page.

For instance, if you want to share some metadata across multiple projects, just write a Directory.Build.props file in the parent directory of your projects:


    <Authors>John Doe</Authors>


You can also do more interesting things like enabling and configuring StyleCop for all your projects:


    <!-- Common ruleset shared by all projects -->

    <!-- Add reference to StyleCop analyzers to all projects  -->
    <PackageReference Include="StyleCop.Analyzers" Version="1.0.2" />
    <!-- Common StyleCop configuration -->
    <AdditionalFiles Include="$(MSBuildThisFileDirectory)stylecop.json" />


Note that the $(MSBuildThisFileDirectory) variable refers to the directory containing the current MSBuild file. Another useful variable is $(MSBuildProjectDirectory), which refers to the directory containing the project being built.

MSBuild looks for the Directory.Build.props file starting from the project directory and going up until it finds a matching file, then it stops looking. In some cases you might want to define some properties for all projects in your repo, and add some more properties in a subdirectory. To do this, the "inner" Directory.Build.props file will need to explicitly import the "outer" one:

  • (rootDir)/Directory.build.props:

  <!-- Properties common to all projects -->
  <!-- ... -->
  • (rootDir)/tests/Directory.build.props:

  <!-- Import parent Directory.build.props -->
  <Import Project="../Directory.Build.props" />

  <!-- Properties common to all test projects -->
  <!-- ... -->

The documentation mentions another approach, using the GetPathOfFileAbove function, but it didn’t seem to work when I tried… Anyway, I think using a relative path is easier to get right.

Using implicit imports brings the following benefits:

  • smaller project files, since common properties and items can be factored to common properties files.
  • single point of truth: if all projects reference the same package, the version to reference is defined in a single place; no more inconsistencies!

It also has a drawback: Visual Studio doesn’t care about where a property or item comes from, so if you change a property or a package reference from the IDE (using the project properties pages or NuGet Package Manager), it will be changed in the project file itself, rather than the Directory.Build.props file. The way I see it, it’s not a major issue, because I got into the habit of editing the projects manually rather than using the IDE features, but it might be annoying for some people.

If you want a real-world example of this technique in action, have a look at the FakeItEasy repository, where we use multiple Directory.Build.props files to keep the project files nice and clean.

Note that you can also create a Directory.Build.targets file, following the same principles, to define common build targets.

Testing and debugging library code from LINQPad

I’ve been meaning to blog about LINQPad in a very long time. In case you don’t know about it, LINQPad is a tool that lets you write and test code very quickly without having to create a full-blown project in Visual Studio. It supports C#, VB.NET, F# and SQL. It was initially intended as an educational tool to experiment with LINQ (its author, Joe Albahari, developed it as companion to his C# in a Nutshell book), but it’s also extremely useful as a general-purpose .NET scratchpad.

I frequently use LINQPad to quickly test a library that I’m working on. It’s very easy, just reference the assembly you want to test and start using it. But when the library doesn’t behave as expected, it’s often useful to be able to debug it step by step… It turns out that it’s pretty simple to do it from LINQPad!

The premium version of LINQPad has an integrated debugger, which isn’t as powerful as the one in Visual Studio, but is useful to debug LINQPad scripts. However, it doesn’t let you step into library code… Fortunately, there’s a trick to use the Visual Studio debugger to debug code running from LINQPad.

First, open your library in Visual Studio if you haven’t already. Build the solution, and add a reference to the assembly to your LINQPad script:

Add reference to the library

Write some code that uses your library:

Use your library from LINQPad

And add this line at the beginning of your LINQPad script:


When you run the script, it will open a dialog window prompting you to choose a debugger:

Choose a debugger

Select the Visual Studio instance in which your solution is loaded and click OK. This will attach the Visual Studio debugger to the process that is running the LINQPad script, and pause the execution on the call to Debugger.Launch():

Debugging in Visual Studio

You can now debug the LINQPad script and your library code. You can set breakpoints, step into methods, add watches, etc, just as when debugging a normal application!

Tuples in C# 7

A tuple is an finite ordered list of values, of possibly different types, which is used to bundle related values together without having to create a specific type to hold them.

In .NET 4.0, a set of Tuple classes has been introduced in the framework, which can be used as follows:

private static Tuple<int, double> Tally(IEnumerable<double> values)
	int count = 0;
	double sum = 0.0;
	foreach (var value in values)
	    sum += value;
	return Tuple.Create(count, sum);


var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.Item1} values and their sum is {t.Item2}");

There are two annoying issues with the Tuple classes:

  • They’re classes, i.e. reference types. This means they must be allocated on the heap, and garbage collected when they’re no longer used. For applications where performance is critical, it can be an issue. Also, the fact that they can be null is often not desirable.
  • The elements in the tuple don’t have names, or rather, they always have the same names (Item1, Item2, etc), which are not meaningful at all. The Tuple<T1, T2> type conveys no information about what the tuple actually represents, which makes it a poor choice in public APIs.

In C# 7, a new feature will be introduced to improve support for tuples: you will be able to declare tuples types “inline”, a little like anonymous types, except that they’re not limited to the current method. Using this new feature, the code above becomes much cleaner:

static (int count, double sum) Tally(IEnumerable<double> values)
	int count = 0;
	double sum = 0.0;
	foreach (var value in values)
	    sum += value;
	return (count, sum);


var values = ...
var t = Tally(values);
Console.WriteLine($"There are {t.count} values and their sum is {t.sum}");

Note how the return type of the Tally method is declared, and how the result is used. This is much better! The tuple elements now have significant names, and the syntax is nicer too. The feature relies on a new ValueTuple<T1, T2> structure, which means it doesn’t involve a heap allocation.

You can try this feature right now in Visual Studio 15 Preview 3. However, the ValueTuple<T1, T2> type is not (yet) part of the .NET Framework; to get this example to work, you’ll need to reference the System.ValueTuple NuGet package.

Finally, one last remark about the names of tuple members: like many other language features, they’re just syntactic sugar. In the compiled code, the tuple members are only referred to as Item1 and Item2, not count and sum. The Tally method above actually returns a ValueTuple<int, double>, not a specially generated type. Note that the compiler that ships with VS 15 Preview 3 emits no metadata about the names of the tuple members. This part of the feature is not yet implemented, but should be included in the final version. This means that in the meantime, you can’t use tuples across assemblies (well, you can, but you will lose the member names and will have to use Item1 and Item2 to refer to the tuple members).

Test driving C# 7 features in Visual Studio “15” Preview

About two weeks ago, Microsoft released the first preview of the next version of Visual Studio. You can read about what’s new in the release notes. Some of the new features are really nice (for instance I love the new “lightweight installer”), but the most interesting for me is that it comes with a version of the compiler that includes a few of the features planned for C# 7. Let’s have a closer look at them!

Enabling the new features

The new features are not enabled by default. You can enable them individually with /feature: command line switches, but the easiest way is to enable them all by adding __DEMO__ and __DEMO_EXPERIMENTAL__ to the conditional compilation symbols (in Project properties, Build tab).

Local functions

Most functional languages allow you to declare functions in the body of other functions. It’s now possible to do the same in C# 7! The syntax for declaring a method inside another is pretty much what you would expect:

long Factorial(int n)
    long Fact(int i, long acc)
        return i == 0 ? acc : Fact(i - 1, acc * i);
    return Fact(n, 1);

Here, the Fact method is local to the Factorial method (in case you’re wondering, it’s a tail-recursive implementation of the factorial — which doesn’t make much sense, since C# doesn’t support tail recursion, but it’s just an example).

Of course, it was already possible to simulate local functions with lambda expressions, but there were a few drawbacks:

  • it’s less readable, because you have to declare the delegate type explicitly
  • it’s slower, due to the overhead of creating a delegate instance, and calling the delegate vs. calling the method directly
  • writing recursive lambdas is a bit awkward

Local functions have the following benefits:

  • when a method is only used as a helper for another method, making it local makes the relation more obvious
  • like lambdas, local functions can capture local variables and parameters of their containing method
  • local functions support recursion like any normal method

You can read more about this feature in the Roslyn Github repository.

Ref returns and ref locals

Since the first version of C#, it has always been possible to pass parameters by reference, which is conceptually similar to passing a pointer to a variable in languages like C. Until now, this feature was limited to parameters, but in C# 7 it becomes possible to return values by reference, or to have local variables that refer to the location of another variable. Here’s an example:

static void TestRefReturn()
    var foo = new Foo();
    Console.WriteLine(foo); // 0, 0
    foo.GetByRef("x") = 42;

    ref int y = ref foo.GetByRef("y");
    y = 99;

    Console.WriteLine(foo); // 42, 99

class Foo
    private int x;
    private int y;

    public ref int GetByRef(string name)
        if (name == "x")
            return ref x;
        if (name == "y")
            return ref y;
        throw new ArgumentException(nameof(name));

    public override string ToString() => $"{x},{y}";

Let’s have a closer look at this code.

  • On line 6, it looks like I’m assigning a value to the return of a method; what does this even mean? Well, the GetByRef method returns a field of the Foo class by reference (note the ref int return type of GetByRef). So, if I pass "x" as an argument, it returns the x field by reference. If I assign a value to that, it actually assigns a value to the x field.
  • On line 8, instead of just assigning a value directly to the field returned by GetByRef, I use a ref local variable y. The local variable now shares the same memory location as the foo.y field. So if I assign a value to it, it changes the value of foo.y.

Note that you can also return an array location by reference:

private MyBigStruct[] array = new MyBigStruct[10];
private int current;

public ref MyBigStruct GetCurrentItem()
    return ref array[current];

It’s likely that most C# developers will never actually need this feature; it’s pretty low level, and not the kind of thing you typically need when writing line-of-business applications. However it’s very useful for code whose performance is critical: copying a large structure is expensive, so if we can return it by reference instead, it can be a non-negligible performance benefit.

You can learn more about this feature on Github.

Pattern matching

Pattern matching is a feature very common in functional languages. C# 7 introduces some aspects of pattern matching, in the form of extensions to the is operator. For instance, when testing the type of a variable, it lets you introduce a new variable after the type, so that this variable is assigned with the left-hand side operand of the is, but with the type specified as the right-hand side operand (it will be clearer with an example).

Typically, if you need to test that a value is of type DateTime, then do something with that DateTime, you need to test the type, then cast to that type:

object o = GetValue();
if (o is DateTime)
    var d = (DateTime)o;
    // Do something with d

In C# 7, you can do this instead:

object o = GetValue();
if (o is DateTime d)
    // Do something with d

d is now declared directly as part of the o is DateTime expression.

This feature can also be used in a switch statement:

object v = GetValue();
switch (v)
    case string s:
        Console.WriteLine($"{v} is a string of length {s.Length}");
    case int i:
        Console.WriteLine($"{v} is an {(i % 2 == 0 ? "even" : "odd")} int");
        Console.WriteLine($"{v} is something else");

In this code, each case introduces a variable of the appropriate type, which you can use in the body of the case.

So far I only covered pattern matching against a simple type, but there are also more advanced forms. For instance:

switch (DateTime.Today)
    case DateTime(*, 10, 31):
        Console.WriteLine("Happy Halloween!");
    case DateTime(var year, 7, 4) when year > 1776:
        Console.WriteLine("Happy Independence Day!");
    case DateTime { DayOfWeek is DayOfWeek.Saturday }:
    case DateTime { DayOfWeek is DayOfWeek.Sunday }:
        Console.WriteLine("Have a nice week-end!");

How cool is that!

There’s also another (still experimental) form of pattern matching, using a new match keyword:

object o = GetValue();
string description = o match
        case string s : $"{o} is a string of length {s.Length}"
        case int i : $"{o} is an {(i % 2 == 0 ? "even" : "odd")} int"
        case * : $"{o} is something else"

It’s very similar to a switch, except that it’s an expression, not a statement.

There’s a lot more to pattern matching than what I mentioned here. You can look at the spec on Github for more details.

Binary literals and digit separators

These features were not explicitly mentioned in the VS Preview release notes, but I noticed they were included as well. They were initially planned for C# 6, but didn’t make it in the final release. They’re back in C# 7.

You can now write numeric literal in binary, in addition to decimal an hexadecimal:

int x = 0b11001010;

Very convenient to define bit masks!

To make large numbers more readable, you can also group digits by introducing separators. This can be used for decimal, hexadecimal or binary literals:

int oneBillion = 1_000_000_000;
int foo = 0x7FFF_1234;
int bar = 0b1001_0110_1010_0101;


So, with Visual Studio “15” Preview, you can start experimenting with the new C# 7 features; don’t hesitate to share your feedback on Github! And keep in mind that it’s still pre-release software, lots of things can change before the final release.

Visual Studio Online + Git integration with Team Explorer

I recently started using Visual Studio Online for personal projects, and I must say it’s a pretty good platform, although it would be nice to be able to host public projects as well as private ones. The thing I like the most is the integration with Visual Studio Team Explorer to manage work items and builds.

However, I noticed a little gotcha when using Git for source control : the remote for VS Online must be named origin, otherwise Team Explorer won’t detect that it’s a VS Online project, and it won’t show the “Builds” and “Work items” pages.

 When VSO remote is named "origin" When VSO remote is named "vso"

This is obviously a bug (although a minor one), since the name origin is just a convention and a git remote can have any name; I reported it on Connect. If you encounter it you can easily work around it by renaming your remote to origin:

git remote rename vso origin

Running a custom tool automatically when a file is modified

As far as I can remember, Visual Studio always had something called “custom tools”, also known as single-file generators. When you apply such a tool to a file in your project, it will generate something (typically code, but not necessarily) based on the content of the file. For instance, the default custom tool for resource files is called ResXFileCodeGenerator, and generates a class that provides easy access to the resources defined in the resx file.


When you save a file that has a custom tool associated to it, Visual Studio will automatically rerun the custom tool to regenerate its output. You can also do it manually, by invoking the “Run custom tool” command in the context menu of a project item.

Usually, the custom tool needs only one input file to generate its output, but sometimes things are a bit more complex. For instance, consider T4 templates : they have a custom tool associated with them (TextTemplatingFileGenerator), so this tool will be run when the template is saved, but in many cases, the template itself uses other input files to generate its output. So the custom tool needs to be run not only when the template is modified, but also when files on which the template depends are modified. Since there is no way to tell Visual Studio about this dependency, you have to rerun the custom tool manually, which is quite annoying…

Because I was in this situation, and was tired of manually invoking the “Run custom tool” command on my T4 templates, I eventually created a Visual Studio extension to do this automatically: AutoRunCustomTool. The name isn’t very imaginative, but at least it’s descriptive…

This tool is designed to be very simple and unobtrusive; it just does its work silently, without getting in your way. It adds a new property to each project item : “Run custom tool on”. This property is a collection of file names for which the custom tool must be run every time this project item is saved. For instance, if you have a T4 template (Template.tt) that generates a file (Output.txt) based on the content of another file (Input.txt), you just need to add “Template.tt” to the “Run custom tool on” property of Input.txt. Every time you save Input.txt, the custom tool will be automatically rerun on Template.tt, which will regenerate the content of Output.txt. You can see a concrete example on the tool’s page in Visual Studio Gallery.

I created AutoRunCustomTool about 6 months ago, but the initial version was a bit rough around the edges, so I didn’t communicate about it. I released the second version a few days ago, and I think it’s now ready for everyone to use. If you’re interested in the code, you can find it on GitHub, which is also the place to report issues and suggest improvements.

[VS2010] Binding support in InputBindings

THE feature that was missing from WPF !

Visual Studio 2010 beta 2 has been released last week, and it brings to WPF a long awaited feature : support for bindings in InputBindings.

As a reminder, the issue in previous releases was that the Command property of the InputBinding class wasn’t a DependencyProperty, so it wasn’t possible to bind it. Furthermore, InputBindings didn’t inherit the parent DataContext, which made it difficult to provide alternative implementations…

Until now, in order to bind the Command of a KeyBinding or MouseBinding to a property of the DataContext, we had to resort to clumsy workarounds… I had eventually came up with an acceptable solution, described in this post, but I wasn’t really satisfied with it (it used reflection on private members, and had annoying limitations).

More recently, I found a better solution in the MVVM toolkit : a CommandReference class, inherited from Freezable, allows to put a reference to a ViewModel command in the page or control resources, so that it can be used later with StaticResource. It’s much cleaner than my previous solution, but still not very straightforward…

WPF 4.0 solves that problem once and for all : the InputBinding class now inherits from Freezable, which allows it to inherit the DataContext, and the Command, CommandParameter and CommandTarget properties are now dependency properties. So, at last, we can forget about the clumsy workarounds described above, and go straight to the point :

        <KeyBinding Key="F5"
                    Command="{Binding RefreshCommand}" />

This new feature should make it much easier to develop MVVM applications !

Help 3

Other than that, I would like to say a few words about the new offline help system that comes with Visual Studio 2010, called “Help 3”. It’s quite a big change compared to previous versions… First, it’s not a standalone application anymore, but a locally hosted web application, so you can access the documentation with your favorite web browser. On the whole, it’s better than the previous system… much faster and more responsive than the old Document Explorer included in previous Visual Studio releases.

However, the new system misses the feature that was the most useful to me : the index ! Now there’s only the hierarchical view, and a search textbox. IMHO, the index was the most convenient way of looking up something in the doc, it made it very easy to access a class or member directly, even without knowing its namespace… why on earth did they remove it ? Worse still : the search results don’t show the namespace, only the class or member name. For instance, if you search “button class”, in the results there is no way to see the difference between System.Windows.Forms.Button, System.Windows.Controls.Button and System.Web.UI.WebControls ! You have to click each link and see where it leads… In Document Explorer, the Index Results pane showed this information clearly.

So, eventually I have mixed feelings about this new help system, because I will have to change the way I use the documentation. But except for this annoying detail, I must concede that it’s objectively a big improvement over the old system…

[Visual Studio] Trick : make a project item a child item of another

You probably noticed that, in a C# project tree, some items are placed “under” a parent item : it is the case, for instance, for files generated by a designer or wizard :

Solution Explorer
Model1.Designer.cs is a child item of Model1.edmx

The following trick shows how to apply the same behavior to your own files.

Let’s assume that you want to customize the classes generated by the EDM designer. You can’t modify the Model1.designer.cs file, because you changes would be overwritten by the designer. So you create a new file, say Model1.Custom.cs, where you will write your custom code for the entity classes (using the partial keyword). By default, this file is placed at the root of the project :

Solution Explorer
Model1.Custom.cs is at the root of the project

In order to show clearly the association with Model1.edmx, we would like to make Model1.Custom.cs a child item of Model1.edmx, at the same level as Model1.designer.cs… Even though the Visual Studio IDE doesn’t offer that option, it is possible : you just need to edit the .csproj file manually. The easiest way to do that is to unload the project (right click on the project, “Unload project“), and edit it directly in Visual Studio (right click, “Edit FooBar.csproj“). Find the <Compile> element corresponding to Model1.Custom.cs, and add a <DependentUpon> child element, as show below :

    <Compile Include="Model1.Custom.cs">

Reload the project : Model1.Custom.cs now appears as a child item of Model1.edmx.

Solution Explorer
Model1.Custom.cs is now a child item of Model1.edmx

This trick enables you to organize your project better and make its structure clearer.