mudzakkir

SSIS Zip Large File

Feb 15th, 2016
363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.66 KB | None | 0 0
  1. #region Help:  Introduction to the script task
  2. /* The Script Task allows you to perform virtually any operation that can be accomplished in
  3.  * a .Net application within the context of an Integration Services control flow.
  4.  *
  5.  * Expand the other regions which have "Help" prefixes for examples of specific ways to use
  6.  * Integration Services features within this script task. */
  7. #endregion
  8.  
  9.  
  10. #region Namespaces
  11. using System;
  12. using System.Data;
  13. using Microsoft.SqlServer.Dts.Runtime;
  14. using System.Windows.Forms;
  15. using System.IO;
  16. using System.IO.Compression;
  17. #endregion
  18.  
  19. namespace ST_4cb59661fb81431abcf503766697a1db
  20. {
  21.     /// <summary>
  22.     /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
  23.     /// or parent of this class.
  24.     /// </summary>
  25.     [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
  26.     public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
  27.     {
  28.         #region Help:  Using Integration Services variables and parameters in a script
  29.         /* To use a variable in this script, first ensure that the variable has been added to
  30.          * either the list contained in the ReadOnlyVariables property or the list contained in
  31.          * the ReadWriteVariables property of this script task, according to whether or not your
  32.          * code needs to write to the variable.  To add the variable, save this script, close this instance of
  33.          * Visual Studio, and update the ReadOnlyVariables and
  34.          * ReadWriteVariables properties in the Script Transformation Editor window.
  35.          * To use a parameter in this script, follow the same steps. Parameters are always read-only.
  36.          *
  37.          * Example of reading from a variable:
  38.          *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
  39.          *
  40.          * Example of writing to a variable:
  41.          *  Dts.Variables["User::myStringVariable"].Value = "new value";
  42.          *
  43.          * Example of reading from a package parameter:
  44.          *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
  45.          *  
  46.          * Example of reading from a project parameter:
  47.          *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
  48.          *
  49.          * Example of reading from a sensitive project parameter:
  50.          *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
  51.          * */
  52.  
  53.         #endregion
  54.  
  55.         #region Help:  Firing Integration Services events from a script
  56.         /* This script task can fire events for logging purposes.
  57.          *
  58.          * Example of firing an error event:
  59.          *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
  60.          *
  61.          * Example of firing an information event:
  62.          *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
  63.          *
  64.          * Example of firing a warning event:
  65.          *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
  66.          * */
  67.         #endregion
  68.  
  69.         #region Help:  Using Integration Services connection managers in a script
  70.         /* Some types of connection managers can be used in this script task.  See the topic
  71.          * "Working with Connection Managers Programatically" for details.
  72.          *
  73.          * Example of using an ADO.Net connection manager:
  74.          *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
  75.          *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
  76.          *  //Use the connection in some code here, then release the connection
  77.          *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
  78.          *
  79.          * Example of using a File connection manager
  80.          *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
  81.          *  string filePath = (string)rawConnection;
  82.          *  //Use the connection in some code here, then release the connection
  83.          *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
  84.          * */
  85.         #endregion
  86.  
  87.  
  88.         /// <summary>
  89.         /// This method is called when this script task executes in the control flow.
  90.         /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
  91.         /// To open Help, press F1.
  92.         /// </summary>
  93.         public void Main()
  94.         {
  95.             try
  96.             {
  97.                 string strDate = DateTime.Now.ToString("yyyyMMdd");
  98.                 string strFolder = DateTime.Now.ToString("yyyyMM");
  99.  
  100.                 string sFileName = String.Format(Dts.Variables["User::sFileName"].Value.ToString(), "CHRGUL", strDate + "_NONCTK");
  101.                 string sFilePath = Dts.Variables["User::sFilePath"].Value.ToString() + "DTST" +Path.DirectorySeparatorChar + strFolder + Path.DirectorySeparatorChar + sFileName;
  102.                 string sDestinationFolder = Dts.Variables["User::sDestination"].Value.ToString() + String.Format("DTST{0}", Path.DirectorySeparatorChar) + strFolder + Path.DirectorySeparatorChar;
  103.                 string sZipFile = sDestinationFolder + String.Format(Dts.Variables["User::sZipFile"].Value.ToString(), "CHRGUL", strDate + "_NONCTK");
  104.                 string sBackupFolder = Dts.Variables["User::sBackupFolder"].Value.ToString();
  105.  
  106.                 System.IO.DirectoryInfo di = new DirectoryInfo(sDestinationFolder);
  107.  
  108.                 #region Clean Dir ANST
  109.                 bool exists = System.IO.Directory.Exists(sDestinationFolder);
  110.                 if (!exists)
  111.                     System.IO.Directory.CreateDirectory(sDestinationFolder);
  112.                 foreach (FileInfo file in di.GetFiles())
  113.                 {
  114.                     file.Delete();
  115.                 }
  116.                 foreach (DirectoryInfo dir in di.GetDirectories())
  117.                 {
  118.                     dir.Delete(true);
  119.                 }
  120.                 #endregion
  121.  
  122.                 #region Create Zip File and Move source to Backup
  123.                 //CHRGUL
  124.                 AddFileToZipUsingStream(sZipFile, sFilePath, sFileName, sBackupFolder, "DTST");
  125.  
  126.                 //ANSTHDR
  127.                 sFileName = String.Format(Dts.Variables["User::sFileName"].Value.ToString(), "TRANUL", strDate + "_NONCTK");
  128.                 sFilePath = Dts.Variables["User::sFilePath"].Value.ToString() + "DTST" + Path.DirectorySeparatorChar + strFolder + Path.DirectorySeparatorChar + sFileName;
  129.                 sDestinationFolder = Dts.Variables["User::sDestination"].Value.ToString() + String.Format("DTST{0}", Path.DirectorySeparatorChar) + strFolder + Path.DirectorySeparatorChar;
  130.                 sZipFile = sDestinationFolder + String.Format(Dts.Variables["User::sZipFile"].Value.ToString(), "TRANUL", strDate + "_NONCTK");
  131.                 AddFileToZipUsingStream(sZipFile, sFilePath, sFileName, sBackupFolder, "DTST");
  132.                 #endregion
  133.  
  134.                 Dts.TaskResult = (int)ScriptResults.Success;
  135.             }
  136.             catch (Exception ex)
  137.             {
  138.                 string filePath = String.Format(@"{0}\{1}.log", Dts.Variables["User::sLogFile"].Value.ToString(), DateTime.Now.ToString("yyyyMMddHHmmss"));
  139.  
  140.                 using (StreamWriter writer = new StreamWriter(filePath, true))
  141.                 {
  142.                     writer.WriteLine(ex.ToString());
  143.                     writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
  144.                 }
  145.                 Dts.TaskResult = (int)ScriptResults.Failure;
  146.             }
  147.         }
  148.  
  149.         #region ScriptResults declaration
  150.         /// <summary>
  151.         /// This enum provides a convenient shorthand within the scope of this class for setting the
  152.         /// result of the script.
  153.         ///
  154.         /// This code was generated automatically.
  155.         /// </summary>
  156.         enum ScriptResults
  157.         {
  158.             Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
  159.             Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
  160.         };
  161.         #endregion
  162.  
  163.         #region  Method
  164.         protected bool AddFileToZip(string sZipFile, string sFilePath, string sFileName, string sBackupFolder, string sPrefixFolder)
  165.         {
  166.             bool bIsSuccess = false;
  167.             try
  168.             {
  169.                 if (File.Exists(sZipFile))
  170.                 {
  171.                     using (ZipArchive addFile = ZipFile.Open(sZipFile, ZipArchiveMode.Update))
  172.                     {
  173.                         addFile.CreateEntryFromFile(sFilePath, sFileName);
  174.  
  175.                         //Move File after zipping it
  176.                         BackupFile(sFilePath, sBackupFolder, sPrefixFolder);
  177.                     }
  178.                 }
  179.                 else
  180.                 {
  181.                     using (ZipArchive addFile = ZipFile.Open(sZipFile, ZipArchiveMode.Update))
  182.                     {
  183.                         addFile.CreateEntryFromFile(sFilePath, sFileName);
  184.                     }
  185.  
  186.                     //Move File after zipping it
  187.                     BackupFile(sFilePath, sBackupFolder, sPrefixFolder);
  188.                 }
  189.                 bIsSuccess = true;
  190.             }
  191.             catch (Exception ex)
  192.             {
  193.                 throw ex;
  194.             }
  195.             return bIsSuccess;
  196.         }
  197.         protected bool BackupFile(string sSourceFile, string sDestination, string sPrefixFolder)
  198.         {
  199.             bool bIsSuccess = false;
  200.             try
  201.             {
  202.                 string sDestinationPath = sDestination + sPrefixFolder + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyy") + Path.DirectorySeparatorChar + DateTime.Now.ToString("MM") + Path.DirectorySeparatorChar + DateTime.Now.ToString("dd");
  203.                 bool exists = System.IO.Directory.Exists(sDestinationPath);
  204.                 if (!exists)
  205.                     System.IO.Directory.CreateDirectory(sDestinationPath);
  206.                 sDestinationPath += Path.DirectorySeparatorChar + Path.GetFileName(sSourceFile);
  207.                 exists = File.Exists(sDestinationPath);
  208.                 if (!exists)
  209.                     File.Move(sSourceFile, sDestinationPath);
  210.                 else
  211.                 {
  212.                     File.Delete(sDestinationPath);
  213.                     File.Move(sSourceFile, sDestinationPath);
  214.                 }
  215.                 bIsSuccess = true;
  216.             }
  217.             catch (Exception ex)
  218.             {
  219.                 throw ex;
  220.             }
  221.             return bIsSuccess;
  222.         }
  223.  
  224.         protected bool AddFileToZipUsingStream(string sZipFile, string sFilePath, string sFileName, string sBackupFolder, string sPrefixFolder)
  225.         {
  226.             bool bIsSuccess = false;
  227.             try
  228.             {
  229.                 if (File.Exists(sZipFile))
  230.                 {
  231.                     using (ZipArchive addFile = ZipFile.Open(sZipFile, ZipArchiveMode.Update))
  232.                     {
  233.                         addFile.CreateEntryFromFile(sFilePath, sFileName);
  234.  
  235.                         //Move File after zipping it
  236.                         BackupFile(sFilePath, sBackupFolder, sPrefixFolder);
  237.                     }
  238.                 }
  239.                 else
  240.                 {
  241.                     //TODO need to optimize Big File
  242.                     //using (var memoryStream = new MemoryStream())
  243.                     //{
  244.                     //    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
  245.                     //    {
  246.                     //        var demoFile = archive.CreateEntry(sFileName);
  247.                     //        using (var entryStream = demoFile.Open())
  248.                     //        using (var streamWriter = new StreamWriter(entryStream))
  249.                     //        {
  250.                     //            streamWriter.Write("Bar!");
  251.                     //        }
  252.                     //    }
  253.                     //    using (var fileStream = new FileStream(sZipFile, FileMode.Create))
  254.                     //    {
  255.                     //        memoryStream.Position = 0;
  256.                     //        memoryStream.WriteTo(fileStream);
  257.                     //    }
  258.                     //}
  259.  
  260.                     //from http://stackoverflow.com/questions/28360775/adding-large-files-to-io-compression-ziparchiveentry-throws-outofmemoryexception
  261.                     using (var zipFile = ZipFile.Open(sZipFile, ZipArchiveMode.Update))
  262.                     {
  263.                         var zipEntry = zipFile.CreateEntry(sFileName);
  264.                         using (var writer = new BinaryWriter(zipEntry.Open()))
  265.                         {
  266.                             using (FileStream fs = File.Open(sFilePath, FileMode.Open))
  267.                             {
  268.                                 var buffer = new byte[16 * 1024];
  269.                                 using (var data = new BinaryReader(fs))
  270.                                 {
  271.                                     int read;
  272.                                     while ((read = data.Read(buffer, 0, buffer.Length)) > 0)
  273.                                     {
  274.                                         writer.Write(buffer, 0, read);
  275.                                     }
  276.                                 }
  277.                             }
  278.                         }
  279.                     }
  280.  
  281.                     //Move File after zipping it
  282.                     BackupFile(sFilePath, sBackupFolder, sPrefixFolder);
  283.                 }
  284.                 bIsSuccess = true;
  285.             }
  286.             catch (Exception ex)
  287.             {
  288.                 throw ex;
  289.             }
  290.             return bIsSuccess;
  291.         }
  292.         #endregion
  293.     }
  294. }
Advertisement
Add Comment
Please, Sign In to add comment