示例#1
0
        public void DrawObjects()
        {
            if (_dependencyObjectList.Count > 0)
            {
                LongRunningOperationManager.ReportProgress(-1);

                DateTime dt = DateTime.Now;
                MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Drawing objects..."));

                this.treeListView1.Roots = _dependencyObjectList.Where(m => m.SystemParentId == -1).OrderBy(m => m.ObjectName);
                tsslObjectCount.Text     = string.Format("{0:n0} total, {1:n0} root, {2:n0} dependency, {3:n0} unique", _dependencyObjectList.Count(), _dependencyObjectList.Count(d => d.HierarchyLevel == 0), _dependencyObjectList.Count(d => d.HierarchyLevel > 0), _dependencyObjectList.Distinct(new MySqlObjectEqualityComparer()).Count());

                MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. {0:n0} objects drawn.", _dependencyObjectList.Count()), (DateTime.Now - dt).TotalSeconds);
            }
        }
示例#2
0
        private void initSqlDatabases()
        {
            DateTime dt = DateTime.Now;

            _sqlDatabases.Clear();

            try
            {
                foreach (MySqlServerObject so in _sqlServerObjects)
                {
                    MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Loading databases from server ({0}) '{1}'...", so.ServerObjectId, getDataSourceName(so.ServerObjectId)));

                    var conn = ConnectionPool.GetConnection(so.ServerObjectId);
                    if (conn != null)
                    {
                        SqlCommand cmd = (SqlCommand)ConnectionPool.GetConnection(so.ServerObjectId).CreateCommand();
                        cmd.CommandText    = QueryReader.Read("databases.sql");
                        cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
                        cmd.CommandType    = CommandType.Text;
                        SqlDataReader rdr = cmd.ExecuteReader();
                        while (rdr.Read())
                        {
                            _sqlDatabases.Add(new MySqlDatabase
                            {
                                ServerObjectId     = so.ServerObjectId,
                                ServerObjectName   = so.ServerObjectName,
                                DatabaseId         = (int)rdr["database_id"],
                                DatabaseName       = (string)rdr["database_name"],
                                State              = (string)rdr["state_desc"],
                                UserHasDbAccess    = (bool)rdr["has_db_access"],
                                CompatibilityLevel = Convert.ToInt32(rdr["compatibility_level"]),
                                CollationName      = (string)rdr["collation_name"],
                                RecoveryModel      = (string)rdr["recovery_model_desc"]
                            });
                        }
                        rdr.Close();

                        MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0:n0} databases.", _sqlDatabases.Count(x => x.ServerObjectId == so.ServerObjectId)), (DateTime.Now - dt).TotalSeconds);
                    }
                }
            }
            catch (Exception ex)
            {
                MyOutput.NewMessage(EOutputMessageType.ERROR, string.Format("Error loading databases: {0}", ex.Message));
                var exForm = new ExceptionForm(ex);
                exForm.ShowDialog();
            }
        }
示例#3
0
        private void LongRunningOperationManager_DoWorkExecQuery(object sender, DoWorkEventArgs e)
        {
            LongRunningOperationManager.StartNextStep();
            LongRunningOperationManager.ReportProgress(-1);

            MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Reading data from {0}... ", this._mySqlObject.ObjectNameFull));

            DateTime dt = DateTime.Now;

            string query = string.Format("SELECT TOP 1000 * FROM [{0}].[{1}] WITH (NOLOCK)", _mySqlObject.SchemaName, _mySqlObject.ObjectName);

            _mySqlServer.ConnectionPool.GetConnection(_mySqlObject.ServerObjectId).ChangeDatabase(_mySqlObject.DatabaseName);
            cmd                = (SqlCommand)_mySqlServer.ConnectionPool.GetConnection(_mySqlObject.ServerObjectId).CreateCommand();
            cmd.CommandText    = query;
            cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
            cmd.CommandType    = CommandType.Text;

            SqlDataReader rdr = null;

            try
            {
                rdr = cmd.ExecuteReader(CommandBehavior.SingleResult);
            }
            catch (Exception ex1)
            {
                if (!LongRunningOperationManager.CancellationPending)
                {
                    MyOutput.AppendToLastMessage(EOutputMessageType.ERROR, string.Format("{0}", ex1.Message));
                    MessageBox.Show(ex1.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MyOutput.AppendToLastMessage(EOutputMessageType.WARNING, string.Format("Done. Cancelled by user."), (DateTime.Now - dt).TotalSeconds);
                }
            }

            if (rdr == null)
            {
                e.Cancel = true;
                return;
            }

            DataTable dataTable = new DataTable();

            dataTable.Load(rdr);
            rdr.Close();

            // Get all byte columns
            List <DataColumn> byteColumns = dataTable.Columns.Cast <DataColumn>().Where(dc => dc.DataType == typeof(byte[])).ToList();

            foreach (DataColumn dc in byteColumns)
            {
                int    colOrdinal = dc.Ordinal;
                string colName    = String.Format("{0} (Hex)", dc.ColumnName);

                DataColumn tmpCol = new DataColumn(colName, typeof(String));
                dataTable.Columns.Add(tmpCol);
                foreach (DataRow row in dataTable.Rows)
                {
                    row[tmpCol] = byteArrayToHexString((byte[])row[dc]);
                }
                dataTable.Columns.Remove(dc);
                dataTable.Columns[colName].SetOrdinal(colOrdinal);
            }

            e.Result = dataTable;

            MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0} rows.", dataTable.Rows.Count), (DateTime.Now - dt).TotalSeconds);
        }
示例#4
0
        public void Load(bool forceReload)
        {
            DateTime dt;
            int      dbCount;
            int      counter;

            this._status = ESqlServerStatus.REFRESHING;

            OnDataChanged?.Invoke(this, null);

            // Make backup of all lists in case of use cancells execution
            MySqlDatabase[]             oldLoadedDatabases           = new MySqlDatabase[_sqlLoadedDatabases.Count];
            MySqlObject[]               oldSqlObjects                = new MySqlObject[_sqlObjects.Count];
            MySqlExpressionDependency[] oldSqlExpressionDependencies = new MySqlExpressionDependency[_sqlExpressionDependencies.Count];

            _sqlLoadedDatabases.CopyTo(oldLoadedDatabases);
            _sqlObjects.CopyTo(oldSqlObjects);
            _sqlExpressionDependencies.CopyTo(oldSqlExpressionDependencies);


            if (forceReload)
            {
                _sqlLoadedDatabases.Clear();
                _sqlObjects.Clear();
                _sqlExpressionDependencies.Clear();
            }

            MySqlDatabase[] newSqlDatabases = SqlCheckedDatabases.Except(SqlLoadedDatabases).ToArray();
            MySqlDatabase[] oldSqlDatabases = SqlLoadedDatabases.Except(SqlCheckedDatabases).ToArray();

            counter = 0;
            dbCount = newSqlDatabases.Length * 2 + oldSqlDatabases.Length;

            // Remove unnecessary objects from unused database
            if (oldSqlDatabases.Length > 0)
            {
                foreach (MySqlDatabase oldDb in oldSqlDatabases)
                {
                    if (LongRunningOperationManager.CancellationPending)
                    {
                        break;
                    }

                    dt = DateTime.Now;
                    MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Removing unnecessary objects for server '{0}', database '{1}' from internal database... ", oldDb.ServerObjectName, oldDb.DatabaseName));
                    int deletedObjectCount = _sqlObjects.RemoveAll(o => o.ServerObjectId == oldDb.ServerObjectId && o.DatabaseId == oldDb.DatabaseId);
                    MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Removed {0:n0} objects.", deletedObjectCount), (DateTime.Now - dt).TotalSeconds);

                    dt = DateTime.Now;
                    MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Removing unnecessary dependencies for server '{0}', database '{1}' from internal database... ", oldDb.ServerObjectName, oldDb.DatabaseName));
                    int deletedExpressionDependencyCount = _sqlExpressionDependencies.RemoveAll(o => o.ServerObjectId == oldDb.ServerObjectId && o.DatabaseId == oldDb.DatabaseId);
                    MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Removed {0:n0} dependencies.", deletedExpressionDependencyCount), (DateTime.Now - dt).TotalSeconds);

                    LongRunningOperationManager.ReportProgress(100 * ++counter / dbCount);
                }
            }

            if (newSqlDatabases.Length > 0)
            {
                foreach (MySqlDatabase newDb in newSqlDatabases)
                {
                    if (LongRunningOperationManager.CancellationPending)
                    {
                        break;
                    }

                    initSqlObjects(newDb.ServerObjectId, newDb.DatabaseId);
                    //loadDatabaseObjects(newDb.ServerObjectName, newDb.DatabaseName);

                    LongRunningOperationManager.ReportProgress(100 * ++counter / dbCount);
                }
                MyOutput.NewMessage(EOutputMessageType.INFORMATION, string.Format("Totally {0:n0} objects loaded from {1:n0} server(s) and {2:n0} database(s).", _sqlObjects.Count, SqlCheckedDatabases.Select(s => s.ServerObjectName).Distinct().Count(), SqlCheckedDatabases.Length));

                // ALL OBJECTS FROM ALL SERVERS / DATABASES MUST BE LOADED FIRST!
                foreach (MySqlDatabase newDb in newSqlDatabases)
                {
                    if (LongRunningOperationManager.CancellationPending)
                    {
                        break;
                    }

                    initSqlExpressionDependencies(newDb.ServerObjectId, newDb.DatabaseId);

                    LongRunningOperationManager.ReportProgress(100 * ++counter / dbCount);
                }
                MyOutput.NewMessage(EOutputMessageType.INFORMATION, string.Format("Totally {0:n0} dependencies loaded from {1:n0} server(s) and {2:n0} database(s).", _sqlExpressionDependencies.Count, SqlCheckedDatabases.Select(s => s.ServerObjectName).Distinct().Count(), SqlCheckedDatabases.Length));
            }

            if (!LongRunningOperationManager.CancellationPending)
            {
                _sqlLoadedDatabases.Clear();
                _sqlLoadedDatabases.AddRange(SqlCheckedDatabases);

                if (oldSqlDatabases.Length > 0 || newSqlDatabases.Length > 0)
                {
                    this._lastDataLoad = DateTime.Now;
                }
            }
            else
            {
                _sqlLoadedDatabases.Clear();
                _sqlObjects.Clear();
                _sqlExpressionDependencies.Clear();

                _sqlLoadedDatabases.AddRange(oldLoadedDatabases);
                _sqlObjects.AddRange(oldSqlObjects);
                _sqlExpressionDependencies.AddRange(oldSqlExpressionDependencies);
            }

            this._status = ESqlServerStatus.READY;


            // Prepare EX lists

            /*
             * SqlExpressionDependenciesEx.Clear();
             * foreach (var ed in _sqlExpressionDependencies)
             * {
             *  var keys = new MyKeyList();
             *  keys.Add(ed.ParentServerObjectId);
             *  keys.Add(ed.ParentDatabaseId);
             *  keys.Add(ed.ParentObjectId);
             *  keys.Add(ed.ChildServerObjectId);
             *  keys.Add(ed.ChildDatabaseId);
             *  keys.Add(ed.ChildObjectId);
             *  SqlExpressionDependenciesEx.Add(keys, ed);
             * }
             */

            OnDataChanged?.Invoke(this, null);
        }
示例#5
0
        //private void initSqlExpressionDependencies(int serverObjectId, int databaseId)
        //{
        //    try
        //    {
        //        var serverObjectName = SqlServerObjects.First(so => so.ServerObjectId == serverObjectId).ServerObjectName;
        //        var databaseName = SqlDatabases.First(d => d.ServerObjectId == serverObjectId && d.DatabaseId == databaseId).DatabaseName;

        //        MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Loading expression dependencies from server object '{0}', database '{1}'... ", serverObjectName, databaseName));

        //        int counter = 0;
        //        DateTime dt = DateTime.Now;

        //        string query = QueryReader.Read("expression_dependencies.sql");

        //        ConnectionPool.GetConnection(serverObjectId).ChangeDatabase(databaseName);
        //        SqlCommand cmd = (SqlCommand)ConnectionPool.GetConnection(serverObjectId).CreateCommand();
        //        cmd.CommandText = query;
        //        cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
        //        cmd.CommandType = CommandType.Text;

        //        SqlDataReader rdr = cmd.ExecuteReader();
        //        while (rdr.Read())
        //        {
        //            counter++;

        //            int referencedId = -1;
        //            int.TryParse(rdr["referenced_id"].ToString(), out referencedId);

        //            _sqlExpressionDependencies.Add(new MySqlExpressionDependency
        //            {
        //                ServerObjectId = serverObjectId,
        //                ServerObjectName = serverObjectName,
        //                DatabaseId = databaseId,
        //                DatabaseName = databaseName,
        //                ReferencingId = (int)rdr["referencing_id"],
        //                ReferencedServerName = (string)rdr["referenced_server_name"],
        //                ReferencedDatabaseName = (string)rdr["referenced_database_name"],
        //                ReferencedSchemaName = (string)rdr["referenced_schema_name"],
        //                ReferencedEntityName = (string)rdr["referenced_entity_name"],
        //                ReferencedId = (referencedId != -1) ? referencedId : (int?)null
        //            });
        //        }
        //        rdr.Close();

        //        MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0:n0} expression dependencies.", counter), (DateTime.Now - dt).TotalSeconds);
        //    }
        //    catch (Exception ex)
        //    {
        //        MyOutput.NewMessage(EOutputMessageType.ERROR, string.Format("Error loading expression dependencies: {0}", ex.Message));
        //        var exForm = new ExceptionForm(ex);
        //        exForm.ShowDialog();
        //    }
        //}

        private void initSqlExpressionDependencies(int serverObjectId, int databaseId)
        {
            var serverObjectName = SqlServerObjects.First(so => so.ServerObjectId == serverObjectId).ServerObjectName;
            var databaseName     = SqlDatabases.First(d => d.ServerObjectId == serverObjectId && d.DatabaseId == databaseId).DatabaseName;

            MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Loading expression dependencies from server '{0}', database '{1}'... ", serverObjectName, databaseName));

            int      initialNumberOfRows = SqlExpressionDependencies.Length;
            DateTime dt = DateTime.Now;
            //DateTime timeCounterInner;

            DataTable ExpressionDependenciesDataTable = new DataTable();
            string    query = QueryReader.Read("expression_dependencies.sql");

            var svr = SqlObjects.FirstOrDefault(o => o.ServerObjectId == serverObjectId);
            var db  = SqlObjects.FirstOrDefault(o => o.ServerObjectId == serverObjectId && o.DatabaseId == databaseId);

            if (svr == null || db == null)
            {
                MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0:n0} dependencies.", SqlExpressionDependencies.Length - initialNumberOfRows), (DateTime.Now - dt).TotalSeconds);
                return;
            }

            ConnectionPool.GetConnection(serverObjectId).ChangeDatabase(databaseName);
            SqlCommand cmd = ConnectionPool.GetConnection(serverObjectId).CreateCommand();

            cmd.CommandText    = query;
            cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
            cmd.CommandType    = CommandType.Text;

            ExpressionDependenciesDataTable.Load(cmd.ExecuteReader());

            //var results = from myRow in dataTable.AsEnumerable()
            //              select new
            //              {
            //                  ReferencingId = Convert.ToInt32(myRow["referencing_id"]),
            //                  ReferencedId = Convert.ToInt32(((myRow["referenced_id"] != DBNull.Value) ? Convert.ToInt32(myRow["referenced_id"]) : -1)),
            //                  ReferencedSchemaId = _objectList.First(o => o.ServerName.Equals(serverName, StringComparison.InvariantCultureIgnoreCase)
            //                      && o.DatabaseName.Equals(databaseName, StringComparison.InvariantCultureIgnoreCase)
            //                      && o.SchemaName.Equals((string)myRow["referenced_schema_name"], StringComparison.InvariantCultureIgnoreCase)).SchemaId,
            //                ReferencedEntityName = (string)myRow["referenced_entity_name"]
            //              };


            var databaseDependencies = from myRow in ExpressionDependenciesDataTable.AsEnumerable()
                                       select new
            {
                ReferencingId      = Convert.ToInt32(myRow["referencing_id"]),
                ReferencedId       = Convert.ToInt32(((myRow["referenced_id"] != DBNull.Value) ? Convert.ToInt32(myRow["referenced_id"]) : -1)),
                ReferencedSchemaId = (SqlObjects.FirstOrDefault(o => o.ServerObjectId == serverObjectId &&
                                                                o.DatabaseId == databaseId &&
                                                                o.SchemaName.Equals((string)myRow["referenced_schema_name"], StringComparison.InvariantCultureIgnoreCase)) != null) ?
                                     (SqlObjects.FirstOrDefault(o => o.ServerObjectId == serverObjectId &&
                                                                o.DatabaseId == databaseId &&
                                                                o.SchemaName.Equals((string)myRow["referenced_schema_name"], StringComparison.InvariantCultureIgnoreCase)).SchemaId)
                                               : -1,
                ReferencedServerName   = (string)myRow["referenced_server_name"],
                ReferencedDatabaseName = (string)myRow["referenced_database_name"],
                ReferencedSchemaName   = (string)myRow["referenced_schema_name"],
                ReferencedEntityName   = (string)myRow["referenced_entity_name"]
            };



            var res = from dbDep in databaseDependencies
                      join parentObj in SqlObjects.Where(p => p.ServerObjectId == serverObjectId && p.DatabaseId == databaseId)
                      on dbDep.ReferencingId equals parentObj.ObjectId
                      join childObj in SqlObjects.Where(c => c.ServerObjectId == serverObjectId && c.DatabaseId == databaseId)
                      on new { SchemaId = dbDep.ReferencedSchemaId, ObjectId = dbDep.ReferencedId, ObjectName = dbDep.ReferencedEntityName } equals
            new { SchemaId = childObj.SchemaId, ObjectId = childObj.ObjectId, ObjectName = childObj.ObjectName }
            select new MySqlExpressionDependency
            {
                ServerObjectId       = serverObjectId,
                DatabaseId           = databaseId,
                ParentServerObjectId = parentObj.ServerObjectId,
                ParentDatabaseId     = parentObj.DatabaseId,
                ParentObjectId       = parentObj.ObjectId,
                ChildServerObjectId  = childObj.ServerObjectId,
                ChildDatabaseId      = childObj.DatabaseId,
                ChildObjectId        = childObj.ObjectId,
                ChildObjectExists    = true
            };

            var uwq = from dbDep in databaseDependencies.Where(dd => dd.ReferencedId == -1 || dd.ReferencedSchemaId == -1)
                      join parentObj in SqlObjects.Where(p => p.ServerObjectId == serverObjectId && p.DatabaseId == databaseId)
                      on dbDep.ReferencingId equals parentObj.ObjectId
                      select new MySqlExpressionDependency
            {
                ServerObjectId        = serverObjectId,
                DatabaseId            = databaseId,
                ParentServerObjectId  = parentObj.ServerObjectId,
                ParentDatabaseId      = parentObj.DatabaseId,
                ParentObjectId        = parentObj.ObjectId,
                ChildServerObjectName = dbDep.ReferencedServerName,
                ChildDatabaseName     = dbDep.ReferencedDatabaseName,
                ChildSchemaName       = dbDep.ReferencedSchemaName,
                ChildObjectName       = dbDep.ReferencedEntityName,
                ChildObjectExists     = false
            };


            _sqlExpressionDependencies.AddRange(res.Union(uwq));

            MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0:n0} dependencies.", res.Count()), (DateTime.Now - dt).TotalSeconds);
        }
示例#6
0
        private void initSqlObjects(int serverObjectId, int databaseId)
        {
            try
            {
                var serverObjectName = SqlServerObjects.First(so => so.ServerObjectId == serverObjectId).ServerObjectName;
                var databaseName     = SqlDatabases.First(d => d.ServerObjectId == serverObjectId && d.DatabaseId == databaseId).DatabaseName;

                MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Loading objects from server object '{0}', database '{1}'... ", serverObjectName, databaseName));

                int      counter = 0;
                DateTime dt      = DateTime.Now;

                string query = QueryReader.Read("objects.sql");

                ConnectionPool.GetConnection(serverObjectId).ChangeDatabase(databaseName);
                SqlCommand cmd = (SqlCommand)ConnectionPool.GetConnection(serverObjectId).CreateCommand();
                cmd.CommandText    = query;
                cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
                cmd.CommandType    = CommandType.Text;

                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    counter++;
                    _sqlObjects.Add(new MySqlObject
                    {
                        ServerObjectId     = serverObjectId,
                        ServerObjectName   = serverObjectName,
                        DatabaseId         = Convert.ToInt32(rdr["db_id"]),
                        DatabaseName       = (string)rdr["db_name"],
                        SchemaId           = Convert.ToInt32(rdr["schema_id"]),
                        SchemaName         = (string)rdr["schema_name"],
                        ObjectId           = (int)(rdr["object_id"]),
                        ObjectName         = (string)rdr["object_name"],
                        ObjectTypeId       = (string)rdr["type"],
                        ObjectType         = (string)rdr["type_desc"],
                        ObjectNameFull     = (string)rdr["object_name_full"],
                        BaseObjectNameFull = (rdr["base_object_name_full"] != DBNull.Value) ? rdr["base_object_name_full"].ToString() : null
                    });
                }
                rdr.Close();


                // Row counts
                query = QueryReader.Read("table_sizes.sql");

                cmd                = (SqlCommand)ConnectionPool.GetConnection(serverObjectId).CreateCommand();
                cmd.CommandText    = query;
                cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
                cmd.CommandType    = CommandType.Text;

                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    var obj = _sqlObjects.FirstOrDefault(o => o.ObjectType.Equals("USER_TABLE") &&
                                                         o.SchemaName.Equals((string)rdr["schema_name"], StringComparison.InvariantCultureIgnoreCase) &&
                                                         o.ObjectName.Equals((string)rdr["table_name"], StringComparison.InvariantCultureIgnoreCase));

                    if (obj != null)
                    {
                        obj.RowCount         = (long)rdr["row_counts"];
                        obj.TotalSpaceUsedKB = (long)rdr["total_space_kb"];
                    }
                }
                rdr.Close();

                // Object definitions
                query = QueryReader.Read("object_definitions.sql");

                cmd                = (SqlCommand)ConnectionPool.GetConnection(serverObjectId).CreateCommand();
                cmd.CommandText    = query;
                cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
                cmd.CommandType    = CommandType.Text;

                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    var obj = _sqlObjects.FirstOrDefault(o => o.ObjectId == (int)rdr["object_id"]);

                    if (obj != null)
                    {
                        obj.ObjectDefinition = (string)rdr["definition"];
                    }
                }
                rdr.Close();

                MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0:n0} objects.", counter), (DateTime.Now - dt).TotalSeconds);
            }
            catch (Exception ex)
            {
                MyOutput.NewMessage(EOutputMessageType.ERROR, string.Format("Error loading database objects: {0}", ex.Message));
                var exForm = new ExceptionForm(ex);
                exForm.ShowDialog();
            }
        }
示例#7
0
        private void initSqlServerObjects()
        {
            DateTime dt = DateTime.Now;

            _sqlServerObjects.Clear();

            try
            {
                MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Loading server objects for server ({0}) '{1}'...", 0, getDataSourceName(0)));

                // Load Server data
                SqlCommand cmd = (SqlCommand)ConnectionPool.GetConnection(0).CreateCommand();
                cmd.CommandText    = QueryReader.Read("server_objects.sql");
                cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
                cmd.CommandType    = CommandType.Text;

                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    // Create new server object
                    var so = new MySqlServerObject
                    {
                        ServerObjectId   = (int)(rdr["server_id"]),
                        ServerObjectName = (string)rdr["data_source"],
                        IsLinked         = (bool)rdr["is_linked"],
                        Product          = (string)rdr["product"],
                        Provider         = (string)rdr["provider"]
                    };

                    // Add new server objects
                    _sqlServerObjects.Add(so);

                    // Add new connections in the pool
                    if (so.ServerObjectId > 0)
                    {
                        SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(ConnectionPool.GetConnection(0).ConnectionString);
                        scsb.DataSource = so.ServerObjectName;

                        ConnectionPool.AddConnection(scsb.ConnectionString, so.ServerObjectId);
                    }
                }
                rdr.Close();

                // Check connections
                ConnectionPool.Connect(_sqlServerObjects.Select(x => x.ServerObjectId).ToArray());
                List <int> soid = new List <int>();
                soid.AddRange(_sqlServerObjects.Select(x => x.ServerObjectId));

                foreach (int id in soid.ToArray())
                {
                    if (!ConnectionPool.ConfirmedServerObjectIds.Contains(id))
                    {
                        _sqlServerObjects.RemoveAll(x => x.ServerObjectId == id);
                    }
                }


                // Server Properties
                foreach (MySqlServerObject so in _sqlServerObjects)
                {
                    cmd                = (SqlCommand)ConnectionPool.GetConnection(so.ServerObjectId).CreateCommand();
                    cmd.CommandText    = QueryReader.Read("server_properties.sql");
                    cmd.CommandTimeout = UserSettings.Default.CommandTimeout;
                    cmd.CommandType    = CommandType.Text;
                    rdr                = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        so.ProductVersionCode = (string)rdr["product_version"];
                        so.ProductLevel       = (string)rdr["product_level"];
                        so.Edition            = (string)rdr["edition"];
                        so.ProcessId          = (int)rdr["process_id"];
                        so.EditionID          = (int)rdr["edition_id"];
                        so.LicenseType        = (string)rdr["license_type"];
                    }
                    rdr.Close();
                }
                MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. Loaded {0:n0} servers.", _sqlServerObjects.Count), (DateTime.Now - dt).TotalSeconds);
            }
            catch (Exception ex)
            {
                MyOutput.NewMessage(EOutputMessageType.ERROR, string.Format("Error loading server objects: {0}", ex.Message));
                var exForm = new ExceptionForm(ex);
                exForm.ShowDialog();
            }
        }
示例#8
0
        public void LoadDependencies(string pattern, string[] objectTypes, bool isTopDown, EMatchMethod matchMethod, bool forceReload, MySqlDatabase[] searchDatabases)
        {
            //_inMemoryDatabase.Load(checkedDatabases, forceReload);\\

            _recommendedDatabases.Clear();

            //----------------
            int objectId = 0;
            IEnumerable <MySqlObject> rootObjects;

            // Parent objects



            rootObjects = from o in _mySqlServer.SqlObjects.AsEnumerable()
                          where
                          (
                string.IsNullOrEmpty(pattern) ||
                (
                    matchMethod == EMatchMethod.StartsWith && o.ObjectName.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase) ||
                    matchMethod == EMatchMethod.EndsWith && o.ObjectName.EndsWith(pattern, StringComparison.InvariantCultureIgnoreCase) ||
                    matchMethod == EMatchMethod.Equals && o.ObjectName.Equals(pattern, StringComparison.InvariantCultureIgnoreCase) ||
                    matchMethod == EMatchMethod.Contains && o.ObjectName.ToUpper().Contains(pattern.ToUpper())
                )
                          )
                          &&
                          (
                objectTypes == null || (objectTypes != null && objectTypes.Contains(o.ObjectTypeId))
                          )
                          &&
                          (
                searchDatabases == null || (searchDatabases != null && searchDatabases.Select(sdb => "[" + sdb.ServerObjectName + "].[" + sdb.DatabaseName + "]").Contains("[" + o.ServerObjectName + "].[" + o.DatabaseName + "]"))
                          )
                          select o;

            // -- nonExisting

            var nonExistingRootObjects = from d in _mySqlServer.SqlExpressionDependencies.Where(dl => dl.ChildObjectExists == false)
                                         where
                                         (
                string.IsNullOrEmpty(pattern) ||
                (
                    matchMethod == EMatchMethod.StartsWith && d.ChildObjectName.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase) ||
                    matchMethod == EMatchMethod.EndsWith && d.ChildObjectName.EndsWith(pattern, StringComparison.InvariantCultureIgnoreCase) ||
                    matchMethod == EMatchMethod.Equals && d.ChildObjectName.Equals(pattern, StringComparison.InvariantCultureIgnoreCase) ||
                    matchMethod == EMatchMethod.Contains && d.ChildObjectName.ToUpper().Contains(pattern.ToUpper())
                )
                                         )
                                         &&
                                         (
                searchDatabases == null || (searchDatabases != null && searchDatabases.Select(sdb => "[" + sdb.ServerObjectName + "].[" + sdb.DatabaseName + "]").Contains("[" + d.ChildServerObjectName + "].[" + d.ChildDatabaseName + "]"))
                                         )
                                         select new MySqlObject
            {
                ServerObjectName = d.ChildServerObjectName,
                DatabaseName     = d.ChildDatabaseName,
                SchemaName       = d.ChildSchemaName,
                ObjectName       = d.ChildObjectName,

                ServerObjectId = -1,
                DatabaseId     = -1,
                SchemaId       = -1,
                ObjectId       = -1,
                ObjectNameFull = string.Format("[{0}].[{1}].[{2}].[{3}]", d.ChildServerObjectName, d.ChildDatabaseName, d.ChildSchemaName, d.ChildObjectName),
                ObjectTypeId   = "UNRESOLVED_ENTITY",
                ObjectType     = "UNRESOLVED_ENTITY"
            };

            MySqlObjectEqualityComparer moec = new MySqlObjectEqualityComparer();

            rootObjects = rootObjects.Union(nonExistingRootObjects.Distinct(moec));



            /*
             *
             *
             *
             * if(string.IsNullOrEmpty(pattern))
             *  rootObjects = from o in _inMemoryDatabase.SqlObjectList.AsEnumerable()
             *                select o;
             * else if (matchMethod == EMatchMethod.StartsWith)
             *  rootObjects = from o in _inMemoryDatabase.SqlObjectList.AsEnumerable()
             *                where o.ObjectName.StartsWith(pattern, StringComparison.InvariantCultureIgnoreCase)
             *                select o;
             * else if (matchMethod == EMatchMethod.EndsWith)
             *  rootObjects = from o in _inMemoryDatabase.SqlObjectList.AsEnumerable()
             *                where o.ObjectName.EndsWith(pattern, StringComparison.InvariantCultureIgnoreCase)
             *                select o;
             * else if (matchMethod == EMatchMethod.Equals)
             *  rootObjects = from o in _inMemoryDatabase.SqlObjectList.AsEnumerable()
             *                where o.ObjectName.Equals(pattern, StringComparison.InvariantCultureIgnoreCase)
             *                select o;
             * else
             *  rootObjects = from o in _inMemoryDatabase.SqlObjectList.AsEnumerable()
             *                where o.ObjectName.ToUpper().Contains(pattern.ToUpper())
             *                select o;
             *
             * // Filter by object types
             * if (objectTypes != null)
             *  rootObjects = rootObjects.Where(ro => objectTypes.Contains(ro.ObjectTypeId));
             */
            // var allowedStatus = new[]{ "A", "B", "C" };
            // var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));


            MyOutput.NewMessage(EOutputMessageType.INFORMATION, string.Format("{0:n0} matching search objects found. ", rootObjects.Count()));

            if (rootObjects.Count() <= 50 || rootObjects.Count() > 50 && MessageBox.Show(string.Format("Large number of matching objects was found - {0}!{1}Searching dependencies may take a while.{1}Are you sure you want to continue?", rootObjects.Count(), Environment.NewLine), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                DateTime dt = DateTime.Now;
                MyOutput.NewMessage(EOutputMessageType.PROGRESS, string.Format("Finding dependent objects..."));
                _dependencyObjectList.Clear();
                loadDependentObjects(null, rootObjects.ToArray(), isTopDown, ref objectId, 0);

                AreDependenciesInitialized = true;
                MyOutput.AppendToLastMessage(EOutputMessageType.INFORMATION, string.Format("Done. {0:n0} dependent objects found.", _dependencyObjectList.Count(d => d.HierarchyLevel > 0)), (DateTime.Now - dt).TotalSeconds);
            }
            else
            {
                AreDependenciesInitialized = false;
                MyOutput.AppendToLastMessage(EOutputMessageType.WARNING, string.Format("Finding dependent objects cancelled."));
            }
        }