<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>script task Archives | ZappySys Blog</title>
	<atom:link href="https://zappysys.com/blog/tag/script-task/feed/" rel="self" type="application/rss+xml" />
	<link>https://zappysys.com/blog/tag/script-task/</link>
	<description>SSIS / ODBC Drivers / API Connectors for JSON, XML, Azure, Amazon AWS, Salesforce, MongoDB and more</description>
	<lastBuildDate>Sun, 01 May 2016 19:14:02 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.4.4</generator>

<image>
	<url>https://zappysys.com/blog/wp-content/uploads/2023/01/cropped-zappysys-symbol-large-32x32.png</url>
	<title>script task Archives | ZappySys Blog</title>
	<link>https://zappysys.com/blog/tag/script-task/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to count file columns in SSIS using C# Script</title>
		<link>https://zappysys.com/blog/how-to-count-file-columns-in-ssis-using-c-script/</link>
		
		<dc:creator><![CDATA[ZappySys]]></dc:creator>
		<pubDate>Sun, 01 May 2016 19:14:02 +0000</pubDate>
				<category><![CDATA[SSIS PowerPack]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[script task]]></category>
		<category><![CDATA[ssis]]></category>
		<guid isPermaLink="false">http://zappysys.com/blog/?p=473</guid>

					<description><![CDATA[<p>Here is the snippet which can be used to count total columns in your flat file. Below script assume that you have column count based on separator=comma. if you use different separator then just change script accordingly [crayon-69ea227531b14541501115/] &#160;</p>
<p>The post <a href="https://zappysys.com/blog/how-to-count-file-columns-in-ssis-using-c-script/">How to count file columns in SSIS using C# Script</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Here is the snippet which can be used to count total columns in your flat file.</p>
<p>Below script assume that you have column count based on separator=comma. if you use different separator then just change script accordingly</p><pre class="crayon-plain-tag">public void Main()
        {
            // TODO: Add your code here

            var colCnt = GetFileColumns("file1",',');
            MessageBox.Show("Your file has total " + colCnt + " columns");
            Dts.TaskResult = (int)ScriptResults.Success;
        }
        private int GetFileColumns(string connName,char colSeperator= ',')
        {
            var filePath=Dts.Connections[connName].ConnectionString;
            string firstline;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath))
            {
                 firstline= sr.ReadLine();
            }              
            var colArr=firstline.Split(new char[]{colSeperator});
            return colArr.Length;
        }</pre><p>
