Beispiel #1
0
        public virtual bool Backup(List <BackupItemEx> items, string backupfile)
        {
            try
            {
                if (items != null && items.Count > 0)
                {
                    string dir = AppDomain.CurrentDomain.BaseDirectory;
                    // make sure the capacity is big enough
                    List <string>  files          = new List <string>(items.Count);
                    int            index          = 0;
                    int            count          = 0;
                    AutoResetEvent autoResetEvent = new AutoResetEvent(false);
                    foreach (BackupItemEx bi in items)
                    {
                        if ((bi.BackupObjects == null || bi.BackupObjects.Count == 0) && string.IsNullOrEmpty(bi.DumpQuery))
                        {
                            continue;
                        }

                        ++count;
                        ThreadPool.QueueUserWorkItem((obj) =>
                        {
                            BackupItemEx tmpBi = obj as BackupItemEx;
                            Backup(tmpBi);
                            if (File.Exists(tmpBi.BackupFileName))
                            {
                                FileInfo fi = new FileInfo(tmpBi.BackupFileName);
                                if (fi.Length > 2)
                                {
                                    lock (this) //need synchronization block
                                    {
                                        files.Add(tmpBi.BackupFileName);
                                    }
                                }
                                else
                                {
                                    FileDirectoryOperate.DeleteFileWithTime(tmpBi.BackupFileName);
                                }
                            }
                            Interlocked.Increment(ref index);
                            if (index == count)
                            {
                                autoResetEvent.Set();
                            }

                            try
                            {
                                if (worker != null && worker.WorkerReportsProgress && worker.IsBusy)
                                {
                                    worker.ReportProgress(index * 100 / items.Count);
                                }
                            }
                            catch
                            {
                            }
                        }, bi);
                    }
                    autoResetEvent.WaitOne(60000, false);


                    if (files.Count == 0)
                    {
                        return(false);
                    }

                    if (worker != null && worker.WorkerReportsProgress && worker.IsBusy)
                    {
                        worker.ReportProgress(50, string.Format("Back up  database:", backupfile));
                    }

                    SharpZipHelper.ZipMultiFiles(files.ToArray(), backupfile, DatabaseCommon.ZipPwd, 3, worker);
                    foreach (string file in files)
                    {
                        FileDirectoryOperate.DeleteFileWithTime(file);
                    }
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return(false);
            }
        }
Beispiel #2
0
        protected bool RestoreDatabase(string[] dbFiles, DbCommand cmd, string database)
        {
            if (dbFiles == null || dbFiles.Length == 0)
            {
                return(false);
            }

            // use the master database
            cmd.CommandText = "USE master";
            cmd.ExecuteNonQuery();

            // set the single_user mode to make sure the following steps work
            cmd.CommandText = string.Format("alter database {0} set single_user with rollback immediate", database);
            cmd.ExecuteNonQuery();

            // get the data directory of the SQL Server
            string dataDir = string.Empty;

            cmd.CommandText = "select physical_name from sys.database_files where type = 0";
            using (DbDataReader reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                {
                    return(false);
                }
                dataDir = Path.GetDirectoryName(reader.GetString(0));
            }
            try
            {
                foreach (string file in dbFiles)
                {
                    // get the file list in the back up file
                    cmd.CommandText = string.Format("restore filelistonly from disk = '{0}'", file);
                    using (DbDataReader reader = cmd.ExecuteReader())
                    {
                        StringBuilder sb = new StringBuilder();
                        if (!reader.HasRows)
                        {
                            return(false);
                        }
                        // construct the command text
                        sb.AppendFormat("restore database {0} from disk = '{1}' with recovery, replace, ", database, file);
                        while (reader.Read())
                        {
                            string logicalName = reader.GetString(0);
                            string fileType    = reader.GetString(2);
                            sb.AppendFormat("move '{0}' to '{1}', ", logicalName,
                                            Path.Combine(dataDir, database + (fileType == "D" ? ".mdf" : "_log.LDF")));
                        }
                        cmd.CommandText = sb.ToString(0, sb.Length - 2);
                    }
                    cmd.ExecuteNonQuery();

                    FileDirectoryOperate.DeleteFileWithTime(file);
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e);
                #region
                //将数据库重新设置成多用户模式以修复无法打开的bug
                cmd.CommandText = string.Format("alter database {0} set multi_user with rollback immediate", database);
                cmd.ExecuteNonQuery();
                return(false);

                #endregion
            }
            return(true);
        }
Beispiel #3
0
        public override bool Backup(string dbName, string backupfile, bool packing)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(GetConnectionString(true)))
                {
                    conn.Open();

                    string dir = string.Empty;
                    dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\");
                    if (!Directory.Exists(dir))
                    {
                        FileDirectoryOperate.CreateDirectoryEx(dir);
                    }
                    else
                    {
                        // SQL Server backup file
                        foreach (string s in Directory.GetFiles(dir, "*.bak"))
                        {
                            FileDirectoryOperate.DeleteFileWithTime(s);
                        }
                    }

                    #region File list to packup
                    string        tempFile = Path.Combine(dir, dbName + ".bak");
                    List <string> files    = new List <string>(2);
                    files.Add(tempFile);
                    #endregion

                    DbCommand cmd = conn.CreateCommand();
                    cmd.CommandText    = string.Format("backup database {0} to disk = '{1}'", dbName, tempFile);
                    cmd.CommandTimeout = 600;
                    cmd.ExecuteNonQuery();

                    if (!File.Exists(tempFile))
                    {
                        return(false);
                    }

                    if (worker != null && worker.WorkerReportsProgress)
                    {
                        if (packing)
                        {
                            worker.ReportProgress(0, string.Format("DataBase Packing Up Files......", backupfile));
                        }
                        else
                        {
                            worker.ReportProgress(100);
                        }
                    }

                    if (!packing)
                    {
                        return(true);
                    }

                    SharpZipHelper.ZipMultiFiles(files.ToArray(), backupfile, DatabaseCommon.ZipPwd, 6, worker);
                    foreach (string file in files)
                    {
                        FileDirectoryOperate.DeleteFileWithTime(file);
                    }
                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #4
0
        public override bool ImportDatafromDir(string dir, bool redirectNHibernate, string destDatabase = null)
        {
            var database = destDatabase ?? _Database;

            errorMessage = string.Empty;
            bool importSuccess = true;

            try
            {
                using (SqlConnection conn = new SqlConnection(GetConnectionString(destDatabase: database)))
                {
                    conn.Open();
                    DbCommand cmd = conn.CreateCommand();
                    cmd.CommandTimeout = 600;

                    string[] files = Directory.GetFiles(dir, "*.bak");
                    if (files.Length > 0)
                    {
                        if (!RestoreDatabase(files, cmd, database))
                        {
                            return(false);
                        }
                    }
                    else if ((files = Directory.GetFiles(dir, "*.sql")).Length > 0)
                    {
                        #region SQL process
                        DbTransaction transc = null;
                        try
                        {
                            // use the current database
                            transc          = conn.BeginTransaction();
                            cmd.Transaction = transc;

                            cmd.CommandText = string.Format("USE {0}", database);
                            cmd.ExecuteNonQuery();

                            // clear all table contents
                            if (worker != null && worker.WorkerReportsProgress)
                            {
                                worker.ReportProgress(0, "Truncating database...");
                            }

                            // delete all data and reset the identity column
                            cmd.CommandText = @"exec sp_MSforeachtable 'truncate table ?', N'?', 
'if exists(select name from sys.columns where object_id = object_id(''?'') and is_identity = 1) DBCC CHECKIDENT(''?'', reseed, 1)'";
                            cmd.ExecuteNonQuery();

                            if (worker != null && worker.WorkerReportsProgress)
                            {
                                worker.ReportProgress(0, "Executing scripts...");
                            }

                            foreach (string file in files)
                            {
                                using (SQLScriptParser parser = new SQLScriptParser(file))
                                {
                                    string tableName = string.Empty;
                                    string prevTable = string.Empty;
                                    string cmdPrefix = string.Empty;
                                    Dictionary <string, string> cmdDic = new Dictionary <string, string>();
                                    int  curProgress = -1;
                                    bool checkTable  = false;

                                    string cmdText = parser.NextCommand();
                                    while (!string.IsNullOrEmpty(cmdText))
                                    {
                                        if (IsSupportedSQL(cmdText, out tableName))
                                        {
                                            try
                                            {
                                                if (!cmdDic.TryGetValue(tableName, out cmdPrefix))
                                                {
                                                    #region Restore database
                                                    if (!string.IsNullOrEmpty(prevTable))
                                                    {
                                                        // switch the identity_insert option off
                                                        cmd.CommandText = string.Format("set identity_insert {0} off", prevTable);
                                                        cmd.ExecuteNonQuery();
                                                    }

                                                    #region prepare the command dictionary
                                                    // construct the full column list
                                                    cmd.CommandText = string.Format("select column_name from information_schema.columns where table_name = '{0}'", tableName);
                                                    using (DbDataReader reader = cmd.ExecuteReader())
                                                    {
                                                        StringBuilder sb = new StringBuilder();
                                                        sb.AppendFormat("INSERT INTO {0}(", tableName);
                                                        while (reader.Read())
                                                        {
                                                            sb.AppendFormat(string.Format("{0}, ", reader.GetString(0)));
                                                        }
                                                        sb.Replace(", ", ")", sb.Length - 2, 2);
                                                        cmdPrefix         = sb.ToString();
                                                        cmdDic[tableName] = cmdPrefix;
                                                    }
                                                    #endregion

                                                    // handle database, set identity_insert on
                                                    prevTable       = tableName;
                                                    cmd.CommandText = string.Format("set identity_insert {0} on", prevTable);
                                                    cmd.ExecuteNonQuery();
                                                    #endregion
                                                }

                                                cmd.CommandText = cmdText;
                                                int affectedRows = cmd.ExecuteNonQuery();
                                                if (affectedRows == 0 && checkTable)
                                                {
                                                    importSuccess = false;
                                                }

                                                if (worker != null && worker.WorkerReportsProgress && curProgress != parser.CurProgress)
                                                {
                                                    curProgress = parser.CurProgress;
                                                    worker.ReportProgress(curProgress);
                                                }
                                            }
                                            catch (Exception innerEx)
                                            {
                                                importSuccess = false;
                                                LogHelper.Log(innerEx);
                                            }
                                        }
                                        cmdText = parser.NextCommand();
                                    }

                                    if (!string.IsNullOrEmpty(prevTable))
                                    {
                                        cmd.CommandText = string.Format("set identity_insert {0} off", prevTable);
                                        cmd.ExecuteNonQuery();
                                    }
                                }

                                FileDirectoryOperate.DeleteFileWithTime(file);
                            }

                            transc.Commit();
                        }
                        catch (System.Exception transactEx)
                        {
                            LogHelper.Log(transactEx);
                            if (transc != null)
                            {
                                transc.Rollback();
                            }
                            importSuccess = false;
                        }
                        finally
                        {
                            if (transc != null)
                            {
                                transc.Dispose();
                            }
                        }
                        #endregion
                    }
                }
            }
            catch (Exception outerEx)
            {
                LogHelper.Log(outerEx);
                return(false);
            }

            if (!importSuccess)
            {
                if (string.IsNullOrEmpty(errorMessage))
                {
                    errorMessage = "Imported Data already exists in the current database!";
                }
                return(false);
            }

            string strException = null;
            return(DatabaseHelper.RedirectNHibernateConfiguration(NHConfigParagraph(), out strException));
        }
Beispiel #5
0
        protected override void Backup(BackupItemEx bi)
        {
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\");

            if (!Directory.Exists(dir))
            {
                FileDirectoryOperate.CreateDirectoryEx(dir);
            }
            if (bi.IsFullTable)
            {
                bi.BackupFileName = Path.Combine(dir, bi.TableName + ".bak");
            }
            else
            {
                bi.BackupFileName = Path.Combine(dir, bi.TableName + "_" + bi.GuidFieldName + ".bak");
            }

            var columnPropertyList = DatabaseHelper.GetColumnPropertyInfo(bi.TableName, bi.ItemType);

            try
            {
                using (FileStream fs = new FileStream(bi.BackupFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
                    using (TextWriter tw = new StreamWriter(fs, Encoding.Unicode))
                    {
                        Type blobType   = typeof(object);
                        Type stringType = typeof(string);
                        Type doubleType = typeof(double);
                        int  recIndex   = 0;
                        do
                        {
                            foreach (object backupObj in bi.BackupObjects)
                            {
                                int count = 0;
                                foreach (PropertyInfo pi in columnPropertyList)
                                {
                                    bool   writeContent = true;
                                    object val          = pi.GetValue(backupObj, null);
                                    if (pi.PropertyType == stringType)
                                    {
                                        if (val != null && string.IsNullOrEmpty(val as string))
                                        {
                                            val = "\0";
                                        }
                                    }
                                    else if (pi.PropertyType == doubleType)
                                    {
                                        val = string.Format(CultureInfo.InvariantCulture, "{0:R}", val);
                                    }
                                    else if (pi.PropertyType == blobType && val is byte[])
                                    {
                                        byte[] array = val as byte[];
                                        EncodingOperateHelper.ToHexString(array, tw);
                                        writeContent = false;
                                    }
                                    if (writeContent)
                                    {
                                        tw.Write(val);
                                    }
                                    if (++count < columnPropertyList.Count)
                                    {
                                        tw.Write(",\0");
                                    }
                                }
                                tw.WriteLine();
                            }

                            bi.RecordsNum -= bi.BackupObjects.Count;
                            recIndex      += bi.BackupObjects.Count;
                            bi.BackupObjects.Clear();
                            if (bi.RecordsNum > 0 && !string.IsNullOrEmpty(bi.DumpQuery))
                            {
                                bi.BackupObjects = DatabaseHelper.GetBoundedEntities(bi.DumpQuery, BackupItemEx.BatchNum, recIndex);
                            }
                            else
                            {
                                break;
                            }
                        } while (bi.RecordsNum > 0);
                    }
            }
            catch (System.Exception ex)
            {
                LogHelper.Log(ex);
            }
        }