Item templates and custom resources

In a previous post I wrote about Custom resources with T4 templates. Back then I used the ReSharper multi-file templates to add the .resx and .tt files to my projects. The one downside of that approach: it requires R# 8.x which might not be readily available.

Thus I wanted to find out how to create a Visual Studio item template that achieves the same goal. Microsoft has a step-by-step guide that explains the process. That gives you the basics. But there is some fine-tuning that they don’t explain.

If you add a .resx file to your project the generated .Designer.cs file is hidden in the solution explorer. I wanted to do the same and hide the .tt file underneath the .resx file. Preferably I wanted both the .tt and the generated .Designer.cs file on the level directly below the .resx file (as shown in the first screenshot). But the TextTemplatingFileGenerator always puts the generated output file on the level below the .tt file (as in the second screenshot) on every run. I decided to stop battling VS. Its not worth the effort in this case.

Screenshot 1: Nice to have

Screenshot 1: Nice to have

Screenshot 2: What you actually get

Screenshot 2: What you actually get

To actually hide the .tt file via the item template is quite easy if not really prominently advertised. There’s a post on stackoverflow that explains how you need to modify your template.

The second <ProjectItem> is the interesting part. You need to prefix the .tt file with the path to the .resx file. When the item template is invoked that will translate to a <DependentUpon> clause in your project file.

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>Resource.resx</DefaultName>
    <Name>Customizable resources</Name>
    <Description>Creates a .resx file that uses a T4 template to generate strongly typed resources.</Description>
    <ProjectType>CSharp</ProjectType>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References>
      <Reference>
        <Assembly>System</Assembly>
      </Reference>
      <Reference>
        <Assembly>mscorlib</Assembly>
      </Reference>
    </References>
    <ProjectItem SubType="" TargetFileName="$fileinputname$.resx" ReplaceParameters="true">Resource.resx</ProjectItem>
    <ProjectItem SubType="" TargetFileName="$fileinputname$.resx\$fileinputname$.tt" ReplaceParameters="true">Resource.tt</ProjectItem>
  </TemplateContent>
</VSTemplate>

File 1: MyTemplate.vstemplate

Also make sure that you set ReplaceParameters="true" for the .resx file. You will want to add template parameters for the namespace and the class name.

For that I used two of the predefined parameters: $rootnamespace$ and $safeitemname$. Note that the first one gives you the full path to your .resx file and not the root namespace of the current project! If you place the resources in project Foo in the folder Assets the value of $rootnamespace$ will thus be Foo.Assets. Maybe someone at MS thought that’s a funny way to lead developers on a wild goose chase …

And that’s what the .tt file looks like

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34003
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".Designer.cs" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml.Linq" #>

namespace $rootnamespace$
{
    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.Resources;
    using System.Threading;
    using MyI18n;

    public class $safeitemname$
    {
        private static IResourceManager resourceManager;
        private static CultureInfo resourceCulture;

        [EditorBrowsableAttribute(EditorBrowsableState.Advanced)]
        public static IResourceManager ResourceManager
        {
            get
            {
                if(resourceManager == null)
                {
                    IResourceManager temp = new ResourceManagerWrapper(new ResourceManager("$rootnamespace$.$safeitemname$", typeof($safeitemname$).Assembly));
                    resourceManager = temp;
                }

                return resourceManager;
            }

            set
            {
                resourceManager = value;
            }
        }

        [EditorBrowsableAttribute(EditorBrowsableState.Advanced)]
        public static CultureInfo Culture
        {
            get
            {
                return resourceCulture;
            }

            set
            {
                resourceCulture = value;
            }
        }
<#
    string resxFileName = this.Host.TemplateFile.Replace(".tt", ".resx");
    XDocument doc = XDocument.Load(resxFileName);

