T4 templates using own project .config file
January 17, 2009 4 Comments
One of the first problem one faces, as soon as he decides to include T4 templates in a project, is how to access .config file of the project. Most of the times .config files are used to store information as connection strings, as well as, other application wide settings, critical to the application. When a T4 template is transformed, it is not run under the context of the project it belongs; the context it runs is the context of the utility that performs the text transformation. Most of the times the utility is TextTemplatingFileGenerator.exe.
The need to access information from app.config from T4 templates, drive me create a T4 template include file, that gives me access to app.config information the same way as ConfigurationManagerobject. You can find this file here:
https://skydrive.live.com/redir.aspx?cid=1a746c4e01342b70&resid=1A746C4E01342B70!502&parid=root
I also included in the archive, a T4 template that demonstrate its usage; it’s easy to instantiate the object:
IServiceProvider hostServiceProvider = (IServiceProvider)this.Host;
SettingsManager config = new SettingsManager(hostServiceProvider);
Then it’s easy to read the configuration from the project:
this.ClearIndent(); this.WriteLine("Namespace : {0}", config.Namespace); this.WriteLine("AssemblyName: {0}", config.AssemblyName); this.WriteLine("ProjectPath : {0}", config.ProjectPath); this.WriteLine("ConfigPath : {0}", config.ConfigPath); this.WriteLine("Is App : {0}", config.IsApplication); this.WriteLine("Is WebApp : {0}", config.IsWebApplication); // Display each ConnectionStringSettings. this.WriteLine(""); this.WriteLine("ConnectionStrings:"); this.PushIndent("\t"); foreach (ConnectionStringSettings connectionstringentry in config.ConnectionStrings) { this.WriteLine("Name: {0}, ConnectionString: {1}, ProviderName: {2}", connectionstringentry.Name, connectionstringentry.ConnectionString, connectionstringentry.ProviderName); } this.PopIndent(); this.WriteLine(""); // Display each KeyValueConfigurationElement. this.WriteLine("ApplicationSettings:"); this.PushIndent("\t"); foreach (KeyValueConfigurationElement keyValueElement in config.AppSettings) { this.WriteLine("Key: {0}, Value: {1}", keyValueElement.Key, keyValueElement.Value); } this.PopIndent(); this.WriteLine("");
Hope you find the template useful…
How can I get the zip file from http://cid-1a746c4e01342b70.skydrive.live.com/embedrowdetail.aspx/T4Templates/SettingsManager.zip? The URL gives back “This item won’t load right now”.
Thanks,
Hong Shen
You can try the link SettingsManager.zip instead!
Regards,
George J.
Got it. Thanks. Will try it.
Hong
Pingback: Table To Enum Using T4 Template « .Net'ers