Exemple #1
0
        public async Task EnumerateDatabases()
        {
            try
            {
                ErrorMessage = "";
                Status       = ConnectionStatus.GettingDatabases;
                var context             = new Data.SchemaDBContext(this);
                var contextGetDatabases = await Data.SchemaDBContext.GetDatabases(this);

                Databases.Clear();
                foreach (var item in contextGetDatabases)
                {
                    item.IsSelected = true;
                    this.Databases.Add(item);
                }
            }
            catch (Exception e)
            {
                ErrorMessage = e.ToString();
            }
            finally
            {
                Status = ConnectionStatus.Dormant;
            }
        }
        private void ReadAndConvertConnectionStrings()
        {
            IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("connectionString.json");
            IConfiguration        connectionStringConfiguration = builder.Build();

            Databases.Clear();
            IConfigurationSection loop = connectionStringConfiguration.GetSection("ConnectionStrings");

            foreach (var item in loop.GetChildren())
            {
                string newConnectionString         = builder.Build().GetConnectionString(item.Key);
                SqlConnectionStringBuilder decoder = new SqlConnectionStringBuilder(newConnectionString);

                ConnectionString tempConnectionString = new ConnectionString();

                if (item.Key != null && item.Key == settings.StartupDatabase)
                {
                    tempConnectionString.Default = true;
                }
                tempConnectionString.Database           = decoder.InitialCatalog;
                tempConnectionString.Identifier         = item.Key;
                tempConnectionString.Server             = decoder.DataSource;
                tempConnectionString.Trusted_Connection = decoder.IntegratedSecurity;

                Databases.Add(tempConnectionString);
            }
        }
Exemple #3
0
        /// <summary>
        /// Triggered on the connect command
        /// </summary>
        /// <param name="sender">The SQL server object</param>
        /// <param name="databases">The databases on the connected server</param>
        void ServerConnected(object sender, IEnumerable <string> databases)
        {
            _connectedServer = (SQLServer)sender;

            Databases.Clear();
            Databases.Fill(databases.OrderBy(e => e));
        }
Exemple #4
0
        public async void LoadDatabasesAsync()
        {
            Databases.Clear();
            LoadConnection = true;
            Cores.ConnectionCore cc = new Cores.ConnectionCore(connection);
            var databases           = await Task.Run(() => cc.DataBases());

            foreach (var dbName in databases)
            {
                var db = new Database
                {
                    DatabaseName   = dbName,
                    ParentTreeBase = this,
                    Tables         = new ObservableCollection <Table>()
                };

                var tables = await Task.Run(() => cc.Tables(dbName));

                foreach (var tableName in tables)
                {
                    db.Tables.Add(new Table()
                    {
                        TableName = tableName, ParentTreeBase = this, DataBaseName = db.DatabaseName
                    });
                }
                Databases.Add(db);
            }

            if (cc.Errors.Count > 0)
            {
                Errors = cc.Errors;
            }

            LoadConnection = false;
        }
Exemple #5
0
 public void ReloadDatabases()
 {
     Databases.Clear();
     foreach (Database db in _server.Databases)
     {
         Databases.Add(new DatabaseInfoNew(this, db));
     }
 }
Exemple #6
0
 /// <summary>
 /// Object disposer which release managed resources of this object.
 /// </summary>
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed && disposing)
     {
         Databases.Clear();
         _disposed = true;
     }
 }
Exemple #7
0
        public void LoadXml(String xml)
        {
            XmlDocument xDoc = new XmlDocument();

            xDoc.LoadXml(xml);
            XmlNode settingsNode = null;

            for (int i = 0; i < xDoc.ChildNodes.Count; i++)
            {
                if (xDoc.ChildNodes[i].Name == "Settings")
                {
                    settingsNode = xDoc.ChildNodes[i];
                }
            }
            if (settingsNode != null)
            {
                for (int i = 0; i < settingsNode.ChildNodes.Count; i++)
                {
                    XmlNode cNode = settingsNode.ChildNodes[i];
                    switch (cNode.Name)
                    {
                    case "UserRegistration":
                        bool val = false;
                        bool.TryParse(cNode.InnerText, out val);
                        UserRegistration = val;
                        break;

                    case "Users":
                        Users.Clear();
                        foreach (XmlNode child in cNode.ChildNodes)
                        {
                            Users.Add(Data.User.LoadXml(child));
                        }
                        break;

                    case "Databases":
                        Databases.Clear();
                        foreach (XmlNode child in cNode.ChildNodes)
                        {
                            Databases.Add(Data.Database.LoadXml(child));
                        }
                        break;

                    case "Groups":
                        Groups.Clear();
                        foreach (XmlNode child in cNode.ChildNodes)
                        {
                            Groups.Add(child.InnerText);
                        }
                        break;
                    }
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Sets the current server.
        /// </summary>
        /// <param name="serverName">Name of the server.</param>
        /// <param name="integratedSecurity">if set to <c>true</c> [integrated security].</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        public void SetCurrentServer(string serverName, bool integratedSecurity, string userName, string password)
        {
            var databaseName = "master";

            var builder = new SqlConnectionStringBuilder();

            builder.DataSource = serverName;
            builder.ApplicationName = "Internals Viewer";
            builder.InitialCatalog = databaseName;

            if (!integratedSecurity)
            {
                builder.UserID = userName;
                builder.Password = password;
            }
            else
            {
                builder.IntegratedSecurity = true;
            }

            ConnectionString = builder.ConnectionString;


            using (var conn = new SqlConnection(builder.ConnectionString))
            {
                conn.Open();

                CheckVersion(conn);

                CheckSysAdmin(conn);

                conn.Close();
            }

            var databasesDataTable = DataAccess.GetDataTable(CurrentConnection().ConnectionString,
                                                                   Properties.Resources.SQL_Databases,
                                                                   "master",
                                                                   "Databases",
                                                                   CommandType.Text);
            Databases.Clear();

            foreach (DataRow r in databasesDataTable.Rows)
            {
                Databases.Add(new Database(ConnectionString,
                                           (int)r["database_id"],
                                           (string)r["name"],
                                           (byte)r["state"],
                                           (byte)r["compatibility_level"]));
            }

            currentDatabase = Databases.Find(d => d.Name == databaseName);
        }
        void LoadDatabases(System.Action continueWith = null)
        {
            Databases.Clear();
            Databases.Add(NewDbSource);

            _asyncWorker.Start(() => GetDatabases().OrderBy(r => r.ResourceName), databases =>
            {
                foreach (var database in databases)
                {
                    Databases.Add(database);
                }
                continueWith?.Invoke();
            });
        }
Exemple #10
0
 /// <summary>
 /// Disposes all cached <see cref="AppDatabase"/>s and clears the cache.
 /// </summary>
 public static void DisposeDatabases()
 {
     // Lock the databases property to prevent conflicts from the GetDatabase method
     lock (Databases)
     {
         // Close all connections
         foreach (var database in Databases.Values)
         {
             Program.Log.Info($"Closing connection to '{database.Connection.DataSource}'...");
             lock (database)                     // Lock each database to ensure a Server instance can complete its task before it is disposed.
                 database.Dispose();
         }
         // Clear all elements from the cache
         Databases.Clear();
     }
 }
        private async void OnLoadSourceTablesAsync()
        {
            IsBusy = true;

            await SourceConnection.TestDBConnectionAsync();

            Databases.Clear();

            string instance = SourceConnection.ServerInstance;

            IEnumerable <DataBaseModel> databases = await GetConnectionDatabasesAsync(SourceConnection);

            LoadDatabases(databases);

            //RefreshDatabases(databases);

            IsBusy = false;
        }
Exemple #12
0
        public void GetDatabaseList()
        {
            Databases.Clear();
            Console.WriteLine($"{ServerName} {UserName} {Password}");
            if (!(ServerName is null) && !(UserName is null) && !(Password is null))
            {
                string conString = $"server={ServerName};uid={UserName};pwd={Password}; database=master; Connection Timeout={TimeOut}";
                try
                {
                    using (SqlConnection con = new SqlConnection(conString))
                    {
                        con.Open();
                        using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
                        {
                            using (IDataReader dr = cmd.ExecuteReader())
                            {
                                while (dr.Read())
                                {
                                    Databases.Add(new Database(dr[0].ToString()));
                                }
                            }
                        }
                    }

                    if (Databases.Count > 0)
                    {
                        Database = Databases[0];
                    }
                    CanConnect = true;
                }
                catch (Exception ex)
                {
                    CanConnect = false;
                    MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.InnerException);
                }
            }

            if (Databases.Count == 0)
            {
                CanConnect = false;
            }
        }
Exemple #13
0
        public void Stop()
        {
            lock (this)
            {
                if (false == IsStart)
                {
                    return;
                }
                ClearInUseAndIAmSureAppStopped();

                IsStart = false;
                Checkpoint?.StopAndJoin();
                GlobalAgent?.Stop();
                foreach (var db in Databases.Values)
                {
                    db.Close();
                }
                TableSys = null;
                Databases.Clear();
            }
        }
Exemple #14
0
        public async Task LoadDatabasesAsync()
        {
            try
            {
                Databases.Clear();
                LoadConnection = true;
                var dteCore   = new DTECore(_connectionBuilder.ConnectionType, _connectionBuilder.ConnectionString, new DTESettings().Settings);
                var databases = await dteCore.GetDatabasesAsync();

                foreach (var dbName in databases)
                {
                    var db = new Database
                    {
                        DatabaseName   = dbName,
                        ParentTreeBase = this,
                        Tables         = new ObservableCollection <Table>()
                    };

                    var tables = await dteCore.GetTablesAsync(dbName);

                    foreach (var tableName in tables)
                    {
                        db.Tables.Add(new Table()
                        {
                            TableName = tableName, ParentTreeBase = this, DataBaseName = db.DatabaseName
                        });
                    }

                    Databases.Add(db);
                }
                LoadConnection = false;
            }
            catch (Exception ex)
            {
                LoadConnection = false;
                throw ex;
            }
        }
Exemple #15
0
        private async void RetrieveDatabases()
        {
            if (String.IsNullOrWhiteSpace(SqlInstance))
            {
                return;
            }

            IsBusy                = true;
            BusyMessage           = "Retrieving Databases for " + SqlInstance;
            Databases.IsNotifying = false;
            try
            {
                Databases.Clear();
                IEnumerable <string> dbs = await RetrieveDatabasesAsync();

                Databases.AddRange(dbs);
            }
            finally
            {
                IsBusy = false;
                Databases.IsNotifying = true;
                Databases.Refresh();
            }
        }
Exemple #16
0
        /// <summary>
        /// Update the list of available databases.
        /// </summary>
        private void UpdateDatabases()
        {
            Databases.Clear();
            try
            {
                //String strConn = String.Format ( "server={0};uid={1};pwd={2}", _server );
                String strConn = String.Format("server={0};Integrated Security=True", _server);
                using (SqlConnection sqlConn = new SqlConnection(strConn))
                {
                    sqlConn.Open();
                    DataTable tblDatabases = sqlConn.GetSchema("Databases");
                    sqlConn.Close();

                    foreach (DataRow row in tblDatabases.Rows)
                    {
                        Databases.Add(row["database_name"].ToString());
                    }
                }
            }
            finally
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs("Databases"));
            }
        }
        private async Task <bool> GetDatabasesAsync()
        {
            DacpRequest request = new DacpRequest("/databases");

            try
            {
                var databases = await GetListAsync(request, n => DacpDatabase.GetDatabase(this, n)).ConfigureAwait(false);

                if (databases == null || databases.Count == 0)
                {
                    return(false);
                }

                List <DacpDatabase> newSharedDatabases = new List <DacpDatabase>();

                for (int i = 0; i < databases.Count; i++)
                {
                    var db = databases[i];

                    // The main database will be first in the list
                    if (i == 0)
                    {
                        if (MainDatabase != null && MainDatabase.ID == db.ID)
                        {
                            continue;
                        }

                        bool success = await db.RequestContainersAsync().ConfigureAwait(false);

                        if (!success)
                        {
                            return(false);
                        }
                        MainDatabase = db;
                        continue;
                    }

                    // Shared database
                    if (db.Type == DatabaseType.Shared)
                    {
                        newSharedDatabases.Add(db);
                        continue;
                    }

                    // Internet Radio
                    if (db.Type == DatabaseType.InternetRadio)
                    {
                        if (InternetRadioDatabase != null && InternetRadioDatabase.ID == db.ID)
                        {
                            continue;
                        }

                        InternetRadioDatabase = db;
                        continue;
                    }

                    // iTunes Radio
                    if (db.Type == DatabaseType.iTunesRadio)
                    {
                        if (iTunesRadioDatabase != null && iTunesRadioDatabase.ID == db.ID)
                        {
                            continue;
                        }

                        iTunesRadioDatabase = (iTunesRadioDatabase)db;
                        // Attempt to load the stations asynchronously to determine whether iTunes Radio is enabled.
                        var task = iTunesRadioDatabase.RequestStationsAsync();
                        continue;
                    }
                }

                // Update shared databases
                Dictionary <int, DacpDatabase> removedSharedDBs = SharedDatabases.ToDictionary(db => db.ID);
                foreach (var sharedDB in newSharedDatabases)
                {
                    removedSharedDBs.Remove(sharedDB.ID);
                    if (SharedDatabases.Any(db => db.ID == sharedDB.ID))
                    {
                        continue;
                    }
                    SharedDatabases.Add(sharedDB);
                }
                foreach (DacpDatabase db in removedSharedDBs.Values)
                {
                    SharedDatabases.Remove(db);
                }

                Databases.Clear();
                Databases.AddRange(databases);
            }
            catch { return(false); }
            return(true);
        }
Exemple #18
0
 internal void InputCredentialsChanged(object sender, EventArgs e)
 {
     CanConnect = false;
     Databases.Clear();
 }
Exemple #19
0
        /// <summary>
        /// Connect to SQL Server and fill in the GUI to provide options for the check
        /// </summary>
        public bool Connect()
        {
            Databases.Clear();
            ConnectionStringBuilder.ConnectTimeout = 10;
            using (var cn = new SqlConnection(ConnectionStringBuilder.ConnectionString))
            {
                try
                {
                    cn.Open();
                }
                catch (SqlException)
                {
                    MessageBox.Show(App.Localized["msgErrorNotConnected"], App.Localized["msgNotConnected"], MessageBoxButton.OK, MessageBoxImage.Error);
                    return(false);
                }

                var qry = $"SELECT Name, compatibility_level FROM sys.databases WHERE database_id > 4 ORDER BY name OPTION (RECOMPILE); {_infos.Query}";
                using (var cmd = new SqlCommand(qry, cn))
                {
                    SqlDataReader rd;
                    try
                    {
                        rd = cmd.ExecuteReader();
                    }
                    catch (SqlException e)
                    {
                        var msg = $"{App.Localized["msgSqlErrorInQuery"]} ({qry}).\n{App.Localized["msgError"]} {e.Number} : {e.Message}";
                        MessageBox.Show(msg, App.Localized["msgSqlError"], MessageBoxButton.OK, MessageBoxImage.Error);
                        SimpleLog.Error(msg);
                        return(false);
                    }
                    while (rd.Read())
                    {
                        Databases.Add(new SqlServer.Database()
                        {
                            Checked            = false,
                            Name               = rd.GetString(0),
                            CompatibilityLevel = (SqlServer.DatabaseCompatibilityLevel)rd.GetByte(1) // danger ! TryParse ??
                        });
                    }

                    rd.NextResult();
                    _infos.Set(rd);
                    _statsCleared = _infos.StartTime;
                    rd.Close();
                    ServerInfos = $"SQL Server version {_infos.ProductVersion}, Edition {_infos.Edition}";
                    OnPropertyChanged("ServerInfos");
                }
                cn.Close();
                // OutputPath
                OutputPath = $@"{_outputRoot}{ConnectionStringBuilder.DataSource.Replace("\\", ".")}\";
                Directory.CreateDirectory(OutputPath);

                // we need to change the output path of the manager
                _ce.OutputPath = OutputPath;

                SimpleLog.SetLogFile(logDir: OutputPath, check: false);
                SimpleLog.Info(_infos.ToString());

                OnPropertyChanged("Databases");

                // status
                StatusText = $"{App.Localized["msgConnectedTo"]} {ConnectionStringBuilder.DataSource} ({_infos.MachineName}), SQL Server {_infos.ProductVersion} {_infos.Edition}";
                OnPropertyChanged("StatusText");
                IsConnected = true;
                return(true);
            }
        }