    if(doc != null && doc.Root != null)
    {
        foreach(XElement x in doc.Root.Descendants("data"))
        {
            string name = x.Attribute("name").Value;
            WriteLine(string.Empty);
            WriteLine("        public static string " + name);
            WriteLine("        {");
            WriteLine("            get { return $safeitemname$.ResourceManager.GetString(\"" + name + "\", resourceCulture ?? CultureInfo.CurrentUICulture); }");
            WriteLine("        }");
        }
    }
#>
    }
}

File 2: Resource.tt

Don’t forget to adjust your using statements to the location of the IResourceManager interface and the ResourceManagerWrapper class.

Your .zip file should look something like this:

Screenshot 3: Contents of the .zip file

Screenshot 3: Contents of the .zip file

 

Now copy it to "C:\Users\[YOUR USERNAME]\Documents\Visual Studio [YOUR VISUAL STUDIO VERSION]\Templates\ItemTemplates\Visual C#" and fire up VS. Once you click “Add new item” your new template should appear right on top of the “Visual C# Items”.

Screenshot 4: Add new item

Screenshot 4: Add new item

 

You can download the template from my pet project’s site.

Advertisements

Custom resources with T4

Resource files are an old hat in .NET. They have been around since v1.1 and are one popular way to localize strings in an application.

Visual Studio provides two built-in tools (namely PublicResXFileCodeGenerator and ResXFileCodeGenerator) that generate code from the *.resx files. They generate classes with different visibility (public vs. internal) but the result is otherwise the same. You get a property to get and set the culture of the resource (to override the usage of the current UI culture), a hardwired instance of the framework’s ResourceManager and a bunch of static properties that forward the call to their getter to the ResourceManager. Nothing truly spectacular so far.

The ResourceManager takes care of the hassles of getting the correct version of your resources out of the files and the static properties allow for very convenient usage throughout your application. Alas, life could be so easy if customers were satisfied with that scenario. But they want to be able to customize their application (preferably without the involvement of a developer) to fit the corporate identity, use established vocabulary etc. pp.

Hard-wired static classes just don’t fit those customer requirements. But I believe they are a very good first step on the way if you could just tweak them a bit.

Unfortunately you cannot do anything to make those classes any more flexible. They are not partial. The creation of and the access to the ResourceManager is out of your reach. You get what the tools give you. Nothing more and nothing less. As I did not want to go through the painful process of writing a custom extension for VS I looked for a different approach. And found the Text Template Transformation Toolkit (T4).

I even found a tutorial on CodeProject that explains how to do what I wanted to achieve. I just wanted my result to look a little different.

What were my requirements?

  • Static properties for convenient access to the localized resources
  • Allow to replace the ResourceManager by editing the template
  • Allow to replace the ResourceManager at runtime via settable property
  • Avoid the complexity of overwriting the virtual methods of ResourceManager

Lets start from the last requirement. The ResourceManager class has way to much functionality for my liking even if most of that functionality seems to be accessible to derived types via virtual methods. So I decided to create a very simple interface that contains the only method that is used by the generated resource classes.

public interface IResourceManager
{
  string GetString(string name, CultureInfo culture);
}

An equally simple adapter from interface to the framework class allows me to use the default ResourceManager.

public class ResourceManagerWrapper : IResourceManager
{
  private readonly ResourceManager resourceManager;

  public ResourceManagerWrapper(ResourceManager resourceManager)
  {
    this.resourceManager = resourceManager;
  }

  public string GetString(string name, CultureInfo culture)
  {
    return this.resourceManager.GetString(name, culture);
  }
}

I added a setter to the static ResourceManager property and changed its type to IResourceManager. And finally I added a fallback to the default ResourceManager in case someone sets the property to null. The result is functionally identical to the code that VS generates but looks less generated. But that’s a matter of taste. Below is a sample of the generated output.

public class Labels
{
  private static IResourceManager resourceManager;
  private static CultureInfo resourceCulture;

  [EditorBrowsableAttribute(EditorBrowsableState.Advanced)]
  public static IResourceManager ResourceManager
  {
    get
    {
      if(resourceManager == null)
      {
        IResourceManager temp = new ResourceManagerWrapper(new ResourceManager("Main.Assets.Resources.Labels", typeof(Labels).Assembly));
        resourceManager = temp;
      }
      return resourceManager;
    }
    set
    {
      resourceManager = value;
    }
  }
  [EditorBrowsableAttribute(EditorBrowsableState.Advanced)]
  public static CultureInfo Culture
  {
    get
    {
      return resourceCulture;
    }
    set
    {
      resourceCulture = value;
    }
  }
  public static string MyMultiLanguageString
  {
    get { return ResourceManager.GetString("MyMultiLanguageString", resourceCulture ?? CultureInfo.CurrentUICulture); }
  }
}

That was the boring part I guess. The actual template file being the more interesting one.

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34003
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".Designer.cs" #>
<#@ assembly name="EnvDTE" #>
<#@ assembly name="System.IO" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml.Linq" #>

namespace Main.Assets.Resources
{
    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.Resources;
    using System.Threading;
    using Infrastructure.I18n;

    public class Labels
    {
        private static IResourceManager resourceManager;
        private static CultureInfo resourceCulture;

        [EditorBrowsableAttribute(EditorBrowsableState.Advanced)]
        public static IResourceManager ResourceManager
        {
            get
            {
                if(resourceManager == null)
                {
                    IResourceManager temp = new ResourceManagerWrapper(new ResourceManager("Main.Assets.Resources.Labels", typeof(Labels).Assembly));
                    resourceManager = temp;
                }

                return resourceManager;
            }

            set
            {
                resourceManager = value;
            }
        }

        [EditorBrowsableAttribute(EditorBrowsableState.Advanced)]
        public static CultureInfo Culture
        {
            get
            {
                return resourceCulture;
            }

            set
            {
                resourceCulture = value;
            }
        }
<#
    string resxFileName = this.Host.TemplateFile.Replace(".tt", ".resx");
    XDocument doc = XDocument.Load(resxFileName);

    if(doc != null && doc.Root != null)
    {
        foreach(XElement x in doc.Root.Descendants("data"))
        {
            string name = x.Attribute("name").Value;
            WriteLine(string.Empty);
            WriteLine("        public static string " + name);
            WriteLine("        {");
            WriteLine("            get { return ResourceManager.GetString(\"" + name + "\", resourceCulture ?? CultureInfo.CurrentUICulture); }");
            WriteLine("        }");
        }
    }
#>
    }
}

One thing to notice is that the namespace for the generated file is hardcoded in the template. This has several reasons.

While T4 is an awesome idea, MS managed to mess it up (as usual you might add). There is a VS implementation of ITextTemplatingHostEngine (which allows you to debug your template from the solution explorer. +1 for that feature!) and one for MSBuild (which does not support debugging as far as I found out). Those implementations are your entry point into the VS API from inside a template. As you might expect: They have just enough subtle differences to screw you up… Getting the correct namespace for a file is just one of them.

Another thing is that I decided to go with one template per *.resx file. You can enhance the template and locate all input files for code generation in your solution and compute the output destination and… I wanted a simple solution so I did not go that route.

And last but not least: I use ReSharper’s Multifile Templates to create new *.resx files. That gives me the resources and the templates in a single step. ReSharper has a macro to insert the default namespace of a project into the template file. I have a convention for the folder structure in which I place resource files so I can just append that to the namespace an be done with it.

And the really, really last thing I want to mention before I finish this post: You can hook up the generation process of your templates to MSBuild (which is the reason I noticed the differences between the VS and the MSBuild template engine). That way you can be sure that your build always uses the latest generated resource code and avoid the error prone step of manually calling “Run custom tool” after you made changes to a *.resx files. Oleg Sych collected a lot of information related to T4 in his blog.