Skip to content

Instantly share code, notes, and snippets.

@FernandoVezzali
Created May 16, 2014 15:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FernandoVezzali/782d6c9e53ff8fe7204d to your computer and use it in GitHub Desktop.
Save FernandoVezzali/782d6c9e53ff8fe7204d to your computer and use it in GitHub Desktop.
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
using System.Configuration;
public static class ConnectionStrings
{
<#
foreach(XElement c in ReadConfig())
{
string cnName = c.Attribute(XName.Get("name")).Value;
string propName = CleanName(cnName);
#>
public static string <#= propName #>
{
get { return ConfigurationManager.ConnectionStrings["<#= cnName #>"].ConnectionString; }
}
<#
}
#>
}
<#+
private string CleanName(string name)
{
return name.Replace(" ", string.Empty);
}
private IEnumerable<XElement> ReadConfig()
{
string cfgPath = GetConfigFilePath();
if(string.IsNullOrEmpty(cfgPath))
{
return new List<XElement>();
}
XDocument cfg = XDocument.Load(cfgPath);
XElement cnElement = cfg.Root.Element(XName.Get("connectionStrings"));
if(cnElement == null)
{
Error("connectionStrings node was not found in the configuration file");
return new List<XElement>();
}
return cnElement.Elements();
}
private string GetConfigFilePath()
{
FileInfo fi = new FileInfo(Host.TemplateFile);
string currentFolder = fi.Directory.FullName;
string appConfig = Path.Combine(currentFolder, "App.config");
string webConfig = Path.Combine(currentFolder, "Web.config");
if(File.Exists(appConfig)) { return appConfig; }
if(File.Exists(webConfig)) { return webConfig; }
Error("Could not find a configuration file!");
return string.Empty;
}
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment