Advertisement
Guest User

Untitled

a guest
May 25th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.08 KB | None | 0 0
  1. enter code here
  2.  
  3. #region Help: Introduction to the script task
  4. /* The Script Task allows you to perform virtually any operation that can be accomplished in
  5. * a .Net application within the context of an Integration Services control flow.
  6. *
  7. * Expand the other regions which have "Help" prefixes for examples of specific ways to use
  8. * Integration Services features within this script task. */
  9. #endregion
  10.  
  11.  
  12. #region Namespaces
  13. using System;
  14. using System.Data;
  15. using Microsoft.SqlServer.Dts.Runtime;
  16. using System.Windows.Forms;
  17. using System.Data.Common;
  18. using System.Net;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Threading;
  22. using System.Globalization;
  23. using System.Text.RegularExpressions;
  24. #endregion
  25.  
  26. namespace ST_77daef2dc8ba47778a2be8e3b40074f5
  27. {
  28. /// <summary>
  29. /// ScriptMain is the entry point class of the script. Do not change the name, attributes,
  30. /// or parent of this class.
  31. /// </summary>
  32. [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
  33. public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
  34. {
  35. #region Help: Using Integration Services variables and parameters in a script
  36. /* To use a variable in this script, first ensure that the variable has been added to
  37. * either the list contained in the ReadOnlyVariables property or the list contained in
  38. * the ReadWriteVariables property of this script task, according to whether or not your
  39. * code needs to write to the variable. To add the variable, save this script, close this instance of
  40. * Visual Studio, and update the ReadOnlyVariables and
  41. * ReadWriteVariables properties in the Script Transformation Editor window.
  42. * To use a parameter in this script, follow the same steps. Parameters are always read-only.
  43. *
  44. * Example of reading from a variable:
  45. * DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
  46. *
  47. * Example of writing to a variable:
  48. * Dts.Variables["User::myStringVariable"].Value = "new value";
  49. *
  50. * Example of reading from a package parameter:
  51. * int batchId = (int) Dts.Variables["$Package::batchId"].Value;
  52. *
  53. * Example of reading from a project parameter:
  54. * int batchId = (int) Dts.Variables["$Project::batchId"].Value;
  55. *
  56. * Example of reading from a sensitive project parameter:
  57. * int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
  58. * */
  59.  
  60. #endregion
  61.  
  62. #region Help: Firing Integration Services events from a script
  63. /* This script task can fire events for logging purposes.
  64. *
  65. * Example of firing an error event:
  66. * Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
  67. *
  68. * Example of firing an information event:
  69. * Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
  70. *
  71. * Example of firing a warning event:
  72. * Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
  73. * */
  74. #endregion
  75.  
  76. #region Help: Using Integration Services connection managers in a script
  77. /* Some types of connection managers can be used in this script task. See the topic
  78. * "Working with Connection Managers Programatically" for details.
  79. *
  80. * Example of using an ADO.Net connection manager:
  81. * object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
  82. * SqlConnection myADONETConnection = (SqlConnection)rawConnection;
  83. * //Use the connection in some code here, then release the connection
  84. * Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
  85. *
  86. * Example of using a File connection manager
  87. * object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
  88. * string filePath = (string)rawConnection;
  89. * //Use the connection in some code here, then release the connection
  90. * Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
  91. * */
  92. #endregion
  93.  
  94.  
  95. /// <summary>
  96. /// This method is called when this script task executes in the control flow.
  97. /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
  98. /// To open Help, press F1.
  99. /// </summary>
  100. public void Main()
  101. {
  102. //ftp Directory listing reg exp (for information)
  103. //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>.*)$");
  104. //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>.*)$");
  105.  
  106. //Get Package parameters
  107. string uri = (String)Dts.Variables["ftpURI"].Value;
  108. if (!uri.StartsWith(@"ftp://"))
  109. {
  110. uri = @"ftp://" + uri;
  111. }
  112. string user = (String)Dts.Variables["ftpUSER"].Value; //
  113. string pass = (String)Dts.Variables["ftpPASS"].Value; //
  114. string ftpTokenFilter = (String)Dts.Variables["ftpTOKENFILTER"].Value; //Filename with date parameters to be replaced in it. For example: 'TEST{YYYYMMDD}.TXT'
  115. bool bDeleteTokenFile = (bool)Dts.Variables["DeleteToken"].Value; //Indicates to delete the token file on the ftp server
  116.  
  117. bool isUnixStyle = false;
  118. string line = "";
  119. byte[] buffer = new byte[4096];
  120. bool isTokenFound = false;
  121. string filename = "";
  122. bool timeoutExcedeed = false;
  123. DateTime timeoutTime;
  124.  
  125. //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"...).
  126. string sParameterDate = substringBetween(ftpTokenFilter, "{", "}");
  127. if (sParameterDate != null)
  128. {
  129. ftpTokenFilter = ftpTokenFilter.Replace("{" + sParameterDate + "}", DateTime.Now.ToString(sParameterDate));
  130. }
  131.  
  132. //Logs
  133. FireInformation("Waiting for token file: '" + ftpTokenFilter + "' on ftp Server '" + uri + "'.");
  134.  
  135. //Keep start time for calculating the timeout
  136. timeoutTime = DateTime.Now.AddHours(6);
  137.  
  138. do
  139. {
  140. ftpWebRequest ftpRequest = (ftpWebRequest)WebRequest.Create(uri);
  141. ftpRequest.Credentials = new NetworkCredential(user, pass);
  142. ftpRequest.Method = WebRequestMethods.ftp.ListDirectoryDetails;
  143. ftpWebResponse dirresponse = (ftpWebResponse)ftpRequest.GetResponse();
  144. List<string> directories = new List<string>();
  145. using (StreamReader streamReader = new StreamReader(dirresponse.GetResponseStream()))
  146. {
  147. while (streamReader.Peek() >= 0)
  148. {
  149.  
  150. line = streamReader.ReadLine();
  151.  
  152. //If directory is listed in UNIX style
  153. if (isUnixStyle)
  154. {
  155. if (line.StartsWith("d") && (!line.EndsWith(".")))
  156. {
  157. //nothing
  158. }
  159. else if (line.StartsWith("-"))
  160. {
  161. filename = line.Substring(line.IndexOf(':') + 3).TrimStart();
  162. //if (filename.StartsWith(ftpTokenFilter + DateTime.Now.ToString("yyyy")))
  163. if (filename.StartsWith(ftpTokenFilter))
  164. {
  165. isTokenFound = true;
  166. break;
  167. }
  168. }
  169.  
  170. }
  171.  
  172. //Else directory is listed in WINDOWS style
  173. else
  174. {
  175. string data = line;
  176.  
  177. // Parse date
  178. data = data.Remove(0, 24);
  179.  
  180. // Parse <DIR>
  181. string dir = data.Substring(0, 5);
  182. bool isDirectory = dir.Equals("<dir>", StringComparison.InvariantCultureIgnoreCase);
  183. data = data.Remove(0, 5);
  184. data = data.Remove(0, 10);
  185.  
  186. // Parse name
  187. filename = data;
  188. if (isDirectory)
  189. {
  190. //nothing
  191. }
  192. else
  193. {
  194. //if (filename.StartsWith(ftpTokenFilter + DateTime.Now.ToString("yyyy")))
  195. if (filename.StartsWith(ftpTokenFilter))
  196. {
  197. isTokenFound = true;
  198. break;
  199. }
  200. }
  201. }
  202. }
  203.  
  204. streamReader.Close();
  205. }
  206. if (isTokenFound == false)
  207. {
  208. Thread.Sleep(60 * 1000); //Sleep 60sec
  209. }
  210.  
  211. //Calculate if the timeout is over
  212. timeoutExcedeed = (DateTime.Now > timeoutTime);
  213. }
  214. while ((isTokenFound == false) && (timeoutExcedeed == false));
  215.  
  216. //If token file is not found and timeout is over, raise an error
  217. if (!isTokenFound)
  218. {
  219. FireError("Timeout is over, token file '" + ftpTokenFilter + "' is not found on the ftp server '" + uri + "'.");
  220. Dts.TaskResult = (int)ScriptResults.Failure;
  221. }
  222. else
  223. {
  224. //Logs
  225. FireInformation("Token file '" + ftpTokenFilter + "' found.");
  226.  
  227. //Move the token file to a directory
  228. if (bDeleteTokenFile)
  229. {
  230. try
  231. {
  232. ftpWebRequest ftpRequest = (ftpWebRequest)WebRequest.Create(uri + filename);
  233. ftpRequest.Credentials = new NetworkCredential(user, pass);
  234. ftpRequest.Method = WebRequestMethods.ftp.DeleteFile;
  235. WebResponse response = ftpRequest.GetResponse();
  236. response.Close();
  237. }
  238. catch (Exception e)
  239. {
  240. FireInformation("Can't move the token file on the ftp Server (Raised exception is: " + e.Message);
  241. }
  242. }
  243.  
  244. Dts.TaskResult = (int)ScriptResults.Success;
  245. }
  246. }
  247.  
  248.  
  249. /// <summary>
  250. /// Replace a string between two delimiters.
  251. /// </summary>
  252. /// <param name="s">Original string.</param>
  253. /// <param name="s1">First delimiter to search for.</param>
  254. /// <param name="s2">Second delimiter to search for.</param>
  255. /// <returns></returns>
  256. private string substringBetween(string s, string s1, string s2)
  257. {
  258. int pFrom = s.IndexOf(s1) + s1.Length;
  259. if (pFrom >= 0)
  260. {
  261. int pTo = s.LastIndexOf(s2);
  262. if (pTo >= 0)
  263. {
  264. return s.Substring(pFrom, pTo - pFrom);
  265. }
  266. }
  267. return null;
  268. }
  269.  
  270.  
  271. #region DTS_LOG_FUNCTIONS
  272. private string _packageName = null;
  273. private bool _packageNameExistenceChecked = false;
  274. public string PackageName
  275. {
  276. get
  277. {
  278. if ((_packageName == null) && (!_packageNameExistenceChecked))
  279. {
  280. _packageName = getPackageName();
  281. _packageNameExistenceChecked = true;
  282. }
  283. return _packageName;
  284. }
  285. }
  286.  
  287. private bool fireAgain = true;
  288.  
  289. private void FireError(string message)
  290. {
  291. if (PackageName != null)
  292. Dts.Events.FireError(-1, PackageName, message, "", 0);
  293. else
  294. Dts.Events.FireError(-1, "", message, "", 0);
  295. }
  296.  
  297. private void FireInformation(string message, string component = "")
  298. {
  299. if (PackageName != null)
  300. Dts.Events.FireInformation(1, PackageName, message, "", 0, ref fireAgain);
  301. else
  302. Dts.Events.FireInformation(1, "", message, "", 0, ref fireAgain);
  303. }
  304.  
  305. private void FireWarning(string message, string component = "")
  306. {
  307. if (PackageName != null)
  308. Dts.Events.FireWarning(0, PackageName, message, "", 0);
  309. else
  310. Dts.Events.FireWarning(0, "", message, "", 0);
  311. }
  312.  
  313. private string getPackageName()
  314. {
  315. if (Dts.Variables.Contains("System::PackageName"))
  316. return (string)Dts.Variables["System::PackageName"].Value;
  317. else
  318. return null;
  319. }
  320. #endregion
  321.  
  322.  
  323. #region ScriptResults declaration
  324. /// <summary>
  325. /// This enum provides a convenient shorthand within the scope of this class for setting the
  326. /// result of the script.
  327. ///
  328. /// This code was generated automatically.
  329. /// </summary>
  330. enum ScriptResults
  331. {
  332. Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
  333. Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
  334. };
  335. #endregion
  336.  
  337. }
  338. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement