Created
May 16, 2014 15:47
-
-
Save FernandoVezzali/782d6c9e53ff8fe7204d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<#@ 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