Search code examples
t4configurationmanager

Syntax for square brackets in a T4 Template statement block


I would like to use the System.Configuration assembly within a T4 template to get the connection string listed in the App.config of the project. However, the compiler does not seem to accept the [ ] in the statement block. How is this done?

<#@ assembly name="System.Configuration" #>
<#@ import namespace="System.Configuration"#>

<#

   var connectionString = ConfigurationManager.ConnectionStrings["localconnection"].ConnectionString;

#>

TIA


Solution

  • If you're running T4 at design time (CustomTool: TextTemplatingFilePreprocessor), the template code gets executed as part of VisualStudio process. VisualStudio is loading devenv.exe.config and not your project config (you can check via AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).

    That's why you get null ref exception - 'localconnection' connection string is not in devenv.exe.config.

    You can load your project config file using ConfigurationManager.OpenMappedExeConfiguration:

    <#@ template debug="false" hostspecific="true" language="C#" #>
    <#@ assembly name="System.Configuration" #>
    <#@ import namespace="System.Configuration"#>
    <#@ import namespace="System.IO" #>
    
    <#
        string configPath = Path.Combine(Host.ResolveAssemblyReference("$(ProjectDir)"), "App.config");
        var configFileMap = new ExeConfigurationFileMap{ExeConfigFilename = configPath};    
    
        var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
        string connectionString = config.ConnectionStrings.ConnectionStrings["localconnection"].ConnectionString;
    
        WriteLine(connectionString);
    #>
    

    Note, it must be hostspecific="true" in order to use Host to resolve your project folder.