Exemple #1
0
        void LoadTables(Database db, SourceGrid.Grid grid, string title, string nameTitle, NodeBase tableViewNode)
        {
            var tc = new TimerCount("LoadTables");

            grid.BorderStyle   = BorderStyle.FixedSingle;
            grid.SelectionMode = SourceGrid.GridSelectionMode.Cell;
            grid.ClipboardMode = SourceGrid.ClipboardMode.All;

            grid.Rows.Clear();
            grid.Columns.Clear();

            grid.ColumnsCount = 11;
            grid.FixedRows    = 1;
            grid.FixedColumns = 2;

            //int r = 0;
            SourceGrid.Cells.Views.Cell categoryView = new SourceGrid.Cells.Views.Cell();
            categoryView.Background    = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.Gainsboro, Color.WhiteSmoke, 0);
            categoryView.ForeColor     = Color.Black;
            categoryView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            categoryView.Border        = DevAge.Drawing.RectangleBorder.NoBorder;
            categoryView.Font          = new Font(Font, FontStyle.Bold);

            //grid.Rows.Insert(r);
            //grid[r, 0] = new SourceGrid.Cells.Cell(title);
            //grid[r, 0].View = categoryView;
            //grid[r, 0].ColumnSpan = grid.ColumnsCount;

            //r++;
            int r = 0;

            grid.Rows.Insert(r);
            headerView = new SourceGrid.Cells.Views.Cell();
            //headerView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.Gainsboro, Color.WhiteSmoke, 0);
            headerView.ForeColor     = Color.FromKnownColor(KnownColor.Black);
            headerView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            headerView.Border        = DevAge.Drawing.RectangleBorder.NoBorder;
            headerView.Font          = new Font(Font, FontStyle.Bold);

            addHeader(grid, Col.SchemaName, "Schema Name", 100);
            addHeader(grid, Col.TableName, "Table Name", 150);
            addHeader(grid, Col.DataClassName, "DataClass Name", 150);
            addHeader(grid, Col.BusinessClassName, "BusinessClass Name", 150);
            addHeader(grid, Col.EnumColumnName, "Enum Column Name", 150);
            addHeader(grid, Col.EnumColumnId, "Enum Column Id", 150);
            addHeader(grid, Col.EnumName, "Enum Name", 150);
            addHeader(grid, Col.EnumAttributes, "Enum Attributes", 150);
            addHeader(grid, Col.SequenceColumn, "Sequence Column", 150);
            addHeader(grid, Col.SequenceName, "Sequence Name", 150);
            addHeader(grid, Col.Attributes, "Attributes", 300);
            //addHeader(grid, 5, "Sub-directory", 150);

            for (int c = 0; c < grid.ColumnsCount; c++)
            {
                grid[r, c].View = categoryView;
            }

            Dictionary <string, GenTable> objects = new Dictionary <string, GenTable>();

            tc.Next("GetSequences");
            var sequences = db.Provider.GetSequences();

            r++;

            foreach (NodeTable node in tableViewNode.Nodes)
            {
                progress.SetProgress();
                //progress.SetProgress("Processing table" + node.Text + " ...");

                var gtb = node.Item;
                if (gtb.TableName == "status")
                {
                    ToString();
                }

                objects.Add(gtb.FullName, null);

                tc.Next(gtb.TableName);

                try
                {
                    //tc.Next("GetTableInfo");
                    //var tb = db.GetTableInfo(gtb.SchemaName, gtb.TableName);
                    var tbCols = db.GetColumnsInfo(gtb.SchemaName, gtb.TableName);

                    if (tbCols == null) // objeto inválido
                    {
                        continue;
                    }

                    Dictionary <string, GenColumn> dict = new Dictionary <string, GenColumn>(StringComparer.InvariantCultureIgnoreCase);
                    foreach (var col in gtb.Columns)
                    {
                        if (!dict.ContainsKey(col.ColumnName))
                        {
                            dict.Add(col.ColumnName, col);
                        }
                    }

                    foreach (var col in tbCols)
                    {
                        GenColumn gcol;
                        if (dict.TryGetValue(col.ColumnName, out gcol))
                        {
                            dict.Remove(col.ColumnName); // remove as existentes
                            // se existe, mas o banco é required, força required;
                            if (!col.IsNullable)
                            {
                                gcol.IsRequired = true;
                            }

                            // o tipo sempre vem do banco
                            gcol.DataType = col.DataTypeDotNet;
                        }
                        else
                        {
                            gcol              = new GenColumn();
                            gcol.ColumnName   = col.ColumnName;
                            gcol.PropertyName = null;
                            gcol.Description  = null;
                            gcol.IsRequired   = !col.IsNullable;
                            gcol.DataType     = col.DataTypeDotNet;
                            gtb.Columns.Add(gcol);
                        }
                    }

                    // se sobrou no dict, é pq as colunas foram apagadas da table, ou renomedas
                    foreach (var pair in dict)
                    {
                        gtb.Columns.RemoveAll(p => p.ColumnName.EqualsICIC(pair.Key));
                    }

                    grid.Rows.Insert(r);
                    //grid.Rows.SetHeight(r, 40);
                    //grid.Rows.AutoSizeRow(r);

                    SourceGrid.GridRow row = grid.Rows[r];

                    // tags
                    row.AutoSizeMode = SourceGrid.AutoSizeMode.EnableAutoSize | SourceGrid.AutoSizeMode.EnableStretch;
                    row.Tag          = node;
                    gtb.Tag          = tbCols;
                    node.Tag         = row;

                    grid[r, Col.SchemaName] = new SourceGrid.Cells.Cell(gtb.SchemaName);
                    grid[r, Col.TableName]  = new SourceGrid.Cells.Cell(gtb.TableName);

                    SourceGrid.Cells.Editors.EditorBase ed;

                    ed = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
                    ed.EditableMode            = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    grid[r, Col.DataClassName] = new SourceGrid.Cells.Cell(gtb.DataClassName, ed);

                    ed = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
                    ed.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    grid[r, Col.BusinessClassName] = new SourceGrid.Cells.Cell(gtb.BusinessClassName, ed);

                    // EnumColumnName
                    SourceGrid.Cells.Editors.ComboBox cbEditor = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
                    var cols = (from c in tbCols where c.DataTypeDotNet.ToLower().Contains("string") orderby c.ColumnName select c.ColumnName).ToList();
                    if (!string.IsNullOrWhiteSpace(gtb.EnumColumnName))
                    {
                        if (cols.FirstOrDefault(p => p.ToUpper() == gtb.EnumColumnName) == null)
                        {
                            gtb.EnumColumnName = gtb.EnumColumnId = gtb.EnumName = null;
                        }
                    }
                    else
                    {
                        gtb.EnumColumnName = gtb.EnumColumnId = gtb.EnumName = null;
                    }

                    if (cols.Count > 0)
                    {
                        cols.Insert(0, "");
                        cbEditor.StandardValues = cols;
                        cbEditor.EditableMode   = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    }
                    else
                    {
                        cbEditor.EditableMode = SourceGrid.EditableMode.None;
                    }
                    grid[r, Col.EnumColumnName] = new SourceGrid.Cells.Cell(gtb.EnumColumnName, cbEditor);

                    // EnumColumnId
                    cbEditor = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
                    cols     = (from c in tbCols where numericTypes.ContainsKey(c.DataTypeDotNet.Replace("?", "")) orderby c.ColumnName select c.ColumnName).ToList();
                    if (cols.Count > 0)
                    {
                        cols.Insert(0, "");
                        cbEditor.StandardValues = cols;
                        cbEditor.EditableMode   = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    }
                    else
                    {
                        cbEditor.EditableMode = SourceGrid.EditableMode.None;
                    }
                    grid[r, Col.EnumColumnId] = new SourceGrid.Cells.Cell(gtb.EnumColumnId, cbEditor);

                    // EnumName
                    ed = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
                    ed.EditableMode       = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    grid[r, Col.EnumName] = new SourceGrid.Cells.Cell(gtb.EnumName, ed);

                    // EnumAttributes
                    ed = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
                    ed.EditableMode             = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    grid[r, Col.EnumAttributes] = new SourceGrid.Cells.Cell(gtb.EnumAttributes, ed);

                    // SequenceColumn
                    cbEditor = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
                    cols     = (from c in tbCols where numericTypes.ContainsKey(c.DataTypeDotNet.Replace("?", "")) orderby c.ColumnName select c.ColumnName).ToList();
                    if (cols.Count > 0)
                    {
                        cols.Insert(0, "");
                        cbEditor.StandardValues = cols;
                        cbEditor.EditableMode   = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    }
                    else
                    {
                        cbEditor.EditableMode = SourceGrid.EditableMode.None;
                    }
                    grid[r, Col.SequenceColumn] = new SourceGrid.Cells.Cell(gtb.SequenceColumn, cbEditor);

                    // SequenceName
                    cbEditor = new SourceGrid.Cells.Editors.ComboBox(typeof(string));
                    if (sequences.Count > 0)
                    {
                        cols.Insert(0, "");
                        cbEditor.StandardValues = (from c in sequences select c.FullName).ToList();
                        cbEditor.EditableMode   = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    }
                    else
                    {
                        cbEditor.EditableMode = SourceGrid.EditableMode.None;
                    }
                    grid[r, Col.SequenceName] = new SourceGrid.Cells.Cell(gtb.SequenceName, cbEditor);

                    var ed2 = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
                    var txt = (SourceGrid.Cells.Editors.TextBox)ed2;
                    txt.Control.Multiline     = true;
                    txt.Control.AcceptsReturn = true;
                    //txt.Control.ScrollBars = ScrollBars.Both;
                    //txt.Control.ImeMode = ImeMode.Disable;

                    ed2.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    //if (gtb.Attributes != null)
                    //{
                    //    gtb.Attributes =  gtb.Attributes.Replace("\r\n", "\n");
                    //    gtb.Attributes = gtb.Attributes.Replace("\n", "\r\n\r\n");
                    //}

                    grid[r, Col.Attributes] = new SourceGrid.Cells.Cell(gtb.Attributes, ed2);

                    //ed = SourceGrid.Cells.Editors.Factory.Create(typeof(string));
                    //ed.EditableMode = SourceGrid.EditableMode.Focus | SourceGrid.EditableMode.SingleClick | SourceGrid.EditableMode.AnyKey;
                    //grid[r, 5] = new SourceGrid.Cells.Cell(gtb.SubDirectory, ed);
                    r++;
                    //string time = tc.ToString();
                }
                catch (Exception ex)
                {
                    //Program.ShowError(ex);
                }
            }

            // remove objetos não mais existentes na base de dados
            var objs = tableViewNode is NodeTables ? file.Parameters.Tables : file.Parameters.Views;

            foreach (var obj in objs.ToList())
            {
                if (!objects.ContainsKey(obj.FullName))
                {
                    objs.Remove(obj);
                }
            }

            grid.Selection.FocusRowEntered += Selection_FocusRowEntered;
            grid.Selection.FocusRowLeaving += Selection_FocusRowLeaving;
            grid.AutoSizeCells();

            string time = tc.ToString();
        }