&nbsp;</p>
<p>The post <a href="https://zappysys.com/blog/how-to-count-file-columns-in-ssis-using-c-script/">How to count file columns in SSIS using C# Script</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SSIS check file is locked and wait until file is unlocked (C# Script)</title>
		<link>https://zappysys.com/blog/ssis-check-file-locked-wait-file-unlocked-c-script/</link>
		
		<dc:creator><![CDATA[ZappySys]]></dc:creator>
		<pubDate>Tue, 23 Feb 2016 13:58:18 +0000</pubDate>
				<category><![CDATA[SSIS Advanced File System Task]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[script task]]></category>
		<category><![CDATA[ssis]]></category>
		<category><![CDATA[ssis advanced file system task]]></category>
		<category><![CDATA[SSIS PowerPack]]></category>
		<category><![CDATA[ssis validation task]]></category>
		<guid isPermaLink="false">http://zappysys.com/blog/?p=362</guid>

					<description><![CDATA[<p>Introduction In this small blog post you will learn How to move files using SSIS Advanced File System Task and How to wait until file is unlocked using C# Script Task. How to check if file is locked (SSIS C# Script Task) If you want to check if file is locked in C# then below [&#8230;]</p>
<p>The post <a href="https://zappysys.com/blog/ssis-check-file-locked-wait-file-unlocked-c-script/">SSIS check file is locked and wait until file is unlocked (C# Script)</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Introduction</h2>
<p>In this small blog post you will learn How to move files using <a href="https://zappysys.com/products/ssis-powerpack/ssis-file-system-task-advanced/">SSIS Advanced File System Task</a> and <i>How to wait until file is unlocked</i> using <strong>C# Script Task</strong>.</p>
<h2>How to check if file is locked (SSIS C# Script Task)</h2>
<p>If you want to check if file is locked in C# then below code will do the trick. But no worry if you dont know C#. ZappySys SSIS PowerPack comes with two tasks which can solve this issue without coding. You can use <a href="https://zappysys.com/products/ssis-powerpack/ssis-file-system-task-advanced/">SSIS Advanced File System Task</a> with <strong>Get file lock status action</strong> or Use <a href="https://zappysys.com/products/ssis-powerpack/ssis-validation-task/">SSIS Validation Task</a> which has option to throw error on lock condition or you can continue by saving lock status into variable and continue without throwing error. </p>
<pre class="crayon-plain-tag">// Attempt to open the file exclusively. -- If you get erro means file is locked
using (FileStream fs = new FileStream(fullPath,
	FileMode.Open, FileAccess.ReadWrite,
	FileShare.None, 100))
{
	fs.ReadByte();

	// If we got this far the file is ready
	break;
}</pre> </p>
<h2>How to wait until file is unlocked (SSIS C# Script Task)</h2>
<p>Now lets check real example which will first check for locked file using <a href="https://zappysys.com/products/ssis-powerpack/ssis-validation-task/">SSIS Validation Task</a> and then if file is locked then  wait until file is unlocked (with some timeout hardcoded in script). </p>
<p>If specified wait time is reached then script will throw error. Once file is unlocked <a href="https://zappysys.com/products/ssis-powerpack/ssis-file-system-task-advanced/">SSIS Advanced File System Task</a> will copy file to target.</p>
<div id="attachment_368" style="width: 563px" class="wp-caption alignnone"><a href="//zappysys.com/blog/wp-content/uploads/2016/02/ssis-check-file-locked-wait-until-unlocked.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-368" src="//zappysys.com/blog/wp-content/uploads/2016/02/ssis-check-file-locked-wait-until-unlocked.png" alt="SSIS - How to check if file is locked. Wait until file is unlocked (C# Code - SSIS Script Task)." width="553" height="458" class="size-full wp-image-368" srcset="https://zappysys.com/blog/wp-content/uploads/2016/02/ssis-check-file-locked-wait-until-unlocked.png 553w, https://zappysys.com/blog/wp-content/uploads/2016/02/ssis-check-file-locked-wait-until-unlocked-300x248.png 300w" sizes="(max-width: 553px) 100vw, 553px" /></a><p id="caption-attachment-368" class="wp-caption-text">SSIS &#8211; How to check if file is locked. Wait until file is unlocked (C# Code &#8211; SSIS Script Task).</p></div>
<h3>SSIS Validation Task -Store file lock status into variable</h3>
<div id="attachment_367" style="width: 550px" class="wp-caption alignnone"><a href="//zappysys.com/blog/wp-content/uploads/2016/02/ssis-validation-task-check-if-file-is-locked.png"><img decoding="async" aria-describedby="caption-attachment-367" src="//zappysys.com/blog/wp-content/uploads/2016/02/ssis-validation-task-check-if-file-is-locked.png" alt="SSIS Validation Task -Check if file is locked. Save status to variable or throw error." width="540" height="567" class="size-full wp-image-367" srcset="https://zappysys.com/blog/wp-content/uploads/2016/02/ssis-validation-task-check-if-file-is-locked.png 540w, https://zappysys.com/blog/wp-content/uploads/2016/02/ssis-validation-task-check-if-file-is-locked-286x300.png 286w" sizes="(max-width: 540px) 100vw, 540px" /></a><p id="caption-attachment-367" class="wp-caption-text">SSIS Validation Task -Check if file is locked. Save status to variable or throw error.</p></div>
<h3>SSIS Advanced File System Task &#8211; Copy, Move, Rename, Delete multiple files</h3>
<div id="attachment_366" style="width: 711px" class="wp-caption alignnone"><a href="//zappysys.com/blog/wp-content/uploads/2016/02/ssis-advanced-file-system-task-how-to-copy-move-files.png"><img decoding="async" aria-describedby="caption-attachment-366" src="//zappysys.com/blog/wp-content/uploads/2016/02/ssis-advanced-file-system-task-how-to-copy-move-files.png" alt="SSIS Advanced File System Task. Copy, Move, Rename, Delete multiple files" width="701" height="559" class="size-full wp-image-366" srcset="https://zappysys.com/blog/wp-content/uploads/2016/02/ssis-advanced-file-system-task-how-to-copy-move-files.png 701w, https://zappysys.com/blog/wp-content/uploads/2016/02/ssis-advanced-file-system-task-how-to-copy-move-files-300x239.png 300w" sizes="(max-width: 701px) 100vw, 701px" /></a><p id="caption-attachment-366" class="wp-caption-text">SSIS Advanced File System Task. Copy, Move, Rename, Delete multiple files</p></div>
<h3>SSIS C# Script Task &#8211; Check file is locked, wait until file is unlocked</h3>
<pre class="crayon-plain-tag">#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
#endregion

namespace ST_334a75922c6a47a5b4ac21ee8e4e5fff
{
	[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
	public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
	{
		public void Main()
		{
			// TODO: Add your code here
            try
            {
                var file = Dts.Variables["User::filePath"].Value.ToString();

                bool continueIfFileMissing = false;
                if (!System.IO.File.Exists(file))
                {
                    if (continueIfFileMissing)
                    {
                        Dts.TaskResult = (int)ScriptResults.Success;
                        return;
                    }
                    LogError("File not found: " + file);
                    Dts.TaskResult = (int)ScriptResults.Failure;
                }
                    
                WaitForFile(file, maxWaitInSec:30);
                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch (Exception ex)
            {
                LogError(ex.Message);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }           
			
		}
        /// &lt;summary&gt;
        /// Blocks until the file is not locked any more.
        /// &lt;/summary&gt;
        /// &lt;param name="fullPath"&gt;&lt;/param&gt;
        bool WaitForFile(string fullPath,int maxWaitInSec)
        {
            int numTries = 0;
            while (true)
            {
                ++numTries;
                try
                {
                    // Attempt to open the file exclusively.
                    using (FileStream fs = new FileStream(fullPath,
                        FileMode.Open, FileAccess.ReadWrite,
                        FileShare.None, 100))
                    {
                        fs.ReadByte();

                        // If we got this far the file is ready
                        break;
                    }
                }
                catch (Exception ex)
                {
                   if(numTries==1 ||  numTries % 20 ==0 )
                      LogWarning(string.Format("WaitForFile {0} failed to get an exclusive lock: {1}",fullPath, ex.Message));

                    //if (numTries &gt; 10)
                    //{
                    //    LogWarning(string.Format(
                    //        "WaitForFile {0} giving up after 10 tries",
                    //        fullPath));
                    //    return false;
                    //}

                   if (numTries &gt;= maxWaitInSec * 2)
                   {
                       throw new Exception("Max wait time reached for file : " + fullPath + ". Waited for " + maxWaitInSec + " seconds but lock not released");
                   }

                    // Wait for the lock to be released
                    System.Threading.Thread.Sleep(500);
                }

                
            }

            LogInformation( string.Format( "WaitForFile {0} returning true after {1} tries",fullPath, numTries));
            return true;
        }

        private void LogInformation(string msg)
        {
            bool again = false;
            Dts.Events.FireInformation(0, "ScriptTask", msg, "", 0,ref again);
        }
        
        private void LogError(string msg)
        {
            Dts.Events.FireError(0, "ScriptTask", msg, "", 0);
        }
        private void LogWarning(string msg)
        {
            Dts.Events.FireWarning(0, "ScriptTask", msg, "", 0);
        }
        #region ScriptResults declaration
        /// &lt;summary&gt;
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// &lt;/summary&gt;
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

	}
}</pre> </p>
<h2>Download Sample Package</h2>
<p>Below sample will work only if you have <a href="https://zappysys.com/products/ssis-powerpack/">SSIS PowerPack</a> Installed. Download it <a href="https://zappysys.com/products/ssis-powerpack/download/">from here</a> it will take only 1 minute to install<br />
<a href="//zappysys.com/downloads/files/ssis/2012/AdvancedFileSystemTask_Copy_Locked.zip">Download SSIS 2012 &#8211; Sample Package (Process Locked file)</a></p>
<h2>Conclusion</h2>
<p>Processing and detecting locked files in SSIS can be tricky but using small C# script it can save you some headache. Download <a href="https://zappysys.com/products/ssis-powerpack/ssis-file-system-task-advanced/">Advanced File System Task</a> to try many options not available in native File System Task.</p>
<p>Other Keywords:<br />
<i>Check locked files in SSIS</i><br />
<i>How to check whether file is locked or not in SSIS</i><br />
<i>Detect locked file in SSIS</i><br />
<i>Wait until file is unlocked using C# script</i><br />
<i>How to handle file locking issue in SSIS using C# script</i></p>
<p>The post <a href="https://zappysys.com/blog/ssis-check-file-locked-wait-file-unlocked-c-script/">SSIS check file is locked and wait until file is unlocked (C# Script)</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>SSIS Code &#8211; Check URL Exists using C# Script &#8211; 404 Error</title>
		<link>https://zappysys.com/blog/ssis-code-check-url-exists-using-c-script-404-error/</link>
		
		<dc:creator><![CDATA[ZappySys]]></dc:creator>
		<pubDate>Wed, 11 Nov 2015 15:56:18 +0000</pubDate>
				<category><![CDATA[SSIS PowerPack]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[json source]]></category>
		<category><![CDATA[rest api]]></category>
		<category><![CDATA[script task]]></category>
		<guid isPermaLink="false">http://zappysys.com/blog/?p=146</guid>

					<description><![CDATA[<p>In this post you will learn how to use SSIS Script Task (C# Code) to detect specific URL found or not (Detect HTTP 404 Error) If you using SSIS JSON Source or our REST API Task then if URL/Document you trying to read not found then server may return 404 (Not Found) Exception. In order [&#8230;]</p>
<p>The post <a href="https://zappysys.com/blog/ssis-code-check-url-exists-using-c-script-404-error/">SSIS Code &#8211; Check URL Exists using C# Script &#8211; 404 Error</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this post you will learn how to use <strong>SSIS Script Task</strong> (<strong>C# Code</strong>) to detect specific URL found or not (<strong>Detect HTTP 404 Error</strong>)</p>
<p>If you using <a href="//zappysys.com/products/ssis-powerpack/ssis-json-file-source/">SSIS JSON Source</a> or our <a href="//zappysys.com/products/ssis-powerpack/ssis-rest-api-web-service-task/">REST API Task </a>then if URL/Document you trying to read not found then server may return 404 (Not Found) Exception. In order to handle this error gracefully you can use following Script to store status in a variable and then you can use conditional Control Flow to Skip data loading from Web Service.</p>
<p>Step1: Drag Script Task from toolbox<br />
Step2: Select Language as <strong>C#</strong><br />
Step3: Select Readonly variable (In this case &#8220;User::url&#8221; &#8211; String Type)<br />
Step4: Select ReadWrite variable (In this case &#8220;User::found&#8221; &#8211; Boolean Type)<br />
Step5: Edit code and paste following script in your script task</p>
<div id="attachment_147" style="width: 598px" class="wp-caption alignnone"><a href="//zappysys.com/blog/wp-content/uploads/2015/11/ssis-check-url-exists-catch-404-error.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-147" class="size-full wp-image-147" src="//zappysys.com/blog/wp-content/uploads/2015/11/ssis-check-url-exists-catch-404-error.png" alt="SSIS C# Code - Check URL Exists (Catch 404 Not Found Error) " width="588" height="403" srcset="https://zappysys.com/blog/wp-content/uploads/2015/11/ssis-check-url-exists-catch-404-error.png 588w, https://zappysys.com/blog/wp-content/uploads/2015/11/ssis-check-url-exists-catch-404-error-300x206.png 300w" sizes="(max-width: 588px) 100vw, 588px" /></a><p id="caption-attachment-147" class="wp-caption-text">SSIS C# Code &#8211; Check URL Exists (Catch 404 Not Found Error)</p></div>
<h2>C# Code: Check URL Exists (Detect 404 Error)</h2>
<pre class="crayon-plain-tag">public void Main()
	{
		// TODO: Add your code here
            Dts.Variables["found"].Value = UrlFound(Dts.Variables["url"].Value.ToString());
		Dts.TaskResult = (int)ScriptResults.Success;
	}

        private bool UrlFound(string url)
        {
            try
            {
                var request = WebRequest.Create(url);
                var response = request.GetResponse();
                return true;
            }
            catch (WebException we)
            {
                HttpWebResponse errorResponse = we.Response as HttpWebResponse;
                if (errorResponse != null)
                    if (errorResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        return false;
                    }
                    else
                        throw; //we only look for 404 Error
            }
            return false;
        }</pre>
<p>The post <a href="https://zappysys.com/blog/ssis-code-check-url-exists-using-c-script-404-error/">SSIS Code &#8211; Check URL Exists using C# Script &#8211; 404 Error</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
