Created
September 8, 2015 11:02
-
-
Save lazytesting/f586951f55166b824d91 to your computer and use it in GitHub Desktop.
database restore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System; | |
using System.Configuration; | |
using System.Data.SqlClient; | |
namespace Nvm.Web.FunctionalTests.Support | |
{ | |
[TestClass] | |
public class Init | |
{ | |
//Restores the master database | |
[AssemblyInitialize()] | |
public static void cloneDatabase(TestContext testContext) | |
{ | |
var dbName = ConfigurationManager.AppSettings["dbName"]; | |
var masterDbName = ConfigurationManager.AppSettings["masterDbName"]; | |
var dbBackupPath = ConfigurationManager.AppSettings["dbBackupPath"]; | |
var dbPath = ConfigurationManager.AppSettings["dbPath"]; | |
var dbLogPath = ConfigurationManager.AppSettings["dbLogPath"]; | |
var createBackup = string.Format(@"BACKUP DATABASE MG_TEST_MASTER TO DISK = '{0}'", dbBackupPath); | |
var singleUser = string.Format(@"IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'{0}') | |
BEGIN | |
ALTER DATABASE MG_TEST | |
SET SINGLE_USER WITH | |
ROLLBACK IMMEDIATE | |
END", dbName); | |
var restoreBackup = string.Format(@"RESTORE DATABASE {0} | |
FROM DISK = '{1}' | |
WITH FILE = 2, | |
REPLACE, | |
MOVE '{2}' TO '{3}', | |
MOVE '{2}_log' TO '{4}'", | |
dbName, | |
dbBackupPath, | |
masterDbName, | |
dbPath, | |
dbLogPath); | |
var multiUser = string.Format(@"ALTER DATABASE {0} SET MULTI_USER", dbName); | |
runQuery(createBackup); | |
runQuery(singleUser); | |
runQuery(restoreBackup); | |
runQuery(multiUser); | |
} | |
//run a query against the master database | |
private static void runQuery(string query) | |
{ | |
try | |
{ | |
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["masterContext"].ConnectionString)) | |
{ | |
using (var command = new SqlCommand(query, connection)) | |
{ | |
connection.Open(); | |
command.CommandType = System.Data.CommandType.Text; | |
command.CommandText = query; | |
command.ExecuteNonQuery(); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
throw ex; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment