<?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>c# Archives | ZappySys Blog</title>
	<atom:link href="https://zappysys.com/blog/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>https://zappysys.com/blog/tag/c/</link>
	<description>SSIS / ODBC Drivers / API Connectors for JSON, XML, Azure, Amazon AWS, Salesforce, MongoDB and more</description>
	<lastBuildDate>Tue, 06 Feb 2024 12:11:43 +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>c# Archives | ZappySys Blog</title>
	<link>https://zappysys.com/blog/tag/c/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to export REST API  to CSV using c# or Python</title>
		<link>https://zappysys.com/blog/how-to-export-rest-api-to-csv/</link>
		
		<dc:creator><![CDATA[ZappySys Team]]></dc:creator>
		<pubDate>Sat, 30 Jun 2018 03:02:59 +0000</pubDate>
				<category><![CDATA[C# (CSharp)]]></category>
		<category><![CDATA[JSON File / REST API Driver]]></category>
		<category><![CDATA[ODBC PowerPack]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[export]]></category>
		<category><![CDATA[import]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[rest api]]></category>
		<guid isPermaLink="false">https://zappysys.com/blog/?p=4250</guid>

					<description><![CDATA[<p>Introduction to export REST API to CSV Export REST API to CSV is in some cases necessary to process the data because many tools can handle CSV files. In this new article, we will show different ways to export the data. The first example will do it using C#. The second example with use Python. Let&#8217;s take a [&#8230;]</p>
<p>The post <a href="https://zappysys.com/blog/how-to-export-rest-api-to-csv/">How to export REST API  to CSV using c# or Python</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Introduction to export REST API to CSV</h2>
<p><a href="https://zappysys.com/blog/wp-content/uploads/2018/06/REST-API-icon.jpg"><img decoding="async" class=" wp-image-4254 alignleft" src="https://zappysys.com/blog/wp-content/uploads/2018/06/REST-API-icon-150x150.jpg" alt="Logo REST API" width="82" height="82" /></a>Export REST API to CSV is in some cases necessary to process the data because many tools can handle CSV files. In this new article, we will show different ways to export the data. The first example will do it using C#. The second example with use Python. Let&#8217;s take a look at these examples.</p>
<h2></h2>
<h2>Requirements to export REST API to CSV</h2>
<ol>
<li>First of all, you will need <a href="https://zappysys.com/products/odbc-powerpack/download/" target="_blank" rel="noopener">ZappySys ODBC PowerPack</a> installed.</li>
<li>Secondly, you will require Visual Studio installed for the C# example.</li>
<li>Finally, it is necessary Python installed for the Python example.</li>
</ol>
<h3>Export REST API to CSV using C#</h3>
<p>C# is a pretty popular programing language. In the first example, we will show how to display the REST API information to a CSV file named. Let&#8217;s take a look at the code:</p>
<ol>
<li>First of all, we will connect to REST API using a connection to the following Data Path:<br />
<pre class="crayon-plain-tag">https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json</pre>
<pre class="crayon-plain-tag">using (OdbcConnection conn = 
      new OdbcConnection("Driver={ZappySys JSON Driver};DataPath='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json';"))</pre>
</li>
<li>Secondly, we create a connection using a file stream. We will save the results to a file in the c:\sql\sample.csv:<br />
<pre class="crayon-plain-tag">FileStream fs = new FileStream("C:\\sql\\sample.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
StringBuilder output = new StringBuilder();</pre>
</li>
<li>Also, we will add a query to REST API. Note that with the ZappySys ODBC PowerPack, you can do a simple SQL query to get REST API data. This is pretty simple and intuitive:<br />
<pre class="crayon-plain-tag">OdbcCommand cmd = new OdbcCommand(
     @"SELECT  CustomerID,CompanyName FROM value", conn);</pre>
</li>
<li>In addition, we will read the data and close the connections:<br />
<pre class="crayon-plain-tag">conn.Close();  
writer.Close(); 
fs.Close();</pre>
</li>
<li>The complete code will be the following:<br />
<pre class="crayon-plain-tag">using System;
using System.IO;
using System.Data.Odbc;

public class Program
{
    public static void Main()
    {
        var outpath = @"C:\temp\sample.txt";

        using (var conn = new OdbcConnection("Driver={ZappySys JSON Driver};DataPath='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json';"))
        {
            conn.Open();
            var cmd = new OdbcCommand(@"SELECT CustomerID,CompanyName FROM $ WITH(Filter='$.value[*]')", conn);
            
            //Increases the timeout duration from the default 30 seconds, which may be insufficient in certain scenarios.
            cmd.CommandTimeout=600; // 600-seconds
            
            var rdr = cmd.ExecuteReader();

            using (var fs = new FileStream(outpath, FileMode.Create))
            {
                using (var writer = new StreamWriter(fs))
                {
                    //write file header
                    writer.WriteLine("CustomerID,CompanyName");

                    while (rdr.Read())
                    {
                        //write file row
                        writer.WriteLine("{0},{1}", rdr["CustomerID"], rdr["CompanyName"]);
                    }
                    conn.Close(); //close connection
                    writer.Close();
                    fs.Close();
                }
            }
        }

        //Read from file and display the content
        Console.Write(File.ReadAllText(outpath));

        Console.WriteLine("\r\n===== Press any key to end the program =====\r\n");
        Console.Read();
    }
}</pre>
&nbsp;</li>
<li>Finally, you will be able to see the file created:
<div id="attachment_4258" style="width: 160px" class="wp-caption aligncenter"><a href="https://zappysys.com/blog/wp-content/uploads/2018/06/REST-API-exported-to-CSV-file.png"><img decoding="async" aria-describedby="caption-attachment-4258" class="size-thumbnail wp-image-4258" src="https://zappysys.com/blog/wp-content/uploads/2018/06/REST-API-exported-to-CSV-file-150x150.png" alt="Export REST API to CSV" width="150" height="150" /></a><p id="caption-attachment-4258" class="wp-caption-text">REST API into CSV</p></div></li>
</ol>
<h3>Export REST API to CSV using Python</h3>
<p>Python is another really popular programming language. The popularity is growing a lot. In this example, we will learn how to Export REST API to CSV using Python.</p>
<ol>
<li>First of all, you will need to install Pip if not included in Python. Pip is Package Installer.<br />
For instructions about the installation, refer to <a href="https://pip.pypa.io/en/stable/installing/" target="_blank" rel="noopener">this link.</a></li>
<li>Secondly, you will also need the pyodbc. The pyodbc allows connecting to ODBC using Python. To install it go to the scripts folder of Python where Python is installed and run this command:pip install pyodbc.</li>
<li>Once that pyodbc is installed, we will run the following code:<strong>Full Code</strong><br />
<pre class="crayon-plain-tag">import csv
import pyodbc

conn = pyodbc.connect(
    r'DRIVER={ZappySys JSON Driver};'
    )
cursor = conn.cursor()	
rows = cursor.execute("SELECT CustomerID,CompanyName FROM value WHERE COUNTRY='Germany' WITH (SRC='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json')") 
with open(r'C:\sql\cus2.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([x[0] for x in cursor.description])  
    for row in rows:
        writer.writerow(row)</pre>
</li>
<li>Now lets&#8217;s understand parts of above code. We have used the csv and pyodbc modules in the code:<br />
<pre class="crayon-plain-tag">import csv
import pyodbc</pre>
</li>
<li>Also, we connect to the <a href="https://zappysys.com/products/odbc-powerpack/" target="_blank" rel="noopener">ZappySys ODBC Driver</a>:<br />
<pre class="crayon-plain-tag">conn = pyodbc.connect(
r'DRIVER={ZappySys JSON Driver};'
)</pre>
</li>
<li>In addition, we have used a cursor to get the rows and send a SQL query to get data from the REST API:<br />
<pre class="crayon-plain-tag">cursor = conn.cursor() 
rows = cursor.execute("SELECT CustomerID,CompanyName FROM value 
WHERE Country='Germany' WITH 
(SRC='https://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json')")</pre>
</li>
<li>Following code is to open the CSV file stream:<br />
<pre class="crayon-plain-tag">with open(r'C:\sql\customer.csv', 'w', newline='') as csvfile:</pre>
</li>
<li>Finally, we will write the data from REST API into the CSV file:<br />
<pre class="crayon-plain-tag">writer = csv.writer(csvfile)
writer.writerow([x[0] for x in cursor.description]) 
for row in rows:
writer.writerow(row)</pre>
</li>
<li>To conclude, if everything is OK, you will be able to see the created CSV file:
<div id="attachment_4264" style="width: 160px" class="wp-caption aligncenter"><a href="https://zappysys.com/blog/wp-content/uploads/2018/06/CSV-file-created.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4264" class="size-thumbnail wp-image-4264" src="https://zappysys.com/blog/wp-content/uploads/2018/06/CSV-file-created-150x106.png" alt="REST API ODBC Python" width="150" height="106" /></a><p id="caption-attachment-4264" class="wp-caption-text">Python code REST API</p></div>
<div class="mceTemp"></div>
</li>
</ol>
<h2></h2>
<h2>Using ODBC DSN in Connection String</h2>
<p>So far we have seen DSN less connection string approach for ODBC Driver but now lets look at another way to use ODBC Driver in your C# or Python code. You can define many settings on DSN Datasource rather than setting in the ConnectionString.</p>
<h3>Configure DSN for REST API Connection</h3>
<ol>
<li>First of all, we will access the following URL:<br />
<pre class="crayon-plain-tag">https://services.odata.org/V3/Northwind/Northwind.svc/Orders?$format=json</pre>
</li>
<li>Secondly, in the windows start menu, Search for “ODBC” open the ODBC Data Sources.</li>
<li>Also, in the ODBC Administrator, press Add and select the ZappySys JSON<br />
Driver:</p>
<div id="attachment_4421" style="width: 471px" class="wp-caption aligncenter"><a href="https://zappysys.com/blog/wp-content/uploads/2018/07/create-new-data-source-zappysys-json-driver.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4421" class="wp-image-4421 size-full" src="https://zappysys.com/blog/wp-content/uploads/2018/07/create-new-data-source-zappysys-json-driver.png" alt="REST API ODBC " width="461" height="346" srcset="https://zappysys.com/blog/wp-content/uploads/2018/07/create-new-data-source-zappysys-json-driver.png 461w, https://zappysys.com/blog/wp-content/uploads/2018/07/create-new-data-source-zappysys-json-driver-300x225.png 300w" sizes="(max-width: 461px) 100vw, 461px" /></a><p id="caption-attachment-4421" class="wp-caption-text">Add ODBC JSON</p></div></li>
<li>Finally, specify the URL of step 1 and save the configuration:
<div id="attachment_4422" style="width: 812px" class="wp-caption aligncenter"><a href="https://zappysys.com/blog/wp-content/uploads/2018/07/Qlik-odata-url-odbc.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4422" class="size-full wp-image-4422" src="https://zappysys.com/blog/wp-content/uploads/2018/07/Qlik-odata-url-odbc.png" alt="REST API" width="802" height="702" srcset="https://zappysys.com/blog/wp-content/uploads/2018/07/Qlik-odata-url-odbc.png 802w, https://zappysys.com/blog/wp-content/uploads/2018/07/Qlik-odata-url-odbc-300x263.png 300w, https://zappysys.com/blog/wp-content/uploads/2018/07/Qlik-odata-url-odbc-768x672.png 768w" sizes="(max-width: 802px) 100vw, 802px" /></a><p id="caption-attachment-4422" class="wp-caption-text">URL ODBC</p></div></li>
</ol>
<h3>Using ODBC DSN in C# Code</h3>
<p>Now to use ODBC DSN you created simply change our previous C# Code as below (Just one line)</p><pre class="crayon-plain-tag">using (var conn = new OdbcConnection("DSN=Your-DSN-Name-Goes-Here"))
{
    conn.Open();
    ...........
    ...........
    ...........</pre><p>
<div id="attachment_4467" style="width: 883px" class="wp-caption alignnone"><a href="https://zappysys.com/blog/wp-content/uploads/2018/06/call-rest-api-in-csharp-odbc-json-driver.png"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-4467" class="size-full wp-image-4467" src="https://zappysys.com/blog/wp-content/uploads/2018/06/call-rest-api-in-csharp-odbc-json-driver.png" alt="Using ODBC DSN in C# code to call REST API" width="873" height="598" srcset="https://zappysys.com/blog/wp-content/uploads/2018/06/call-rest-api-in-csharp-odbc-json-driver.png 873w, https://zappysys.com/blog/wp-content/uploads/2018/06/call-rest-api-in-csharp-odbc-json-driver-300x205.png 300w, https://zappysys.com/blog/wp-content/uploads/2018/06/call-rest-api-in-csharp-odbc-json-driver-768x526.png 768w" sizes="(max-width: 873px) 100vw, 873px" /></a><p id="caption-attachment-4467" class="wp-caption-text">Using ODBC DSN in C# code to call REST API</p></div>
<h3>Using ODBC DSN in Python Code</h3>
<p>Now to use ODBC DSN you created simply change our previous C# Code as below (Just one line)</p><pre class="crayon-plain-tag">conn = pyodbc.connect(
    r'DSN=Your-DSN-name-Goes-Here;'
    )
	
	...........
	...........
	...........</pre><p>
&nbsp;</p>
<h2><span id="ZappySys_JSON_REST_API_Driver_Query_Examples">ZappySys JSON /REST API Driver Query Examples</span></h2>
<p>Reading from XML files or API can be done using the same way as previous sections except you have to use ZappySys XML Driver. Read help file here to <a href="https://zappysys.com/onlinehelp/odbc-powerpack/scr/json-odbc-driver-sql-query-examples.htm" target="_blank" rel="noopener">see json query examples</a>.</p>
<h2><span id="ZappySysXML_SOAP_Driver_Query_Examples">ZappySys XML / SOAP Driver Query Examples</span></h2>
<p>Reading from XML files or API can be done using the same way as previous sections except you have to use ZappySys XML Driver. Read help file here to <a href="https://zappysys.com/onlinehelp/odbc-powerpack/scr/xml-odbc-driver-sql-query-examples.htm" target="_blank" rel="noopener">see xml query examples</a>.</p>
<h2></h2>
<h2>Conclusion</h2>
<p>To conclude, in this article, we show how to access REST API using C# and Python. We used the ZappySys ODBC PowerPack that allows accessing to REST API data and JSON files using SQL queries. It is possible to create simple SQL queries and access the data. It is also possible to access to XML files and Web API with this tool. If you liked this tool you can test the <a href="https://zappysys.com/products/odbc-powerpack/download/" target="_blank" rel="noopener">ZappySys ODBC PowerPack here</a>.</p>
<h2>References</h2>
<p>Finally, if you want to read more about this topic, refer to these links:</p>
<ul>
<li><a href="https://zappysys.com/products/odbc-powerpack/download/" target="_blank" rel="noopener">Download ZappySys ODBC PowerPack Installer</a></li>
<li><a href="https://support.microsoft.com/en-us/help/310988/how-to-use-the-odbc-net-managed-provider-in-visual-c-net-and-connectio" target="_blank" rel="noopener">How To Use the ODBC .NET Managed Provider in Visual C# .NET and Connection Strings</a></li>
<li><a href="https://wiki.python.org/moin/ODBC" target="_blank" rel="noopener">Python ODBC Wiki</a></li>
</ul>
<p>&nbsp;</p>
<p>The post <a href="https://zappysys.com/blog/how-to-export-rest-api-to-csv/">How to export REST API  to CSV using c# or Python</a> appeared first on <a href="https://zappysys.com/blog">ZappySys Blog</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<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-69d5a31197c40314069676/] &#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 loading="lazy" 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 loading="lazy" 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 loading="lazy" 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>
