Пример #1
0
        protected override void CreateClass()
        {
            TableSchema schema = new TableSchema(tname);
            Func<IColumn, string> COLUMN = column => "_" + column.ColumnName.ToUpper();

            var clss = new Class(cname, OptionalBaseType()) { modifier = Modifier.Public | Modifier.Partial };
            builder.AddClass(clss);

            //Const Field
            Field field;
            foreach (var column in schema.Columns)
            {
                field = new Field(new TypeInfo { type = typeof(string) }, COLUMN(column), column.ColumnName)
                {
                    modifier = Modifier.Public | Modifier.Const
                };
                clss.Add(field);
            }

            clss.AddCopyCloneEqualsFunc(cname, schema.Columns.Select(column => column.ColumnName));
        }
Пример #2
0
        public void GetConstStringColumnName()
        {
            var clss = dpoClass.clss;
            string _columnName = dpoClass.dict_column_field[column.ColumnName].PropertyName;

            Field field = new Field(new CodeBuilder.TypeInfo { type = typeof(string) }, $"_{_columnName}", $"{column.ColumnName}")
            {
                modifier= Modifier.Public | Modifier.Const
            };

            clss.Add(field);

            return;
        }
Пример #3
0
        protected override void CreateClass()
        {
            var clss = new Class(cname) { modifier = Modifier.Public | Modifier.Partial };

            builder.AddClass(clss);

            foreach (DataColumn column in dt.Columns)
            {
                clss.Add(new Property(dict[column], column.ColumnName) { modifier = Modifier.Public });
            }

            int i;
            int count;
            Statement sent;

            clss = new Class(cname + "Extension") { modifier = Modifier.Public | Modifier.Static };
            builder.AddClass(clss);

            Func<DataColumn, string> COLUMN = column => "_" + column.ColumnName.ToUpper();

            //Const Field
            Field field;
            foreach (DataColumn column in dt.Columns)
            {
                field = new Field(new TypeInfo { type = typeof(string) }, COLUMN(column), column.ColumnName)
                {
                    modifier = Modifier.Public | Modifier.Const
                };
                clss.Add(field);
            }

            if (dt.TableName != null)
            {
                field = new Field(new TypeInfo { type = typeof(string) }, "TableName", dt.TableName)
                {
                    modifier = Modifier.Public | Modifier.Const
                };
                clss.Add(field);
            }

            //primary keys
            var pk = dt.Columns
                .Cast<DataColumn>()
                .Where(column => keys.Select(key => key.ToUpper()).Contains(column.ColumnName.ToUpper()))
                .ToArray();

            if (pk.Length == 0)
                pk = new DataColumn[] { dt.Columns[0] };

            string pks = string.Join(", ", pk.Select(key => COLUMN(key)));
            field = new Field(new TypeInfo { type = typeof(string[]) }, "Keys")
            {
                modifier = Modifier.Public | Modifier.Static | Modifier.Readonly,
                userValue = $"new string[] {LP} {pks} {RP}"
            };
            clss.Add(field);

            Method method = new Method($"To{cname}Collection")
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { userType = $"List<{cname}>" },
                args = new Arguments().Add(typeof(DataTable), "dt"),
                IsExtensionMethod = true
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine("return dt.AsEnumerable()");
            sent.AppendLine(".Select(row => NewObject(row))");
            sent.AppendLine(".ToList();");

            {
                Method method0 = new Method("NewObject")
                {
                    modifier = Modifier.Public | Modifier.Static,
                    type = new TypeInfo { userType = cname },
                    args = new Arguments().Add(typeof(DataRow), "row"),
                    IsExtensionMethod = false
                };
                clss.Add(method0);
                sent = method0.statements;
                sent.AppendLine($"return new {cname}");
                sent.Begin();

                count = dt.Columns.Count;
                i = 0;
                foreach (DataColumn column in dt.Columns)
                {
                    var type = dict[column];
                    var name = COLUMN(column);
                    var line = $"{column.ColumnName} = row.Field<{type}>({name})";
                    if (++i < count)
                        line += ",";

                    sent.AppendLine(line);
                }
                sent.End(";");

                Method method1 = new Method("FillObject")
                {
                    modifier = Modifier.Public | Modifier.Static,
                    args = new Arguments().Add(cname, "item").Add(typeof(DataRow), "row"),
                    IsExtensionMethod = true
                };
                clss.Add(method1);

                Method method2 = new Method("UpdateRow")
                {
                    modifier = Modifier.Public | Modifier.Static,
                    args = new Arguments().Add(cname, "item").Add(typeof(DataRow), "row"),
                    IsExtensionMethod = true
                };
                clss.Add(method2);

                var sent1 = method1.statements;
                var sent2 = method2.statements;
                foreach (DataColumn column in dt.Columns)
                {
                    var type = dict[column];
                    var name = COLUMN(column);
                    var line = $"item.{column.ColumnName} = row.Field<{type}>({name});";
                    if (++i < count)
                        line += ",";

                    sent1.AppendLine(line);

                    line = $"row.SetField({name}, item.{column.ColumnName});";
                    sent2.AppendLine(line);
                }
            }

            method = new Method("CreateTable")
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { type = typeof(DataTable) }
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine("DataTable dt = new DataTable();");
            foreach (DataColumn column in dt.Columns)
            {
                Type ty = dict[column].type;
                var name = COLUMN(column);
                sent.AppendLine($"dt.Columns.Add(new DataColumn({name}, typeof({ty})));");
            }
            sent.AppendLine();
            sent.AppendLine("return dt;");

            method = new Method(mtd2)
            {
                modifier = Modifier.Public | Modifier.Static,
                args = new Arguments().Add($"IEnumerable<{cname}>", "items").Add(typeof(DataTable), "dt"),
                IsExtensionMethod = true
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine("foreach (var item in items)");
            sent.Begin();
            sent.AppendLine("var row = dt.NewRow();");
            sent.AppendLine("UpdateRow(item, row);");
            sent.AppendLine("dt.Rows.Add(row);");
            sent.End();
            sent.AppendLine("dt.AcceptChanges();");

            method = new Method(mtd2)
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { type = typeof(DataTable) },
                args = new Arguments().Add($"IEnumerable<{cname}>", "items"),
                IsExtensionMethod = true
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine("var dt = CreateTable();");
            sent.AppendLine("ToDataTable(items, dt);");
            sent.AppendLine("return dt;");
            sent = method.statements;

            method = new Method("ToDictionary")
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { type = typeof(IDictionary<string, object>) },
                args = new Arguments().Add(cname, "item"),
                IsExtensionMethod = true
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine("return new Dictionary<string,object>() ");
            sent.Begin();
            count = dt.Columns.Count;
            i = 0;
            foreach (DataColumn column in dt.Columns)
            {
                Type ty = dict[column].type;
                var name = COLUMN(column);
                var line = $"[{name}] = item.{column.ColumnName}";
                if (++i < count)
                    line += ",";

                sent.AppendLine(line);
            }
            sent.End(";");

            method = new Method("FromDictionary")
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { userType = cname },
                args = new Arguments().Add(typeof(IDictionary<string, object>), "dict"),
                IsExtensionMethod = true
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine($"return new {cname}");
            sent.Begin();
            count = dt.Columns.Count;
            i = 0;
            foreach (DataColumn column in dt.Columns)
            {
                var type = dict[column];
                var name = COLUMN(column);
                var line = $"{column.ColumnName} = ({type})dict[{name}]";
                if (++i < count)
                    line += ",";

                sent.AppendLine(line);
            }
            sent.End(";");

            //method = new Method("ForEach")
            //{
            //    modifier = Modifier.Public | Modifier.Static,
            //    args = new Arguments().Add(typeof(DataTable), "dt").Add($"Action<{cname}>", "action"),
            //    IsExtensionMethod = true
            //};
            //clss.Add(method);
            //sent = method.statements;
            //sent.AppendLine("foreach (DataRow row in dt.Rows)");
            //sent.Begin();
            //sent.AppendLine("var item = NewObject(row);");
            //sent.AppendLine("action(item);");
            //sent.AppendLine("UpdateRow(item, row);");
            //sent.End();

            //method = new Method("ForEach<T>")
            //{
            //    modifier = Modifier.Public | Modifier.Static,
            //    type = new TypeInfo { userType = "IEnumerable<T>" },
            //    args = new Arguments().Add(typeof(DataTable), "dt").Add($"Func<{cname},T>", "func"),
            //    IsExtensionMethod = true
            //};
            //clss.Add(method);
            //sent = method.statements;
            //sent.AppendLine("List<T> list = new List<T>();");
            //sent.AppendLine("foreach (DataRow row in dt.Rows)");
            //sent.Begin();
            //sent.AppendLine("var item = NewObject(row);");
            //sent.AppendLine(" T t = func(item);");
            //sent.AppendLine("list.Add(t);");
            //sent.End();
            //sent.AppendLine("return list;");

            clss.AddCopyCloneCompareExtension(cname, dict.Keys.Select(column => column.ColumnName));
        }
Пример #4
0
        protected override void CreateClass()
        {
            var clss = new Class(cname, new TypeInfo { type = typeof(IDataContractRow) }, new TypeInfo { userType = $"IEquatable<{cname}>" })
            {
                modifier = Modifier.Public | Modifier.Partial
            };
            builder.AddClass(clss);

            foreach (DataColumn column in dt.Columns)
            {
                clss.Add(new Property(dict[column], column.ColumnName) { modifier = Modifier.Public });
            }

            int i;
            int count;
            Statement sent;

            Func<DataColumn, string> COLUMN = column => "_" + column.ColumnName.ToUpper();

            Method method;

            Method mtdFillObject = new Method("FillObject")
            {
                modifier = Modifier.Public,
                args = new Arguments().Add(typeof(DataRow), "row")
            };
            clss.Add(mtdFillObject);

            Method mtdUpdateRow = new Method("UpdateRow")
            {
                modifier = Modifier.Public,
                args = new Arguments().Add(typeof(DataRow), "row")
            };
            clss.Add(mtdUpdateRow);

            Method mtdCopyTo = new Method("CopyTo")
            {
                modifier = Modifier.Public,
                args = new Arguments().Add(cname, "obj")
            };
            clss.Add(mtdCopyTo);

            var sent1 = mtdFillObject.statements;
            var sent2 = mtdUpdateRow.statements;
            var sent3 = mtdCopyTo.statements;

            count = dt.Columns.Count;
            i = 0;
            foreach (DataColumn column in dt.Columns)
            {
                var type = dict[column];
                var NAME = COLUMN(column);
                var name = column.ColumnName;

                var line = $"this.{name} = row.Field<{type}>({NAME});";
                sent1.AppendLine(line);

                line = $"row.SetField({NAME}, this.{name});";
                sent2.AppendLine(line);

                line = $"obj.{name} = this.{name};";
                sent3.AppendLine(line);
            }

            Method mtdEquals = new Method("Equals")
            {
                modifier = Modifier.Public,
                type = new TypeInfo { type = typeof(bool) },
                args = new Arguments().Add(cname, "obj")
            };
            clss.Add(mtdEquals);
            sent = mtdEquals.statements;
            sent.AppendLine("return ");
            var variables = dict.Keys.Select(column => column.ColumnName);
            variables.ForEach(
               variable => sent.Append($"this.{variable} == obj.{variable}"),
               variable => sent.AppendLine("&& ")
               );
            sent.Append(";");

            Method mtdNewObject = new Method("NewObject")
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { userType = cname },
                args = new Arguments().Add(typeof(DataRow), "row"),
                IsExtensionMethod = false
            };
            clss.Add(mtdNewObject);
            sent = mtdNewObject.statements;
            sent.AppendLine($"return new {cname}");
            sent.Begin();

            count = dt.Columns.Count;
            i = 0;
            foreach (DataColumn column in dt.Columns)
            {
                var type = dict[column];
                var NAME = COLUMN(column);
                var line = $"{column.ColumnName} = row.Field<{type}>({NAME})";
                if (++i < count)
                    line += ",";

                sent.AppendLine(line);
            }
            sent.End(";");

            method = new Method("CreateTable")
            {
                modifier = Modifier.Public | Modifier.Static,
                type = new TypeInfo { type = typeof(DataTable) }
            };
            clss.Add(method);
            sent = method.statements;
            sent.AppendLine("DataTable dt = new DataTable();");
            foreach (DataColumn column in dt.Columns)
            {
                Type ty = dict[column].type;
                var NAME = COLUMN(column);
                sent.AppendLine($"dt.Columns.Add(new DataColumn({NAME}, typeof({ty})));");
            }
            sent.AppendLine();
            sent.AppendLine("return dt;");

            method = new Method(new TypeInfo { type = typeof(string) }, "ToString")
            {
                modifier = Modifier.Public | Modifier.Override
            };
            clss.Add(method);
            sent = method.statements;

            StringBuilder sb = new StringBuilder("\"{{");
            int index = 0;
            variables.ForEach(
                variable => sb.Append($"{variable}:{{{index++}}}"),
                variable => sb.Append(", ")
                );

            sb.AppendLine("}}\", ");

            variables.ForEach(
                variable => sb.Append($"{variable}"),
                variable => sb.AppendLine(", ")
                );

            sent.AppendFormat("return string.Format({0});", sb);

            //Const Field
            foreach (DataColumn column in dt.Columns)
            {
                Field field = new Field(new TypeInfo { type = typeof(string) }, COLUMN(column), column.ColumnName)
                {
                    modifier = Modifier.Public | Modifier.Const
                };
                clss.Add(field);
            }
        }
