-
-
Save NicoJuicy/6746617516da0d6e7ede83fa141595f8 to your computer and use it in GitHub Desktop.
Linqpad extensions
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
<Query Kind="Program"> | |
<NuGetReference>Newtonsoft.Json</NuGetReference> | |
<Namespace>Newtonsoft.Json</Namespace> | |
<Namespace>System.Globalization</Namespace> | |
</Query> | |
void Main() | |
{ | |
// Write code to test your extensions here. Press F5 to compile and run. | |
} | |
/* | |
## Classes: | |
* Mine | |
* Necronet | |
*/ | |
public static class Mine | |
{ | |
// Write custom extension methods here. They will be available to all queries. | |
public static IEnumerable<string> ReadFrom(string file) | |
{ | |
string line; | |
using (var reader = File.OpenText(file)) | |
{ | |
while ((line = reader.ReadLine()) != null) | |
{ | |
yield return line; | |
} | |
} | |
} | |
public static IEnumerable<string[]> ReadFromCsv(string file, bool hasHeader = false, char separator = ',') | |
{ | |
string line; | |
using (var reader = File.OpenText(file)) | |
{ | |
if(hasHeader) { | |
reader.ReadLine(); | |
} | |
while ((line = reader.ReadLine()) != null) | |
{ | |
yield return line.Split(separator); | |
} | |
} | |
} | |
public static string ToTitleCase(this string input) | |
{ | |
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input); | |
} | |
public static string ToCamelCase(this string input, bool uppercaseFirstLetter = false) | |
{ | |
var result = new List<char>(); | |
foreach(var c in input) { | |
if(char.IsUpper(c)) { | |
result.Add('_'); | |
} | |
result.Add(c); | |
} | |
var splitted = (new string(result.ToArray())).Split('_'); | |
var titleCased = splitted.Select(s => s.ToTitleCase()); | |
var fullCased = String.Concat(titleCased); | |
var camelCased = Char.ToLowerInvariant(fullCased[0]) + fullCased.Substring(1); | |
return uppercaseFirstLetter ? fullCased: camelCased; | |
} | |
public static string ToJson<T>(this T obj) { | |
var settings = new JsonSerializerSettings() { | |
ReferenceLoopHandling = ReferenceLoopHandling.Ignore | |
}; | |
return Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented, settings); | |
} | |
public static T FromJson<T>(string text) { | |
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(text); | |
} | |
private static string GetTempFile(string filename) { | |
var path = Path.Combine(System.IO.Path.GetTempPath(), "LinqpadFileCache"); | |
System.IO.Directory.CreateDirectory(path); | |
var fullpath = Path.Combine(path, filename); | |
if(!File.Exists(fullpath)) { | |
File.Create(fullpath); | |
File.SetAttributes(fullpath, FileAttributes.Temporary); | |
} | |
return fullpath; | |
} | |
public static T ToFileCache<T>(this T obj, string cachename) { | |
var target = GetTempFile(cachename + ".json"); | |
File.WriteAllText(target, obj.ToJson<T>()); | |
return obj; | |
} | |
public static T FromFileCache<T>(string cachename) { | |
var target = GetTempFile(cachename + ".json"); | |
return FromJson<T>(File.ReadAllText(target)); | |
} | |
} | |
// Source: http://www.necronet.org/archive/2012/10/09/generate-c-pocos-from-sql-statement-in-linqpad.aspx | |
public static class Necronet | |
{ | |
private static readonly Dictionary<Type, string> TypeAliases = new Dictionary<Type, string> { | |
{ typeof(int), "int" }, | |
{ typeof(short), "short" }, | |
{ typeof(byte), "byte" }, | |
{ typeof(byte[]), "byte[]" }, | |
{ typeof(long), "long" }, | |
{ typeof(double), "double" }, | |
{ typeof(decimal), "decimal" }, | |
{ typeof(float), "float" }, | |
{ typeof(bool), "bool" }, | |
{ typeof(string), "string" } | |
}; | |
private static readonly HashSet<Type> NullableTypes = new HashSet<Type> { | |
typeof(int), | |
typeof(short), | |
typeof(long), | |
typeof(double), | |
typeof(decimal), | |
typeof(float), | |
typeof(bool), | |
typeof(DateTime) | |
}; | |
///<summary> | |
/// Usage: this.Connection.DumpClass("SELECT * FROM mytable") | |
///</summary> | |
public static string DumpClass(this IDbConnection connection, string sql) | |
{ | |
if (connection.State != ConnectionState.Open) | |
connection.Open(); | |
var cmd = connection.CreateCommand(); | |
cmd.CommandText = sql; | |
var reader = cmd.ExecuteReader(); | |
var builder = new StringBuilder(); | |
do | |
{ | |
if (reader.FieldCount <= 1) continue; | |
var schema = reader.GetSchemaTable(); | |
builder.AppendLine(string.Format("[Table(\"{0}\")]", schema.TableName)); | |
builder.AppendLine(string.Format("public class {0}", schema.TableName.ToCamelCase(true))); | |
builder.AppendLine("{"); | |
foreach (DataRow row in schema.Rows) | |
{ | |
var type = (Type)row["DataType"]; | |
var name = TypeAliases.ContainsKey(type) ? TypeAliases[type] : type.Name; | |
var isNullable = (bool)row["AllowDBNull"] && NullableTypes.Contains(type); | |
var collumnName = (string)row["ColumnName"]; | |
builder.AppendLine(string.Format("\t[Column(\"{0}\")]", collumnName)); | |
var casedCollumnName = collumnName.ToCamelCase(true); | |
builder.AppendLine(string.Format("\tpublic {0}{1} {2} {{ get; set; }}", name, isNullable ? "?" : string.Empty, casedCollumnName)); | |
} | |
builder.AppendLine("}"); | |
builder.AppendLine(); | |
} while (reader.NextResult()); | |
return builder.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment