add a from to backup routine

Posted by Gerard Flynn on Stack Overflow See other posts from Stack Overflow or by Gerard Flynn
Published on 2010-04-02T15:46:54Z Indexed on 2010/04/02 16:03 UTC
Read the original article Hit count: 480

Filed under:

hi how do you put a process bar and button onto this code i have class and want to add a gui on to the code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using Tamir.SharpSsh;
using System.Security.Cryptography;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;


namespace backup
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Summary description for Class1.
        /// </summary>
        public class Backup
        {
            private string dbName;
            private string dbUsername;
            private string dbPassword;

            private static string baseDir;
            private string backupName;

            private static bool isBackup;

            private string keyString;
            private string ivString;

            private string[] backupDirs = new string[0];
            private string[] excludeDirs = new string[0];

            private ZipOutputStream zipOutputStream;

            private string backupFile;
            private string zipFile;
            private string encryptedFile;


            static void Main()
            {
                Backup.Log("BackupUtility loaded");
                try
                {
                    new Backup();
                    if (!isBackup)
                        MessageBox.Show("Restore complete");
                }
                catch (Exception e)
                {
                    Backup.Log(e.ToString());
                    if (!isBackup)
                        MessageBox.Show("Error restoring!\r\n" + e.Message);
                }
            }

            private void LoadAppSettings()
            {
                this.backupName = System.Configuration.ConfigurationSettings.AppSettings["BackupName"].ToString();

                this.dbName = System.Configuration.ConfigurationSettings.AppSettings["DBName"].ToString();
                this.dbUsername = System.Configuration.ConfigurationSettings.AppSettings["DBUsername"].ToString();
                this.dbPassword = System.Configuration.ConfigurationSettings.AppSettings["DBPassword"].ToString();

                //default to using where we are executing this assembly from
                Backup.baseDir = System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.LastIndexOf("\\")) + "\\";

                Backup.isBackup = bool.Parse(System.Configuration.ConfigurationSettings.AppSettings["IsBackup"].ToString());
                this.keyString = System.Configuration.ConfigurationSettings.AppSettings["KeyString"].ToString();
                this.ivString = System.Configuration.ConfigurationSettings.AppSettings["IVString"].ToString();


                this.backupDirs = GetSetting("BackupDirs", ',');
                this.excludeDirs = GetSetting("ExcludeDirs", ',');
            }

            private string[] GetSetting(string settingName, char delimiter)
            {
                if (System.Configuration.ConfigurationSettings.AppSettings[settingName] != null)
                {
                    string settingVal = System.Configuration.ConfigurationSettings.AppSettings[settingName].ToString();
                    if (settingVal.Length > 0)
                        return settingVal.Split(delimiter);
                }

                return new string[0];
            }

            public Backup()
            {
                this.LoadAppSettings();

                if (isBackup)
                    this.DoBackup();

                else
                    this.DoRestore();

                Log("Finished");

            }

            private void DoRestore()
            {
                System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
                fileDialog.Title = "Choose .encrypted file";
                fileDialog.Filter = "Encrypted files (*.encrypted)|*.encrypted|All files (*.*)|*.*";
                fileDialog.InitialDirectory = Backup.baseDir;
                if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //string encryptedFile = GetFileName("encrypted");
                    string encryptedFile = fileDialog.FileName;
                    string decryptedFile = this.GetDecryptedFilename(encryptedFile);
                    //string originalFile = GetFileName("original");

                    this.Decrypt(encryptedFile, decryptedFile);
                    //this.UnzipFile(decryptedFile, originalFile);
                }
            }

            //use the same filename as the backup except replace ".encrypted" with ".decrypted.zip"
            private string GetDecryptedFilename(string encryptedFile)
            {
                string name = encryptedFile.Substring(0, encryptedFile.LastIndexOf("."));
                name += ".decrypted.zip";
                return name;
            }

            private void DoBackup()
            {
                this.backupFile = GetFileName("bak");
                this.zipFile = GetFileName("zip");
                this.encryptedFile = GetFileName("encrypted");

                this.DeleteFiles();

                this.zipOutputStream = new ZipOutputStream(File.Create(zipFile));
                try
                {
                    //backup database first
                    if (this.dbName.Length > 0)
                    {
                        this.BackupDB(backupFile);
                        this.ZipFile(backupFile, this.GetName(backupFile));
                    }

                    //zip any directories specified in config file
                    this.ZipUserSpecifiedFilesAndDirectories(this.backupDirs);
                }
                finally
                {
                    this.zipOutputStream.Finish();
                    this.zipOutputStream.Close();
                }

                this.Encrypt(zipFile, encryptedFile);
                this.SCPFile(encryptedFile);

                this.DeleteFiles();
            }

            /// <summary>
            /// Deletes any files created by the backup process, namely the DB backup file,
            /// the zip of all files backuped up, and the encrypred zip file
            /// </summary>
            private void DeleteFiles()
            {
                File.Delete(this.backupFile);
                File.Delete(this.zipFile);
                ///File.Delete(this.encryptedFile);         
            }

            private void ZipUserSpecifiedFilesAndDirectories(string[] fileNames)
            {
                foreach (string fileName in fileNames)
                {
                    string name = fileName.Trim();
                    if (name.Length > 0)
                    {
                        Log("Zipping " + name);
                        this.ZipFile(name, this.GetNameFromDir(name));
                    }
                }
            }

            private void SCPFile(string inputPath)
            {
                string sshServer = System.Configuration.ConfigurationSettings.AppSettings["SSHServer"].ToString();
                string sshUsername = System.Configuration.ConfigurationSettings.AppSettings["SSHUsername"].ToString();
                string sshPassword = System.Configuration.ConfigurationSettings.AppSettings["SSHPassword"].ToString();
                if (sshServer.Length > 0 && sshUsername.Length > 0 && sshPassword.Length > 0)
                {
                    Scp scp = new Scp(sshServer, sshUsername, sshPassword);
                    //Copy a file from local machine to remote SSH server
                    scp.Connect();
                    Log("Connected to " + sshServer);
                    //scp.Put(inputPath, "/home/wal/temp.txt");
                    scp.Put(inputPath, GetName(inputPath));
                    scp.Close();
                }
                else
                {
                    Log("Not SCP as missing login details");
                }
            }

            private string GetName(string inputPath)
            {
                FileInfo info = new FileInfo(inputPath);
                return info.Name;
            }

            private string GetNameFromDir(string inputPath)
            {
                DirectoryInfo info = new DirectoryInfo(inputPath);
                return info.Name;
            }

            private static void Log(string msg)
            {
                try
                {
                    string toLog = DateTime.Now.ToString() + ": " + msg;
                    System.Diagnostics.Debug.WriteLine(toLog);
                    System.IO.FileStream fs = new System.IO.FileStream(baseDir + "app.log", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
                    System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs);
                    m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                    m_streamWriter.WriteLine(toLog);
                    m_streamWriter.Flush();
                    m_streamWriter.Close();
                    fs.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            private byte[] GetFileBytes(string path)
            {
                FileStream stream = new FileStream(path, FileMode.Open);
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Close();
                return bytes;
            }

            private void WriteFileBytes(byte[] bytes, string path)
            {
                FileStream stream = new FileStream(path, FileMode.Create);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }

            private void UnzipFile(string inputPath, string outputPath)
            {
                ZipInputStream zis = new ZipInputStream(File.OpenRead(inputPath));
                ZipEntry theEntry = zis.GetNextEntry();
                FileStream streamWriter = File.Create(outputPath);

                int size = 2048;
                byte[] data = new byte[2048];
                while (true)
                {
                    size = zis.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }

                streamWriter.Close();
                zis.Close();
            }


            private bool ExcludeDir(string dirName)
            {
                foreach (string excludeDir in this.excludeDirs)
                {
                    if (dirName == excludeDir)
                        return true;
                }
                return false;
            }

            private void ZipFile(string inputPath, string zipName)
            {
                FileAttributes fa = File.GetAttributes(inputPath);
                if ((fa & FileAttributes.Directory) != 0)
                {
                    string dirName = zipName + "/";
                    ZipEntry entry1 = new ZipEntry(dirName);
                    this.zipOutputStream.PutNextEntry(entry1);
                    string[] subDirs = Directory.GetDirectories(inputPath);

                    //create directories first
                    foreach (string subDir in subDirs)
                    {
                        DirectoryInfo info = new DirectoryInfo(subDir);
                        string name = info.Name;
                        if (this.ExcludeDir(name))
                            Log("Excluding " + dirName + name);
                        else
                            this.ZipFile(subDir, dirName + name);
                    }

                    //then store files
                    string[] fileNames = Directory.GetFiles(inputPath);
                    foreach (string fileName in fileNames)
                    {
                        FileInfo info = new FileInfo(fileName);
                        string name = info.Name;
                        this.ZipFile(fileName, dirName + name);
                    }
                }
                else
                {

                    Crc32 crc = new Crc32();


                    this.zipOutputStream.SetLevel(6); // 0 - store only to 9 - means best compression


                    FileStream fs = null;
                    try
                    {
                        fs = File.OpenRead(inputPath);
                    }
                    catch (IOException ioEx)
                    {
                        Log("WARNING! " + ioEx.Message);//might be in use, skip file in this case
                    }

                    if (fs != null)
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        ZipEntry entry = new ZipEntry(zipName);

                        entry.DateTime = DateTime.Now;

                        // set Size and the crc, because the information
                        // about the size and crc should be stored in the header
                        // if it is not set it is automatically written in the footer.
                        // (in this case size == crc == -1 in the header)
                        // Some ZIP programs have problems with zip files that don't store
                        // the size and crc in the header.
                        entry.Size = fs.Length;
                        fs.Close();

                        crc.Reset();
                        crc.Update(buffer);

                        entry.Crc = crc.Value;

                        this.zipOutputStream.PutNextEntry(entry);

                        this.zipOutputStream.Write(buffer, 0, buffer.Length);
                    }
                }



            }

            private void Encrypt(string inputPath, string outputPath)
            {

                RijndaelManaged rijndaelManaged = new RijndaelManaged();


                byte[] encrypted;
                byte[] toEncrypt;


                //Create a new key and initialization vector.
                //myRijndael.GenerateKey();
                //myRijndael.GenerateIV();
                /*des.GenerateKey();
                des.GenerateIV();

                string temp1 = Convert.ToBase64String(des.Key);
                string temp2 = Convert.ToBase64String(des.IV);*/

                //Get the key and IV.
                byte[] key = Convert.FromBase64String(keyString);
                byte[] IV = Convert.FromBase64String(ivString);

                //Get an encryptor.
                ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(key, IV);


                //Encrypt the data.
                MemoryStream msEncrypt = new MemoryStream();
                CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

                //Convert the data to a byte array.
                toEncrypt = this.GetFileBytes(inputPath);

                //Write all data to the crypto stream and flush it.
                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
                csEncrypt.FlushFinalBlock();

                //Get encrypted array of bytes.
                encrypted = msEncrypt.ToArray();

                WriteFileBytes(encrypted, outputPath);
            }


            private void Decrypt(string inputPath, string outputPath)
            {
                RijndaelManaged myRijndael = new RijndaelManaged();
                //DES des = new DESCryptoServiceProvider();
                byte[] key = Convert.FromBase64String(keyString);
                byte[] IV = Convert.FromBase64String(ivString);
                byte[] encrypted = this.GetFileBytes(inputPath);
                byte[] fromEncrypt;

                //Get a decryptor that uses the same key and IV as the encryptor.
                ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

                //Now decrypt the previously encrypted message using the decryptor
                // obtained in the above step.
                MemoryStream msDecrypt = new MemoryStream(encrypted);
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

                fromEncrypt = new byte[encrypted.Length];

                //Read the data out of the crypto stream.
                int bytesRead = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

                byte[] readBytes = new byte[bytesRead];
                Array.Copy(fromEncrypt, 0, readBytes, 0, bytesRead);

                this.WriteFileBytes(readBytes, outputPath);

            }

            private string GetFileName(string extension)
            {
                return baseDir + backupName + "_" + DateTime.Now.ToString("yyyyMMdd") + "." + extension;
            }

            private void BackupDB(string backupPath)
            {
                string sql = @"DECLARE @Date VARCHAR(300), @Dir VARCHAR(4000)

--Get today date
SET @Date = CONVERT(VARCHAR, GETDATE(), 112)

--Set the directory where the back up file is stored
SET @Dir = '";
                sql += backupPath;
                sql += @"'


--create a 'device' to write to first
EXEC sp_addumpdevice 'disk', 'temp_device', @Dir

--now do the backup
BACKUP DATABASE " + this.dbName;
                sql += @" TO temp_device WITH FORMAT

--Drop the device
EXEC sp_dropdevice 'temp_device'
";
                //Console.WriteLine("sql="+sql);
                Backup.Log("Starting backup of " + this.dbName);
                ExecuteSQL(sql);

            }


            /// <summary>
            /// Executes the specified SQL
            /// Returns true if no errors were encountered during execution
            /// </summary>
            /// <param name="procedureName"></param>
            private void ExecuteSQL(string sql)
            {
                SqlConnection conn = new SqlConnection(this.GetDBConnectString());
                try
                {
                    SqlCommand comm = new SqlCommand(sql, conn);
                    conn.Open();
                    comm.ExecuteNonQuery();
                }
                finally
                {
                    conn.Close();
                }
            }

            private string GetDBConnectString()
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("Data Source=127.0.0.1; User ID=");
                builder.Append(this.dbUsername);
                builder.Append("; Password=");
                builder.Append(this.dbPassword);
                builder.Append("; Initial Catalog=");
                builder.Append(this.dbName);
                builder.Append(";Connect Timeout=30");
                return builder.ToString();
            }

        }
    }
}

© Stack Overflow or respective owner

Related posts about c#