Example #1
0
 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();
     }
 }
Example #2
0
        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();
            }
        }