public DpoClass(ITable metaTable, ClassName cname, DpoOption option) { this.metaTable = metaTable; this.nameSpace = cname.Namespace; this.className = cname.Class; this.option = option; this.code = new CSharpBuilder { nameSpace = cname.Namespace, }; code.AddUsing("System"); code.AddUsing("System.Collections.Generic"); code.AddUsing("System.Text"); code.AddUsing("System.Data"); code.AddUsing("System.Drawing"); code.AddUsing("Sys.Data"); code.AddUsing("Sys.Data.Manager"); clss = new Class(cname.Class, new CodeBuilder.TypeInfo { type = typeof(DPObject) }) { modifier = Modifier.Public | Modifier.Partial, Sorted = option.CodeSorted }; this.code.AddClass(clss); nonvalized = NonvalizedList(nameSpace, className); nullableFields = NullableList(nameSpace, className); }
public DpoClass(ITableSchema metaTable, ClassName cname, DpoOption option) { this.metaTable = metaTable; this.nameSpace = cname.Namespace; this.className = cname.Class; this.option = option; this.code = new CSharpBuilder { Namespace = cname.Namespace, }; code.AddUsing("System"); code.AddUsing("System.Collections.Generic"); code.AddUsing("System.Text"); code.AddUsing("System.Data"); code.AddUsing("System.Drawing"); code.AddUsing("Sys.Data"); code.AddUsing("Sys.Data.Manager"); clss = new Class(cname.Class, new CodeBuilder.TypeInfo { Type = typeof(DPObject) }) { Modifier = Modifier.Public | Modifier.Partial, Sorted = option.CodeSorted }; this.code.AddClass(clss); nonvalized = NonvalizedList(nameSpace, className); nullableFields = NullableList(nameSpace, className); }
public static (string filename, string source) Emit(UnionTypeSchema unionTypeSchema, Action <Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { var builder = new CSharpBuilder(); builder.WriteUsings("System", "System.Threading.Tasks"); using (builder.Namespace(unionTypeSchema.Namespace)) { using (builder.PublicStaticPartialClass("MatchExtension")) { GenerateMatchMethod(builder, unionTypeSchema, "T"); builder.WriteLine(""); GenerateMatchMethod(builder, unionTypeSchema, "Task<T>"); builder.WriteLine(""); var thisParameter = ThisParameter(unionTypeSchema, $"Task<{unionTypeSchema.TypeName}>"); WriteMatchSignature(builder, unionTypeSchema, thisParameter, "Task<T>", "T", "public static async"); var caseParameters = unionTypeSchema.Cases.Select(c => c.ParameterName).ToSeparatedString(); builder.WriteLine($"(await {thisParameter.Name}.ConfigureAwait(false)).Match({caseParameters});"); builder.WriteLine(""); var thisParameter1 = ThisParameter(unionTypeSchema, $"Task<{unionTypeSchema.TypeName}>"); WriteMatchSignature(builder, unionTypeSchema, thisParameter1, "Task<T>", handlerReturnType: "Task<T>", "public static async"); builder.WriteLine($"await (await {thisParameter1.Name}.ConfigureAwait(false)).Match({caseParameters}).ConfigureAwait(false);"); } } return($"{unionTypeSchema.TypeName}MatchExtension.g.cs", builder.ToString()); }
public TheClassBuilder(string ns, Command cmd) { this.cmd = cmd; this._using = cmd.GetValue("using"); this._base = cmd.GetValue("base"); builder = new CSharpBuilder { nameSpace = ns }; }
public override string ToString() { var printTransformation = new CSharpBuilder(); using (new Indent(printTransformation, m_Start, m_End)) { } return(printTransformation.ToString()); }
private void ConvertJson2CS(string code, CSharpBuilder builder, string cname, bool isExpression) { var x = new Json2CSharp(builder, code, isExpression); x.Generate(cname); builder.AddUsingRange(base.Usings); PrintOutput(builder, cname); }
public Indent(CSharpBuilder tt, string?start = null, string?end = null) { Builder = tt; m_End = end; m_Start = start; if (start != null) { Builder.WriteLine(start); } Builder.PushIndent("\t"); }
public Json2CSharp(CSharpBuilder builder, string code, bool isExpression) { this.builder = builder; if (isExpression) { VAL result = Script.Evaluate(code, DS); DS = (Memory)result; } else { Script.Execute(code, DS); } }
public Packing(Type dpoType) { this.dpoType = dpoType; instance = (PersistentObject)Activator.CreateInstance(this.dpoType); this.publicFields = dpoType.GetFields(BindingFlags.Public | BindingFlags.Instance); //ignore public const fields Type baseType = typeof(BasePackage <>); baseType = baseType.MakeGenericType(dpoType); this.classBuilder = new CSharpBuilder() { Namespace = dpoType.Assembly.GetName().Name + "." + Setting.DPO_PACKAGE_SUB_NAMESPACE, }; this.classBuilder.AddUsing("System") .AddUsing("System.Data") .AddUsing("System.Text") .AddUsing("System.Collections.Generic") .AddUsing("Sys") .AddUsing("Sys.Data") .AddUsing("Sys.Data.Manager") .AddUsing(dpoType.Namespace); var clss = new Class(ClassName, new CodeBuilder.TypeInfo { Type = baseType }) { Modifier = Modifier.Public }; //constructor clss.Add(new Constructor(ClassName)); this.pack = new Method("Pack") { Modifier = Modifier.Protected | Modifier.Override }; clss.Add(pack); classBuilder.AddClass(clss); }
private CSharpBuilder CreateClass(IEnumerable <Buildable> elements) { CSharpBuilder builder = new CSharpBuilder { Namespace = NamespaceName }; Class clss = new Class(ClassName) { Modifier = Modifier.Public | Modifier.Static | Modifier.Partial }; builder.AddUsing("System"); clss.AddRange(elements); builder.AddClass(clss); return(builder); }
static void GenerateMatchMethod(CSharpBuilder builder, UnionTypeSchema unionTypeSchema, string t) { var thisParameterType = unionTypeSchema.TypeName; var thisParameter = ThisParameter(unionTypeSchema, thisParameterType); var thisParameterName = thisParameter.Name; WriteMatchSignature(builder, unionTypeSchema, thisParameter, t); builder.WriteLine($"{thisParameterName} switch"); using (builder.ScopeWithSemicolon()) { var caseIndex = 0; foreach (var c in unionTypeSchema.Cases) { caseIndex++; builder.WriteLine($"{c.FullTypeName} case{caseIndex} => {c.ParameterName}(case{caseIndex}),"); } builder.WriteLine( $"_ => throw new ArgumentException($\"Unknown type derived from {unionTypeSchema.TypeName}: {{{thisParameterName}.GetType().Name}}\")"); } }
public Packing(Type dpoType) { this.dpoType = dpoType; instance = (PersistentObject)Activator.CreateInstance(this.dpoType); this.publicFields = dpoType.GetFields(BindingFlags.Public | BindingFlags.Instance); //ignore public const fields Type baseType = typeof(BasePackage<>); baseType = baseType.MakeGenericType(dpoType); this.classBuilder = new CSharpBuilder() { nameSpace = dpoType.Assembly.GetName().Name + "." + Setting.DPO_PACKAGE_SUB_NAMESPACE, }; this.classBuilder.AddUsing("System") .AddUsing("System.Data") .AddUsing("System.Text") .AddUsing("System.Collections.Generic") .AddUsing("Sys") .AddUsing("Sys.Data") .AddUsing("Sys.Data.Manager") .AddUsing(dpoType.Namespace); var clss = new Class(ClassName, new CodeBuilder.TypeInfo { type = baseType }) { modifier = Modifier.Public }; //constructor clss.Add(new Constructor(ClassName)); this.pack = new Method("Pack") { modifier = Modifier.Protected | Modifier.Override }; clss.Add(pack); classBuilder.AddClass(clss); }
public void Run_this_before_each_test() { // two spaces as indent builder = new CSharpBuilder(" "); }
private void ExportConstant(DataTable dt) { //command: export /c# /type:const /field:col1,col2 /value:col3,col4 string[] optionColumns = cmd.GetStringArray("field"); string[] optionConstants = cmd.GetStringArray("value"); if (optionColumns.Length == 0) { cerr.WriteLine("missing parameter /field:col1,col2"); return; } if (optionConstants.Length == 0) { optionConstants = optionColumns; } else if (optionColumns.Length != optionConstants.Length) { cerr.WriteLine($"invalid parameter /value:{string.Join(",", optionConstants)}"); return; } CSharpBuilder builder = new CSharpBuilder() { Namespace = NamespaceName }; builder.AddUsingRange(base.Usings); string cname = ClassName; Class clss = new Class(cname) { Modifier = Modifier.Public | Modifier.Static }; builder.AddClass(clss); SortedDictionary <string, object> dict = new SortedDictionary <string, object>(); Type type = null; int i = 0; foreach (string column in optionColumns) { string constant = optionConstants[i++]; Type _type = dt.Columns[constant].DataType; if (type == null) { type = _type; } else if (type != _type) { cerr.WriteLine($"column [{constant}] data type is imcompatible"); continue; } foreach (DataRow row in dt.Rows) { if (row[column] == DBNull.Value) { continue; } string key = row.Field <string>(column); if (!dict.ContainsKey(key)) { dict.Add(key, row[constant]); } } } foreach (var kvp in dict) { string fieldName = Sys.ident.Identifier(kvp.Key); Field field = new Field(new TypeInfo(type), fieldName, new Value(kvp.Value)) { Modifier = Modifier.Public | Modifier.Const, Comment = new Comment(kvp.Key), }; clss.Add(field); } PrintOutput(builder, cname); }
public Namespace(CSharpBuilder tt, string name) : base(tt, $"namespace {name}") { }
public ScopeWithComma(CSharpBuilder textTransformation) : base(textTransformation, null, ",") { }
public void ExportCSharpData() { string code = LoadCode(); if (code == null) { return; } ClassType ctype = getClassType(); string _GetValueMethodName = cmd.GetValue("method"); string _ConstKeyClassName = cmd.GetValue("kc"); string _DefaultValueClassName = cmd.GetValue("dc"); var builder = new CSharpBuilder { Namespace = NamespaceName }; builder.AddUsing("System"); builder.AddUsing("System.Collections.Generic"); string cname = ClassName; if (ctype == ClassType.TieDataContract || ctype == ClassType.JsonDataContract) { bool isExpression = ctype == ClassType.JsonDataContract; string inputPath = cmd.InputPath(); if (inputPath != null && Path.GetExtension(inputPath).ToLower() == ".json") { isExpression = true; } ConvertJson2CS(code, builder, cname, isExpression); return; } var maker = new ConfigScript(code); if ((ctype & ClassType.HierarchicalProperty) == ClassType.HierarchicalProperty) { maker.HierarchicalMemberType = CodeMemberType.Property; } else if ((ctype & ClassType.HierarchicalMethod) == ClassType.HierarchicalMethod) { maker.HierarchicalMemberType = CodeMemberType.Method; } else { maker.HierarchicalMemberType = CodeMemberType.Field; } if (_GetValueMethodName != null) { maker.GetValueMethodName = _GetValueMethodName; } if (_ConstKeyClassName != null) { maker.ConstKeyClassName = _ConstKeyClassName; } if (_DefaultValueClassName != null) { maker.DefaultValueClassName = _DefaultValueClassName; } var clss = maker.Generate(cname); builder.AddClass(clss); if (ctype == ClassType.ConstKey) { builder = CreateClass(maker.ConstKeyFields); } else if (ctype == ClassType.DefaultValue) { builder = CreateClass(maker.DefaultValueFields); } else if (ctype == ClassType.StaticField) { builder = CreateClass(maker.StaticFields); } else if (ctype == ClassType.StaticPropery) { builder = CreateClass(maker.StaticProperties); } else if (ctype == ClassType.StaticMethod) { builder = CreateClass(maker.StaticMethods); } else if (ctype == ClassType.HierarchicalField || ctype == ClassType.HierarchicalProperty || ctype == ClassType.HierarchicalMethod) { //skip, because clss has created class already } else { if ((ctype & ClassType.HierarchicalField) != ClassType.HierarchicalField && (ctype & ClassType.HierarchicalProperty) != ClassType.HierarchicalProperty && (ctype & ClassType.HierarchicalMethod) != ClassType.HierarchicalMethod ) { clss.Clear(); } if ((ctype & ClassType.StaticField) == ClassType.StaticField) { clss.AddRange(maker.StaticFields); } if ((ctype & ClassType.StaticPropery) == ClassType.StaticPropery) { clss.AddRange(maker.StaticProperties); } if ((ctype & ClassType.StaticMethod) == ClassType.StaticMethod) { clss.AddRange(maker.StaticMethods); } if ((ctype & ClassType.ConstKey) == ClassType.ConstKey) { clss.AddRange(maker.ConstKeyFields); } if ((ctype & ClassType.DefaultValue) == ClassType.DefaultValue) { clss.AddRange(maker.DefaultValueFields); } } builder.AddUsingRange(base.Usings); PrintOutput(builder, cname); }
public ObjectInitScope(CSharpBuilder textTransformation) : base(textTransformation, null, ";") { }
public Interface(CSharpBuilder tt, string name, string?modifiers, params string[] baseInterfaceNames) : base(tt, $"{(modifiers != null ? modifiers + " " : "")}interface {name}{(baseInterfaceNames.Any() ? " : " + string.Join(", ", baseInterfaceNames) : "")}") =>
/// <summary> /// create C# data from data table /// </summary> /// <param name="cmd"></param> public void ExportCSharpData(Command cmd) { if (!(SqlShell.LastResult is DataTable)) { stdio.ErrorFormat("display data table first by sql clause or command [type]"); return; } string ns = cmd.GetValue("ns") ?? "Sql.Data"; string cname = cmd.GetValue("class") ?? "Table"; var dt = SqlShell.LastResult as DataTable; var builder = new CSharpBuilder { nameSpace = ns }; var clss = new Class(cname) { modifier = Modifier.Public | Modifier.Partial }; builder.AddClass(clss); Property prop; foreach (DataColumn column in dt.Columns) { bool nullable = dt.AsEnumerable().Any(row => row[column] is DBNull); TypeInfo ty = new TypeInfo(column.DataType) { Nullable = nullable }; prop = new Property(ty, column.ColumnName.ToFieldName()) { modifier = Modifier.Public}; clss.Add(prop); } clss = new Class(cname + "Data") { modifier = Modifier.Public }; builder.AddClass(clss); Func<int, string> tab = n => new string('\t', n); string[] columns = dt.Columns.Cast<DataColumn>().Select(col => col.ColumnName).ToArray(); List<string> L = new List<string>(); foreach (DataRow row in dt.Rows) { List<string> V = new List<string>(); for (int i = 0; i < columns.Length; i++) { V.Add(string.Format("{0} = {1}", columns[i], VAL.Boxing(row[i]).ToString())); } L.Add($"{tab(3)}new {cname} {{ " + string.Join(", ", V) + " }"); } var value = $"new {cname}[]\n" + $"{tab(2)}{{\n" + string.Join(",\n", L) + $"\n{tab(2)}}}"; Field field = new Field(new TypeInfo { userType = $"{cname}[]" }, "data") { modifier = Modifier.Public | Modifier.Static | Modifier.Readonly, userValue = value }; clss.Add(field); string code = $"{builder}"; string path = cmd.GetValue("out"); if (path == null) { stdio.WriteLine(code); } else { string file = Path.ChangeExtension(Path.Combine(path, cname), "cs"); code.WriteIntoFile(file); stdio.WriteLine("code generated on {0}", file); } }
private void ExportEnum(DataTable dt) { int count = dt.Columns.Count; if (count < 2) { cerr.WriteLine("cannot generate enum class because table is < 2 columns"); return; } CSharpBuilder builder = new CSharpBuilder() { Namespace = NamespaceName }; builder.AddUsingRange(base.Usings); string cname = ClassName; if (count > 2) { builder.AddUsing("System.ComponentModel"); } DataColumn _feature = null; //1st string column as property name DataColumn _value = null; //1st int column as property value DataColumn _label = null; //2nd string column as attribute [DataEnum("label")] DataColumn _category = null; //3rd string column as category to generate multiple enum types foreach (DataColumn column in dt.Columns) { if (column.DataType == typeof(string)) { if (_feature == null) { _feature = column; } else if (_label == null) { _label = column; } else if (_category == null) { _category = column; } } if (_value == null && column.DataType == typeof(int)) { _value = column; } } if (_feature == null) { cerr.WriteLine("invalid enum property name"); return; } if (_value == null) { cerr.WriteLine("invalid enum property value"); return; } var rows = dt .AsEnumerable() .Select(row => new { Feature = row.Field <string>(_feature), Value = row.Field <int>(_value), Category = _category != null ? row.Field <string>(_category) : null, Label = _label != null ? row.Field <string>(_label) : null }); if (_category != null) { var groups = rows.GroupBy(row => row.Category); foreach (var group in groups) { var _enum = new EnumType(group.First().Category); foreach (var row in group) { _enum.Add(row.Feature, row.Value, $"\"{row.Label}\""); } builder.AddEnum(_enum); } } else { var _enum = new EnumType(cname); foreach (var row in rows) { _enum.Add(row.Feature, row.Value, $"\"{row.Label}\""); } builder.AddEnum(_enum); } PrintOutput(builder, cname); }
public void Run_this_before_each_test() { // two spaces as indent builder = new CSharpBuilder(" "); }
public Class(CSharpBuilder tt, string name, string?modifiers, params string[] baseClassNames) : base(tt, $"{(modifiers != null ? modifiers + " " : "")}class {name}{(baseClassNames.Any() ? " : " + string.Join(", ", baseClassNames) : "")}") =>
public TheClassBuilder(ApplicationCommand cmd) : base(cmd) { builder = new CSharpBuilder(); }
public void ExportEnum(Command cmd) { DataTable dt = null; if (SqlShell.LastResult is DataTable) { dt = SqlShell.LastResult as DataTable; } if (dt == null) { stdio.ErrorFormat("data table cannot find, use command type or select first"); return; } string path = cfg.GetValue<string>("de.path", $"{Configuration.MyDocuments}\\DataModel\\DataEnum"); string ns = cmd.GetValue("ns") ?? cfg.GetValue<string>("de.ns", "Sys.DataModel.DataEnum"); CSharpBuilder builder = new CSharpBuilder() { nameSpace = ns }; builder.AddUsing("Sys.Data"); var rows = dt .AsEnumerable() .Select(row => new { Category = row.Field<string>("Category"), Feature = row.Field<string>("Feature"), Value = row.Field<int>("Value"), Label = row.Field<string>("Label") }); var groups = rows.GroupBy(row => row.Category); foreach (var group in groups) { var _enum = new Sys.CodeBuilder.Enum(group.First().Category); foreach (var row in group) _enum.Add(row.Feature, row.Value, row.Label); builder.AddEnum(_enum); } string filename = "DataEnum"; string code = builder.ToString(); string file = Path.ChangeExtension(Path.Combine(path, filename), "cs"); code.WriteIntoFile(file); stdio.WriteLine("code generated on {0}", file); }
public PublicStaticClass(CSharpBuilder tt, string name) : base(tt, name, "public static") { }
/// <summary> /// create C# data from data table /// </summary> /// <param name="cmd"></param> public void ExportCSData(DataTable dt) { string dataclass = cmd.GetValue("dataclass") ?? "DbReadOnly"; CSharpBuilder builder = new CSharpBuilder { Namespace = NamespaceName }; builder.AddUsingRange(base.Usings); string cname = ClassName; Dictionary <string, TypeInfo> codeColumns = CodeColumnDef(); var clss = new Class(cname) { Modifier = Modifier.Public | Modifier.Partial }; if (!cmd.Has("dataonly")) { builder.AddClass(clss); } Property prop; foreach (DataColumn column in dt.Columns) { bool nullable = dt.AsEnumerable().Any(row => row[column] is DBNull); TypeInfo ty = new TypeInfo(column.DataType) { Nullable = nullable }; if (codeColumns.ContainsKey(column.ColumnName)) { ty = codeColumns[column.ColumnName]; } prop = new Property(ty, column.ColumnName.ToFieldName()) { Modifier = Modifier.Public }; clss.Add(prop); } clss = new Class(dataclass) { Modifier = Modifier.Public | Modifier.Partial }; if (!cmd.Has("classonly")) { builder.AddClass(clss); } string[] columns = dt.Columns.Cast <DataColumn>().Select(col => col.ColumnName).ToArray(); string fieldName = cmd.GetValue("dataname") ?? $"{cname}Data"; if (dataType == DataClassType.List || dataType == DataClassType.Array) { Field field = CreateListOrArrayField(fieldName, dataType, dt, cname, columns, codeColumns); clss.Add(field); } else { if (dt.Columns.Count < 2) { cerr.WriteLine("cannot generate dictionary class, column# > 2"); return; } Field field = CreateDictionaryField(fieldName, dt, cname, columns, codeColumns); clss.Add(field); } PrintOutput(builder, cname); }
public Scope(CSharpBuilder tt, string?preamble = null, string?postamble = null) : base(tt, (preamble != null ? preamble + Environment.NewLine + tt.CurrentIndent : "") + "{", "}" + postamble) { }
public static Class PublicStaticPartialClass(this CSharpBuilder builder, string name) => new(builder, name, "public static partial");
protected void PrintOutput(CSharpBuilder builder, string cname) { string code = $"{builder}"; PrintOutput(code, cname, ".cs"); }
public void SetUp() { _builder = new CSharpBuilder(); }