Пример #5
0
        /// <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);
            }
        }
Пример #6
0
        /// <summary>
        /// add children tables
        /// </summary>
        /// <param name="clss"></param>
        /// <param name="constructor"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private Property AddEntitySet(Class clss, Constructor constructor, IForeignKey key)
        {
            TableName fk_tname = new TableName(tname.DatabaseName, key.FK_Schema, key.FK_Table);
            string fk_cname = fk_tname.ToClassName(null);
            string pname;

            Property prop;
            TypeInfo ty;
            Field field;

            var fk_schema = GetSchema(fk_tname);
            var _keys = fk_schema.PrimaryKeys.Keys;

            if (_keys.Length == 1 && _keys.Contains(key.FK_Column))
            {
                // 1:1 mapping
                pname = clss.MakeUniqueName(Pluralization.Singularize(fk_cname));
                ty = new TypeInfo { userType = $"EntityRef<{fk_cname}>" };
                field = new Field(ty, $"_{pname}") { modifier = Modifier.Private };

                prop = new Property(new TypeInfo { userType = fk_cname }, pname) { modifier = Modifier.Public };
                prop.gets.Append($"return this._{pname}.Entity;");
                prop.sets.Append($"this._{pname}.Entity = value;");

                prop.AddAttribute(new AttributeInfo("Association",
                 new
                 {
                     Name = $"{this.cname}_{fk_cname}",
                     Storage = $"_{pname}",
                     ThisKey = key.PK_Column,
                     OtherKey = key.FK_Column,
                     IsUnique = true,
                     IsForeignKey = false
                 }));
            }
            else
            {
                //1:n mapping
                pname = clss.MakeUniqueName(Pluralization.Pluralize(fk_cname));
                constructor.statements.AppendLine($"this._{pname} = new EntitySet<{fk_cname}>();");

                ty = new TypeInfo { userType = $"EntitySet<{fk_cname}>" };
                field = new Field(ty, $"_{pname}") { modifier = Modifier.Private };

                prop = new Property(ty, pname) { modifier = Modifier.Public };
                prop.gets.Append($"return this._{pname};");
                prop.sets.Append($"this._{pname}.Assign(value);");

                prop.AddAttribute(new AttributeInfo("Association",
                 new
                 {
                     Name = $"{this.cname}_{fk_cname}",
                     Storage = $"_{pname}",
                     ThisKey = key.PK_Column,
                     OtherKey = key.FK_Column,
                     IsForeignKey = false
                 }));
            }

            clss.Add(field);

            return prop;
        }
Пример #7
0
        /// <summary>
        /// add foreighn keys
        /// </summary>
        /// <param name="clss"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private Property AddEntityRef(Class clss, IForeignKey key)
        {
            string pk_cname = new TableName(tname.DatabaseName, key.PK_Schema, key.PK_Table).ToClassName(null);
            string pname = clss.MakeUniqueName(pk_cname);

            var field = new Field(new TypeInfo { userType = $"EntityRef<{pk_cname}>" }, $"_{pname}") { modifier = Modifier.Private };
            clss.Add(field);

            var prop = new Property(new TypeInfo { userType = pk_cname }, pname) { modifier = Modifier.Public };
            prop.gets.Append($"return this._{pname}.Entity;");
            prop.sets.Append($"this._{pname}.Entity = value;");
            prop.AddAttribute(new AttributeInfo("Association",
                new
                {
                    Name = $"{pk_cname}_{this.cname}",
                    Storage = $"_{pname}",
                    ThisKey = key.FK_Column,
                    OtherKey = key.PK_Column,
                    IsForeignKey = true
                }));
            return prop;
        }