Compartilhando conhecimento com o mundo

Com tecnologia do Blogger.

Pesquisa

Download

Blogger Tricks

Blogger Themes

Visitas

Assuntos

3/07/2015

Compactando Pasta do Servidor - SSIS


Este é um exemplo de um programa feito pelo SSIS que faz backup de algumas pastas importantes do servidor. Este procedimento pelo SSIS faz o backup de algumas pastas (retirando algumas pastas que não quero), compactando, colocando o arquivo compactado em uma pasta especifica e fazendo um controle da quantidade de arquivos compactados. Primeiro, vamos criar uma tabela onde vai ficar armazenado as pasta que vamos usar. Download Clique Aqui

1 - Criando a Tabela

Definindo uma tabela onde vamos inserir os caminhos das pastas, dá para colocar nas variaveis as pastas o problema é que no futuro uma mudança no nome dos servidores ou no nome das pastas temos que editar cada uma das variaveis no SSIS e alterar na unha o nome das pastas, colocando em uma tabela é só rodar um simples update resolve, o nome da tabela vai ser bdfaz_programas;
CREATE TABLE [dbo].[bdfaz_programas](
 [prg_codigo] [int] NOT NULL,
 [prg_descricao] [varchar](60) NOT NULL,
 [prg_sigla] [varchar](20) NULL,
 [prg_nome_detalhado] [varchar](100) NULL,
 [prg_sistema_origem] [varchar](60) NOT NULL,
 [prg_analista_origem] [varchar](60) NOT NULL,
 [prg_fone_origem] [varchar](9) NOT NULL,
 [prg_email_origem] [varchar](60) NOT NULL,
 [prg_job_grande_porte] [varchar](60) NULL,
 [prg_area_grande_porte] [varchar](60) NULL,
 [prg_nome_arquivo_texto] [varchar](60) NULL,
 [prg_origem_inicial] [varchar](60) NULL,
 [prg_origem_final] [varchar](60) NULL,
 [prg_destino_inicial] [varchar](60) NULL,
 [prg_destino_final] [varchar](60) NULL,
 [prg_nome_arquivo_compactado] [varchar](60) NULL,
 [prg_servidor_carga] [varchar](60) NULL,
 [prg_servidor_banco] [varchar](60) NULL,
 [prg_banco_dados] [varchar](60) NULL,
 [frequencia] [varchar](40) NULL,
 [prg_observacao] [varchar](max) NULL
) 
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
Este vai ser o registro que vamos inserir que contem os dados sobre as pastas que vamos salvar;
INSERT INTO [dbo]. [bdfaz_programas]
           ([prg_codigo]
           ,[prg_descricao]
           ,[prg_sigla]
           ,[prg_nome_detalhado]
           ,[prg_sistema_origem]
           ,[prg_analista_origem]
           ,[prg_fone_origem]
           ,[prg_email_origem]
           ,[prg_job_grande_porte]
           ,[prg_area_grande_porte]
           ,[prg_nome_arquivo_texto]
           ,[prg_origem_inicial]
           ,[prg_origem_final]
           ,[prg_destino_inicial]
           ,[prg_destino_final]
           ,[prg_nome_arquivo_compactado]
           ,[prg_servidor_carga]
           ,[prg_servidor_banco]
           ,[prg_banco_dados]
           ,[frequencia]
           ,[prg_observacao])
     VALUES
(
   '1',                             --- prg_codigo
   'Compacta_gql',                  --- prg_descricao
   '',                              --- prg_sigla
   'Compacta Pasta',                --- prg_nome_detalhado
   'XXXXX',                         --- prg_sistema_origem
   'Equipe BI',                     --- prg_analista_origem
   '9999-9999',                     --- prg_fone_origem
   'meu_e_mail@alguma.coisa.br',    --- prg_email_origem
   'NULL',                          --- prg_job_grande_porte
   'NULL',                          --- prg_area_grande_porte
   '',                              --- prg_nome_arquivo_texto
   'C:\Claudemar\CARGA\FONTES\',    --- prg_origem_inicial  --- pasta fonte
   'C:\Claudemar\CARGA\TMP',        --- prg_origem_final    --- pasta temporaria
   'C:\Claudemar\CARGA\BACKUP',     --- prg_destino_inicial --- pasta backup (sem \)
   'C:\Claudemar\CARGA\BACKUP\',    --- prg_destino_final   --- pasta backup (com \)
   'modelos_gql_compactados.zip',   --- prg_nome_arquivo_compactado
   'NULL',                          --- prg_servidor_carga
   'NULL',                          --- prg_servidor_banco
   'NULL',                          --- prg_banco_dados
   'mensal',                        --- frequencia
   'NULL'                           --- prg_observacao
)
2 - Variáveis

Abrindo o SSIS vamos definir essas variaveis;
+-----------------------------+---------------+-------------------------+
| nome                        | Data Type     | Value                   |
+-----------------------------+---------------+-------------------------+
| caminho_backup_dois_gql     | String        | caminho_backup_dois_gql |
| caminho_backup_gql          | String        |                         |
| caminho_fonte_gql           | String        | caminho_fonte_gql       |
| caminho_pasta_tmp           | String        | caminho_pasta_tmp       |
| compactar_arquivos          | String        | N                       |
| pasta_modelo_gql            | String        | pasta_modelo_gql        |
| pastas_modelos_gql          | Objet         | System.Object           |
| prg_codigo                  | Int32         | 1                       |
| prg_periodo                 | String        | 15                      |
+-----------------------------+---------------+-------------------------+
O valor da variavel prg_codigo é o mesmo valor que foi colocado no insert acima;

Tela do SSIS das variáveis;



3 - Configurando a Conexão OLE DB

Neste passo vamos apontar no SSIS o banco/tabela onde criamos a tabela acima;



4 - Pelo SSIS

Vamos abrir o SSIS e vamos criar um componente Data Flow (Data Flow Task), depois de adicionar vamos clicar duas vezes nele para acessar o Control Flow, dai vamos adicionar dentro dele dois componentes;

- OLE BD Source e o;
- Script Task (Transformation)

4.1 - OLE BD Source - Script Transformation



4.2 - OLE BD Source

Vamos pegar no banco os valores da tabela que fizemos o insert;

SQL command text
SELECT [prg_codigo]
  ,[prg_origem_inicial] as caminho_fonte_gql
  ,[prg_origem_final] as caminho_pasta_tmp
  ,[prg_destino_inicial] as  caminho_backup_dois_gql
  ,[prg_destino_final] as caminho_backup_gql
  ,[prg_nome_arquivo_compactado] as nome_arquivo_zip
  ,[prg_nome_arquivo_texto]
FROM [dbo].[bdfaz_programas]
WHERE   prg_codigo= ?
Clique em Parameters e adicione a variavel User::prg_codigo



4.3 - Script Transformation

Ele vai gravar as variáveis que estão no banco (do nosso insert) para gravar nas variáveis do nosso SSIS;



ReadWriteVariables marque essas variaveis
User::caminho_backup_dois_gql,User::caminho_backup_gql,User::caminho_fonte_gql,User::caminho_pasta_tmp,User::pasta_modelo_gql
Em (Edit Script) cole o script abaixo - vai gravar nas variaveis os dados (nomes das pastas) que inserimos na tabela;
/* Microsoft SQL Server Integration Services Script Component

*  Write scripts using Microsoft Visual C# 2008.
*  ScriptMain is the entry point class of the script.*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Windows.Forms;

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent

{
    string caminho_backup_gql       = string.Empty;
    string caminho_backup_dois_gql  = string.Empty;
    string caminho_fonte_gql        = string.Empty;
    string caminho_pasta_tmp        = string.Empty;
    string pasta_modelo_gql         = string.Empty;
    //string caminho_processar = string.Empty;

    public override void PreExecute()
    {
        base.PreExecute();
    }

    public override void PostExecute()
    {
        base.PostExecute();

        Variables.caminhofontegql       = caminho_fonte_gql;
        Variables.caminhobackupdoisgql  = caminho_backup_dois_gql;
        Variables.caminhobackupgql      = caminho_backup_gql;
        Variables.caminhopastatmp       = caminho_pasta_tmp;
        Variables.pastamodelogql        = string.Empty;

        // ---------------------------------------------------------------------------------------------
        // Imprimi na tela as variaveis carregadas
        // ---------------------------------------------------------------------------------------------
        //MessageBox.Show(Variables.caminhofontegql, "caminho_fonte_gql");
        //MessageBox.Show(Variables.caminhopastatmp, "caminho_pasta_tmp");
        //MessageBox.Show(Variables.caminhofontedoisgql, "caminho_fonte_dois_gql");
        //MessageBox.Show(Variables.caminhobackupgql, "caminho_backup_gql");
        //MessageBox.Show(Variables.pastamodelogql, "pastamodelogql");
        // ---------------------------------------------------------------------------------------------

    }
    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        caminho_fonte_gql = Row.caminhofontegql;
        caminho_pasta_tmp = Row.caminhopastatmp;
        caminho_backup_dois_gql = Row.caminhobackupdoisgql;
        caminho_backup_gql = Row.caminhobackupgql + DateTime.Now.ToString("yyyyMMddHHmmss_") + Row.nomearquivozip;
     }
}
5 - Adicionando um Script Task - Data Flow

No Data Flow vamos criar um componente - Script Task (Transformation)



ReadOnlyVariables marque essas variaveis
User::caminho_fonte_gql,User::caminho_pasta_tmp
Em (Edit Script) cole o script abaixo - este script descobre o nome das pastas e inicia a copia das pastas (tem uma parte que que colocamos algumas pastas para não copiar);
#region Help:  Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
 * a .Net application within the context of an Integration Services control flow. 
 * 
 * Expand the other regions which have "Help" prefixes for examples of specific ways to use
 * Integration Services features within this script task. */
#endregion


using System;
using System.Data;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Collections.Generic;

namespace ST_34ad99c71d8c4458afb662e9cd553c03
{
    /// 

    /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
    /// or parent of this class.
    /// 

    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        #region Help:  Using Integration Services variables and parameters in a script
        /* To use a variable in this script, first ensure that the variable has been added to 
         * either the list contained in the ReadOnlyVariables property or the list contained in 
         * the ReadWriteVariables property of this script task, according to whether or not your
         * code needs to write to the variable.  To add the variable, save this script, close this instance of
         * Visual Studio, and update the ReadOnlyVariables and 
         * ReadWriteVariables properties in the Script Transformation Editor window.
         * To use a parameter in this script, follow the same steps. Parameters are always read-only.
         * 
         * Example of reading from a variable:
         *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
         * 
         * Example of writing to a variable:
         *  Dts.Variables["User::myStringVariable"].Value = "new value";
         * 
         * Example of reading from a package parameter:
         *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
         *  
         * Example of reading from a project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
         * 
         * Example of reading from a sensitive project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
         * */

        #endregion

        #region Help:  Firing Integration Services events from a script
        /* This script task can fire events for logging purposes.
         * 
         * Example of firing an error event:
         *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
         * 
         * Example of firing an information event:
         *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
         * */
        #endregion

        #region Help:  Using Integration Services connection managers in a script
        /* Some types of connection managers can be used in this script task.  See the topic 
         * "Working with Connection Managers Programatically" for details.
         * 
         * Example of using an ADO.Net connection manager:
         *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
         *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
         *
         * Example of using a File connection manager
         *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
         *  string filePath = (string)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
         * */
        #endregion

        static string CONST_ORIGEM = null;
        static string CONST_DESTINO = null;
        //List lista_origem = new List(); //um arraymultidimensional
        //List lista_destino = new List();

        List lista_origem = new List(); //um arraymultidimensional
        List lista_destino = new List();


        /// 

        /// This method is called when this script task executes in the control flow.
        /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        /// To open Help, press F1.
        /// 

        public void Main()
        {

            //            CONST_ORIGEM = Dts.Variables["prg_origem_inicial_gql"].Value.ToString();
            //            CONST_DESTINO = Dts.Variables["prg_origem_final_gql"].Value.ToString();

            CONST_ORIGEM = Dts.Variables["caminho_fonte_gql"].Value.ToString();
            CONST_DESTINO = Dts.Variables["caminho_pasta_tmp"].Value.ToString() + "\\";

            //descobre o nome das pastas
            ListaDiretorios();

            //executa copia
            for (int i = 0; i < lista_origem.Count; i++)
            {
                CopiaDiretorio(lista_origem[i], lista_destino[i], true);
            }

        }

        #region ListaDiretorios
        void ListaDiretorios()
        {

            // buscar pastas dos modelos GQL

            List lista = new List();

            //List lista = new List();
            string[] dirs = System.IO.Directory.GetDirectories(CONST_ORIGEM);
            //string pasta_suporte_gql = CONST_ORIGEM + "\\suporte_gql";
            //string pasta_suporte_gql = CONST_ORIGEM + "\\DfsrPrivate";


            //lista de nome das pastas (limpa string do caminho completo da past)
            for (int i = 0; i < dirs.LongLength; i++)
            {
                //if (!dirs[i].Contains("suporte"))
                if (
                    //-----------------------------------------------------------------------
                    // 3 pastas que não quero que sejam copiadas para a tmp
                    //-----------------------------------------------------------------------
                    !dirs[i].Contains("DfsrPrivate") &&
                    !dirs[i].Contains("instalacao_gql") &&
                    !dirs[i].Contains("__DFSR_DIAGNOSTICS_TEST_FOLDER__")
                    )

                //if (!dirs[i].Contains("DfsrPrivate"))
                {
                    lista.Add(dirs[i].Replace(CONST_ORIGEM, ""));
                }
            }

            //monta caminho completo da origem
            foreach (string p in lista)
            {
                lista_origem.Add(CONST_ORIGEM + p);


                //--------------------------------------------------------------------------
                // Mensagem das pastas de origem
                //--------------------------------------------------------------------------    
                //MessageBox.Show("Origem " + CONST_ORIGEM + p);
            }

            //monta caminho completo do destino
            foreach (string p in lista)
            {
                lista_destino.Add(CONST_DESTINO + p);


                //--------------------------------------------------------------------------
                // Mensagem das pastas de origem
                //--------------------------------------------------------------------------    
                //MessageBox.Show("Destino " + CONST_DESTINO + p);
            }

        }
        #endregion ListaDiretorios

