using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;

namespace DBSetupAction
{
	/// <summary>
	/// DBInstallAssist 的摘要说明。
	/// </summary>
	public class DBInstallAssist
	{
		private SqlConnection cn;
		public DBInstallAssist(string strCnStr)
		{
			//
			cn=new SqlConnection(strCnStr);
			//
		}
		/// <summary>
		/// open the sql connection
		/// </summary>
		private void OpenConnction(){
			if(cn.State!=ConnectionState.Open  )
				cn.Open();
		}

		/// <summary>
		/// Close the sql connection
		/// </summary>
		private void CloseConnction()
		{
			if(cn.State==ConnectionState.Open  )
				cn.Close();
		}

		/// <summary>
		/// 执行Sql语句
		/// </summary>
		/// <param name="sql"></param>
		public void ExecSql(string sql)
		{
			try
			{
				OpenConnction();
				SqlCommand cmd=new SqlCommand(sql,cn);
				cmd.ExecuteNonQuery(); 
			}
			catch(Exception ex)
			{
				throw new ApplicationException("Exec sql error!",ex);
			}
			finally{
				CloseConnction();
			}
		}

		/// <summary>
		/// 还原数据库
		/// </summary>
		/// <param name="backupfile"></param>
		/// <param name="dbname"></param>
		/// <param name="descfiles"></param>
		public void RestoreDB(string backupfile,string dbname,string[,] descfiles){
			try
			{
				string sql=string.Format("RESTORE DATABASE {0} FROM DISK = '{1}' WITH MOVE "
					+"'{2}' TO '{3}',MOVE '{4}' TO '{5}'",
					new object[]{dbname,backupfile,descfiles[0,0],descfiles[0,1],descfiles[1,0],descfiles[1,1] });
				ExecSql(sql);
			}
			catch(Exception ex){
				throw new ApplicationException("Install DB Error!",ex);
			}
		}
	}

	public class InstallerPath{
		static InstallerPath(){}
		public static string GetCurrent(){
			return new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent.FullName;
		}
	}
}
