0

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

Alan Wayne
  • 5,122
  • 10
  • 52
  • 95
  • What error do you get? – Alex Pokislyuk Jul 24 '16 at 14:52
  • Possibly a duplicate of [how-to-make-connection-strings-available-in-a-t4-template](http://stackoverflow.com/questions/25460348/how-to-make-connection-strings-available-in-a-t4-template) – Alex Pokislyuk Jul 24 '16 at 14:54
  • @AlexP Sorry for taking so long to reply. With some study of the tmp files, it turns out that the [] string was being correctly compiled, but the configuration manager was not seeing the connection string in the App.config of the project -- so "null" was being returned. By looping through all the connection strings, only the default machine.config connection string is being found--not the one specific to the console project. :( (VS 2015) Thanks for any guidance on this. (I have applied your link before writing this question and it did not work :( ). – Alan Wayne Jul 25 '16 at 01:12

1 Answers1

1

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.

Alex Pokislyuk
  • 213
  • 3
  • 8