Exemplo n.º 1
0
        public bool DbRestore(string url)
        {
            bool result;

            if (!this.exepro())
            {
                result = false;
            }
            else
            {
                Restore   oRestore   = new RestoreClass();
                SQLServer oSQLServer = new SQLServerClass();
                try
                {
                    oSQLServer.LoginSecure = false;
                    oSQLServer.Connect(this.server, this.uid, this.pwd);
                    oRestore.Action          = SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
                    oRestore.Database        = this.database;
                    oRestore.Files           = url;
                    oRestore.FileNumber      = 1;
                    oRestore.ReplaceDatabase = true;
                    oRestore.SQLRestore(oSQLServer);
                    result = true;
                }
                catch
                {
                    result = false;
                }
                finally
                {
                    oSQLServer.DisConnect();
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        public bool CheckScriptGrammar(string sSql, out string sMessage)
        {
            bool flag2;

            sMessage = string.Empty;
            SQLServer server = new SQLServerClass();
            bool      flag   = false;

            try
            {
                server.Connect(this.Server, this.UserID, this.Password);
                flag = true;
                server.ExecuteImmediate(string.Format("SET PARSEONLY ON;{0}", sSql), SQLDMO_EXEC_TYPE.SQLDMOExec_Default, null);
                flag2 = true;
            }
            catch (Exception exception)
            {
                sMessage = exception.Message;
                flag2    = false;
            }
            finally
            {
                if (flag)
                {
                    server.ExecuteImmediate("SET PARSEONLY OFF; ", SQLDMO_EXEC_TYPE.SQLDMOExec_Default, null);
                    server.DisConnect();
                }
            }
            return(flag2);
        }
Exemplo n.º 3
0
 public static bool DbBackup(string url)
 {
     bool flag;
     Backup backup = new BackupClass();
     SQLServer serverObject = new SQLServerClass();
     try
     {
         serverObject.LoginSecure = false;
         serverObject.Connect(ConfigurationManager.AppSettings["Server"], ConfigurationManager.AppSettings["User"], ConfigurationManager.AppSettings["Password"]);
         backup.Action = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
         backup.Database = ConfigurationManager.AppSettings["DB"];
         backup.Files = url;
         backup.BackupSetName = ConfigurationManager.AppSettings["DB"];
         backup.BackupSetDescription = "数据库备份";
         backup.Initialize = true;
         backup.SQLBackup(serverObject);
         flag = true;
     }
     catch
     {
         flag = false;
     }
     finally
     {
         serverObject.DisConnect();
     }
     return flag;
 }
Exemplo n.º 4
0
        public bool BackupDatabase(string sFullName, string sDataBase)
        {
            bool flag = false;

            SQLDMO.Backup backup       = new BackupClass();
            SQLServer     serverObject = new SQLServerClass();

            try
            {
                serverObject.LoginSecure = false;
                serverObject.Connect(this.Server, this.UserID, this.Password);
                backup.Action               = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                backup.Database             = sDataBase;
                backup.Files                = string.Format("[{0}]", sFullName);
                backup.BackupSetName        = sDataBase;
                backup.BackupSetDescription = string.Format("数据库备份:{0}", sDataBase);
                backup.Initialize           = true;
                backup.SQLBackup(serverObject);
                if (System.IO.File.Exists(sFullName))
                {
                    flag = true;
                }
            }
            catch (Exception exception)
            {
                Log.WriteLog(string.Format("备份数据库[{0}]:BackupDatabase(string sFullName, string sDataBase)", sDataBase), exception.Message);
                return(flag);
            }
            finally
            {
                serverObject.DisConnect();
            }
            return(flag);
        }
Exemplo n.º 5
0
        public static bool DBExists(string sDBName, string sServer, string sUID, string sPWD)
        {
            bool      flag   = false;
            SQLServer server = new SQLServerClass();

            try
            {
                server.LoginSecure = false;
                server.Connect(sServer, sUID, sPWD);
                Databases databases = server.Databases;
                if (databases.Count > 0)
                {
                    foreach (SQLDMO.Database database in databases)
                    {
                        if (sDBName.Trim() == database.Name.Trim())
                        {
                            return(true);
                        }
                    }
                    return(flag);
                }
            }
            catch (Exception exception)
            {
                Log.WriteLog("判断连接的数据库服务器上有无同名数据库:DatabaseExists(string sDBName)", exception.Message);
                return(flag);
            }
            finally
            {
                server.DisConnect();
            }
            return(flag);
        }
Exemplo n.º 6
0
            public void ApagarFicharioSQLREL()
            {
                try
                {
                    var sql = $"SELECT * FROM TB_Cliente WHERE Id = {this.Id}";
                    var db  = new SQLServerClass();
                    var dt  = db.SQLQuery(sql);

                    if (dt.Rows.Count == 0)
                    {
                        db.Close();
                        throw new Exception($"Identificador não existente: {this.Id}");
                    }
                    else
                    {
                        sql = $"DELETE FROM TB_Cliente WHERE Id = '{this.Id}'";
                        db.SQLCommand(sql);
                        db.Close();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Erro ao excluir o conteúdo do identificador: {ex.Message}");
                }
            }
Exemplo n.º 7
0
        public List <string> GetServerDatabases()
        {
            List <string> list   = new List <string>();
            SQLServer     server = new SQLServerClass();

            try
            {
                server.LoginSecure = false;
                server.Connect(this.Server, this.UserID, this.Password);
                Databases databases = server.Databases;
                if (databases.Count > 0)
                {
                    foreach (SQLDMO.Database database in databases)
                    {
                        list.Add(database.Name.ToLower());
                    }
                }
            }
            catch (Exception exception)
            {
                Log.WriteLog("获取数据库服务器数据库列表:GetServerDatabases()", exception.Message);
                return(list);
            }
            finally
            {
                server.DisConnect();
            }
            return(list);
        }
Exemplo n.º 8
0
        public bool DbBackup(string url)
        {
            Backup    oBackup    = new BackupClass();
            SQLServer oSQLServer = new SQLServerClass();
            bool      result;

            try
            {
                oSQLServer.LoginSecure = false;
                oSQLServer.Connect(this.server, this.uid, this.pwd);
                oBackup.Action               = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
                oBackup.Database             = this.database;
                oBackup.Files                = url;
                oBackup.BackupSetName        = this.database;
                oBackup.BackupSetDescription = "数据库备份";
                oBackup.Initialize           = true;
                oBackup.SQLBackup(oSQLServer);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                oSQLServer.DisConnect();
            }
            return(result);
        }
Exemplo n.º 9
0
    public bool DbBackup(string url)
    {
        bool      result    = true;
        Backup    backup    = new BackupClass();
        SQLServer sQLServer = new SQLServerClass();

        try
        {
            sQLServer.LoginSecure = false;
            string[] array = backup_BackupList.pstr.Split(new char[]
            {
                ';'
            });
            sQLServer.Connect(array[0].Split(new char[]
            {
                '='
            })[1], array[3].Split(new char[]
            {
                '='
            })[1], array[4].Split(new char[]
            {
                '='
            })[1]);
            backup.Action   = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
            backup.Database = array[1].Split(new char[]
            {
                '='
            })[1];
            url = url + array[1].Split(new char[]
            {
                '='
            })[1] + ".bak";
            backup.Files         = url;
            backup.BackupSetName = array[1].Split(new char[]
            {
                '='
            })[1];
            backup.BackupSetDescription = DateTime.Now.ToString("yyyyMMddHHmm") + "数据库备份";
            backup.Initialize           = true;
            backup.SQLBackup(sQLServer);
        }
        catch (Exception)
        {
            result = false;
            throw;
        }
        finally
        {
            sQLServer.DisConnect();
        }
        return(result);
    }
Exemplo n.º 10
0
 public void IncluirFicharioSQLREL()
 {
     try
     {
         var sql = this.ToInsert();
         var db  = new SQLServerClass();
         db.SQLCommand(sql);
         db.Close();
     }
     catch (Exception ex)
     {
         throw new Exception($"Inclusão não permitida. Identificador: {this.Id}, erro: {ex.Message}");
     }
 }
Exemplo n.º 11
0
        public int BatchExecuteSql(List <string> lstDatabases, List <string> lstFiles)
        {
            Exception      exception;
            FileManagement management = new FileManagement();
            int            num        = 0;
            StringBuilder  builder    = new StringBuilder();

            builder.Append(string.Format("/**************************************[{0}]开始批量执行脚本**************************************/\r\n", DateTime.Now.ToString()));
            SQLServer server = new SQLServerClass();

            try
            {
                server.Connect(this.Server, this.UserID, this.Password);
                string command = string.Empty;
                foreach (string str2 in lstDatabases)
                {
                    builder.Append(string.Format("\r\n[{0}] 数据库[{1}]准备升级\r\n", DateTime.Now.ToString(), str2));
                    foreach (string str3 in lstFiles)
                    {
                        try
                        {
                            command = string.Format("USE {0}\r\n{1}", str2, management.ReadFile(str3));
                            server.ExecuteImmediate(command, SQLDMO_EXEC_TYPE.SQLDMOExec_Default, null);
                        }
                        catch (Exception exception1)
                        {
                            exception = exception1;
                            num++;
                            builder.Append(string.Format("\r\n{0}、[{1}]:{2} 脚本文件异常\r\n异常信息为:{3}\r\n", new object[] { num, DateTime.Now.ToString(), str3, exception.Message }));
                        }
                    }
                    builder.Append(string.Format("\r\n[{0}] 数据库[{1}]升级完毕\r\n", DateTime.Now.ToString(), str2));
                }
                builder.Append(string.Format("\r\n/**************************************[{0}]结束批量执行脚本**************************************/\r\n\r\n", DateTime.Now.ToString()));
                Log.WriteLog(builder.ToString());
            }
            catch (Exception exception2)
            {
                exception = exception2;
                num       = -1;
                Log.WriteLog("批量执行数据库升级脚本:BatchExecuteSql(List<string> lstDatabases, List<string> lstFiles) ", exception.Message);
                return(num);
            }
            finally
            {
                server.DisConnect();
                GC.Collect();
            }
            return(num);
        }
Exemplo n.º 12
0
        public static string[] GetDatabases(string serverName, string userName, string password, BLL.ConnectionStringHelper.DatabaseTypes dbType, bool trustedConnection)
        {
            List <string> databases = new List <string>();

            SQLDMO.SQLServer sqlServer = new SQLServerClass();
            sqlServer.Connect(serverName, userName, password);

            foreach (SQLDMO.Database database in sqlServer.Databases)
            {
                databases.Add(database.Name);
            }

            return((string[])databases.ToArray());
        }
Exemplo n.º 13
0
        public static string[] GetDatabases(string serverName, string userName, string password, BLL.ConnectionStringHelper.DatabaseTypes dbType, bool trustedConnection)
        {
            List<string> databases = new List<string>();

            SQLDMO.SQLServer sqlServer = new SQLServerClass();
            sqlServer.Connect(serverName, userName, password);

            foreach (SQLDMO.Database database in sqlServer.Databases)
            {
                databases.Add(database.Name);
            }

            return (string[])databases.ToArray();
        }
Exemplo n.º 14
0
        public void ExecuteSql(string sSql)
        {
            SQLServer server = new SQLServerClass();

            try
            {
                server.Connect(this.Server, this.UserID, this.Password);
                server.ExecuteImmediate(sSql, SQLDMO_EXEC_TYPE.SQLDMOExec_Default, null);
            }
            catch (Exception exception)
            {
                Log.WriteLog("执行脚本:ExecuteSql(string sSql)", exception.Message);
            }
            finally
            {
                server.DisConnect();
            }
        }
Exemplo n.º 15
0
        public bool Connect()
        {
            bool      flag;
            SQLServer server = new SQLServerClass();

            try
            {
                server.LoginSecure = false;
                server.Connect(this.Server, this.UserID, this.Password);
                flag = true;
            }
            catch (Exception exception)
            {
                Log.WriteLog(string.Format("连接数据库服务器[{0}]:Connect()", this.Server), exception.Message);
                flag = false;
            }
            finally
            {
                server.DisConnect();
            }
            return(flag);
        }
Exemplo n.º 16
0
            public Unit BuscarFicharioSQLREL(string id)
            {
                try
                {
                    var sql = $"SELECT * FROM TB_Cliente WHERE Id = {id}";
                    var db  = new SQLServerClass();
                    var dt  = db.SQLQuery(sql);
                    db.Close();

                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception($"Identificador não existente: {id}");
                    }
                    else
                    {
                        Unit u = this.DataRowToUnit(dt.Rows[0]);
                        return(u);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Erro ao buscar o conteúdo do identificador: {ex.Message}");
                }
            }
Exemplo n.º 17
0
            public List <List <string> > BuscarFicharioDBTodosSQLREL()
            {
                var listaBusca = new List <List <string> >();

                try
                {
                    var sql = "SELECT * FROM TB_Cliente";
                    var db  = new SQLServerClass();
                    var dt  = db.SQLQuery(sql);

                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        listaBusca.Add(new List <string> {
                            dt.Rows[i]["Id"].ToString(), dt.Rows[i]["Nome"].ToString()
                        });
                    }

                    return(listaBusca);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Erro ao conectar com a base de dados: {ex.Message}");
                }
            }
Exemplo n.º 18
0
		public string RestoreDatabase(string backuppath, string ServerName, string UserName, string Password, string strDbName, string strFileName)
		{
			#region 数据库的恢复的代码

			SQLServer svr = new SQLServerClass();
			try
			{
				svr.Connect(ServerName, UserName, Password);
				QueryResults qr = svr.EnumProcesses(-1);
				int iColPIDNum = -1;
				int iColDbName = -1;
				for (int i = 1; i <= qr.Columns; i++)
				{
					string strName = qr.get_ColumnName(i);
					if (strName.ToUpper().Trim() == "SPID")
					{
						iColPIDNum = i;
					}
					else if (strName.ToUpper().Trim() == "DBNAME")
					{
						iColDbName = i;
					}
					if (iColPIDNum != -1 && iColDbName != -1)
						break;
				}

				for (int i = 1; i <= qr.Rows; i++)
				{
					int lPID = qr.GetColumnLong(i, iColPIDNum);
					string strDBName = qr.GetColumnString(i, iColDbName);
					if (strDBName.ToUpper() == strDbName.ToUpper())
						svr.KillProcess(lPID);
				}


				Restore res = new RestoreClass();
				res.Action = 0;
				string path = backuppath + strFileName + ".config";
				res.Files = path;

				res.Database = strDbName;
				res.ReplaceDatabase = true;
				res.SQLRestore(svr);

				return string.Empty;
			}
			catch (Exception err)
			{
				string message = err.Message.Replace("'", " ");
				message = message.Replace("\n", " ");
				message = message.Replace("\\", "/");
                
				return message;
			}
			finally
			{
				svr.DisConnect();
			}

			#endregion
		}
Exemplo n.º 19
0
		public string BackUpDatabase(string backuppath, string ServerName, string UserName, string Password, string strDbName, string strFileName)
		{
			SQLServer svr = new SQLServerClass();
			try
			{
				svr.Connect(ServerName, UserName, Password);
				Backup bak = new BackupClass();
				bak.Action = 0;
				bak.Initialize = true;
				bak.Files = backuppath + strFileName + ".config";
				bak.Database = strDbName;
				bak.SQLBackup(svr);
				return string.Empty;
			}
			catch(Exception ex)
			{
				string message = ex.Message.Replace("'", " ");
				message = message.Replace("\n", " ");
				message = message.Replace("\\", "/");
				return message;
			}
			finally
			{
				svr.DisConnect();
			}
		}
Exemplo n.º 20
0
        private void btnCatalogs_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.btnCatalogs.Enabled = false;
                this.cboCatalog.Enabled = false;
                this.cboCatalog.Items.Clear();
                this.cboCatalog.Text = Resources.SEARCHING;
                System.Windows.Forms.Application.DoEvents();

                SQLServerClass server = new SQLServerClass();

                string serverName = this.cboServers.Text;
                string userName = string.Empty;
                string password = string.Empty;

                if (!this.cbUIS.Checked)
                {
                    // If the user has not selected Integrated Security
                    // ensure that they have given a user id and password.
                    if (string.IsNullOrEmpty(this.txtUserId.Text) || string.IsNullOrEmpty(this.txtPassword.Text))
                    {
                        this.btnCatalogs.Enabled = true;
                        this.cboCatalog.Enabled = true;
                        this.cboCatalog.Text = string.Empty;
                        this.Cursor = Cursors.Default;

                        string message =
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.NO_USER_DETAIL,
                                Environment.NewLine);
                        // Display the message/warning and leave.
                        MessageBox.Show(message, ApplicationAttributes.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    else
                    {
                        userName = this.txtUserId.Text;
                        password = this.txtPassword.Text;
                        server.Connect(serverName, userName, password);
                    }
                }
                else
                {
                    server.LoginSecure = true;
                    server.Connect(serverName, string.Empty, string.Empty);
                }

                // To hold found objects.
                Collection<string> catalogs = new Collection<string>();

                // Get the objects.
                foreach (Database2 db in server.Databases)
                {
                    if (!db.SystemObject)
                    {
                        catalogs.Add(db.Name);
                    }
                }

                // Add all of the found objects to the combo.
                this.cboCatalog.DataSource = catalogs;

                this.btnCatalogs.Enabled = true;
                this.cboCatalog.Enabled = true;
                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                this.btnCatalogs.Enabled = true;
                this.cboCatalog.Enabled = true;
                this.cboCatalog.Text = string.Empty;
                this.Cursor = Cursors.Default;
                Messages.BadConnection(ex);
            }
        }
Exemplo n.º 21
0
        public int BatchAnalysisScript(List <string> lstFiles, bool blnCheckDataBase, bool blnYesOrNo)
        {
            Exception      exception;
            FileManagement management = new FileManagement();
            string         sSql       = string.Empty;
            int            num        = 0;
            StringBuilder  builder    = new StringBuilder();

            builder.Append(string.Format("/**************************************[{0}]开始批量分析脚本**************************************/\r\n", DateTime.Now.ToString()));
            SQLServer server = new SQLServerClass();

            try
            {
                server.Connect(this.Server, this.UserID, this.Password);
                foreach (string str2 in lstFiles)
                {
                    if (Path.GetExtension(str2) != ".sql")
                    {
                        num++;
                        builder.Append(string.Format("\r\n{0}、[{1}]:{2} 非脚本文件\r\n", num, DateTime.Now.ToString(), str2));
                    }
                    else
                    {
                        try
                        {
                            sSql = management.ReadFile(str2);
                            if (blnCheckDataBase)
                            {
                                if (blnYesOrNo)
                                {
                                    if (this.CheckUseDatabase(sSql))
                                    {
                                        num++;
                                        builder.Append(string.Format("\r\n{0}、[{1}] 脚本文件“{2}”指定了数据库名\r\n", num, DateTime.Now.ToString(), str2));
                                    }
                                }
                                else if (!this.CheckUseDatabase(sSql))
                                {
                                    num++;
                                    builder.Append(string.Format("\r\n{0}、[{1}] 脚本文件“{2}”未指定数据库名\r\n", num, DateTime.Now.ToString(), str2));
                                }
                            }
                            server.ExecuteImmediate(string.Format("SET PARSEONLY ON;{0}", sSql), SQLDMO_EXEC_TYPE.SQLDMOExec_Default, null);
                        }
                        catch (Exception exception1)
                        {
                            exception = exception1;
                            num++;
                            builder.Append(string.Format("\r\n{0}、[{1}]:{2} 脚本文件异常\r\n异常信息为:{3}\r\n", new object[] { num, DateTime.Now.ToString(), str2, exception.Message }));
                        }
                        finally
                        {
                            server.ExecuteImmediate("SET PARSEONLY OFF; ", SQLDMO_EXEC_TYPE.SQLDMOExec_Default, null);
                        }
                    }
                }
                builder.Append(string.Format("\r\n/**************************************[{0}]结束批量分析脚本**************************************/\r\n\r\n", DateTime.Now.ToString()));
                Log.WriteLog(builder.ToString());
            }
            catch (Exception exception2)
            {
                exception = exception2;
                num       = -1;
                Log.WriteLog("批量分析脚本:BatchAnalysisScript(string lstFiles, bool blnCheckDataBase, bool blnYesOrNo)", exception.Message);
                return(num);
            }
            finally
            {
                server.DisConnect();
                GC.Collect();
            }
            return(num);
        }
Exemplo n.º 22
0
        public bool StoreDatabase(string sFile, string sPath, string sDataBase)
        {
            bool      flag         = false;
            SQLServer serverObject = new SQLServerClass();

            SQLDMO.Restore restore = new RestoreClass();
            try
            {
                int num3;
                serverObject.LoginSecure = false;
                serverObject.Connect(this.Server, this.UserID, this.Password);
                QueryResults results = serverObject.EnumProcesses(-1);
                int          column  = -1;
                int          num2    = -1;
                for (num3 = 1; num3 < results.Columns; num3++)
                {
                    string str = results.get_ColumnName(num3);
                    if (str.ToUpper().Trim() == "SPID")
                    {
                        column = num3;
                    }
                    else if (str.ToUpper().Trim() == "DBNAME")
                    {
                        num2 = num3;
                    }
                    if ((column != -1) && (num2 != -1))
                    {
                        break;
                    }
                }
                num3 = 1;
                while (num3 < results.Rows)
                {
                    int columnLong = results.GetColumnLong(num3, column);
                    if (results.GetColumnString(num3, num2).ToUpper() == sDataBase.ToUpper())
                    {
                        serverObject.KillProcess(columnLong);
                    }
                    num3++;
                }
                QueryResults results2 = serverObject.ExecuteWithResults(string.Format("RESTORE FILELISTONLY FROM DISK = '{0}'", sFile), null);
                int          num5     = 0;
                int          num6     = 0;
                for (num3 = 1; num3 < results2.Columns; num3++)
                {
                    if ("LOGICALNAME" == results2.get_ColumnName(num3).ToUpper())
                    {
                        num5 = num3;
                    }
                    if ("PHYSICALNAME" == results2.get_ColumnName(num3).ToUpper())
                    {
                        num6 = num3;
                    }
                    if ((num6 != 0) && (num5 != 0))
                    {
                        break;
                    }
                }
                StringBuilder builder = new StringBuilder();
                for (num3 = 1; num3 <= results2.Rows; num3++)
                {
                    builder.Append(string.Format(@"[{0}],[{1}\{2}]", results2.GetColumnString(num3, num5), sPath, Path.GetFileName(results2.GetColumnString(num3, num6))));
                    if (num3 != results2.Rows)
                    {
                        builder.Append(",");
                    }
                }
                restore.Action          = SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
                restore.Database        = sDataBase;
                restore.Files           = sFile;
                restore.FileNumber      = 1;
                restore.ReplaceDatabase = false;
                restore.RelocateFiles   = builder.ToString();
                restore.SQLRestore(serverObject);
                Databases databases = serverObject.Databases;
                foreach (SQLDMO.Database database in databases)
                {
                    if (database.Name == sDataBase)
                    {
                        return(true);
                    }
                }
                return(flag);
            }
            catch (Exception exception)
            {
                Log.WriteLog(string.Format("还原数据库[{0}]:StoreDatabase(string sFile,string sPath,string sDataBase)", sDataBase), exception.Message);
                return(flag);
            }
            finally
            {
                serverObject.DisConnect();
            }
            return(flag);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Populate the databases dropdown list with the DBs found on the specified server
        /// </summary>
        private void PopulateDatabaseNamesCmb()
        {
            ArrayList dbNames = new ArrayList();
            SQLServer sqlInstance = new SQLServerClass();
            try
            {
                if (_connStr.TrustedConnection)
                {
                    sqlInstance.LoginSecure=true;
                    sqlInstance.Connect(_connStr.Server,null,null);
                }
                else
                    sqlInstance.Connect(_connStr.Server,_connStr.UserId,_connStr.Password);
                foreach(Database db in sqlInstance.Databases)
                {
                    dbNames.Add(db.Name);
                }
                databaseName.DataSource=dbNames;
                databaseName.DataBind();

                if (databaseName.Items.FindByValue(_connStr.Database)!=null)
                    databaseName.SelectedValue=_connStr.Database;
            }
            catch(Exception)
            {
                connResult.Text="Error retrieving database list";
                databaseName.Items.Clear();
                databaseName.Items.Add(new ListItem("-- Error retrieving database list --","0"));
            }
            finally
            {
                sqlInstance.DisConnect();
            }
        }
		private void cmbDatabase_DropDown(object sender, EventArgs e) {
			if (cmbSqlServer.Text.Equals("")) {
				return;
			}

			this.cmbDatabase.Items.Clear();

			try {
				SQLServer server = new SQLServerClass();
				server.LoginSecure = chkIntegrated.Checked;
				server.Connect(cmbSqlServer.Text, txtUid.Text, txtPassword.Text);
				foreach (Database item in server.Databases) {
					this.cmbDatabase.Items.Add(item.Name);
				}
			}
			catch (Exception e1) {
				MessageBox.Show("Impossível enumerar os servidores da rede. Cheque a versão " +
					"do cliente do SQL Server 2000 instalado na sua máquina. Versões anteriores " +
					"ao SP2 contêm um bug que impede a enumeração dos servidores por aplicações .NET",
				                "Erro - " + e1.Source, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			}
		}
Exemplo n.º 25
0
        // Token: 0x0600027B RID: 635 RVA: 0x00008AA4 File Offset: 0x00006CA4
        public static string BackUpDatabase()
        {
            string mapPath = FPUtils.GetMapPath(WebConfig.WebPath + "backup/datas");

            if (!Directory.Exists(mapPath))
            {
                Directory.CreateDirectory(mapPath);
            }
            DbConfigInfo dbConfig = DbConfigs.GetDbConfig();
            string       str      = dbConfig.dbname + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");

            if (dbConfig.dbtype == FangPage.Data.DbType.SqlServer)
            {
                SQLServer sqlserver = new SQLServerClass();
                sqlserver.Connect(dbConfig.dbpath, dbConfig.userid, dbConfig.password);
                try
                {
                    if (File.Exists(mapPath + "\\" + dbConfig.dbname + ".bak"))
                    {
                        File.Delete(mapPath + "\\" + dbConfig.dbname + ".bak");
                    }
                    ((_Backup) new BackupClass
                    {
                        Action = SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database,
                        Initialize = true,
                        Files = mapPath + "\\" + dbConfig.dbname + ".bak",
                        Database = dbConfig.dbname
                    }).SQLBackup(sqlserver);
                    if (File.Exists(mapPath + "\\" + str + ".config"))
                    {
                        using (FPZip fpzip = new FPZip())
                        {
                            fpzip.AddFile(mapPath + "\\" + dbConfig.dbname + ".bak", dbConfig.dbname + ".bak");
                            fpzip.ZipSave(mapPath + "\\" + str + ".config");
                        }
                        File.Delete(mapPath + "\\" + dbConfig.dbname + ".bak");
                    }
                    return(string.Empty);
                }
                catch (Exception ex)
                {
                    string text = ex.Message.Replace("'", " ");
                    text = text.Replace("\n", " ");
                    return(text.Replace("\\", "/"));
                }
                finally
                {
                    sqlserver.DisConnect();
                }
            }
            string result;

            try
            {
                if (File.Exists(mapPath + "\\" + str + ".config"))
                {
                    File.Delete(mapPath + "\\" + str + ".zip");
                    using (FPZip fpzip = new FPZip())
                    {
                        fpzip.AddFile(WebConfig.WebPath + dbConfig.dbpath, dbConfig.dbpath);
                        fpzip.ZipSave(mapPath + "\\" + str + ".config");
                    }
                }
                result = string.Empty;
            }
            catch (Exception ex)
            {
                string text = ex.Message.Replace("'", " ");
                text   = text.Replace("\n", " ");
                text   = text.Replace("\\", "/");
                result = text;
            }
            return(result);
        }
Exemplo n.º 26
0
        // Token: 0x0600027C RID: 636 RVA: 0x00008E34 File Offset: 0x00007034
        public static string RestoreDatabase(string backupfile)
        {
            string result;

            if (!File.Exists(backupfile))
            {
                result = "备份文件已不存在。";
            }
            else
            {
                DbConfigInfo dbConfig = DbConfigs.GetDbConfig();
                if (dbConfig.dbtype == FangPage.Data.DbType.SqlServer)
                {
                    SQLServer sqlserver = new SQLServerClass();
                    if (Path.GetExtension(backupfile) == ".zip" || Path.GetExtension(backupfile) == ".config")
                    {
                        FPZip.UnZipFile(backupfile, "");
                    }
                    backupfile = string.Concat(new string[]
                    {
                        Path.GetDirectoryName(backupfile),
                        "\\",
                        Path.GetFileName(backupfile),
                        "\\",
                        dbConfig.dbname,
                        ".bak"
                    });
                    if (!File.Exists(backupfile))
                    {
                        return("备份文件已不存在。");
                    }
                    try
                    {
                        sqlserver.Connect(dbConfig.dbpath, dbConfig.userid, dbConfig.password);
                        QueryResults queryResults = sqlserver.EnumProcesses(-1);
                        int          num          = -1;
                        int          num2         = -1;
                        for (int i = 1; i <= queryResults.Columns; i++)
                        {
                            string text = queryResults.get_ColumnName(i);
                            if (text.ToUpper().Trim() == "SPID")
                            {
                                num = i;
                            }
                            else if (text.ToUpper().Trim() == "DBNAME")
                            {
                                num2 = i;
                            }
                            if (num != -1 && num2 != -1)
                            {
                                break;
                            }
                        }
                        for (int i = 1; i <= queryResults.Rows; i++)
                        {
                            int    columnLong   = queryResults.GetColumnLong(i, num);
                            string columnString = queryResults.GetColumnString(i, num2);
                            if (columnString.ToUpper() == dbConfig.dbname.ToUpper())
                            {
                                sqlserver.KillProcess(columnLong);
                            }
                        }
                        ((_Restore) new RestoreClass
                        {
                            Action = SQLDMO_RESTORE_TYPE.SQLDMORestore_Database,
                            Files = backupfile,
                            Database = dbConfig.dbname,
                            ReplaceDatabase = true
                        }).SQLRestore(sqlserver);
                        File.Delete(backupfile);
                        return(string.Empty);
                    }
                    catch (Exception ex)
                    {
                        return(ex.Message);
                    }
                    finally
                    {
                        sqlserver.DisConnect();
                    }
                }
                string mapPath = FPUtils.GetMapPath(WebConfig.WebPath + Path.GetDirectoryName(dbConfig.dbpath));
                try
                {
                    if (!Directory.Exists(mapPath))
                    {
                        Directory.CreateDirectory(mapPath);
                    }
                    if (Path.GetExtension(backupfile) == ".zip" || Path.GetExtension(backupfile) == ".config")
                    {
                        FPZip.UnZipFile(backupfile, mapPath);
                    }
                    else
                    {
                        File.Copy(backupfile, mapPath + "\\" + dbConfig.dbname);
                    }
                    result = string.Empty;
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                }
            }
            return(result);
        }
Exemplo n.º 27
0
        // load databases,tables and sps into treeView
        private void GetServerObjects()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(this.GetServerObjects), null);
            }
            else
            {
                this.treeView1.Nodes.Clear();

                SQLServerClass m_sqlServer = new SQLServerClass();
                string serverName = this.cmbInstances.Text;
                string userName = string.Empty;
                string pass = string.Empty;
                if (!this.checkTrustConnection.Checked)
                {
                    userName = this.txtUser.Text;
                    pass = this.txtPass.Text;
                    m_sqlServer.Connect(serverName, userName, pass);
                }
                else
                {
                    m_sqlServer.LoginSecure = true;
                    m_sqlServer.Connect(serverName, "", "");
                }

                TreeNode database;
                TreeNode procedures;
                TreeNode storedProcedure;
                TreeNode storedProcedureParameter;

                TreeNode tables;
                TreeNode table;
                TreeNode column;

                #region Iterate through all databases to extract sps and tables

                foreach (Database2 db in m_sqlServer.Databases)
                {
                    if (!db.SystemObject)
                    {
                        database = new TreeNode(db.Name);
                        database.ImageIndex = 0;

                        procedures = new TreeNode("Procedures");
                        procedures.ImageIndex = 8;
                        procedures.SelectedImageIndex = 8;

                        #region Get All stored procedures for each database
                        // Get all procedures for each database
                        foreach (StoredProcedure2 sp in db.StoredProcedures)
                        {
                            if (!sp.SystemObject && sp.Name != "sp_alterdiagram" && sp.Name != "sp_creatediagram" && sp.Name != "sp_dropdiagram" && sp.Name != "sp_helpdiagrams" && sp.Name != "sp_renamediagram" && sp.Name != "sp_upgraddiagrams" && sp.Name != "sp_helpdiagramdefinition")
                            {
                                storedProcedure = new TreeNode(sp.Name);
                                storedProcedure.ImageIndex = 10;
                                storedProcedure.SelectedImageIndex = 10;
                                QueryResults res = sp.EnumParameters();
                                StoredProcedureParameter spParameter;
                                StoredProcedureParameterCollection spParameterCollection = new StoredProcedureParameterCollection();
                                int row, col;
                                for (row = 1; row <= res.Rows; row++)
                                {
                                    for (col = 1; col <= res.Columns; col++)
                                    {
                                        string spParamName = res.GetColumnString(row, col);
                                        string spParamType = res.GetColumnString(row, col + 1);
                                        string spParamLength = res.GetColumnString(row, col + 2);
                                        string spIsOutput = res.GetColumnString(row, col + 4) != "0" ? ",OutPut" : "";
                                        bool checkBooleanExpression = res.GetColumnString(row, col + 4) != "0" ? true : false;
                                        storedProcedureParameter = new TreeNode(string.Format("{0},{1}({2}){3}", spParamName, spParamType, spParamLength, spIsOutput));
                                        storedProcedureParameter.ImageIndex = 9;
                                        storedProcedureParameter.SelectedImageIndex = 11;
                                        spParameter = new StoredProcedureParameter(spParamName, spParamType, int.Parse(spParamLength), checkBooleanExpression);
                                        spParameterCollection.Add(spParameter);
                                        storedProcedure.Nodes.Add(storedProcedureParameter);
                                        break;
                                    }
                                }
                                procedures.Nodes.Add(storedProcedure);
                            }
                        }
                        database.Nodes.Add(procedures);
                        #endregion

                        #region Get all tables for each database
                        // Get all tables for each database
                        tables = new TreeNode("Tables");
                        tables.ImageIndex = 1;
                        tables.SelectedImageIndex = 1;

                        foreach (Table2 tbl in db.Tables)
                        {
                            if (!tbl.SystemObject && tbl.Name != "sysdiagrams")
                            {
                                table = new TreeNode(tbl.Name);
                                table.ImageIndex = 1;
                                table.SelectedImageIndex = 1;
                                foreach (Column2 col in tbl.Columns)
                                {
                                    column = new TreeNode(string.Format("{0},{1}", col.Name, col.Datatype));
                                    column.ImageIndex = 6;
                                    column.SelectedImageIndex = 6;
                                    table.Nodes.Add(column);
                                }
                                tables.Nodes.Add(table);
                            }
                        }
                        database.Nodes.Add(tables);
                        #endregion

                        // Add database to treeView1.Nodes
                        this.treeView1.Nodes.Add(database);
                    }
                }
                #endregion
            }
        }