Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- enter code here
- #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
- #region Namespaces
- using System;
- using System.Data;
- using Microsoft.SqlServer.Dts.Runtime;
- using System.Windows.Forms;
- using System.Data.Common;
- using System.Net;
- using System.Collections.Generic;
- using System.IO;
- using System.Threading;
- using System.Globalization;
- using System.Text.RegularExpressions;
- #endregion
- namespace ST_77daef2dc8ba47778a2be8e3b40074f5
- {
- /// <summary>
- /// ScriptMain is the entry point class of the script. Do not change the name, attributes,
- /// or parent of this class.
- /// </summary>
- [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
- /// <summary>
- /// 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.
- /// </summary>
- public void Main()
- {
- //ftp Directory listing reg exp (for information)
- //Regex unixStyle = new Regex(@"^(?<dir>[-dl])(?<ownerSec>[-r][-w][-x])(?<groupSec>[-r][-w][-x])(?<everyoneSec>[-r][-w][-x])s+(?:d)s+(?<owner>w+)s+(?<group>w+)s+(?<size>d+)s+(?<month>w+)s+(?<day>d{1,2})s+(?<hour>d{1,2}):(?<minutes>d{1,2})s+(?<name>.*)$");
- //Regex winStyle = new Regex(@"^(?<month>d{1,2})-(?<day>d{1,2})-(?<year>d{1,2})s+(?<hour>d{1,2}):(?<minutes>d{1,2})(?<ampm>am|pm)s+(?<dir>[<]dir[>])?s+(?<size>d+)?s+(?<name>.*)$");
- //Get Package parameters
- string uri = (String)Dts.Variables["ftpURI"].Value;
- if (!uri.StartsWith(@"ftp://"))
- {
- uri = @"ftp://" + uri;
- }
- string user = (String)Dts.Variables["ftpUSER"].Value; //
- string pass = (String)Dts.Variables["ftpPASS"].Value; //
- string ftpTokenFilter = (String)Dts.Variables["ftpTOKENFILTER"].Value; //Filename with date parameters to be replaced in it. For example: 'TEST{YYYYMMDD}.TXT'
- bool bDeleteTokenFile = (bool)Dts.Variables["DeleteToken"].Value; //Indicates to delete the token file on the ftp server
- bool isUnixStyle = false;
- string line = "";
- byte[] buffer = new byte[4096];
- bool isTokenFound = false;
- string filename = "";
- bool timeoutExcedeed = false;
- DateTime timeoutTime;
- //Replace the parameters in the token filename: the parameters are in brackets "{...}", and the parameter value is a DateTime format (for ex: "YYYY", "YYMMDD", "YYYYMMDD"...).
- string sParameterDate = substringBetween(ftpTokenFilter, "{", "}");
- if (sParameterDate != null)
- {
- ftpTokenFilter = ftpTokenFilter.Replace("{" + sParameterDate + "}", DateTime.Now.ToString(sParameterDate));
- }
- //Logs
- FireInformation("Waiting for token file: '" + ftpTokenFilter + "' on ftp Server '" + uri + "'.");
- //Keep start time for calculating the timeout
- timeoutTime = DateTime.Now.AddHours(6);
- do
- {
- ftpWebRequest ftpRequest = (ftpWebRequest)WebRequest.Create(uri);
- ftpRequest.Credentials = new NetworkCredential(user, pass);
- ftpRequest.Method = WebRequestMethods.ftp.ListDirectoryDetails;
- ftpWebResponse dirresponse = (ftpWebResponse)ftpRequest.GetResponse();
- List<string> directories = new List<string>();
- using (StreamReader streamReader = new StreamReader(dirresponse.GetResponseStream()))
- {
- while (streamReader.Peek() >= 0)
- {
- line = streamReader.ReadLine();
- //If directory is listed in UNIX style
- if (isUnixStyle)
- {
- if (line.StartsWith("d") && (!line.EndsWith(".")))
- {
- //nothing
- }
- else if (line.StartsWith("-"))
- {
- filename = line.Substring(line.IndexOf(':') + 3).TrimStart();
- //if (filename.StartsWith(ftpTokenFilter + DateTime.Now.ToString("yyyy")))
- if (filename.StartsWith(ftpTokenFilter))
- {
- isTokenFound = true;
- break;
- }
- }
- }
- //Else directory is listed in WINDOWS style
- else
- {
- string data = line;
- // Parse date
- data = data.Remove(0, 24);
- // Parse <DIR>
- string dir = data.Substring(0, 5);
- bool isDirectory = dir.Equals("<dir>", StringComparison.InvariantCultureIgnoreCase);
- data = data.Remove(0, 5);
- data = data.Remove(0, 10);
- // Parse name
- filename = data;
- if (isDirectory)
- {
- //nothing
- }
- else
- {
- //if (filename.StartsWith(ftpTokenFilter + DateTime.Now.ToString("yyyy")))
- if (filename.StartsWith(ftpTokenFilter))
- {
- isTokenFound = true;
- break;
- }
- }
- }
- }
- streamReader.Close();
- }
- if (isTokenFound == false)
- {
- Thread.Sleep(60 * 1000); //Sleep 60sec
- }
- //Calculate if the timeout is over
- timeoutExcedeed = (DateTime.Now > timeoutTime);
- }
- while ((isTokenFound == false) && (timeoutExcedeed == false));
- //If token file is not found and timeout is over, raise an error
- if (!isTokenFound)
- {
- FireError("Timeout is over, token file '" + ftpTokenFilter + "' is not found on the ftp server '" + uri + "'.");
- Dts.TaskResult = (int)ScriptResults.Failure;
- }
- else
- {
- //Logs
- FireInformation("Token file '" + ftpTokenFilter + "' found.");
- //Move the token file to a directory
- if (bDeleteTokenFile)
- {
- try
- {
- ftpWebRequest ftpRequest = (ftpWebRequest)WebRequest.Create(uri + filename);
- ftpRequest.Credentials = new NetworkCredential(user, pass);
- ftpRequest.Method = WebRequestMethods.ftp.DeleteFile;
- WebResponse response = ftpRequest.GetResponse();
- response.Close();
- }
- catch (Exception e)
- {
- FireInformation("Can't move the token file on the ftp Server (Raised exception is: " + e.Message);
- }
- }
- Dts.TaskResult = (int)ScriptResults.Success;
- }
- }
- /// <summary>
- /// Replace a string between two delimiters.
- /// </summary>
- /// <param name="s">Original string.</param>
- /// <param name="s1">First delimiter to search for.</param>
- /// <param name="s2">Second delimiter to search for.</param>
- /// <returns></returns>
- private string substringBetween(string s, string s1, string s2)
- {
- int pFrom = s.IndexOf(s1) + s1.Length;
- if (pFrom >= 0)
- {
- int pTo = s.LastIndexOf(s2);
- if (pTo >= 0)
- {
- return s.Substring(pFrom, pTo - pFrom);
- }
- }
- return null;
- }
- #region DTS_LOG_FUNCTIONS
- private string _packageName = null;
- private bool _packageNameExistenceChecked = false;
- public string PackageName
- {
- get
- {
- if ((_packageName == null) && (!_packageNameExistenceChecked))
- {
- _packageName = getPackageName();
- _packageNameExistenceChecked = true;
- }
- return _packageName;
- }
- }
- private bool fireAgain = true;
- private void FireError(string message)
- {
- if (PackageName != null)
- Dts.Events.FireError(-1, PackageName, message, "", 0);
- else
- Dts.Events.FireError(-1, "", message, "", 0);
- }
- private void FireInformation(string message, string component = "")
- {
- if (PackageName != null)
- Dts.Events.FireInformation(1, PackageName, message, "", 0, ref fireAgain);
- else
- Dts.Events.FireInformation(1, "", message, "", 0, ref fireAgain);
- }
- private void FireWarning(string message, string component = "")
- {
- if (PackageName != null)
- Dts.Events.FireWarning(0, PackageName, message, "", 0);
- else
- Dts.Events.FireWarning(0, "", message, "", 0);
- }
- private string getPackageName()
- {
- if (Dts.Variables.Contains("System::PackageName"))
- return (string)Dts.Variables["System::PackageName"].Value;
- else
- return null;
- }
- #endregion
- #region ScriptResults declaration
- /// <summary>
- /// This enum provides a convenient shorthand within the scope of this class for setting the
- /// result of the script.
- ///
- /// This code was generated automatically.
- /// </summary>
- enum ScriptResults
- {
- Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
- Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
- };
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement