Exemplo n.º 1
0
        private void BuildBackup()
        {
            StringBuilder bkpLog = new StringBuilder();

            IAMDatabase db = null;

            try
            {
                db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                db.openDB();


                bkpLog.AppendLine("Listando tabelas da base de dados...");

                DataTable dtS = db.Select("select TABLE_NAME from information_schema.tables where TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME");

                if ((dtS == null) || (dtS.Rows.Count == 0))
                {
                    bkpLog.AppendLine("Listagem de tabelas vazia ou nula");
                    throw new Exception("Table list is null or empty");
                }

                bkpLog.AppendLine(dtS.Rows.Count + " tabelas");


                FileInfo bkpFile = new FileInfo(Path.Combine(Path.Combine(basePath, "Backup"), "bkp-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".iambkp"));
                if (!bkpFile.Directory.Exists)
                {
                    bkpFile.Directory.Create();
                }

                bkpLog.AppendLine("Criando arquivo de backup: " + bkpFile.FullName);

                using (SqliteBase exportDB = new SqliteBase(bkpFile))
                {
                    foreach (DataRow drSrc in dtS.Rows)
                    {
                        String tableName = drSrc["TABLE_NAME"].ToString();

                        bkpLog.AppendLine("Exportando tabela: " + tableName);
                        Console.WriteLine(tableName);


                        DataTable dtSchema = db.GetSchema(tableName);

                        StringBuilder createCmd = new StringBuilder();

                        createCmd.AppendLine("DROP TABLE IF EXISTS [" + tableName.ToLower() + "];");

                        /*
                         * CREATE TABLE [Events] (
                         * id INTEGER PRIMARY KEY AUTOINCREMENT,
                         * test_id TEXT NOT NULL,
                         * date datetime not null  DEFAULT (datetime('now','localtime')),
                         * event_text TEXT NULL
                         * );*/
                        List <String> columns = new List <string>();

                        bkpLog.AppendLine("Criando estrutura da tabela");
                        try
                        {
                            foreach (DataColumn dc in dtSchema.Columns)
                            {
                                if (dc.DataType.Equals(typeof(Int32)) || dc.DataType.Equals(typeof(Int64)))
                                {
                                    columns.Add("[" + dc.ColumnName + "] INTEGER NULL");
                                }
                                else if (dc.DataType.Equals(typeof(DateTime)))
                                {
                                    columns.Add("[" + dc.ColumnName + "] datetime NULL");
                                }
                                else
                                {
                                    columns.Add("[" + dc.ColumnName + "] TEXT NULL");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro ao listar as colunas da tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro ao listar as colunas da tabela '" + tableName + "': " + ex.Message);
                            throw ex;
                        }


                        try
                        {
                            createCmd.AppendLine("CREATE TABLE [" + tableName.ToLower() + "] (");

                            createCmd.AppendLine(String.Join(", " + Environment.NewLine, columns));

                            createCmd.AppendLine(");");

                            exportDB.ExecuteNonQuery(createCmd.ToString());
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro ao criando tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro ao criando tabela '" + tableName + "': " + ex.Message);
                            throw ex;
                        }

                        //Copiando dados das tabelas
                        try
                        {
                            bkpLog.AppendLine("Copiando dados");

                            if (tableName.ToLower() == "logs")
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select l.* from [logs] l with(nolock) inner join [entity_timeline] et with(nolock) on et.log_id = l.id");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                            else if (tableName.ToLower() == "entity")
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                            else
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)");

                                exportDB.BulkCopy(dtSrcData, tableName.ToLower());
                            }
                        }
                        catch (Exception ex)
                        {
                            bkpLog.AppendLine("Erro copiando dados da tabela '" + tableName + "': " + ex.Message);
                            TextLog.Log("Backup", "\tErro copiando dados da tabela '" + tableName + "': " + ex.Message);
                            //throw ex;
                        }
                    }

                    //No final de todo o processo atualiza as senhas como cleartext
                    try
                    {
                        bkpLog.AppendLine("Atualizando as senhas das entidades");
                        DataTable dtEnt = db.ExecuteDataTable("select id from [enterprise] with(nolock)");

                        foreach (DataRow drEnt in dtEnt.Rows)
                        {
                            using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)drEnt["id"]))
                            {
                                DataTable dtSrcData = db.ExecuteDataTable("select e.id, e.password, c.enterprise_id from [entity] e with(nolock) inner join [context] c with(nolock) on e.context_id = c.id where c.enterprise_id = " + drEnt["id"]);

                                //Atualiza senha em clear text de cada usu[ario
                                foreach (DataRow drUser in dtSrcData.Rows)
                                {
                                    try
                                    {
                                        using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(drUser["password"].ToString())))
                                        {
                                            exportDB.ExecuteNonQuery("update entity set password = '******' where id = " + drUser["id"]);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        bkpLog.AppendLine("Erro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message);
                                        TextLog.Log("Backup", "\tErro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message);
                                        //throw ex;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        bkpLog.AppendLine("Erro atualizando as senhas para cleartext: " + ex.Message);
                        TextLog.Log("Backup", "\tErro atualizando as senhas para cleartext: " + ex.Message);
                        //throw ex;
                    }
                }



                db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Backup realizado com sucesso", bkpLog.ToString());
            }
            catch (Exception ex)
            {
                TextLog.Log("Backup", "\tError building backup: " + ex.Message);
                bkpLog.AppendLine("Error building backup: " + ex.Message);
                try
                {
                    db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Backup finalizado com erro", bkpLog.ToString());
                }
                catch { }
            }
            finally
            {
                if (bkpLog != null)
                {
                    bkpLog = null;
                }

                if (db != null)
                {
                    db.Dispose();
                }
            }
        }