//internal static int FetchAndDisplayRows(IDataReader reader, SqlConsole.ProcessingOption option, out DataTable table, out object scalar) //{ // DataTable dataTable = new DataTable(); // for (int i = 0; i < reader.FieldCount; i++) // { // dataTable.Columns.Add(reader.GetName(i), reader.GetFieldType(i)); // } // dataTable.BeginLoadData(); // object[] values = new object[reader.FieldCount]; // while (reader.Read()) // { // reader.GetValues(values); // dataTable.LoadDataRow(values, true); // } // dataTable.EndLoadData(); // ITableFormatter formatter = TableFormatterBuilder.BuildTableFormatter(dataTable); // Console.WriteLine(formatter.ReadHeader()); // Console.WriteLine(""); // Console.WriteLine(new string('-', formatter.TotalColumnWidth)); // int num2 = 0; // string str = null; // while ((str = formatter.ReadNextRow()) != null) // { // Console.WriteLine(str); // Console.WriteLine(""); // num2++; // } // scalar = null; // table = null; // if (option == SqlConsole.ProcessingOption.Scalar) // { // if ((dataTable.Rows.Count > 0) && (dataTable.Columns.Count > 0)) // { // scalar = dataTable.Rows[0][0]; // } // return num2; // } // if (option == SqlConsole.ProcessingOption.Table) // { // table = dataTable; // } // return num2; //} internal static List<DatabaseFileInfo> GetDatabaseFiles(ConnectionManager connectionManager, IDbConnection connection) { IDbCommand command = CreateCommand(connectionManager, connection); command.CommandText = "sp_helpfile"; List<DatabaseFileInfo> list = new List<DatabaseFileInfo>(); SqlDataReader reader = (SqlDataReader)command.ExecuteReader(); if (reader != null) { try { string str; int ordinal = reader.GetOrdinal("name"); int num2 = reader.GetOrdinal("filename"); int num3 = reader.GetOrdinal("size"); if (reader.HasRows && (num2 >= 0)) { goto Label_0094; } throw new Exception("Could not get file information from the server for the given database."); Label_0066: str = reader.GetString(ordinal); string filePath = reader.GetString(num2); string size = reader.GetString(num3); list.Add(new DatabaseFileInfo(str, filePath, size)); Label_0094: if (reader.Read()) { goto Label_0066; } } finally { reader.Close(); } } return list; }
internal static string IsFileAttached(ConnectionManager connectionManager, IDbConnection connection, string filePath) { filePath = PathUtil.EnsureFullPath(filePath); List<DatabaseInfo> list = BuildDatabaseInfoList(connectionManager, connection); if ((list != null) && (list.Count > 0)) { foreach (DatabaseInfo info in list) { string b = PathUtil.EnsureFullPath(info.Path); if (string.Equals(filePath, b, StringComparison.OrdinalIgnoreCase)) { return info.Name; } } } return null; }
internal static void DetachDatabase(ConnectionManager connectionManager, IDbConnection connection, string dbName, bool silent) { IDbCommand command = CreateCommand(connectionManager, connection); command.CommandType = CommandType.Text; string str = dbName.Replace("]", "]]").Replace("'", "''"); command.CommandText = string.Format("USE master\nIF EXISTS (SELECT * FROM sysdatabases WHERE name = N'{0}')\nBEGIN\n\tALTER DATABASE [{1}] SET OFFLINE WITH ROLLBACK IMMEDIATE\n\tEXEC sp_detach_db [{1}]\nEND", dbName, str); try { command.ExecuteNonQuery(); if (!silent) { Console.WriteLine("Detached '" + dbName + "' successfully."); } } catch (SqlException exception) { if (!exception.Message.StartsWith("Unable to open the physical file", StringComparison.OrdinalIgnoreCase)) { if (!silent) { Console.WriteLine("Failed to detach '" + dbName + "'"); } return; } if (!silent) { Console.WriteLine("Detached '" + dbName + "' successfully."); } } catch { } }
internal static void CreateDatabaseFile(ConnectionManager connectionManager, string filePath) { IDbConnection connection = connectionManager.BuildMasterConnection(); connection.Open(); try { string str = Path.GetFileNameWithoutExtension(filePath).Replace("]", "]]").Replace("'", "''"); filePath = Path.GetFullPath(filePath).Replace("'", "''''"); try { IDbCommand command = CreateCommand(connectionManager, connection); command.CommandText = string.Format(CultureInfo.InvariantCulture, "DECLARE @databaseName sysname\nSET @databaseName = CONVERT(sysname, NEWID())\nWHILE EXISTS (SELECT name FROM sys.databases WHERE name = @databaseName)\nBEGIN\n\tSET @databaseName = CONVERT(sysname, NEWID())\nEND\nSET @databaseName = '[' + @databaseName + ']'\nDECLARE @sqlString nvarchar(MAX)\nSET @sqlString = 'CREATE DATABASE ' + @databaseName + N' ON ( NAME = [{0}], FILENAME = N''{1}'')'\nEXEC sp_executesql @sqlString\nSET @sqlString = 'ALTER DATABASE ' + @databaseName + ' SET AUTO_SHRINK ON'\nEXEC sp_executesql @sqlString\nSET @sqlString = 'ALTER DATABASE ' + @databaseName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE'\nEXEC sp_executesql @sqlString\nSET @sqlString = 'EXEC sp_detach_db ' + @databaseName\nEXEC sp_executesql @sqlString", new object[] { str, filePath }); command.ExecuteNonQuery(); } catch (Exception exception) { throw new Exception("An error occurred while creating a new DB file: " + Environment.NewLine + exception.ToString()); } } finally { connection.Close(); } }
internal static IDbCommand CreateCommand(ConnectionManager connectionManager, IDbConnection connection) { IDbCommand command = connection.CreateCommand(); command.CommandTimeout = connectionManager.ConnectionOptions.commandTimeout; return command; }
internal static List<DatabaseInfo> BuildDatabaseInfoList(ConnectionManager connectionManager, IDbConnection connection) { List<DatabaseInfo> list = new List<DatabaseInfo>(); IDbCommand command = CreateCommand(connectionManager, connection); command.CommandText = "SELECT * FROM SYSDATABASES"; try { IDataReader reader = command.ExecuteReader(); if (reader == null) { return list; } try { string str; if (!((SqlDataReader)reader).HasRows || (reader.FieldCount <= 0)) { return list; } int ordinal = reader.GetOrdinal("name"); int i = reader.GetOrdinal("filename"); if ((ordinal != -1) && (i != -1)) { goto Label_0088; } throw new Exception("SYSDATABASE didn't adhere to the expected schema."); Label_0066: str = reader.GetString(ordinal); string path = reader.GetString(i); list.Add(new DatabaseInfo(str, path)); Label_0088: if (reader.Read()) { goto Label_0066; } return list; } finally { try { reader.Close(); } catch { } } } catch { connection.Close(); } return list; }
internal static void DetachDatabase(string database) { ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionManager connectionManager = new ConnectionManager(); connectionManager.Initialize(connectionOptions); if (string.IsNullOrEmpty(database)) { throw new Exception("Detach requires a file path or database name (within brackets)."); } bool flag = false; DatabaseIdentifier identifier = DatabaseIdentifier.Parse(database); database = identifier.Value; if (identifier.IsDatabaseName) { if (string.IsNullOrEmpty(database)) { throw new Exception("Invalid database name specified."); } } else { if (database.EndsWith("*")) { database = database.Substring(0, database.Length - 1); flag = true; } database = PathUtil.EnsureFullPath(database); } IDbConnection connection = connectionManager.BuildMasterConnection(); connection.Open(); try { List<DatabaseInfo> list = DataUtil.BuildDatabaseInfoList(connectionManager, connection); if (list != null) { bool flag2 = false; foreach (DatabaseInfo info in list) { bool flag3 = false; try { if (identifier.IsDatabaseName) { if (string.Equals(database, info.Name, StringComparison.OrdinalIgnoreCase)) { flag3 = true; } } else { string b = PathUtil.EnsureFullPath(info.Path); if (flag) { if (b.StartsWith(database, StringComparison.OrdinalIgnoreCase)) { flag3 = true; } } else if (string.Equals(database, b, StringComparison.OrdinalIgnoreCase)) { flag3 = true; } } if (flag3 && (((string.Compare(info.Name, "master", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(info.Name, "tempdb", StringComparison.OrdinalIgnoreCase) == 0)) || ((string.Compare(info.Name, "model", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(info.Name, "msdb", StringComparison.OrdinalIgnoreCase) == 0)))) { Console.WriteLine("Warning: Not detaching system database '{0}'. Use SQL commands in the console to do it.", info.Name); flag3 = false; } } catch { } if (flag3) { DataUtil.DetachDatabase(connectionManager, connection, info.Name, false); flag2 = true; } } if (!flag2) { if (identifier.IsDatabaseName) { Console.WriteLine("No valid database name matches the value specified."); } else { Console.WriteLine("No valid database path matches the value specified."); } } } } finally { connection.Close(); } }