public void EscapedNamesLeadingToACollisionAreHandledCorrectly() { var resultSet = new FlexResultSet(); var result = new FlexResult(); result.schema = new List <SQLColumn>() { new SQLColumn() { ColumnName = "test_1", DataType = "varchar" }, new SQLColumn() { ColumnName = "test?1", DataType = "varchar" } }; result.data = new List <object[]>(); resultSet.results.Add(result); var srp = new SqlRunParameters(new SqlConnectionStringBuilder(), SqlRunParameters.TO_CSHARP, ""); CSharpRenderer.renderAsCSharp(resultSet, srp); var expected = @"public class Result0 { public string test_1 { get; set; } public string test_1_2 { get; set; } } "; Assert.AreEqual(srp.resultsText.ToString(), expected); }
public void AnonymousColumnsAreHandledCorrectly() { var resultSet = new FlexResultSet(); var result = new FlexResult(); result.schema = new List <SQLColumn>() { new SQLColumn() { ColumnName = "", DataType = "varchar" }, new SQLColumn() { ColumnName = "", DataType = "int" } }; result.data = new List <object[]>(); resultSet.results.Add(result); var srp = new SqlRunParameters(new SqlConnectionStringBuilder(), SqlRunParameters.TO_CSHARP, ""); CSharpRenderer.renderAsCSharp(resultSet, srp); var expected = @"public class Result0 { public string anonymousProperty { get; set; } public int anonymousProperty_2 { get; set; } } "; Assert.AreEqual(srp.resultsText.ToString(), expected); }
public void handle_duplicate_column_names() { var resultSet = new FlexResultSet(); var result = new FlexResult(); result.schema = new List <SQLColumn>() { new SQLColumn() { ColumnName = "testa", DataType = "int" }, new SQLColumn() { ColumnName = "testa", DataType = "varchar" } }; result.data = new List <object[]>(); resultSet.results.Add(result); var srp = new SqlRunParameters(new SqlConnectionStringBuilder(), SqlRunParameters.TO_CSHARP, ""); CSharpRenderer.renderAsCSharp(resultSet, srp); var expected = @"public class Result0 { public int testa { get; set; } public string testa_2 { get; set; } } "; Assert.AreEqual(srp.resultsText.ToString(), expected); }
public string GetStarterClassCode() { StringBuilder sb = new StringBuilder(); var fieldNames = this.Expressions .GroupBy(a => a.Name) .SelectMany(gr => gr.Count() == 1 ? new[] { KVP.Create(gr.SingleEx().Name + "Expression", gr.SingleEx()) } : gr.Select(a => KVP.Create(a.Name + "_" + a.FromType.RemoveChars('<', '>', '.') + "Expression", a)) ).ToDictionaryEx("DynamicExpressions"); var namesToTranslate = this.Expressions.Where(a => a.Translation == DynamicExpressionTranslation.TranslateExpressionName).Select(a => a.Name).Distinct(); if (namesToTranslate.Any()) { sb.AppendLine($"public enum CodeGenExpressionMessage"); sb.AppendLine("{"); foreach (var item in namesToTranslate) { sb.AppendLine(" " + item + ","); } sb.AppendLine("}"); sb.AppendLine(); } sb.AppendLine($"public static class CodeGenExpressionStarter"); sb.AppendLine("{"); foreach (var kvp in fieldNames) { sb.AppendLine($" static Expression<Func<{kvp.Value.FromType}, {kvp.Value.ReturnType}>> {kvp.Key} ="); sb.AppendLine($" e => {kvp.Value.Body};"); sb.AppendLine($" [ExpressionField(\"{kvp.Key}\")]"); sb.AppendLine($" public static {kvp.Value.ReturnType} {kvp.Value.Name}(this {kvp.Value.FromType} e)"); sb.AppendLine($" {{"); sb.AppendLine($" return {kvp.Key}.Evaluate(e);"); sb.AppendLine($" }}"); sb.AppendLine(""); } sb.AppendLine(" public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)"); sb.AppendLine(" {"); foreach (var kvp in fieldNames) { sb.AppendLine($" var ei = dqm.RegisterExpression(({kvp.Value.FromType} e) => e.{kvp.Value.Name}(){GetNiceNameCode(kvp.Value)});"); if (kvp.Value.Format.HasText()) { sb.AppendLine($" ei.ForceFormat = {CSharpRenderer.Value(kvp.Value.Format, typeof(string), new string[0])};"); } if (kvp.Value.Unit.HasText()) { sb.AppendLine($" ei.ForceUnit = {CSharpRenderer.Value(kvp.Value.Unit, typeof(string), new string[0])};"); } } sb.AppendLine(" }"); sb.AppendLine("}"); return(sb.ToString()); }
string Value(object obj) { if (obj is decimal) { obj = (double)(decimal)obj; } return(CSharpRenderer.Value(obj)); }
string Value(object obj) { if (obj is decimal) { obj = (double)(decimal)obj; } return(CSharpRenderer.Value(obj, obj.GetType(), null)); }
public void Test2() { var builder = new AstBuilder(); builder.WithUsing() .WithNamespaceName("System"); var namespaceBuilder = builder.WithNamespace() .WithName("TestNamespace"); var classBuilder = namespaceBuilder.WithClass() .WithName("FooBar") .WithVisibility(AccessType.Public) .IsPartial(true); var fooProperty = classBuilder.WithProperty() .WithName("Foo") .WithType("int") .WithVisibility(AccessType.Public) .WithSetVisibility(AccessType.Public); var methodBuilder = classBuilder.WithMethod() .WithVisibility(AccessType.Public) .WithReturnType("void") .WithName("Serialize"); var bufferParameter = methodBuilder.WithParameter() .WithName("buffer") .WithType("IWriteableBuffer"); var body = methodBuilder.WithBody() .WithLine("{1}.WriteInt32({0});", fooProperty.Name, bufferParameter.Name); methodBuilder = classBuilder.WithMethod() .WithVisibility(AccessType.Public) .WithReturnType("void") .WithName("Deserialize"); bufferParameter = methodBuilder.WithParameter() .WithName("buffer") .WithType("IReadableBuffer"); body = methodBuilder.WithBody() .WithLine("{0} = {1}.ReadInt32();", fooProperty.Name, bufferParameter.Name); var ast = builder.Build(); var renderer = new CSharpRenderer(); var result = renderer.Render(ast); var location = System.Reflection.Assembly.GetExecutingAssembly().Location; System.IO.File.WriteAllText(location + ".result2.cs", result); }
public void Test3() { var builder = new AstBuilder(); var classBuilder = builder.WithClass() .WithName("Foo"); var constructorBuilder = classBuilder.WithConstructor() .WithVisibility(AccessType.Public); var methodBuilder = classBuilder.WithMethod() .WithName("Bar"); methodBuilder.WithBody() .WithLine("for(var i = 0; i < 10; i++)") .WithLine("{{") .WithLine("}}"); var secondMethodBuilder = classBuilder.WithMethod() .WithName("FooBar") .WithVisibility(AccessType.Public) .WithTypeParameter("T") .WithTypeParameter("U"); secondMethodBuilder.WithParameter() .WithName("barFoo") .WithType("T"); secondMethodBuilder.WithParameter() .WithName("fooBar") .WithType("U"); secondMethodBuilder.WithTypeConstraint() .WithTypeParameterName("T") .WithStructConstraint(); secondMethodBuilder.WithTypeConstraint() .WithTypeParameterName("U") .WithStructConstraint() .WithConstraint("IDisposable"); var ast = builder.Build(); var renderer = new CSharpRenderer(); var result = renderer.Render(ast); var location = System.Reflection.Assembly.GetExecutingAssembly().Location; System.IO.File.WriteAllText(location + ".result3.cs", result); }
protected static void Log(SqlPreCommandSimple pcs) { var log = logger.Value; if (log != null) { log.WriteLine(pcs.Sql); if (pcs.Parameters != null) { log.WriteLine(pcs.Parameters .ToString(p => "{0} {1}: {2}".FormatWith( p.ParameterName, Connector.Current.GetSqlDbType(p), p.Value?.Let(v => CSharpRenderer.Value(v, v.GetType(), null))), "\r\n")); } log.WriteLine(); } }
public void NullabilityWorksCorrectly() { var resultSet = new FlexResultSet(); var result = new FlexResult(); result.schema = new List <SQLColumn>() { new SQLColumn() { ColumnName = "a", DataType = "varchar", AllowNulls = true }, new SQLColumn() { ColumnName = "b", DataType = "int", AllowNulls = true }, new SQLColumn() { ColumnName = "c", DataType = "smalldatetime", AllowNulls = true } }; result.data = new List <object[]>(); resultSet.results.Add(result); var srp = new SqlRunParameters(new SqlConnectionStringBuilder(), SqlRunParameters.TO_CSHARP, ""); CSharpRenderer.renderAsCSharp(resultSet, srp); var expected = @"public class Result0 { public string a { get; set; } public int? b { get; set; } public DateTime? c { get; set; } } "; Assert.AreEqual(expected, srp.resultsText.ToString()); }
public void AtSignAfterFirstCharacter_WhenProcessed_IsReplaced( string fieldName, string expectedResult) { Assert.AreEqual(CSharpRenderer.FieldNameToCSharpPropertyName(fieldName), expectedResult); }
public string GetStarterClassCode() { StringBuilder sb = new StringBuilder(); var fieldNames = this.Expressions .GroupBy(a => a.Name) .SelectMany(gr => gr.Count() == 1 ? new[] { KeyValuePair.Create(gr.SingleEx().Name + "Expression", gr.SingleEx()) } : gr.Select(a => KeyValuePair.Create(a.Name + "_" + a.FromType.RemoveChars('<', '>', '.') + "Expression", a)) ).ToDictionaryEx("DynamicExpressions"); var namesToTranslate = this.Expressions.Where(a => a.Translation == DynamicExpressionTranslation.TranslateExpressionName).Select(a => a.Name).Distinct(); if (namesToTranslate.Any()) { sb.AppendLine($"public enum CodeGenExpressionMessage"); sb.AppendLine("{"); foreach (var item in namesToTranslate) { sb.AppendLine(" " + item + ","); } sb.AppendLine("}"); sb.AppendLine(); } sb.AppendLine($"public static class CodeGenExpressionStarter"); sb.AppendLine("{"); foreach (var kvp in fieldNames) { var expressionName = $"{kvp.Value.Name}From{kvp.Value.FromType.BeforeLast("Entity")}Expression".FirstUpper(); sb.AppendLine($" static Expression<Func<{kvp.Value.FromType}, {kvp.Value.ReturnType}>> {expressionName} = "); sb.AppendLine($" e => {kvp.Value.Body};"); sb.AppendLine($" [ExpressionField(\"{expressionName}\")]"); sb.AppendLine($" public static {kvp.Value.ReturnType} {kvp.Value.Name}(this {kvp.Value.FromType} e)"); sb.AppendLine($" {{"); sb.AppendLine($" return {expressionName}.Evaluate(e);"); sb.AppendLine($" }}"); sb.AppendLine(""); } sb.AppendLine(" public static void Start(SchemaBuilder sb)"); sb.AppendLine(" {"); foreach (var kvp in fieldNames) { var entity = kvp.Value; var varName = $"{entity.Name}{entity.FromType.BeforeLast("Entity")}".FirstLower(); sb.AppendLine($" var {varName} = QueryLogic.Expressions.Register(({entity.FromType} e) => e.{entity.Name}(){GetNiceNameCode(entity)});"); if (entity.Format.HasText()) { sb.AppendLine($" {varName}.ForceFormat = {CSharpRenderer.Value(entity.Format)};"); } if (entity.Unit.HasText()) { sb.AppendLine($" {varName}.ForceUnit = {CSharpRenderer.Value(entity.Unit)};"); } } sb.AppendLine(" }"); sb.AppendLine("}"); return(sb.ToString()); }
public void FieldNameStartsWithAZazUnderscoreAt_WhenProcessed_FirstCharIsSame( string fieldName, char expectedFirstChar) { Assert.AreEqual(CSharpRenderer.FieldNameToCSharpPropertyName(fieldName)[0], expectedFirstChar); }
string Literal(object obj) { return(CSharpRenderer.Value(obj, obj.GetType(), null)); }
public void Test() { var builder = new AstBuilder(); builder.WithUsing() .WithNamespaceName("System"); var namespaceBuilder = builder.WithNamespace() .WithName("TestNamespace"); var classBuilder = namespaceBuilder.WithClass() .WithName("FooBar") .WithVisibility(AccessType.Public) .IsPartial(true); classBuilder.WithProperty() .WithName("Foo") .WithType("int") .WithVisibility(AccessType.Public) .WithSetVisibility(AccessType.Public); classBuilder.WithProperty() .WithName("Bar") .WithType("int") .WithVisibility(AccessType.Public) .WithSetVisibility(AccessType.Private); classBuilder = namespaceBuilder.WithClass() .WithName("FooBar") .WithVisibility(AccessType.Public) .IsPartial(true); classBuilder.WithField() .WithName("BarFoo") .WithVisibility(AccessType.Public) .WithType("int"); var methodBuilder = classBuilder.WithMethod() .WithVisibility(AccessType.Public) .WithReturnType("void") .WithName("Serialize"); methodBuilder.WithParameter() .WithName("buffer") .WithType("IWriteableBuffer"); methodBuilder.WithParameter() .WithName("anotherBuffer") .WithType("IWriteableBuffer"); methodBuilder = classBuilder.WithMethod() .WithVisibility(AccessType.Public) .WithReturnType("void") .WithName("Deserialize"); methodBuilder.WithParameter() .WithName("buffer") .WithType("IReadableBuffer"); var structBuilder = namespaceBuilder.WithStruct() .WithName("FooStruct") .WithVisibility(AccessType.Public); structBuilder.WithField() .WithName("Foo") .WithType("int") .WithVisibility(AccessType.Public); var enumBuilder = namespaceBuilder.WithEnum() .WithVisibility(AccessType.Public) .WithName("MyEnum"); enumBuilder.WithOption("One"); enumBuilder.WithOption("Two"); enumBuilder.WithOption("Three"); var ast = builder.Build(); var renderer = new CSharpRenderer(); var result = renderer.Render(ast); var location = System.Reflection.Assembly.GetExecutingAssembly().Location; System.IO.File.WriteAllText(location + ".result.cs", result); }
public void DumpObject(object o) { if (o == null) { Sb.Append("null"); return; } if (o is Type) { Sb.Append("typeof("); Sb.Append(CSharpRenderer.TypeName((Type)o)); Sb.Append(")"); return; } Type t = o.GetType(); if (IsDelegate(t)) { Sb.Append("[DELEGATE]"); return; } if (IsBasicType(t) || t.IsValueType) { Sb.Append(DumpValue(o)); return; } Sb.Append("new "); Sb.Append(CSharpRenderer.CleanIdentifiers(CSharpRenderer.TypeName(t))); if (IgnoreTypes.Contains(t)) { Sb.Append("{ " + o.ToString() + " }"); return; } if (objects.Contains(o)) { if (o is Entity) { var ident = o as Entity; var ent = o as Entity; Sb.Append("({0}{1})".FormatWith( ident.IsNew ? "IsNew": ident.IdOrNull.ToString(), ent == null ? null : ", ticks: " + ent.ticks )); } if (o is Lite <Entity> ) { var id = ((Lite <Entity>)o).IdOrNull; Sb.Append(id.HasValue ? "({0})".FormatWith(id.Value) : ""); } Sb.Append(" /* [CICLE] {0} */".FormatWith(SafeToString(o))); return; } objects.Add(o); if (o is Entity) { var ent = (Entity)o; Sb.Append("({0}{1})".FormatWith( ent.IsNew ? "IsNew" : ent.IdOrNull.ToString(), ent.ticks == 0 ? null : ", ticks: " + ent.ticks )); string toString = SafeToString(o); Sb.Append(" /* {0} */".FormatWith(toString)); } if (o is Lite <Entity> ) { var l = o as Lite <Entity>; Sb.Append("({0}, \"{1}\")".FormatWith((l.IdOrNull.HasValue ? l.Id.ToString() : "null"), l.ToString())); if (((Lite <Entity>)o).UntypedEntityOrNull == null) { return; } } if (o is IEnumerable && !Any((o as IEnumerable))) { Sb.Append("{}"); return; } if (o is byte[] && !showByteArrays) { Sb.Append("{...}"); return; } Sb.AppendLine().AppendLine("{".Indent(level)); level += 1; if (t.Namespace.HasText() && t.Namespace.StartsWith("System.Reflection")) { Sb.AppendLine("ToString = {0},".FormatWith(SafeToString(o)).Indent(level)); } else if (o is Exception) { var ex = o as Exception; DumpPropertyOrField(typeof(string), "Message", ex.Message); DumpPropertyOrField(typeof(string), "StackTrace", ex.StackTrace); DumpPropertyOrField(typeof(Exception), "InnerException", ex.InnerException); DumpPropertyOrField(typeof(IDictionary), "Data", ex.Data); } else if (o is IEnumerable) { if (o is IDictionary) { foreach (DictionaryEntry item in (o as IDictionary)) { Sb.Append("{".Indent(level)); DumpObject(item.Key); Sb.Append(", "); DumpObject(item.Value); Sb.AppendLine("},"); } } else { foreach (var item in (o as IEnumerable)) { Sb.Append("".Indent(level)); DumpObject(item); Sb.AppendLine(","); } } } else if (!typeof(ModifiableEntity).IsAssignableFrom(t)) { foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { DumpPropertyOrField(prop.PropertyType, prop.Name, prop.GetValue(o, null)); } } else { foreach (var field in Reflector.InstanceFieldsInOrder(t).OrderBy(IsMixinField)) { if (IsIdOrTicks(field)) { continue; } if (IsMixinField(field)) { var val = field.GetValue(o); if (val == null) { continue; } DumpPropertyOrField(field.FieldType, GetFieldName(field), val); } if (!showIgnoredFields && (field.HasAttribute <IgnoreAttribute>()) || (Reflector.TryFindPropertyInfo(field)?.HasAttribute <IgnoreAttribute>() == true)) { continue; } DumpPropertyOrField(field.FieldType, GetFieldName(field), field.GetValue(o)); } } level -= 1; Sb.Append("}".Indent(level)); return; }
public void DumpObject(object?o, bool avoidDumpEntity = false) { if (o == null) { Sb.Append("null"); return; } if (o is Type type) { Sb.Append("typeof("); Sb.Append(CSharpRenderer.TypeName(type)); Sb.Append(")"); return; } Type t = o.GetType(); if (IsDelegate(t)) { Sb.Append("[DELEGATE]"); return; } if (IsBasicType(t) || t.IsValueType) { Sb.Append(DumpValue(o !)); return; } Sb.Append("new "); Sb.Append(CSharpRenderer.CleanIdentifiers(CSharpRenderer.TypeName(t))); if (IgnoreTypes.Contains(t)) { Sb.Append("{ " + o !.ToString() + " }"); return; } if (objects.Contains(o !)) { if (o is Entity ent) { Sb.Append("({0}{1})".FormatWith( ent.IsNew ? "IsNew": ent.IdOrNull.ToString(), ent == null ? null : ", ticks: " + ent.ticks )); } if (o is Lite <Entity> ) { var id = ((Lite <Entity>)o).IdOrNull; Sb.Append(id.HasValue ? "({0})".FormatWith(id.Value) : ""); } Sb.Append(" /* [ALREADY] {0} */".FormatWith(SafeToString(o !))); return; } objects.Add(o !); if (o is Entity e) { Sb.Append("({0}{1})".FormatWith( e.IsNew ? "IsNew" : e.IdOrNull.ToString(), e.ticks == 0 ? null : ", ticks: " + e.ticks )); string toString = SafeToString(o); Sb.Append(" /* {0} {1} */".FormatWith(toString, (avoidDumpEntity ? "[DUMP AS LITE]" : ""))); if (avoidDumpEntity) { return; } } if (o is Lite <Entity> l) { Sb.Append("({0}, \"{1}\")".FormatWith((l.IdOrNull.HasValue ? l.Id.ToString() : "null"), l.ToString())); if (((Lite <Entity>)o).EntityOrNull != null && !avoidDumpEntity) { Sb.AppendLine().AppendLine("{".Indent(level)); level += 1; var prop = o.GetType().GetProperty(nameof(Lite <Entity> .Entity)) !; DumpPropertyOrField(prop.PropertyType, prop.Name, prop.GetValue(o, null) !); level -= 1; Sb.Append("}".Indent(level)); } return; } if (o is IEnumerable ie && !Any(ie)) { Sb.Append("{}"); return; } if (o is byte[] && !showByteArrays) { Sb.Append("{...}"); return; } Sb.AppendLine().AppendLine("{".Indent(level)); level += 1; if (t.Namespace.HasText() && t.Namespace.StartsWith("System.Reflection")) { Sb.AppendLine("ToString = {0},".FormatWith(SafeToString(o !)).Indent(level)); } else if (o is Exception ex) { DumpPropertyOrField(typeof(string), "Message", ex.Message); DumpPropertyOrField(typeof(string), "StackTrace", ex.StackTrace); DumpPropertyOrField(typeof(Exception), "InnerException", ex.InnerException); DumpPropertyOrField(typeof(IDictionary), "Data", ex.Data); } else if (o is IEnumerable) { if (o is IDictionary dic) { foreach (DictionaryEntry?item in dic) { Sb.Append("{".Indent(level)); DumpObject(item !.Value.Key); Sb.Append(", "); DumpObject(item !.Value.Value); Sb.AppendLine("},"); } } else { foreach (var item in (o as IEnumerable) !) { Sb.Append("".Indent(level)); DumpObject(item, avoidDumpEntity); Sb.AppendLine(","); } } } else if (!typeof(ModifiableEntity).IsAssignableFrom(t)) { foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var hasAvoidDumpEntityAttr = prop.HasAttribute <AvoidDumpEntityAttribute>(); DumpPropertyOrField(prop.PropertyType, prop.Name, prop.GetValue(o, null), hasAvoidDumpEntityAttr); } } else { foreach (var field in Reflector.InstanceFieldsInOrder(t).OrderBy(IsMixinField)) { if (IsIdOrTicks(field)) { continue; } var hasAvoidDumpEntityAttr = field.HasAttribute <AvoidDumpEntityAttribute>() || Reflector.TryFindPropertyInfo(field)?.HasAttribute <AvoidDumpEntityAttribute>() == true; if (IsMixinField(field)) { var val = field.GetValue(o); if (val == null) { continue; } DumpPropertyOrField(field.FieldType, GetFieldName(field), val, hasAvoidDumpEntityAttr); } var skip = this.showIgnoredFields == ShowIgnoredFields.Yes ? false : this.showIgnoredFields == ShowIgnoredFields.OnlyQueryables ? IsIgnored(field) && Reflector.TryFindPropertyInfo(field)?.HasAttribute <QueryablePropertyAttribute>() != true : this.showIgnoredFields == ShowIgnoredFields.No ? IsIgnored(field) : throw new InvalidOperationException("Unexpected ShowIgnoredFields"); if (!skip) { DumpPropertyOrField(field.FieldType, GetFieldName(field), field.GetValue(o), hasAvoidDumpEntityAttr); } } } level -= 1; Sb.Append("}".Indent(level)); return; }
bool IsBasicType(Type type) { var unType = type.UnNullify(); return(CSharpRenderer.IsBasicType(unType) || unType == typeof(DateTime)); }