|
public static class MyExtensions |
|
{ |
|
// Write custom extension methods here. They will be available to all queries. |
|
public static string CodeGen(this Type type, string typeName, string description, string filePath){ |
|
|
|
var t = new StringBuilder(); |
|
|
|
var className = type.Name.StartsWith("<>")?"AnonymousType":type.Name; |
|
|
|
if (typeName!="") className = typeName; |
|
|
|
var listName = className.ToLower() + "Enumerable"; |
|
|
|
|
|
if (description!="") |
|
t.AppendLine("// " + description); |
|
t.AppendLine("// Generated " + DateTime.Now.ToString()); |
|
|
|
t.AppendLine("void Main() {"); |
|
t.AppendLine(" var " + listName + @"=Get" + typeName + @"Records(@""" + filePath + @""");"); |
|
t.AppendLine(" " + listName + ".Dump();"); |
|
|
|
t.AppendLine("}"); |
|
|
|
t.AppendLine(@"public IEnumerable<" + className + "> Get" + typeName + "Records(string filePath){"); |
|
t.AppendLine(@" var csvReader = new CsvHelper.CsvReader(File.OpenText(filePath));"); |
|
t.AppendLine(@" return csvReader.GetRecords<" + className + @">();"); |
|
t.AppendLine("}"); |
|
|
|
|
|
t.AppendLine("public class " + className + " {"); |
|
|
|
type.GetFields().Select (x => new {Name=x.Name, Type=(x.FieldType.IsGenericType && x.FieldType.GetGenericTypeDefinition()==typeof(Nullable<>))?Nullable.GetUnderlyingType(x.FieldType).Name + "?":x.FieldType.Name}).ToList().ForEach(row=>{ |
|
t.AppendLine(" public " + row.Type + " " + row.Name + " {get;set;}"); |
|
}); |
|
|
|
type.GetProperties().Select(x=>new { Name = x.Name, Type = x.PropertyType.Name}).ToList().ForEach(row=>{ |
|
t.AppendLine(" public " + row.Type + " " + row.Name + " {get;set;}"); |
|
}); |
|
|
|
t.AppendLine("}"); |
|
|
|
|
|
return t.ToString(); |
|
|
|
} |
|
|
|
public static void DumpAsClassAndCsv<TIn>(this IEnumerable<TIn> records, string typeName, string queryDescription){ |
|
|
|
var path = Path.GetDirectoryName(Util.CurrentQueryPath); |
|
|
|
if (path !=null) { |
|
|
|
path = path + "/" + typeName; |
|
Directory.CreateDirectory(path); |
|
var csvPath = path + "/" + queryDescription + ".csv"; |
|
Util.WriteCsv(records, csvPath); |
|
|
|
var code = CodeGen(records.First().GetType(), typeName, queryDescription, csvPath); |
|
|
|
var sb = new StringBuilder(); |
|
sb.AppendLine(@"<Query Kind=""Program"">"); |
|
sb.AppendLine(@"<NuGetReference>CsvHelper</NuGetReference>"); |
|
sb.AppendLine(@"</Query>"); |
|
sb.AppendLine(code); |
|
|
|
var codeFilePath = path + "/" + queryDescription + ".linq"; |
|
File.WriteAllText(codeFilePath,sb.ToString()); |
|
|
|
Console.WriteLine("Generated file " + codeFilePath); |
|
|
|
} else { |
|
|
|
throw new Exception("Save current query first"); |
|
|
|
} |
|
|
|
} |
|
|
|
} |