        #region CopiaFolderSubfolder
        /// 

        /// Metodo para copiar folders e subfolders
        /// 

        /// pasta de origem
        /// pasta de destino
        /// indica se eh para copiar subdiretorios
        private static void CopiaDiretorio(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);
            DirectoryInfo[] dirs = dir.GetDirectories();

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourceDirName);
            }

            // If the destination directory doesn't exist, create it. 
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();
            foreach (FileInfo file in files)
            {
                string temppath = Path.Combine(destDirName, file.Name);
                file.CopyTo(temppath, false);
            }

            // If copying subdirectories, copy them and their contents to new location. 
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    CopiaDiretorio(subdir.FullName, temppath, copySubDirs);
                }
            }
        }
        #endregion  CopiaFolderSubfolder

    }
}
Imagens



6 - Adicionando o Execute Process Task

No Data Flow vamos criar colocar o Execute Process Task - Este processo vai compactar a pasta temporaria;



Em > Process
RequireFullFileName                  - True
Executable                           - C:\Program Files\WinRAR\Rar.exe
Arguments                            - a -df -ep1 -m5 + caminho_pasta_tmp
FailTaskIfReturnCodeIsNotSucessValue - True
SucessValue                          - 0
TimeOut                              - 0
Em > Arguments > Adicione
"a -df -ep1 -m5 " + @[User::caminho_backup_gql]   + " " +   @[User::caminho_pasta_tmp]
7 - Adicionando o Script Task

No Data Flow vamos adicionar o Script Task (Transformation) - esta parte vai deletar os arquivos compactados antigos - vou deixar somente os 12 últimos arquivos compactados, surgindo mais um novo o arquivo mais antigo será deletado;



ReadOnlyVariable
User::caminho_backup_dois_gql,User::prg_periodo
Em (Edit Script) cole o script abaixo;
/*
   Microsoft SQL Server Integration Services Script Task
   Write scripts using Microsoft Visual C# 2008.
   The ScriptMain is the entry point class of the script.

* Este script deleta o arquivo mais antigo do backup compactado da s371
*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;

namespace ST_bb39ea0d414d46bbbe9be76558ec7188.csproj
{
    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {

        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

        /*
            The execution engine calls this method when the task executes.
            To access the object model, use the Dts property. Connections, variables, events,
            and logging features are available as members of the Dts property as shown in the following examples.

            To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
            To post a log entry, call Dts.Log("This is my log text", 999, null);
            To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);

            To use the connections collection use something like the following:
            ConnectionManager cm = Dts.Connections.Add("OLEDB");
            cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";

            Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
            
            To open Help, press F1.
      */

        public void Main()
        {


            //----------------------------------------------------------------------------
            //Display da variavel da pasta que vamos deletar
            //----------------------------------------------------------------------------
            //MessageBox.Show(Dts.Variables["User::caminho_backup_dois_gql"].Value.ToString());
            
            int RetentionPeriod = Convert.ToInt32(Dts.Variables["User::prg_periodo"].Value.ToString());
            string directoryPath = Dts.Variables["User::caminho_backup_dois_gql"].Value.ToString();
            //string directoryPath = Dts.Variables["User::prg_pasta_backup"].Value.ToString();
            string[] oldfiles = System.IO.Directory.GetFiles(directoryPath, "*.*");
            foreach (string currFile in oldfiles)
            {
                FileInfo currFileInfo = new FileInfo(currFile);
                
                //================================================================================
                //abaixo deleta os arquivos pela data de criacao 
                //================================================================================
                
                if (currFileInfo.CreationTime < (DateTime.Now.AddDays(-RetentionPeriod)))
                
                //================================================================================
                //abaixo deleta os arquivos pela data de modificacao
                //================================================================================
                //if (currFileInfo.LastWriteTime < (DateTime.Now.AddDays(-RetentionPeriod)))
                //================================================================================
                {
                    currFileInfo.Delete();
                }
            }

            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
        }
    }
}
8 - Rodando o Projeto

Rodando para ver;