Exemple #2
0
        public void Fill(Database db, ConnectionInfo ci, bool selectFirst)
        {
            isLoading = true;
            //trv.Nodes.Clear();
            string time;

            var tc = new TimerCount();

            using (progress = new FormProgress())
            {
                //f.StartProgress(1, count);
                progress.SetMessage("Loading objects");
                progress.Show(this);
                progress.Update();

                try
                {
                    tc.Next("NodeDatabase");

                    if (nodeDb == null)
                    {
                        nodeDb = new NodeDatabase(ci.Text);
                        nodeDb.Fill(db);
                        trv.Nodes.Add(nodeDb);

                        trv.HandleMultiSelection = true;

                        tc.Next("ExpandAllForce");
                        trv.ExpandAllForce(db);
                    }

                    tc.Next("DataToView");
                    DataToView();
                    tc.Next("LoadGrid");
                    LoadGrid(db);
                    tc.Next("nodeDb.Expand()");
                    nodeDb.Expand();

                    if (selectFirst)
                    {
                        bool isSelected = false;

                        int count = 0;

                        var nodeTables = GetNode <NodeTables>();
                        foreach (NodeBase node in nodeTables.Nodes)
                        {
                            count++;
                            if (node.Checked)
                            {
                                isSelected       = true;
                                trv.SelectedNode = node;
                                node.EnsureVisible();
                                break;
                            }
                        }

                        if (!isSelected)
                        {
                            var nodeViews = GetNode <NodeViews>();
                            foreach (NodeBase node in nodeViews.Nodes)
                            {
                                count++;
                                if (node.Checked)
                                {
                                    trv.SelectedNode = node;
                                    node.EnsureVisible();
                                    break;
                                }
                            }
                        }

                        if (count <= 15)
                        {
                            trv.TopNode = nodeDb;
                        }
                    }


                    //nodeDb.Checked = false;
                    //nodeDb.UncheckChildren();
                    //nodeDb.Checked = false;

                    time = tc.ToString();
                }
                catch (Exception ex)
                {
                    time = tc.ToString();
                    Program.ShowError(ex);
                }
            }

            //ControlUtil.ChangeFontOnlyParent(tabObjects, 12);

            isLoading = false;

#if DEBUG2
            if (db.ProviderType == EnumDbProviderType.Oracle)
            {
                Program.ShowInformation(time);
            }
#endif
        }
Exemple #3
0
        public void Fill(Database db, ConnectionInfo ci)
        {
            isLoading = true;
            trv.Nodes.Clear();
            string time;

            var tc = new TimerCount();

            file.Parameters.Tables.ForEach(p => p.IsSelected = false);
            file.Parameters.Views.ForEach(p => p.IsSelected  = false);

            using (progress = new FormProgress())
            {
                //f.StartProgress(1, count);
                progress.SetMessage("Loading objects");
                progress.Show(this);
                progress.Update();

                try
                {
                    tc.Next("NodeDatabase");
                    nodeDb = new NodeDatabase(ci.Text);
                    nodeDb.Fill(db);
                    trv.Nodes.Add(nodeDb);

                    trv.HandleMultiSelection = true;

                    tc.Next("ExpandAllForce");
                    trv.ExpandAllForce(db);

                    tc.Next("DataToView");
                    DataToView();
                    tc.Next("LoadGrid");
                    LoadGrid(db);
                    tc.Next("nodeDb.Expand()");
                    nodeDb.Expand();

                    nodeDb.Checked = false;
                    nodeDb.UncheckChildren();
                    nodeDb.Checked = false;

                    time = tc.ToString();
                }
                catch (Exception ex)
                {
                    time = tc.ToString();
                    Program.ShowError(ex);
                }
            }

            //ControlUtil.ChangeFontOnlyParent(tabObjects, 12);

            isLoading = false;

#if DEBUG2
            if (db.ProviderType == EnumDbProviderType.Oracle)
            {
                Program.ShowInformation(time);
            }
#endif
        }
        // TODO: implementar schemaName
        public DbTableInfo(Database db, string schemaName, string tableName, bool isCommand = false, string sequenceColumn = null, string sequenceName = null)
        {
            this.SchemaName     = schemaName;
            this.TableName      = tableName;
            this.SequenceColumn = sequenceColumn;
            this.SequenceName   = sequenceName;

            Columns           = new Dictionary <string, DbColumnInfo>(StringComparer.InvariantCultureIgnoreCase);
            PrimaryKey        = new Dictionary <string, DbColumnInfo>(StringComparer.InvariantCultureIgnoreCase);
            ParentRelations   = new Dictionary <string, DbReferencialConstraintInfo>(StringComparer.InvariantCultureIgnoreCase);
            ChildrenRelations = new Dictionary <string, DbReferencialConstraintInfo>();
            //DataTable tb = db.GetSchema("Columns", new string[] { null, null, tableName, null });
            DataTable tb = db.GetSchemaColumns(schemaName, tableName);

            DataTable tb2 = null;

            var tc = new TimerCount("GetCalculatedColumns");

            var calculatedColumns = db.Provider.GetCalculatedColumns(db.DatabaseName, schemaName, tableName);

            bool newMethod = false;

            string sql = db.Provider.SetTop("select * from " + db.Provider.GetObjectName(schemaName, tableName) + "", db.ProviderType == EnumDbProviderType.Access ? 1 : 0);

            if (!isCommand) //is object (table or view)
            {
                try
                {
                    //if (db.ProviderType == EnumDbProviderType.Oracle)
                    //{
                    //    newMethod = true;
                    //    sql = "select * from " + db.Provider.GetObjectName(schemaName, tableName) + " where rownum = 0";
                    //}

                    tc.Next("GetSchemaTable");
                    if (newMethod)
                    {
                        tb2 = db.GetSchemaTable(sql);
                    }
                    else
                    {
                        tb2 = db.ExecuteDataTable(sql, 0); // top 0 dá erro no access
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Speed: Error generating data class for the table/view '" + tableName + "'", ex);
                }
            }
            else
            {
                tc.Next("GetSchemaTable2");
                if (newMethod)
                {
                    tb2 = db.GetSchemaTable(sql);
                }
                else
                {
                    tb2 = db.ExecuteDataTable(sql);
                }
            }

            DataRow[] rows;
            try
            {
                rows = tb.Select("", "ORDINAL_POSITION");
            }
            catch
            {
                rows = tb.Select("");
            }

            string tbSchemaName = null;

            if (rows.Length > 0)
            {
                tc.Next("Parse");
                Dictionary <string, DbDataType> dataTypes = db.Provider.DataTypes;
                foreach (DataRow row in rows)
                {
                    DbColumnInfo col = new DbColumnInfo(db, row);

                    if (tb2.Columns.Contains(col.ColumnName))
                    {
                        if (calculatedColumns != null && calculatedColumns.Count > 0)
                        {
                            bool isComputed = calculatedColumns.Exists(p => p.ToUpper() == col.ColumnName.ToUpper());
                            if (isComputed)
                            {
                                col.IsComputed = true;
                            }
                        }

                        // coloca algumas propridades adicionais
                        if (tb2 != null)
                        {
                            col.DataTypeDotNet = tb2.Columns[col.ColumnName].DataType.Name;
                        }
                        else
                        {
                            col.DataTypeDotNet = dataTypes[col.DataType].DataType;
                            if (col.DataTypeDotNet.StartsWith("System."))
                            {
                                col.DataTypeDotNet = col.DataTypeDotNet.Substring("System.".Length, col.DataTypeDotNet.Length - "System.".Length);
                            }
                        }
                        Columns.Add(col.ColumnName, col);

                        if (string.IsNullOrEmpty(schemaName))
                        {
                            if (Columns.Count == 1)
                            {
                                if (db.ProviderType == EnumDbProviderType.Oracle)
                                {
                                    tbSchemaName = tb.Columns.Contains("TABLE_CATALOG") ? Conv.ToString(row["TABLE_CATALOG"]) : Conv.ToString(row["TABLE_SCHEMA"]);
                                }
                                else
                                {
                                    tbSchemaName = Conv.ToString(row["TABLE_SCHEMA"]);
                                }
                                if (!string.IsNullOrEmpty(tbSchemaName))
                                {
                                    schemaName      = tbSchemaName;
                                    this.SchemaName = schemaName;
                                }
                            }
                        }

                        if (db.ProviderType == EnumDbProviderType.PostgreSQL)
                        {
                            var seqs = db.Sequences;
                            if (!col.IsIdentity && (!string.IsNullOrEmpty(col.ColumnDefault) && col.ColumnDefault.ToLower().Contains("nextval(")))
                            {
                                this.SequenceColumn = col.ColumnName;
                                string key = Conv.GetKey(Conv.Unquote(schemaName), Conv.Unquote(tableName), col.ColumnName);
                                if (seqs.ContainsKey(key))
                                {
                                    this.SequenceName = seqs[key].SequenceName;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                // Usa DataTable
                tc.Next("DbColumnInfo");
                foreach (DataColumn col in tb2.Columns)
                {
                    DbColumnInfo item = new DbColumnInfo(db, tableName, col);
                    // coloca algumas propridades adicionais
                    item.DataTypeDotNet = col.DataType.Name;
                    Columns.Add(item.ColumnName, item);
                }
            }

            // Identity
            tc.Next("Identity");
            var    idCol = (from c in Columns where c.Value.IsIdentity select c.Value.ColumnName).FirstOrDefault();
            string identity;

            if (idCol != null)
            {
                identity = idCol;
            }
            else
            {
                identity = db.Provider.GetIdentityColumn(db.DatabaseName, schemaName, tableName);

                if (!string.IsNullOrEmpty(identity))
                {
                    if (Columns.ContainsKey(identity))
                    {
                        Columns[identity].IsIdentity = true;
                    }
                }
            }

            // se o datatable retornar a pk é melhor, pq sp_keys não retorna nada para views
            tc.Next("Pk");
            if (tb2 != null && tb2.PrimaryKey != null && tb2.PrimaryKey.Length > 0)
            {
                foreach (DataColumn col in tb2.PrimaryKey)
                {
                    DbColumnInfo ci = Columns[col.ColumnName];
                    PrimaryKey.Add(ci.ColumnName, ci);
                }
            }
            else
            {
                string[] keys = db.Provider.GetPrimaryKeyColumns(db.DatabaseName, schemaName, tableName);
                if (keys != null && keys.Length > 0)
                {
                    foreach (var key in keys)
                    {
                        DbColumnInfo ci = Columns[key];
                        PrimaryKey.Add(ci.ColumnName, ci);
                    }
                }
            }

            //            // ParentRelations
            //            try
            //            {
            //#if DEBUG2
            //                try
            //                {
            //                    tc.Next("GetParentRelations");
            //                    var x = db.Provider.GetParentRelations(schemaName, tableName);

            //                }
            //                catch (Exception ex)
            //                {
            //                    ex.ToString();
            //                }
            //#endif
            //                    tc.Next("GetParentRelations");
            //                var fks = db.Provider.GetParentRelations(schemaName, tableName);
            //                if (fks != null && fks.Count > 0)
            //                {
            //                    foreach (var fk in fks)
            //                    {
            //                        if (!ParentRelations.ContainsKey(fk.ConstraintName))
            //                            ParentRelations.Add(fk.ConstraintName, fk);
            //                    }
            //                    ToString();
            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                throw new Exception("Error in GetParentRelations", ex);
            //            }

            //            // ChildRelations
            //                    tc.Next("ChildRelations");
            //            try
            //            {
            //                foreach (var pair in db.ReferentialContraints)
            //                {
            //                    foreach (DbReferencialConstraintInfo constr in pair.Value)
            //                    {
            //                        if (constr.Columns.Count > 0)
            //                        {
            //                            var col = constr.Columns[0];
            //                            if (db.ProviderType == EnumDbProviderType.Access)
            //                            {
            //                                if (col.ReferencedTableSchema.EqualsICIC(schemaName) && col.ReferencedTableName.EqualsICIC(tableName))
            //                                {
            //                                    ChildrenRelations.Add(constr.ConstraintFullName, constr);
            //                                }
            //                            }
            //                            else
            //                            {
            //                                if ((col.ReferencedTableSchema.EqualsICIC(schemaName) | schemaName == "sqlite_default_schema") && col.ReferencedTableName.EqualsICIC(tableName))
            //                                {
            //                                    ChildrenRelations.Add(constr.ConstraintFullName, constr);
            //                                }
            //                            }
            //                        }
            //                    }
            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                throw new Exception("Error in DbTableInfo", ex);
            //            }
            string time = tc.ToString();
        }
        private void GenerateDataClasses(Database db, List <Type> types, bool singleClass = false, bool recompile = false)
        {
            Sys.Trace("GenerateDataClasses. types.Count = " + types.Count);
            if (types.Count == 0)
            {
                return;
            }

            var erros = new StringBuilder();

            Sys.Trace("db.Provider.GetLastModified()");

            string lastModified = db.Provider.GetLastModified();
            string dir          = GetDirectory(types, db, lastModified);
            string fileCode     = Path.Combine(dir, "Speed.Code.cs");
            string fileDll      = Path.Combine(dir, "Speed." + types[0].Assembly.GetName().Name + ".dll");

            if (!recompile && lastModified != null)
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                Sys.Trace("GetDirectory: " + dir);
                Sys.Trace("fileDll: " + fileDll);

                if (File.Exists(fileDll))
                {
                    Sys.Trace("fileDll Exists");
                    try
                    {
                        var assCache = Assembly.LoadFile(fileDll);

                        var typesDataClass = assCache.GetExportedTypes();

                        foreach (var type in types)
                        {
                            addToCache(type, (DataClass)assCache.CreateInstance("DataClass" + type.Name));
                        }

                        Sys.Trace("fileDll carregada do cache");
                        return;
                    }
                    catch (Exception ex)
                    {
                        Sys.Trace(ex, "Erro ao carregar do cache");
                        //throw;
                        // deu erro? continua e recompila
                    }
                }
            }

            TimerCount tc = new TimerCount("TestSelect");

            Dictionary <Type, dataInfo> dataInfos = new Dictionary <Type, dataInfo>();
            // other usings
            Dictionary <string, string> otherUsings = new Dictionary <string, string>();

            List <string> codes = new List <string>();

            int i = 0;

            foreach (var type in types)
            {
                try
                {
                    DbTableInfo table;
                    var         infos = new Dictionary <string, DbColumnInfo>();
                    string      className;
                    string      tableName;
                    if (type.Name == "VwSisLog")
                    {
                        type.ToString();
                    }
                    string text = CodeGenerator.GenerateDataClassCode(db, type, out className, out tableName,
                                                                      out table, out infos, otherUsings);
                    if (text != null)
                    {
                        codes.Add(text);

                        dataInfo di = new dataInfo {
                            Table = table, Infos = infos, TableName = tableName, ClassName = className
                        };
                        dataInfos.Add(type, di);
                    }
                }
                catch (Exception ex)
                {
                    erros.AppendFormat("Error generating class for type: " + type.Name + " - " + ex.Message);
                }
                i++;
            }

            if (erros.Length > 0)
            {
                Sys.Trace("Erros: " + erros.ToString());
                Database.Errors.Add(erros.ToString());
            }

            StringBuilder b = new StringBuilder();

            b.AppendLine(DataClassTemplate.DATACLASSTEMPLATE_USING);
            foreach (var pair in otherUsings)
            {
                b.AppendLine(pair.Key);
            }
            codes.ForEach(p => b.AppendLine(p));

#if DEBUG
            string code = b.ToString();
#else
            string code = string.Join("\r\n", b.ToString().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Where(line => !string.IsNullOrWhiteSpace(line) && !line.Trim().StartsWith("//")).Select(line => line.Trim()));
#endif
            b.Clear();

            Sys.Trace("code gerado");

            Assembly ass = null;

#if DEBUG
            //Descomentar somente se for necessário. Impacta muito a performance
            try
            {
                string dirAc = Path.Combine(@"..\..\DataClass", types[0].Namespace);
                if (!System.IO.Directory.Exists(dirAc))
                {
                    System.IO.Directory.CreateDirectory(dirAc);
                }
                using (System.IO.StreamWriter w = new System.IO.StreamWriter(Path.Combine(dirAc, "AllClasses.cs"), false))
                    w.Write(code);
            }
            catch { }
#endif

            // para aplicações web, Assembly.GetEntryAssembly() sempre retorna null
            //if (Assembly.GetEntryAssembly() != null)
            //{
            tc.Next("Compile");

            bool hasCache = false;

            Sys.Trace("Compile");
            if (hasCache)
            {
                try
                {
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    else
                    {
                        if (File.Exists(fileCode) && File.Exists(fileDll))
                        {
                            if (File.ReadAllText(fileCode) == code)
                            {
                                try
                                {
                                    ass      = Assembly.LoadFile(fileDll);
                                    hasCache = true;
                                }
                                catch (Exception ex)
                                {
                                    Sys.Trace(ex, "asm1");
                                    ass = null;
                                    ex.ToString();
                                }
                            }
                        }
                    }
                    if (ass == null)
                    {
                        if (File.Exists(fileDll))
                        {
                            File.Delete(fileDll);
                        }

                        Sys.Trace("Compilando em disco");
                        ass = CodeGenerator.Compile(db, types[0], code, "All Classes", fileDll, otherUsings);
                        File.WriteAllText(fileCode, code);
                        Sys.Trace("Compilando no disco: " + fileDll);
                    }
                }
                catch (Exception ex)
                {
                    Sys.Trace(ex, "asm2");
                    ass = null;
                }
            }

            if (ass == null)
            {
                Sys.Trace("Compilando na memória");
                // compila na memória
                if (!singleClass)
                {
                    ass = CodeGenerator.Compile(db, types[0], code, "All Classes", fileDll, otherUsings);
                }
                else
                {
                    ass = CodeGenerator.Compile(db, types[0], code, types[0].FullName, null, otherUsings);
                }
                Sys.Trace("Compilado na memória: " + fileDll);
            }

#if DEBUG2
            var exTypes = ass.GetExportedTypes().Where(p => p.Name.StartsWith("DataClass")).ToList();
#endif


            tc.Next("Depois");
            lock (cache)
            {
                foreach (var pair in dataInfos)
                {
                    Type     type = pair.Key;
                    dataInfo info = pair.Value;
                    if (cache.ContainsKey(type))
                    {
                        cache.Remove(type);
                    }
                    if (cacheByName.ContainsKey(type.Name))
                    {
                        cacheByName.Remove(type.Name);
                    }

                    Type objType = ass.GetType(info.ClassName);

                    if (objType == null)
                    {
                        Database.Errors.Add("Not found in the database: " + type.Name + " - " + info.TableName);
                        continue;
                    }

                    DataClass dc = (DataClass)Activator.CreateInstance(objType);
                    if (dc == null)
                    {
                        continue;
                    }
                    dc.TableInfo   = info.Table;
                    dc.ColumnInfos = info.Infos;
                    addToCache(type, dc);
                }
            }
            string time = tc.ToString();
        }