In My Application I have so Many Connection that open and Close as Needed, but maybe some of them not close completely ! if i need exclusive access to database for reasons like restoring Data base or other Goals
if i want to restore my bak file, because of active connection an exception occure that it is not possible to have exlusive access to database for restoring. So I should kill Connection for restoring !
update 1: All Of connection in my code handle by using code block
using (SqlConnection con = new SqlConnection(BaseModule.ConnectionString))
{
//Code
}
but already i have opened connection
update 2: my problem Solved by This Code :
ALTER DATABASE [dbName]
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE [dbName]
SET ONLINE
but Is it good Way To kill Active Connection ? it can be caused losing data in programs that working in network ?
update 3:
Restoring bak File Code :
try
{
Restore objRestore = new Restore();
ServerConnection con;
con = new ServerConnection("(local)", BaseModule.dbUserName, BaseModule.dbPassWord);
Server srv = new Server(con);
objRestore.Database = BaseModule.dbName;
objRestore.Action = RestoreActionType.Database;
objRestore.Devices.AddDevice(dialogOpen.FileName, DeviceType.File);
this.progressRestore.Value = 0;
this.progressRestore.Maximum = 100;
this.progressRestore.Value = 100;
objRestore.PercentCompleteNotification = 10;
objRestore.ReplaceDatabase = true;
objRestore.PercentComplete += new PercentCompleteEventHandler(objRestore_PercentComplete);
objRestore.SqlRestore(srv);
MessageBox.Show("Completed");
}
catch (Exception exp)
{
MessageBox.Show("Error Occured" + exp.InnerException.ToString());
}