<?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>Dot Net Thoughts &#187; SQL Server</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>thoughts about .Net, WPF, Sharepoint, Javascript and more.</description>
	<lastBuildDate>Wed, 28 Jul 2010 09:59:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Implementing Paging in SQL Server 2005 Stored Procedures</title>
		<link>http://www.dotnetthoughts.net/2010/04/29/implementing-paging-in-sql-server-2005-stored-procedures/</link>
		<comments>http://www.dotnetthoughts.net/2010/04/29/implementing-paging-in-sql-server-2005-stored-procedures/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 15:21:24 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Paging]]></category>
		<category><![CDATA[SQL 2005]]></category>
		<category><![CDATA[Stored Procedure]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=870</guid>
		<description><![CDATA[Normally for implementing Paging in Grid View, we enable the Paging property in GridView and will write code in the PageIndex Changed event. But the problem with this approach is it will fetch all the data from Database for Paging, will result wastage of network bandwidth and resources, also affect in the Page Performance. In [...]]]></description>
			<content:encoded><![CDATA[<p>Normally for implementing Paging in Grid View, we enable the Paging property in GridView and will write code in the PageIndex Changed event. But the problem with this approach is it will fetch all the data from Database for Paging, will result wastage of network bandwidth and resources, also affect in the Page Performance. In SQL Server 2005 Microsoft introduced a new concepts called Row_Number() and Derived Table with the help these two we can move the Paging logic to Database instead of ASP.Net web forms. This concept also works with custom paging implementations for DataList or Repeater controls.</p>
<pre class="brush: sql;">
CREATE PROCEDURE usp_GetContacts
(@Page INT, @RecsPerPage INT)
AS
SELECT tblContacts.[Name], tblContacts.[IsParent] FROM
(SELECT ROW_NUMBER() OVER(ORDER BY [ID]) AS RowNumber,
[Name], [IsParent] FROM [TreeView].[dbo].[Contacts]) tblContacts
WHERE RowNumber &gt; @RecsPerPage*(@Page) AND RowNumber &lt;= @RecsPerPage*(@Page+1)
</pre>
<p>In this code we are creating a Column called &#8220;RowNumber&#8221;. And we are comparing the input parameters with the derived table tblContacts.</p>
<p>Thanks to Aneesh / Prasanth for their valueable suggestions and comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/04/29/implementing-paging-in-sql-server-2005-stored-procedures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enumerating Instances of SQL Server using C#</title>
		<link>http://www.dotnetthoughts.net/2009/12/18/enumerating-instances-of-sql-server-using-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/12/18/enumerating-instances-of-sql-server-using-c/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 07:49:26 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[SMO]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=680</guid>
		<description><![CDATA[One of the project I am worked, I had to enumerate SQL Server instances of the network for creating dynamic connection string. Here is a code snippet which will retrieve all the SQL Server instance in a network using C# and ADO.Net. using System.Data; using System.Data.Sql; SqlDataSourceEnumerator sqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance; DataTable sqlServerInstances = sqlDataSourceEnumerator.GetDataSources(); The [...]]]></description>
			<content:encoded><![CDATA[<p>One of the project I am worked, I had to enumerate SQL Server instances of the network for creating dynamic connection string. Here is a code snippet which will retrieve all the SQL Server instance in a network using C# and ADO.Net.</p>
<pre class="brush: csharp;">
using System.Data;
using System.Data.Sql;

SqlDataSourceEnumerator sqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance;
DataTable sqlServerInstances = sqlDataSourceEnumerator.GetDataSources();
</pre>
<p>The Data Table contains 4 columns, and columns are</p>
<ol>
<li><em>ServerName </em>- Name of the Server.</li>
<li><em>InstanceName </em>- Name of the server instance. Blank if the server is running as the default instance.</li>
<li><em>IsClustered </em>- Indicates whether the server is part of a cluster.</li>
<li><em>Version </em>- Version of the server (8.00.x for SQL Server 2000, 9.00.x for SQL Server 2005, and 10.0.x for SQL Server 2008).</li>
</ol>
<p>Another way is using SQL Server Management Objects (SMO). For this you need to add reference of Microsoft.SqlServer.Smo assembly.</p>
<pre class="brush: csharp;">
DataTable sqlServerInstances = SmoApplication.EnumAvailableSqlServers();
</pre>
<p>It will also return a Data Table, with 6 columns and the columns are</p>
<ol>
<li><em>Name</em>- Name of the Server.</li>
<li><em> Server </em>- The name of the server on which the instance of SQL Server is installed.</li>
<li><em>Instance</em>-The instance of SQL Server.</li>
<li><em>IsClustered </em>-A Boolean value that is True if the instance is participating in failover clustering, or False if it is not.</li>
<li><em>Version </em>-Version of the SQL Server (8.00.x for SQL Server 2000, 9.00.x for SQL Server 2005, and 10.0.x for SQL Server 2008).</li>
<li><em>IsLocal</em>-A Boolean value that is True if the instance is local, or False if the instance is remote.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/12/18/enumerating-instances-of-sql-server-using-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Custom Paging in DataRepeater using C# and SQL Server</title>
		<link>http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 14:40:23 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Databinding]]></category>
		<category><![CDATA[Repeater]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=558</guid>
		<description><![CDATA[Normally DataRepeater doesn&#8217;t have a paging feature; and you can implement it using LINQ, if you are using .Net 3.5. Here is an implementation which is using SQL Server 2005 feature ROW_NUMBER(). You can get more information about ROW_NUMBER() from MSDN. Stored Procedure &#8211; xsp_GetPersons CREATE PROCEDURE xsp_GetPersons @StartIndex INT, @Count INT AS BEGIN DECLARE [...]]]></description>
			<content:encoded><![CDATA[<p>Normally DataRepeater doesn&#8217;t have a paging feature; and you can implement it using LINQ, if you are using .Net 3.5. Here is an implementation which is using SQL Server 2005 feature ROW_NUMBER(). You can get more information about ROW_NUMBER() from <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" target="_blank">MSDN</a>.</p>
<p>Stored Procedure &#8211; xsp_GetPersons</p>
<pre class="brush: sql;">
CREATE PROCEDURE xsp_GetPersons
@StartIndex INT, @Count INT
AS
BEGIN
DECLARE @EndIndex INT
SET @StartIndex = @StartIndex * @Count
SET @EndIndex = @StartIndex + @Count
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY UserId DESC) AS SlNo, UserId, FirstName, LastName, Email, ISNULL(DOB, GETDATE()) AS DOB FROM U_MyRegistration)Registration WHERE Registration.SlNo BETWEEN @StartIndex AND @EndIndex
END
</pre>
<p>And I added a DataRepeater control, with Next and Previous buttons in the Footer.</p>
<pre class="brush: xml;">
&lt;tr&gt;
    &lt;td colspan=&quot;3&quot; align=&quot;left&quot;&gt;
        &lt;asp:LinkButton CommandName=&quot;Navigation&quot; CommandArgument=&quot;Prev&quot; runat=&quot;server&quot; ID=&quot;linkPrevious&quot;
            Text=&quot;&lt;&lt; Previous&quot; /&gt;
    &lt;/td&gt;
    &lt;td colspan=&quot;3&quot; align=&quot;right&quot;&gt;
        &lt;asp:LinkButton CommandName=&quot;Navigation&quot; CommandArgument=&quot;Next&quot; runat=&quot;server&quot; ID=&quot;linkNext&quot; Text=&quot;Next &gt;&gt;&quot; /&gt;
    &lt;/td&gt;
&lt;/tr&gt;
</pre>
<p>Code behind. As it is a sample code, I am not added any validations.</p>
<pre class="brush: csharp;">
int count = 10;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        BindData(); //Binding Data.
    }
}

private void BindData()
{
    int startIndex = Convert.ToInt32(this.hidCurrentIndex.Value);
    Persons p = new Persons();
    this.Repeater1.DataSource = null;
    this.Repeater1.DataSource = p.GetPersons(startIndex, count);
    this.Repeater1.DataBind();
}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName.Equals(&quot;Navigation&quot;,
StringComparison.CurrentCultureIgnoreCase))
    {
        if (e.CommandArgument.ToString().Equals(&quot;Prev&quot;,
StringComparison.CurrentCultureIgnoreCase))
        {
            this.hidCurrentIndex.Value = (Convert.ToInt32
(this.hidCurrentIndex.Value) - 1).ToString(); //Decrementing the count
            this.BindData();
        }
        else
        {
            this.hidCurrentIndex.Value = (Convert.ToInt32
(this.hidCurrentIndex.Value) + 1).ToString(); //Incrementing the count
            this.BindData();
        }
    }
}
</pre>
<p>And the implementation of Persons class from App_Code</p>
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Data.SqlClient;

public class Persons : List&lt;Persons.Person&gt;
{
    public class Person
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public DateTime DOB { get; set; }
    }

    public Persons GetPersons(int startIndex, int count)
    {
        Persons persons = new Persons();
        using (SqlConnection connection = new SqlConnection (&quot;Server=.\SQLEXPRESS;User Id=sa;Password=sapwd;Database=myDatabase&quot;))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(&quot;xsp_GetPersons&quot;,

connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.AddWithValue(&quot;@StartIndex&quot;, startIndex);
                command.Parameters.AddWithValue(&quot;@Count&quot;, count);
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    persons.Add(new Person()
                    {
                        DOB = Convert.ToDateTime(reader[&quot;DOB&quot;].ToString()),
                        Email = reader[&quot;Email&quot;].ToString(),
                        FirstName = reader[&quot;FirstName&quot;].ToString(),
                        LastName = reader[&quot;LastName&quot;].ToString(),
                        UserId = Convert.ToInt32(reader[&quot;UserId&quot;].ToString()),
                    });
                }
            }
        }
        return persons;
    }
}
</pre>
<p>The core thing is stored procedure, which will return the results based on the given index. Thanks to <strong>Aneesh</strong> for the details of ROW_NUMBER() function.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/22/implementing-custom-paging-in-datarepeater-using-c-and-sql-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Store and Retrieve files from SQL Server Database</title>
		<link>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 07:41:48 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[File to Database]]></category>
		<category><![CDATA[IIS 7]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=417</guid>
		<description><![CDATA[The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for [...]]]></description>
			<content:encoded><![CDATA[<p>The forum I joined recently got lot of queries like How to Save Images in the Database, How to save files in SQL Server, How read files from Database etc. So I thought of writing a post regarding this. Even though I am part of a Web project, I am doing some Windows applications for the client. So I thought it will nice to brush-up the ASP.Net skills.</p>
<p>Here is the code. I am using SQL Server 2008, but I am not using FileStream for the current project, I already wrote a <a href="http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/">post</a> to how to<br />
manage files with FileStream feature. In this post I am using nvarchar(MAX) datatype for storing the file content.</p>
<p><strong>Table Design</strong></p>
<pre class="brush: sql;">
CREATE TABLE [dbo].[tblFiles](
	[FileId] [uniqueidentifier] NOT NULL,
	[Filename] [nvarchar](255) NOT NULL,
	[FileContent] [varbinary](max) NULL
)
</pre>
<p>And the I set FileId default to newId() and FileContent default to NULL</p>
<pre class="brush: sql;">
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileId]  DEFAULT (newid()) FOR [FileId]
GO
ALTER TABLE [dbo].[tblFiles] ADD  CONSTRAINT [DF_tblFiles_FileContent]  DEFAULT (NULL) FOR [FileContent]
GO
</pre>
<p>I wrote the code in C#. I am having a Asp FileUpload control and a button to upload the file, and a Repeater control with two controls, a label for displaying the filename and hyper link control for downloading the file.</p>
<pre class="brush: xml;">
&lt;body&gt;
&lt;form runat=&quot;server&quot;&gt;
&lt;asp:FileUpload runat=&quot;server&quot; ID=&quot;fileUploadImage&quot; /&gt;
&lt;asp:Button runat=&quot;server&quot; ID=&quot;cmdUpload&quot; Text=&quot;Upload File&quot; OnClick=&quot;cmdUpload_Click&quot; /&gt;
&lt;asp:Repeater runat=&quot;server&quot; ID=&quot;rptrFiles&quot;&gt;
    &lt;HeaderTemplate&gt;
        &lt;table&gt;
    &lt;/HeaderTemplate&gt;
    &lt;ItemTemplate&gt;
        &lt;tr&gt;
            &lt;td&gt;
                &lt;asp:Label runat=&quot;server&quot; ID=&quot;lblFilename&quot; Text='&lt;%# Eval(&quot;FileName&quot;)%&gt;' /&gt;
            &lt;/td&gt;
            &lt;td&gt;
              &lt;asp:HyperLink runat=&quot;server&quot; Target=&quot;_blank&quot; ID=&quot;lbtDownload&quot; Text=&quot;Download&quot; NavigateUrl='&lt;%# &quot;Download.aspx?File=&quot;  + Eval(&quot;FileId&quot;).ToString() %&gt;' /&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ItemTemplate&gt;
    &lt;FooterTemplate&gt;
        &lt;/table&gt;
    &lt;/FooterTemplate&gt;
&lt;/asp:Repeater&gt;
&lt;/form&gt;
&lt;/body&gt;
</pre>
<p><strong>Uploading the File to the Database</strong><br />
Code behind</p>
<pre class="brush: csharp;">
protected void cmdUpload_Click(object sender, EventArgs e)
{
    string fileName = Path.GetFileName(this.fileUploadImage.FileName);
    byte[] fileContent = this.fileUploadImage.FileBytes;
    using (SqlConnection connection = new SqlConnection(&quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb&quot;))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(&quot;INSERT INTO tblFiles(Filename, FileContent) VALUES(@Filename, @FileContent)&quot;, connection))
        {
            SqlParameter fileNameParameter = new SqlParameter(&quot;@Filename&quot;, System.Data.SqlDbType.NVarChar, 255);
            fileNameParameter.Value = fileName;
            SqlParameter fileContentParameter = new SqlParameter(&quot;@FileContent&quot;, System.Data.SqlDbType.VarBinary);
            fileContentParameter.Value = fileContent;
            command.Parameters.AddRange(new SqlParameter[] { fileNameParameter, fileContentParameter });
            command.ExecuteNonQuery();
        }
    }
}
</pre>
<p>And here is code to bind the repeater from the Database</p>
<pre class="brush: csharp;">
DataTable dtFiles = new DataTable(&quot;Files&quot;);
using (SqlDataAdapter adapter = new SqlDataAdapter(&quot;SELECT FileId, FileName FROM tblFiles&quot;, &quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=sampledb&quot;))
{
    adapter.Fill(dtFiles);
}
this.rptrFiles.DataSource = dtFiles;
this.rptrFiles.DataBind();
</pre>
<p><strong>Download / Read the file from Database</strong><br />
And to download / read the file from Database, I am passing the File unique id to another page(download.aspx).I this page I am checking for the File querysting and based on that reading filecontent from Sql and writing it to Asp.net output stream. You can get more information about how to download files from IIS in this <a href="http://www.dotnetthoughts.net/2007/05/06/download-files-from-iis-server-using-aspnet/">post</a>.</p>
<pre class="brush: csharp;">
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString[&quot;File&quot;] != null)
    {
        string fileId = Request.QueryString[&quot;File&quot;];
        using (SqlConnection connection = new SqlConnection(&quot;Server=.\\SQLEXPRESS;User Id=sa;Password=sapassword;Database=Sample&quot;))
        {
            connection.Open();
            using (SqlCommand command = new SqlCommand(&quot;SELECT Filename, FileContent FROM tblFiles WHERE FileId = @FileId&quot;, connection))
            {
                command.Parameters.AddWithValue(&quot;@FileId&quot;, fileId);
                SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                if (reader.HasRows)
                {
                    reader.Read();
                    byte[] content = reader[&quot;FileContent&quot;] as byte[];
                    string filename = reader[&quot;FileName&quot;].ToString();
                    Response.Clear();
                    Response.ClearContent();
                    Response.AddHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=&quot; + filename);
                    Response.AddHeader(&quot;Content-Length&quot;, content.Length.ToString());
                    Response.OutputStream.Write(content, 0, content.Length);
                    Response.End();
                }
            }
        }
    }
}
</pre>
<p>Please write to me if I missed something. Happy Programming .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/07/how-to-store-and-retrieve-files-from-sql-server-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Import / export data in MS Excel using C#</title>
		<link>http://www.dotnetthoughts.net/2009/09/23/import-export-data-in-ms-excel-using-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/09/23/import-export-data-in-ms-excel-using-c/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 07:38:02 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Import /Export Excel]]></category>
		<category><![CDATA[OleDb]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=401</guid>
		<description><![CDATA[Sometimes we may require to generate Excel file from our reports,read from excel files to import data etc. This can be achieved using Office Interop (Office Automation) assemblies, but Office Automation in Web servers,got some issues;(More details: http://support.microsoft.com/kb/257757). The alternative is using OleDb provider. You may need to add one more attribute to connection string [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes we may require to generate Excel file from our reports,read from excel files to import data etc. This can be achieved using Office Interop (Office Automation) assemblies, but Office Automation in Web servers,got some issues;(More details: <a target="_blank" href="http://support.microsoft.com/kb/257757">http://support.microsoft.com/kb/257757</a>). The alternative is using OleDb provider. You may need to add one more attribute to connection string to connect to the Excel file. And connection string will be</p>
<pre class="brush: csharp;">
string connectionString = &quot;Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;&quot;
</pre>
<p>Please note the &#8220;Extended Properties&#8221; attribute. This attribute helps us to query the excel file.</p>
<p>Exporting Data from Data Table to Excel File.</p>
<pre class="brush: csharp;">
string connectionString = &quot;Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;&quot;
// Establish a connection to the data source.
using(OleDbConnection Connection = new OleDbConnection(connectionString))
{
Connection.Open()
//creating a new Sheet with name sample and three columns with Heading firstname, lastname and email
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = Connection;
command.CommandText = &quot;CREATE TABLE [Sample$](FirstName Char(255), LastName char(255), Email char(255))&quot;;
command.ExecuteNonQuery();
}
//Adding records to the Sample Worksheet
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = Connection;
command.CommandText = &quot;INSERT INTO TABLE [Sample$](FirstName,LastName,Email) VALUES('Anuraj','P','anuraj.p@example.com')&quot;;
command.ExecuteNonQuery();
command.CommandText = &quot;INSERT INTO TABLE [Sample$](FirstName,LastName,Email) VALUES('sreekumar','vn','sreekumar.vn@example.com')&quot;;
command.ExecuteNonQuery();
}
}
</pre>
<p>Import the Data from Excel</p>
<pre class="brush: csharp;">
DataTable dt;
string connectionString = &quot;Provider=Microsoft.Jet.OleDb.4.0; Data Source=C:\Sample.xls; Extended Properties=Excel 8.0;&quot;
// Establish a connection to the data source.
using(OleDbConnection Connection = new OleDbConnection(connectionString))
{
Connection.Open()
//reading data from excel to Data Table
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = Connection;
command.CommandText = &quot;SELECT * FROM [Sample]&quot;;
using(OleDbDataAdapter adapter =new OleDbDataAdapter())
{
adapter.SelectCommand = command;
adapter.Fill(dt);
}
}
}
</pre>
<p>You can get more information from Microsoft support site<br />
<a href="http://support.microsoft.com/kb/306023" target="_blank"><br />
http://support.microsoft.com/kb/306023 &#8211; How to transfer data to an Excel workbook by using Visual C# 2005 or Visual C# .NET</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/09/23/import-export-data-in-ms-excel-using-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Adding and Reading files from SQL Server 2008 Filestream</title>
		<link>http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/</link>
		<comments>http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 12:38:46 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[SQL Server 2008]]></category>
		<category><![CDATA[VB.Net]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=393</guid>
		<description><![CDATA[Few days back I wrote a Post about FileStream feature in SQL 2008.(Filestream in SQL Server 2008). In this post I am trying to write the how to manage or use the FileStream feature from .Net managed code. For adding a File to FileStream enabled table, we are using a new Data Type, SqlFileStream, which [...]]]></description>
			<content:encoded><![CDATA[<p>Few days back I wrote a Post about FileStream feature in SQL 2008.(<a href="http://www.dotnetthoughts.net/2009/07/06/filestream-in-sql-server-2008/">Filestream in SQL Server 2008</a>). In this post I am trying to write the how to manage or use the FileStream feature from .Net managed code.</p>
<p>For adding a File to FileStream enabled table, we are using a new Data Type, SqlFileStream, which comes with .Net 3.5.</p>
<p>I am using the Table structure as in the Previous post, as the example, that Table contains 3 columns, FileID(PK), FileName and FileContents.<br />
For inserting a File you need to begin a transaction, insert an row in to the Table, without the contents of the File, for reading the Transaction context. Then using FileStream, write the contents of the File to the Row. After writting the stream, need to commit the transaction to update the file to the Database. I am writing the code in VB.Net.</p>
<p>Code for saving the File to the Database</p>
<pre class="brush: vb;">
Private Sub AddFile(ByVal fileName As String)
	Dim _Transaction As SqlTransaction
	Dim _Command As SqlCommand
	Dim _DataReader As SqlDataReader
	Dim _Connection As SqlConnection
	Dim _FileId As String
	Dim _FilePath As String
	Dim _FileNameParameter As SqlParameter
	Dim _FileIdParameter As SqlParameter
	Dim _FilePathParameter As SqlParameter

	Dim _SQLFileStream As SqlTypes.SqlFileStream
	Dim _Context As Byte()

	Try
		_Connection = New SqlConnection(&quot;Server=.\SQL2008;Integrated Authentication=SSPI;Database=FileSystemExample;&quot;)
		_Connection.Open()
		_Transaction = _Connection.BeginTransaction()
		_Command = New SqlCommand(&quot;xsp_InsertFile&quot;, _Connection, _Transaction)
		_Command.CommandType = CommandType.StoredProcedure
		_Command.Parameters.AddRange(New Object() {_FileIdParameter, _FileNameParameter, _FilePath})
		_FileId = Guid.NewGuid().ToString

		_FileIdParameter = New SqlParameter(&quot;@FileId&quot;, SqlDbType.UniqueIdentifier)
		_FileIdParameter.Value = _FileId

		_FileNameParameter = New SqlParameter(&quot;@FileName&quot;, SqlDbType.VarChar)
		_FileNameParameter.Value = fileName

		_FilePathParameter = New SqlParameter(&quot;@FilePath&quot;, SqlDbType.VarChar)
		_FilePathParameter.Direction = ParameterDirection.Output

		_DataReader = _Command.ExecuteReader(CommandBehavior.SingleRow)
		If _DataReader.HasRows Then
			_FilePath = _DataReader(&quot;FilePath&quot;).ToString
		End If
		If Not _DataReader.IsClosed Then
			_DataReader.Close()
		End If

		_Command = New SqlCommand(&quot;SELECT GET_FILESTREAM_TRANSACTION_CONTEXT() FROM SQLFileSystem&quot;, _Connection, _Transaction)
		_Context = _Command.ExecuteScalar()

		_SQLFileStream = New SqlFileStream(_FilePath, _Context, FileAccess.Write)
		_SQLFileStream.Write(_Context, 0, _Context.Length)
		_SQLFileStream.Close()

		_Transaction.Commit()
	Catch ex As Exception
		If _Transaction IsNot Nothing Then
			_Transaction.Rollback()
		End If
	Finally
		If _Connection IsNot Nothing Then
			_Connection.Close()
		End If
	End Try
End Sub
</pre>
<p>Code for reading the File from the Database</p>
<pre class="brush: vb;">
Private Function ReadFile(ByVal fileId As String) As Byte()
	Dim _Transaction As SqlTransaction
	Dim _Command As SqlCommand
	Dim _DataReader As SqlDataReader
	Dim _Connection As SqlConnection
	Dim _FilePath As String
	Dim _FileIdParameter As SqlParameter

	Dim _SQLFileStream As SqlTypes.SqlFileStream
	Dim _Context As Byte()

	Try
		_Connection = New SqlConnection(&quot;Server=.\SQL2008;Integrated Authentication=SSPI;Database=FileSystemExample;&quot;)
		_Connection.Open()
		_Transaction = _Connection.BeginTransaction()
		_Command = New SqlCommand(&quot;SELECT FileStreamData.PathName() AS [FilePath],GET_FILESTREAM_TRANSACTION_CONTEXT() AS [Context] FROM SQLFileSystem WHERE FileId=@FileId&quot;, _Connection, _Transaction)
		_Command.CommandType = CommandType.StoredProcedure

		_FileIdParameter = New SqlParameter(&quot;@FileId&quot;, SqlDbType.UniqueIdentifier)
		_FileIdParameter.Value = fileId
		_Command.Parameters.Add(_FileIdParameter)

		_DataReader = _Command.ExecuteReader(CommandBehavior.SingleRow)
		If _DataReader.HasRows Then
			_FilePath = _DataReader(&quot;FilePath&quot;).ToString()
			_Context = TryCast(_DataReader(&quot;Context&quot;), Byte())
		End If

		_SQLFileStream = New SqlFileStream(_FilePath, _Context, FileAccess.Read)
		_SQLFileStream.Read(_Context, 0, _Context.Length)
		_SQLFileStream.Close()

		_Transaction.Commit()
	Catch ex As Exception
		If _Transaction IsNot Nothing Then
			_Transaction.Rollback()
		End If
	Finally
		If _Connection IsNot Nothing Then
			_Connection.Close()
		End If
	End Try
	Return _Context
End Function
</pre>
<p>Stored Procedure</p>
<pre class="brush: sql;">
CREATE PROCEDURE xsp_InsertFile
(
@FileName VARCHAR(255),
@FileId UNIQUEIDENTIFIER,
@FilePath VARCHAR(MAX) OUTPUT)
AS
BEGIN
SET NOCOUNT OFF
INSERT INTO SQLFileSystem (FileId, FileName) VALUES(@FileId, @FileName)
SELECT @FilePath = SystemFile.PathName() from SQLFileSystem where FileId = @FileId
END
</pre>
<p>Note: I didn&#8217;t tested the code. Please let me know if you found any issues in the implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/09/22/adding-and-reading-files-from-sql-server-2008-filestream/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
