Skip to content

Instantly share code, notes, and snippets.

@rushfrisby
Last active August 29, 2015 14:02
Show Gist options
  • Save rushfrisby/b7439f56c14d2b702fcd to your computer and use it in GitHub Desktop.
Save rushfrisby/b7439f56c14d2b702fcd to your computer and use it in GitHub Desktop.
<#@ template language="C#" debug="true" hostspecific="True" #>
<#@ output extension=".cs"#>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#
//*** Edit these settings below ***
var connectionString = "Server=servername;Database=databasename;Trusted_Connection=True;";
var sourceTableName = "TableName";
var sourceValueColumnName = "Value";
var sourceTypeNameColumnName = "Name";
var flagsAttribute = false;
//*** that's it ***
#>
<# if(flagsAttribute) { WriteLine("using System;"); } #>
using System.Runtime.Serialization;
namespace <#=System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint")#>
{
<# if(flagsAttribute) { WriteLine("\t[Flags]"); } #>
[DataContract]
public enum <#=Path.GetFileNameWithoutExtension(Host.TemplateFile)#>
{
<#
try {
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT " + sourceValueColumnName + ", " + sourceTypeNameColumnName + " FROM " + sourceTableName + " ORDER BY " + sourceValueColumnName, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
var i = 0;
while (reader.Read())
{
if(i > 0) {
WriteLine(",");
}
i++;
var name = reader[sourceTypeNameColumnName].ToString();
var value = reader[sourceValueColumnName].ToString();
if(!String.IsNullOrWhiteSpace(name))
{
StringBuilder sb = new StringBuilder(name.Length);
if (name.Length < 2)
name = name.ToUpper();
string[] words = name.Split(new char[] { }, StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
sb.Append(string.Format("{0}{1}", word.Substring(0, 1).ToUpper(), word.Substring(1)));
name = sb.ToString();
}
Write("\t\t[EnumMember] {0} = {1}", name, value);
}
WriteLine("");
}
else
{
WriteLine("\t\t//No data found in source table");
}
reader.Close();
}
} catch(Exception ex) {
WriteLine("\t\t/*");
WriteLine("\t\tError running template:");
WriteLine("\t\t" + ex.Message);
WriteLine("\t\t*/");
}
#>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment