1. Add this code in your app.config file
3.Now when your application runs for the first time check the name of the database if it exists in sql express
with the above connection string.
4.for eg.
CheckDBExist("Transactions");//database name
5.
private bool CheckDBExist(string dbName)
{
BLLTransaction bllTransaction = new BLLTransaction(classGlobal.connectionStringM);
DataSet dsChkDBExist;
dsChkDBExist = bllTransaction.Select("select * from sys.databases where name = '" + dbName + "'");
if (dsChkDBExist.Tables[0].Rows.Count == 0)
{
DialogResult result = MessageBox.Show("Database not found.\nDo you want to Restore Database?", "Restore Database", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
try
{
Server mServer = new Server(@".\sqlexpress");
//mServer.KillAllProcesses("Transactions");
//mServer.DetachDatabase("Transactions", true);
//Application.StartupPath.Replace only needed at project devlopment
File.Move(Application.StartupPath.Replace("bin\\Debug", "") + @"TranDB\Transactions.mdf", @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\Transactions.mdf");
File.Move(Application.StartupPath.Replace("bin\\Debug", "") + @"TranDB\Transactions_log.ldf", @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\Transactions_log.ldf");
//File.Move(Application.StartupPath + @"TranDB\Transactions.mdf", @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\Transactions.mdf");
//File.Move(Application.StartupPath + @"TranDB\Transactions_log.ldf", @"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\Transactions_log.ldf");
StringCollection files = new StringCollection();
files.Add(@"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\Transactions.mdf");
files.Add(@"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\Transactions_log.ldf");
mServer.AttachDatabase("Transactions", files, AttachOptions.None);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
return true;
}
6.The above code have my bll class which i use for connection above code to give some idea ;)
7.getSqlExpressPath() //to get sqlexpress path
{
string path = "";
using (RegistryKey sqlServerKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server"))
{
foreach (string subKeyName in sqlServerKey.GetSubKeyNames())
{
if (subKeyName.StartsWith("MSSQL."))
{
using (RegistryKey instanceKey = sqlServerKey.OpenSubKey(subKeyName))
{
string instanceName = instanceKey.GetValue("").ToString();
if (instanceName == "SQLEXPRESS")//say
{
path = instanceKey.OpenSubKey(@"Setup").GetValue("SQLBinRoot").ToString();
path = Path.Combine(path, "sqlserver.exe");
}
}
}
}
}
return path;
}
http://www.prpraveen.blogspot.com
No comments:
Post a Comment