public string GetStructAspNetFormsView(Table table)
        {
            StringBuilder sbFile = new StringBuilder();

            sbFile.AppendFormat(@"using KPComponents;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using KPExtension;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using SpecialistEnumerator;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Collections.Generic;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Linq;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Web;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Web.UI;").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Web.UI.WebControls;").Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE);

            sbFile.AppendFormat(@"namespace {0}", ApplicationSettings.NamespaceWebProject).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}public partial class Frm{1}View :  KPPage", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}public Frm{1}View()", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}: base(WindowEnum.{1}_VIEW)", UtilCharacter.TAB_SPACE, table.Name.ToUpper()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}protected void Page_Load(object sender, EventArgs e)", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"}}").Append(UtilCharacter.NEW_LINE);

            return sbFile.ToString();
        }
 public void Generate(Table table)
 {
     GeneratedEntityBOCode = _castleEntityBoGenerator.Generate(table);
     GeneratedEntityCode = _castleEntityGenerator.Generate(table);
     GeneratedFormsViewASPXCode = _kpAspNetFormsViewGerenator.Generate(table);
     GeneratedFormsViewCSCode = _kpAspNetFormsViewCSGerenator.Generate(table);
     GeneratedFormsViewDesignerCode = _kpAspNetFormsViewDesignerGerenator.Generate(table);
     GeneratedFormsASPXCode = _kpAspNetFormsGerenator.Generate(table);
     GeneratedFormsCSCode = _kpAspNetFormsCSGerenator.Generate(table);
     GeneratedFormsDesignerCode = _kpAspNetFormsDesignerGerenator.Generate(table);
 }
        public IList<Column> GetTableDetails(Table table)
        {
            IList<Column> columnsData = GetTablesDetails(table, table.OwnerSchema);

            columnsData = columnsData.OrderByDescending(x => x.IsPrimaryKey).
                                            ThenByDescending(x => x.IsForeignKey).
                                                ThenBy(x => x.Name).ToList();

            if (ColumnsData != null)
                columnsData = ColumnsData(table, columnsData);

            return columnsData;
        }
        public void GenerateFiles(Table table)
        {
            Generate(table);

            CreateFile(_applicationSettings.DirFileEntity + "\\" + _applicationSettings.EntityName + ".cs", GeneratedEntityCode);
            CreateFile(_applicationSettings.DirFileEntityBO + "\\" + _applicationSettings.EntityName + "BO.cs", GeneratedEntityBOCode);
            CreateFile(_applicationSettings.DirFileForms + "\\Frm" + _applicationSettings.EntityName + "View.aspx", GeneratedFormsViewASPXCode);
            CreateFile(_applicationSettings.DirFileForms + "\\Frm" + _applicationSettings.EntityName + "View.aspx.cs", GeneratedFormsViewCSCode);
            CreateFile(_applicationSettings.DirFileForms + "\\Frm" + _applicationSettings.EntityName + "View.aspx.designer.cs", GeneratedFormsViewDesignerCode);
            CreateFile(_applicationSettings.DirFileForms + "\\Frm" + _applicationSettings.EntityName + ".aspx", GeneratedFormsASPXCode);
            CreateFile(_applicationSettings.DirFileForms + "\\Frm" + _applicationSettings.EntityName + ".aspx.cs", GeneratedFormsCSCode);
            CreateFile(_applicationSettings.DirFileForms + "\\Frm" + _applicationSettings.EntityName + ".aspx.designer.cs", GeneratedFormsDesignerCode);

        }
        protected override IList<Column> GetTablesDetails(Table table, string owner)
        {
            var columns = new List<Column>();

            using (var sqlCon = new SQLiteConnection(_connectionString))
            {
                try
                {
                    using (var tableDetailsCommand = sqlCon.CreateCommand())
                    {
                        tableDetailsCommand.CommandText = string.Format("SELECT * FROM {0}", table.Name);
                        sqlCon.Open();

                        var dr = tableDetailsCommand.ExecuteReader(CommandBehavior.SchemaOnly);
                        var dt = dr.GetSchemaTable();
                        var m = new DataTypeMapper();

                        foreach (DataRow row in dt.Rows)
                        {
                            bool isPrimaryKey = (bool)row["IsKey"];
                            columns.Add(
                                    new Column(table)
                                    {
                                        Name = row["ColumnName"].ToString(),
                                        IsNullable = (bool)row["AllowDBNull"],
                                        IsPrimaryKey = (bool)row["IsKey"],
                                        MappedDataType = m.MapFromDBType(DatabaseServerType.SQLite, row["DataTypeName"].ToString(), (int)row["ColumnSize"], null, null, isPrimaryKey),
                                        DataLength = (int)row["ColumnSize"],
                                        DataType = row["DataTypeName"].ToString(),
                                        IsUnique = (bool)row["IsUnique"]
                                    });
                            dr.Close();
                        }
                    }

                    table.OwnerSchema = owner;
                    table.Columns = columns;
                    table.PrimaryKey = DeterminePrimaryKeys(table);
                    table.ForeignKeys = new List<ForeignKey>();// DetermineForeignKeyReferences(table);
                    table.HasManyRelationships = new List<HasMany>();// DetermineHasManyRelationships(table);
                }
                finally
                {
                    sqlCon.Close();
                }
            }

            return columns;
        }
        private string GetStructEntityBO(Table table)
        {
            StringBuilder sbFile = new StringBuilder();
            sbFile.Append(AddStandardHeader());
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"namespace {0} {{", this.ApplicationSettings.NamespaceEntityBO).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}public class {1}BO : BaseBO<{1}>", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}public {1}BO({1} entity)", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}: base(entity)", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// <summary>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// This method is responsible for save and return the Entity,", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// so if you need to save some extra data you could use this method.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}///", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// TODO: This method is Auto-generated by the KP Mapping Generator.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// </summary>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// <returns>The Entity saved in the database</returns>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}public override {1} SaveEntity()", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}// Your code here", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}return base.SaveEntity(); // Default framework SaveEntity, it call's the Validate method.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// <summary>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// This method is responsible for save and return the Entity,", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// so if you need to save some extra data you could use this method.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}///", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// TODO: This method is Auto-generated by the KP Mapping Generator.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// </summary>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// <returns>True if the Entity is validated and False if not, e.g: if some required field is empty, returns false.</returns>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}public override bool Validate()", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}// Your code here", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}return base.Validate(); // Default framework validation.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);

            return sbFile.ToString();
        }
        public string GetStructAspNetFormsView(Table table)
        {
            StringBuilder sbFile = new StringBuilder();


            sbFile.AppendFormat(@"namespace {0} {{", ApplicationSettings.NamespaceWebProject).Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}public partial class Frm{1}View {{", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// <summary>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// KPGridControl control.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// </summary>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// <remarks>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// Auto-generated field.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// To modify move field declaration from designer file to code-behind file.", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}/// </remarks>", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}protected global::KPComponents.KPGridControl KPGridControl;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"}}").Append(UtilCharacter.NEW_LINE);

            return sbFile.ToString();
        }
        private IList<HasMany> DetermineHasManyRelationships(Table table)
        {
            var hasManyRelationships = new List<HasMany>();
            var conn = new IngresConnection(_connectionString);
            conn.Open();
            using (conn)
            {
                using (var command = conn.CreateCommand())
                {
                    command.CommandText = String.Format("SELECT f.table_name " +
                                                        "FROM iiref_constraints rc " +
                                                        "INNER JOIN iikeys p " +
                                                        "ON p.schema_name = rc.unique_schema_name " +
                                                        "AND p.constraint_name = rc.unique_constraint_name " +
                                                        "INNER JOIN iiconstraints c " +
                                                        "ON c.schema_name = rc.ref_schema_name " +
                                                        "AND c.constraint_name = rc.ref_constraint_name " +
                                                        "INNER JOIN iikeys f " +
                                                        "ON f.constraint_name = rc.ref_constraint_name " +
                                                        "AND p.key_position = f.key_position " +
                                                        "WHERE p.schema_name = '{0}' " +
                                                        "AND p.table_name = '{1}'",
                                                        table.OwnerSchema,
                                                        table.Name);
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            hasManyRelationships.Add(new HasMany
                                {
                                    Reference = reader.GetString(0).TrimEnd(),
                                });
                        }
                    }

                    return hasManyRelationships;
                }
            }
        }
 public override string Generate(Table table)
 {
     return GetStructEntityBO(table);
 }
        private string GetStructEntity(Table table)
        {
            StringBuilder sbFile = new StringBuilder();
            sbFile.Append(AddStandardHeader());
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat("namespace {0}", this.ApplicationSettings.NamespaceEntity).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat("{{").Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}[Serializable]", UtilCharacter.TAB_SPACE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            var columCompany = table.Columns.Where(x => x.IsForeignKey == true && x.ForeignKeyTableName == "FRW_COMPANY" && x.ForeignKeyColumnName == "ID_COMPANY");
            if (columCompany != null && columCompany.Count() > 0)
                sbFile.AppendFormat(@"{0}[KPEntityTable(""{1}"", ""obj{2}"")]", UtilCharacter.TAB_SPACE, table.Name, columCompany.First().Name.GetFormattedText());
            else
                sbFile.AppendFormat(@"{0}[KPEntityTable(""{1}"")]", UtilCharacter.TAB_SPACE, table.Name);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}public class {1} : KPActiveRecordBase<{1}>", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat("{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);



            #region PK and FK Columns
            foreach (var columnItem in table.Columns.Where(x => x.IsPrimaryKey == true || x.IsForeignKey == true).OrderByDescending(x => x.IsPrimaryKey))
            {
                sbFile.AppendFormat(@"{0}{0}#region {1}", UtilCharacter.TAB_SPACE, columnItem.Name).Append(UtilCharacter.NEW_LINE);
                if (!columnItem.IsNullable && columnItem.MappedDataType == typeof(String) && !columnItem.IsPrimaryKey)
                {
                    sbFile.AppendFormat("{0}{0}[NotNull, NotEmpty]", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
                }
                else if (!columnItem.IsNullable && !columnItem.IsPrimaryKey)
                {
                    sbFile.AppendFormat("{0}{0}[NotNull]", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
                }

                sbFile.AppendFormat(@"{0}{0}[KPDisplayName(""{1}"")]", UtilCharacter.TAB_SPACE, columnItem.DisplayName).Append(UtilCharacter.NEW_LINE);

                if (table.PrimaryKey != null && table.PrimaryKey.Columns.Count() != 0)
                {
                    if (columnItem.IsPrimaryKey)
                    {
                        sbFile.AppendFormat(@"{0}{0}[PrimaryKey(Column = ""{1}"")]", UtilCharacter.TAB_SPACE, columnItem.Name).Append(UtilCharacter.NEW_LINE);
                    }
                }

                if (columnItem.DataLength.HasValue && columnItem.DataLength > 0)
                {
                    sbFile.AppendFormat(@"{0}{0}[Length(Max = {1})]", UtilCharacter.TAB_SPACE, columnItem.DataLength).Append(UtilCharacter.NEW_LINE);
                }

                var foreignKey = table.ForeignKeys.FirstOrDefault(x => x.Name.Equals(columnItem.ConstraintName));
                if (!columnItem.IsPrimaryKey && foreignKey != null)
                {
                    sbFile.AppendFormat(@"{0}{0}[BelongsTo(""{1}"", Lazy = FetchWhen.OnInvoke)]", UtilCharacter.TAB_SPACE, columnItem.Name).Append(UtilCharacter.NEW_LINE);
                    sbFile.AppendFormat(@"{0}{0}public virtual {1} obj{2} {{ get; set; }}", UtilCharacter.TAB_SPACE, foreignKey.References.GetFormattedText(), columnItem.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
                }
                else
                {
                    if ((columnItem.DataPrecision.HasValue && columnItem.DataPrecision.Value > 0 && columnItem.DataScale.HasValue && columnItem.DataScale.Value > 0))
                    {
                        sbFile.AppendFormat(@"{0}{0}[Digits(IntegerDigits = {1}, FractionalDigits = {2})]", UtilCharacter.TAB_SPACE, columnItem.DataPrecision, columnItem.DataScale).Append(UtilCharacter.NEW_LINE);
                    }

                    sbFile.AppendFormat(@"{0}{0}public virtual {1} {2} {{ get; set; }}", UtilCharacter.TAB_SPACE, columnItem.MappedDataType.EntityTypeName(), columnItem.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
                }

                sbFile.AppendFormat(@"{0}{0}#endregion {1}", UtilCharacter.TAB_SPACE, columnItem.Name).Append(UtilCharacter.NEW_LINE);
                sbFile.Append(UtilCharacter.NEW_LINE);
            }
            #endregion PK and FK Columns

            #region Normal Columns
            foreach (var property in table.Columns.Where(x => x.IsPrimaryKey != true && x.IsForeignKey != true))
            {
                sbFile.AppendFormat(@"{0}{0}#region {1}", UtilCharacter.TAB_SPACE, property.Name).Append(UtilCharacter.NEW_LINE);
                if (!property.IsNullable && property.MappedDataType == typeof(String))
                {
                    sbFile.AppendFormat("{0}{0}[NotNull, NotEmpty]", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
                }
                else if (!property.IsNullable)
                {
                    sbFile.AppendFormat("{0}{0}[NotNull]", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
                }

                sbFile.AppendFormat(@"{0}{0}[KPDisplayName(""{1}"")]", UtilCharacter.TAB_SPACE, property.DisplayName).Append(UtilCharacter.NEW_LINE);

                if (property.DataLength.HasValue && property.DataLength > 0)
                {
                    sbFile.AppendFormat(@"{0}{0}[Length(Max = {1})]", UtilCharacter.TAB_SPACE, property.DataLength).Append(UtilCharacter.NEW_LINE);
                }
                else if ((property.DataPrecision.HasValue && property.DataPrecision.Value > 0 && property.DataScale.HasValue && property.DataScale.Value > 0))
                {
                    sbFile.AppendFormat(@"{0}{0}[Digits(IntegerDigits = {1}, FractionalDigits = {2})]", UtilCharacter.TAB_SPACE, property.DataPrecision, property.DataScale).Append(UtilCharacter.NEW_LINE);
                }

                sbFile.AppendFormat(@"{0}{0}[Property(Column = ""{1}"")]", UtilCharacter.TAB_SPACE, property.Name).Append(UtilCharacter.NEW_LINE);

                sbFile.AppendFormat(@"{0}{0}public virtual {1} {2} {{ get; set; }}", UtilCharacter.TAB_SPACE, property.MappedDataType.EntityTypeName(), property.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);

                sbFile.AppendFormat(@"{0}{0}#endregion {1}", UtilCharacter.TAB_SPACE, property.Name).Append(UtilCharacter.NEW_LINE);
                sbFile.Append(UtilCharacter.NEW_LINE);
            }
            #endregion Normal Columns

            sbFile.AppendFormat(@"{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);

            return sbFile.ToString();
        }
        public override PrimaryKey DeterminePrimaryKeys(Table table)
        {
            IList<Column> primaryKeys = table.Columns.Where(x => x.IsPrimaryKey.Equals(true)).ToList();

            if (primaryKeys.Count() == 1)
            {
                var c = primaryKeys.First();
                var key = new PrimaryKey
                    {
                        Type = PrimaryKeyType.PrimaryKey,
                        Columns =
                            {
                                new Column(table)
                                    {
                                        DataType = c.DataType,
                                        Name = c.Name
                                    }
                            }
                    };
                return key;
            }
            else
            {
                var key = new PrimaryKey
                    {
                        Type = PrimaryKeyType.CompositeKey
                    };
                foreach (var primaryKey in primaryKeys)
                {
                    key.Columns.Add(new Column(table)
                        {
                            DataType = primaryKey.DataType,
                            Name = primaryKey.Name
                        });
                }
                return key;
            }
        }
        protected override IList<Column> GetTablesDetails(Table table, string owner)
        {
            var columns = new List<Column>();
            var conn = new SqlConnection(connectionStr);
            conn.Open();
            try
            {
                using (conn)
                {
                    using (var tableDetailsCommand = conn.CreateCommand())
                    {
                        tableDetailsCommand.CommandText = string.Format(
                            @"SELECT distinct c.column_name, c.data_type, c.is_nullable, tc.constraint_type, convert(int,c.numeric_precision) numeric_precision, c.numeric_scale, c.character_maximum_length, c.table_name, c.ordinal_position, tc.constraint_name,
       columnproperty(object_id(c.table_schema + '.' + c.table_name), c.column_name,'IsIdentity') IsIdentity, 
       (SELECT CASE WHEN count(1) = 0 THEN 0 ELSE 1 END 
       FROM information_schema.table_constraints x 
       INNER JOIN information_schema.constraint_column_usage ccux ON c.table_name = ccux.table_name and c.column_name = ccux.column_name and c.table_schema = ccux.table_schema
       WHERE x.constraint_type = 'UNIQUE' and x.table_schema = ccux.table_schema and x.constraint_name = ccux.constraint_name) IsUnique
        from information_schema.columns c
	        left outer join (
		        information_schema.constraint_column_usage ccu
		        join information_schema.table_constraints tc on (
			        tc.table_schema = ccu.table_schema
			        and tc.constraint_name = ccu.constraint_name
			        and NOT tc.constraint_type IN ('CHECK','UNIQUE')
		        )
	        ) on (
		        c.table_schema = ccu.table_schema
		        and c.table_name = ccu.table_name
		        and c.column_name = ccu.column_name
	        )
						        where c.table_name = '{0}'
							          and c.table_schema ='{1}'
						        order by c.table_name, c.ordinal_position",
                                    table.Name.Replace("'", "''"), owner);

                        using (var sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default))
                        {
                            while (sqlDataReader.Read())
                            {
                                string columnName = sqlDataReader.GetString(0);
                                string dataType = sqlDataReader.GetString(1);
                                bool isNullable = sqlDataReader.GetString(2).Equals("YES", StringComparison.CurrentCultureIgnoreCase);
                                var isIdentity = Convert.ToBoolean(sqlDataReader["IsIdentity"]);
                                var characterMaxLenth = sqlDataReader["character_maximum_length"] as int?;
                                var numericPrecision = sqlDataReader["numeric_precision"] as int?;
                                var numericScale = sqlDataReader["numeric_scale"] as int?;
                                var constraintName = sqlDataReader["constraint_name"].ToString();
                                var isUnique = Convert.ToBoolean(sqlDataReader["IsUnique"]);
                                bool isPrimaryKey = (!sqlDataReader.IsDBNull(3) && sqlDataReader.GetString(3).Equals(SqlServerConstraintType.PrimaryKey.ToString(), StringComparison.CurrentCultureIgnoreCase));
                                bool isForeignKey = (!sqlDataReader.IsDBNull(3) && sqlDataReader.GetString(3).Equals(SqlServerConstraintType.ForeignKey.ToString(), StringComparison.CurrentCultureIgnoreCase));

                                var m = new DataTypeMapper();

                                columns.Add(new Column(table)
                                                {
                                                    Name = columnName,
                                                    DataType = dataType,
                                                    IsNullable = isNullable,
                                                    IsIdentity = isIdentity,
                                                    IsPrimaryKey = isPrimaryKey,
                                                    IsForeignKey = isForeignKey,
                                                    IsUnique = isUnique,
                                                    MappedDataType = m.MapFromDBType(DatabaseServerType.SqlServer, dataType, characterMaxLenth, numericPrecision, numericScale, isPrimaryKey),
                                                    DataLength = characterMaxLenth,
                                                    DataScale = numericScale,
                                                    DataPrecision = numericPrecision,
                                                    ConstraintName = constraintName
                                                });

                                table.Columns = columns;
                            }
                            table.OwnerSchema = owner;
                            table.PrimaryKey = DeterminePrimaryKeys(table);

                            // Need to find the table name associated with the FK
                            foreach (var c in table.Columns)
                            {
                                if (c.IsForeignKey)
                                {
                                    string referencedTableName;
                                    string referencedColumnName;
                                    GetForeignKeyReferenceDetails(c.ConstraintName, out referencedTableName, out referencedColumnName);

                                    c.ForeignKeyTableName = referencedTableName;
                                    c.ForeignKeyColumnName = referencedColumnName;
                                }
                            }
                            table.ForeignKeys = DetermineForeignKeyReferences(table);
                            table.HasManyRelationships = DetermineHasManyRelationships(table);
                        }
                    }
                }
            }
            finally
            {
                conn.Close();
            }

            return columns;
        }
        public string GetStructAspNetFormsView(Table table)
        {
            StringBuilder sbFile = new StringBuilder();
            sbFile.AppendFormat(@"<%@ Page Language=""C#"" AutoEventWireup=""true"" CodeBehind=""Frm{0}View.aspx.cs"" ", table.Name.GetFormattedText());
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"MasterPageFile=""~/Master/View.Master"" Inherits=""{0}.Frm{1}View"" %>", ApplicationSettings.NamespaceWebProject, table.Name.GetFormattedText());
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);

            sbFile.AppendFormat(@"<asp:Content ID=""ContentHead"" ContentPlaceHolderID=""HeadView"" runat=""server"">{0}</asp:Content>", UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.Append(UtilCharacter.NEW_LINE);

            sbFile.AppendFormat(@"<asp:Content ID=""ContentBody"" ContentPlaceHolderID=""BodyView"" runat=""server"">");
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}<KP:KPGridControl ID=""KPGridControl"" TypeEntityNamespace=""{1}.{2}""", UtilCharacter.TAB_SPACE, this.ApplicationSettings.NamespaceEntity, table.Name.GetFormattedText());
            sbFile.Append(UtilCharacter.NEW_LINE);
            string propertyPK = String.Empty;
            if (table.PrimaryKey != null && table.PrimaryKey.Columns.Count() != 0)
                propertyPK = table.PrimaryKey.Columns[0].Name.GetFormattedText();

            sbFile.AppendFormat(@"{0}{0}runat=""server"" PageFormUrl=""Frm{1}.aspx"">", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText());
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}<KPItemsModel>", UtilCharacter.TAB_SPACE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            string maskConcat = String.Empty;
            int width = 0;
            foreach (Column column in table.Columns)
            {
                maskConcat = String.Empty;
                width = 100;

                if (column.EntityComponentView != null)
                {
                    KPMaskTypeClassEnum? maskType = null;

                    switch (column.ColumnTypeView)
                    {
                        case KPComponentsViewEnum.KPColumnModel:
                            maskType = ((KPColumnModelEntity)column.EntityComponentView).MaskType;
                            width = ((KPColumnModelEntity)column.EntityComponentView).Width;
                            break;
                        case KPComponentsViewEnum.KPEntityModel:
                            maskType = ((KPEntityModelEntity)column.EntityComponentView).MaskType;
                            width = ((KPEntityModelEntity)column.EntityComponentView).Width;
                            break;
                    }

                    if (maskType.HasValue && maskType.Value != KPMaskTypeClassEnum.ALPHANUMERIC)
                        maskConcat = String.Format(@" Mask=""{0}""", maskType);

                    if (width <= 0)
                        width = GetWidthComponent(maskType, column);
                }

                IList<Column> tableFKcolumnList = MetadataReader.GetTableDetails(column.ForeignKeyTableName, ApplicationSettings.OwnerSchema);

                /* Primeira coluna string da FK, para simular o descritivo da tabela FK
                string FieldNameDescription = column.ForeignKeyColumnName;
                var columnsString = tableFKcolumnList.Where(x => x.MappedDataType.Equals(typeof(String)));
                if (columnsString != null && columnsString.Count() > 0)
                    FieldNameDescription = columnsString.First().Name;
                 */

                if (column.IsPrimaryKey)
                {
                    string propertyConcat = String.Format(@" Width=""{0}""", width);
                    if (column.EntityComponentView != null)
                    {
                        switch (column.ColumnTypeView)
                        {
                            case KPComponentsViewEnum.KPColumnModel:
                                propertyConcat += GetControlKPColumnModelEntity(column.EntityComponentView as KPColumnModelEntity);
                                break;
                            default:
                                throw new Exception(@"Coluna PrimaryKey deverá ser do tipo componente: ""KPColumnModel""");
                        }
                    }

                    sbFile.AppendFormat(@"{0}{0}{0}<KP:{1} FieldName=""{2}""{3} />", UtilCharacter.TAB_SPACE, column.ColumnTypeView, column.Name.GetFormattedText(), propertyConcat);
                }
                else if (column.IsForeignKey)
                {
                    string propertyConcat = String.Format(@" Width=""{0}""", width);
                    if (column.EntityComponentView != null)
                    {
                        switch (column.ColumnTypeView)
                        {
                            case KPComponentsViewEnum.KPColumnModel:
                                propertyConcat += GetControlKPColumnModelEntity(column.EntityComponentView as KPColumnModelEntity);
                                break;
                            case KPComponentsViewEnum.KPEntityModel:
                                propertyConcat += GetControlKPEntityModelEntity(column.EntityComponentView as KPEntityModelEntity);
                                break;

                            default:
                                throw new Exception(@"Coluna ForeignKey deverá ser do tipo componente: ""KPColumnModel, KPEntityModel""");
                        }
                    }

                    sbFile.AppendFormat(@"{0}{0}{0}<KP:{1} FieldName=""obj{2}""{3}{4} />", UtilCharacter.TAB_SPACE, column.ColumnTypeView, column.Name.GetFormattedText(), propertyConcat, maskConcat);
                }
                else
                {
                    string propertyConcat = String.Format(@" Width=""{0}""", width);
                    if (column.EntityComponentView != null)
                    {
                        switch (column.ColumnTypeView)
                        {
                            case KPComponentsViewEnum.KPColumnModel:
                                propertyConcat += GetControlKPColumnModelEntity(column.EntityComponentView as KPColumnModelEntity);
                                break;
                            case KPComponentsViewEnum.KPBooleanModel:
                                propertyConcat += GetControlKPBooleanModelEntity(column.EntityComponentView as KPBooleanModelEntity);
                                break;
                            case KPComponentsViewEnum.KPEnumModel:
                                propertyConcat += GetControlKPEnumModelEntity(column.EntityComponentView as KPEnumModelEntity);
                                break;
                            default:
                                throw new Exception(@"Coluna comum deverá ser do tipo componente: ""KPColumnModel, KPBooleanModel, KPEnumModel""");
                        }
                    }

                    sbFile.AppendFormat(@"{0}{0}{0}<KP:{1} FieldName=""{2}""{3}{4} />", UtilCharacter.TAB_SPACE, column.ColumnTypeView, column.Name.GetFormattedText(), propertyConcat, maskConcat);
                }
                sbFile.Append(UtilCharacter.NEW_LINE);
            }

            sbFile.AppendFormat(@"{0}{0}</KPItemsModel>", UtilCharacter.TAB_SPACE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}</KP:KPGridControl>", UtilCharacter.TAB_SPACE);
            sbFile.Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"</asp:Content>");
            return sbFile.ToString();
        }
 public override string Generate(Table table)
 {
     return GetStructAspNetForms(table);
 }
        public override IList<ForeignKey> DetermineForeignKeyReferences(Table table)
        {
            var foreignKeys = (from c in table.Columns
                               where c.IsForeignKey
                               group c by new { c.ConstraintName, c.ForeignKeyTableName, c.IsNullable } into g
                               select new ForeignKey
                               {
                                   Name = g.Key.ConstraintName,
                                   IsNullable = g.Key.IsNullable,
                                   References = g.Key.ForeignKeyTableName,
                                   Columns = g.ToList(),
                                   UniquePropertyName = g.Key.ForeignKeyTableName
                               }).ToList();

            Table.SetUniqueNamesForForeignKeyProperties(foreignKeys);

            return foreignKeys;
        }
        private void UpdateApplicationSettings(Table tableName, ApplicationSettings appSettings)
        {
            string sequence = string.Empty;
            object sequenceName = null;
            if (cmbSequencesOracle.InvokeRequired)
            {
                cmbSequencesOracle.Invoke(new MethodInvoker(delegate
                {
                    sequenceName = cmbSequencesOracle.SelectedItem;
                }));
            }
            else
            {
                sequenceName = cmbSequencesOracle.SelectedItem;
            }

            if (sequenceName != null)
            {
                sequence = sequenceName.ToString();
            }

            string dirFileEntity = txtDirFileEntity.Text;
            if (!String.IsNullOrEmpty(dirFileEntity) && !Directory.Exists(dirFileEntity))
            {
                Directory.CreateDirectory(dirFileEntity);
            }

            string dirFileEntityBO = txtDirFileEntityBO.Text;
            if (!String.IsNullOrEmpty(dirFileEntityBO) && !Directory.Exists(dirFileEntityBO))
            {
                Directory.CreateDirectory(dirFileEntityBO);
            }

            string dirFileForms = txtDirFileForms.Text;
            if (!String.IsNullOrEmpty(dirFileForms) && !Directory.Exists(dirFileForms))
            {
                Directory.CreateDirectory(dirFileForms);
            }

            if (appSettings == null)
                appSettings = new ApplicationSettings();


            appSettings.DatabaseServerType = CurrentConnection.Type;
            appSettings.DirFileEntity = dirFileEntity;
            appSettings.DirFileEntityBO = dirFileEntityBO;
            appSettings.DirFileForms = dirFileForms;
            appSettings.OwnerSchema = cmbSchemaOwners.SelectedItem != null ? cmbSchemaOwners.SelectedItem.ToString() : String.Empty;
            appSettings.TableName = tableName.Name;
            appSettings.NamespaceEntityBO = txtNamespaceEntityBO.Text;
            appSettings.NamespaceEntity = txtNamespaceEntity.Text;
            appSettings.NamespaceWebProject = txtNamespaceWebProject.Text;
            appSettings.Sequence = sequence;
            appSettings.Language = Language.CSharp;
            appSettings.FieldNamingConvention = FieldNamingConvention.PascalCase;
            appSettings.FieldGenerationConvention = FieldGenerationConvention.Property;
            appSettings.ConnectionString = CurrentConnection.ConnectionString;
            appSettings.ClassNamePrefix = appSettings.ClassNamePrefix;
            appSettings.ValidationStyle = appSettings.ValidationStyle;
            appSettings.EntityName = txtEntityName.Text;

        }
        private void Generate(Table table, ApplicationSettings appSettings)
        {
            UpdateApplicationSettings(table, appSettings);
            foreach (Column column in table.Columns)
            {
                if (column.EntityComponentForm == null)
                    column.EntityComponentForm = KPComponentsFormsBO.GetEntityControlForm(column);

                if (column.EntityComponentView == null)
                    column.EntityComponentView = KPComponentsViewBO.GetEntityControlView(column);
            }

            new ApplicationController(appSettings, MetadataReader).GenerateFiles(table);
        }
        private void GetTableHistorySettings(Table selectedTable)
        {
            using (ISession session = ActiveRecordConfiguration.GetISession())
            {
                IQueryable<KPMappingEntity> queryable = session.Query<KPMappingEntity>()
                    .Where(x => x.OwnerSchema.Equals(selectedTable.OwnerSchema) &&
                                x.Database.Equals(selectedTable.DatabaseName) &&
                                x.Table.Equals(selectedTable.Name));

                foreach (KPMappingEntity entityMap in queryable.ToList())
                {
                    foreach (Column col in selectedTable.Columns)
                    {
                        if (col.Name.Equals(entityMap.Column))
                        {
                            if (!String.IsNullOrWhiteSpace(entityMap.DisplayName))
                                col.DisplayName = entityMap.DisplayName;

                            if (!String.IsNullOrWhiteSpace(entityMap.ColumnTypeForm))
                            {
                                KPComponentsFormsEnum enumComponentForm = KPComponentsFormsEnum.KPFormItemText;
                                if (Enum.TryParse<KPComponentsFormsEnum>(entityMap.ColumnTypeForm, out enumComponentForm))
                                    col.ColumnTypeForm = enumComponentForm;
                            }

                            if (!String.IsNullOrWhiteSpace(entityMap.ColumnTypeView))
                            {
                                KPComponentsViewEnum enumComponentView = KPComponentsViewEnum.KPColumnModel;
                                if (Enum.TryParse<KPComponentsViewEnum>(entityMap.ColumnTypeView, out enumComponentView))
                                    col.ColumnTypeView = enumComponentView;
                            }

                            if (!String.IsNullOrWhiteSpace(entityMap.CSharpType))
                                col.EntityTypeName = entityMap.CSharpType;

                            break;
                        }
                    }
                }
            }
        }
        private void PopulateTableDetails(Table selectedTable)
        {
            SetStatusView(string.Empty);
            try
            {
                gridViewDetails.DataSource = MetadataReader.GetTableDetails(selectedTable) ?? new List<Column>();
                GetTableHistorySettings(selectedTable);

                UpdateApplicationSettings(selectedTable, ApplicationSettings);
                var formatter = TextFormatterFactory.GetTextFormatter(ApplicationSettings);
                txtEntityName.Text = formatter.FormatText(selectedTable.Name);
            }
            catch (Exception ex)
            {
                SetStatusView(ex.Message);
            }
        }
 public abstract string Generate(Table table);
 public abstract IList<ForeignKey> DetermineForeignKeyReferences(Table table);
        public override IList<ForeignKey> DetermineForeignKeyReferences(Table table)
        {
            var constraints = table.Columns.Where(x => x.IsForeignKey.Equals(true)).Select(x => x.ConstraintName).Distinct().ToList();
            var foreignKeys = new List<ForeignKey>();
            constraints.ForEach(c =>
                {
                    var fkColumns = table.Columns.Where(x => x.ConstraintName.Equals(c)).ToArray();
                    var fk = new ForeignKey
                        {
                            Name = fkColumns[0].Name,
                            References = GetForeignKeyReferenceTableName(table.OwnerSchema, table.Name, fkColumns[0].Name),
                            Columns = fkColumns
                        };
                    foreignKeys.Add(fk);
                });

            Table.SetUniqueNamesForForeignKeyProperties(foreignKeys);

            return foreignKeys;
        }
        public override PrimaryKey DeterminePrimaryKeys(Table table)
        {
            var primaryKeys = table.Columns.Where(x => x.IsPrimaryKey.Equals(true)).ToList();

            if (primaryKeys.Count() == 1)
            {
                var c = primaryKeys.First();
                var key = new PrimaryKey
                              {
                                  Type = PrimaryKeyType.PrimaryKey,
                                  Columns = { c }
                              };
                return key;
            }

            if (primaryKeys.Count() > 1)
            {
                // Composite key
                var key = new PrimaryKey
                              {
                                  Type = PrimaryKeyType.CompositeKey,
                                  Columns = primaryKeys
                              };

                return key;
            }

            return null;
        }
        private void CreateKPMappingEntityForAllColumns(Table table)
        {
            KPMappingEntity mappingEntity = null;
            using (ISession session = ActiveRecordConfiguration.GetISession())
            {
                foreach (Column column in table.Columns)
                {
                    IQueryable<KPMappingEntity> queryable = session.Query<KPMappingEntity>()
                        .Where(x => x.OwnerSchema.Equals(table.OwnerSchema) &&
                                    x.Database.Equals(table.DatabaseName) &&
                                    x.Table.Equals(table.Name) &&
                                    x.Column.Equals(column.Name));


                    mappingEntity = queryable.FirstOrDefault();
                    if (mappingEntity == null)
                    {
                        mappingEntity = new KPMappingEntity()
                        {
                            OwnerSchema = table.OwnerSchema,
                            Database = table.DatabaseName,
                            Table = table.Name,
                            Column = column.Name
                        };

                        mappingEntity.SaveAndFlush();
                    }
                }
            }
        }
        // http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/
        private IList<HasMany> DetermineHasManyRelationships(Table table)
        {
            var hasManyRelationships = new List<HasMany>();
            var conn = new SqlConnection(connectionStr);
            conn.Open();
            try
            {
                using (conn)
                {
                    using (var command = new SqlCommand())
                    {
                        command.Connection = conn;
                        command.CommandText =
                            String.Format(
                                @"
						SELECT DISTINCT 
							PK_TABLE = b.TABLE_NAME,
							FK_TABLE = c.TABLE_NAME,
							FK_COLUMN_NAME = d.COLUMN_NAME,
							CONSTRAINT_NAME = a.CONSTRAINT_NAME
						FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS a 
						  JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS b ON a.CONSTRAINT_SCHEMA = b.CONSTRAINT_SCHEMA AND a.UNIQUE_CONSTRAINT_NAME = b.CONSTRAINT_NAME 
						  JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS c ON a.CONSTRAINT_SCHEMA = c.CONSTRAINT_SCHEMA AND a.CONSTRAINT_NAME = c.CONSTRAINT_NAME
						  JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE d on a.CONSTRAINT_NAME = d.CONSTRAINT_NAME
						WHERE b.TABLE_NAME = '{0}'
						ORDER BY 1,2",
                                table.Name.Replace("'", "''"));
                        SqlDataReader reader = command.ExecuteReader();

                        while (reader.Read())
                        {
                            var constraintName = reader["CONSTRAINT_NAME"].ToString();
                            var fkColumnName = reader["FK_COLUMN_NAME"].ToString();
                            var pkTableName = reader["PK_TABLE"].ToString();
                            var existing = hasManyRelationships.FirstOrDefault(hm => hm.ConstraintName == constraintName);
                            if (existing == null)
                            {
                                var newHasManyItem = new HasMany
                                                {
                                                    ConstraintName = constraintName,
                                                    Reference = reader.GetString(1),
                                                    PKTableName = pkTableName
                                                };
                                newHasManyItem.AllReferenceColumns.Add(fkColumnName);
                                hasManyRelationships.Add(newHasManyItem);

                            }
                            else
                            {
                                existing.AllReferenceColumns.Add(fkColumnName);
                            }
                        }
                    }
                }
            }
            finally
            {
                conn.Close();
            }
            return hasManyRelationships;
        }
        private void GenerateCodeGen(Table table)
        {
            if (table != null)
            {
                CaptureApplicationSettings();

                PopulateTableDetails(table);

                GenerateAndDisplayCode(table);

                // Display entity name based on formatted table name
                UpdateApplicationSettings(table, ApplicationSettings);
                var formatter = TextFormatterFactory.GetTextFormatter(ApplicationSettings);
                txtEntityName.Text = formatter.FormatText(table.Name);
            }
        }
        private void GenerateAndDisplayCode(Table table)
        {
            table.PrimaryKey = MetadataReader.DeterminePrimaryKeys(table);
            table.ForeignKeys = MetadataReader.DetermineForeignKeyReferences(table);

            UpdateApplicationSettings(table, ApplicationSettings);
            var applicationController = new ApplicationController(ApplicationSettings, MetadataReader);
            applicationController.Generate(table);
            txtEntityCode.Text = applicationController.GeneratedEntityCode;
            txtEntityBOCode.Text = applicationController.GeneratedEntityBOCode;

            txtFormViewASPXCode.Text = applicationController.GeneratedFormsViewASPXCode;
            txtFormViewDESIGNERCode.Text = applicationController.GeneratedFormsDesignerCode;
            txtFormViewCSCode.Text = applicationController.GeneratedFormsViewCSCode;

            txtFormASPXCode.Text = applicationController.GeneratedFormsASPXCode;
            txtFormDESIGNERCode.Text = applicationController.GeneratedFormsDesignerCode;
            txtFormCSCode.Text = applicationController.GeneratedFormsCSCode;
        }
        protected override IList<Column> GetTablesDetails(Table table, string owner)
        {
            table.OwnerSchema = owner;
            var columns = new List<Column>();
            var conn = new IngresConnection(_connectionString);
            conn.Open();
            try
            {
                using (conn)
                {
                    using (var tableDetailsCommand = conn.CreateCommand())
                    {
                        tableDetailsCommand.CommandText = string.Format("SELECT" +
                                                                        " column_name," +
                                                                        " column_datatype," +
                                                                        " column_nulls," +
                                                                        " column_length," +
                                                                        " column_scale " +
                                                                        "FROM iicolumns " +
                                                                        "WHERE table_owner = '{0}' " +
                                                                        "AND table_name = '{1}' " +
                                                                        "ORDER BY column_sequence",
                                                                        owner, table.Name);

                        using (var sqlDataReader = tableDetailsCommand.ExecuteReader(CommandBehavior.Default))
                        {
                            while (sqlDataReader.Read())
                            {
                                string columnName = sqlDataReader.GetString(0).TrimEnd();
                                string dataType = sqlDataReader.GetString(1).TrimEnd();
                                bool isNullable = sqlDataReader.GetString(2).Equals("Y", StringComparison.CurrentCultureIgnoreCase);
                                int characterMaxLenth = sqlDataReader.GetInt32(3);
                                int numericPrecision = sqlDataReader.GetInt32(3);
                                int numericScale = sqlDataReader.GetInt32(4);

                                var m = new DataTypeMapper();
                                bool isPrimaryKey = IsPrimaryKey(owner, table.Name, columnName);

                                columns.Add(new Column(table)
                                    {
                                        Name = columnName,
                                        DataType = dataType,
                                        IsNullable = isNullable,
                                        IsPrimaryKey = isPrimaryKey,
                                        IsForeignKey = IsForeignKey(owner, table.Name, columnName),
                                        MappedDataType = m.MapFromDBType(DatabaseServerType.Ingres, dataType, characterMaxLenth, numericPrecision, numericScale, isPrimaryKey),
                                        DataLength = characterMaxLenth,
                                        ConstraintName = GetConstraintName(owner, table.Name, columnName),
                                        DataPrecision = numericPrecision,
                                        DataScale = numericScale
                                    });

                                table.Columns = columns;
                            }
                            table.PrimaryKey = DeterminePrimaryKeys(table);
                            table.ForeignKeys = DetermineForeignKeyReferences(table);
                            table.HasManyRelationships = DetermineHasManyRelationships(table);
                        }
                    }
                }
            }
            finally
            {
                conn.Close();
            }

            return columns;
        }
        private string GetStructAspNetForms(Table table)
        {

            StringBuilder sbFile = new StringBuilder();

            sbFile.AppendFormat(@"using KPComponents;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using KPExtension;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using SpecialistEnumerator;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Collections.Generic;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Linq;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Web;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Web.UI;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"using System.Web.UI.WebControls;", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE);

            sbFile.AppendFormat(@"namespace {0}", ApplicationSettings.NamespaceWebProject).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{{").Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}public partial class Frm{1} : KPPage", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}public Frm{1}()", UtilCharacter.TAB_SPACE, table.Name.GetFormattedText()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{0}: base(WindowEnum.{1}_FORM)", UtilCharacter.TAB_SPACE, table.Name.ToUpper()).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE);

            sbFile.AppendFormat(@"{0}{0}#region Events", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}protected void Page_Load(object sender, EventArgs e)", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}{{", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"{0}{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);

            string concatEvent = String.Empty;
            foreach (Column column in table.Columns)
            {
                if (column.EntityComponentForm != null)
                {
                    switch (column.ColumnTypeForm)
                    {
                        case KPComponentsFormsEnum.KPFormItemButton:
                            concatEvent += GetControlKPFormItemButtonEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemCheckBox:
                            concatEvent += GetControlKPFormItemCheckBoxEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemCombo:
                            concatEvent += GetControlKPFormItemComboEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemEntity:
                            break;
                        case KPComponentsFormsEnum.KPFormItemGrid:
                            concatEvent += GetControlKPFormItemGridEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemKey:
                            break;
                        case KPComponentsFormsEnum.KPFormItemPassword:
                            concatEvent += GetControlKPFormItemPasswordEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemSpacer:
                            break;
                        case KPComponentsFormsEnum.KPFormItemText:
                            concatEvent += GetControlKPFormItemTextEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemZoom:
                            concatEvent += GetControlKPFormItemZoomEntity(column);
                            break;
                        case KPComponentsFormsEnum.KPFormItemDateTime:
                            concatEvent += GetControlKPFormItemDateTimeEntity(column);
                            break;
                        default:
                            break;
                    }
                }
            }

            if (!String.IsNullOrWhiteSpace(concatEvent))
            {
                sbFile.Append(UtilCharacter.NEW_LINE);
                sbFile.AppendFormat(@"{0}", concatEvent).Append(UtilCharacter.NEW_LINE);
            }

            sbFile.AppendFormat(@"{0}{0}#endregion Events", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE).Append(UtilCharacter.NEW_LINE); ;
            sbFile.AppendFormat(@"{0}}}", UtilCharacter.TAB_SPACE).Append(UtilCharacter.NEW_LINE);
            sbFile.AppendFormat(@"}}").Append(UtilCharacter.NEW_LINE);

            return sbFile.ToString();
        }
        private IList<Column> MetadataReader_ColumnsData(Table table, IList<Column> columns)
        {
            List<KPMappingEntity> KPMappingEntityList = KPMappingEntityBO.GetKPMappingEntity(table);

            foreach (Column itemColumn in columns)
            {
                itemColumn.ColumnTypeView = KPComponentsViewBO.GetKPComponentsView(itemColumn);
                itemColumn.ColumnTypeForm = KPComponentsFormsBO.GetKPComponentsForms(itemColumn);

                if (KPMappingEntityList != null)
                {
                    var objMapping = KPMappingEntityList.FirstOrDefault(x => x.Column.Equals(itemColumn.Name));
                    if (objMapping != null)
                    {
                        if (!String.IsNullOrWhiteSpace(objMapping.DisplayName))
                            itemColumn.DisplayName = objMapping.DisplayName;
                        if (!String.IsNullOrWhiteSpace(objMapping.CSharpType))
                            itemColumn.EntityTypeName = objMapping.CSharpType;
                    }
                }
            }

            return columns;
        }