<?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/category/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>How to use Stored Procedures in Entity Framework</title>
		<link>http://www.dotnetthoughts.net/2010/07/08/how-to-use-stored-procedures-in-entity-framework/</link>
		<comments>http://www.dotnetthoughts.net/2010/07/08/how-to-use-stored-procedures-in-entity-framework/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 10:34:33 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Entity Framewrok]]></category>
		<category><![CDATA[SP]]></category>
		<category><![CDATA[Stored Procedure]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=976</guid>
		<description><![CDATA[In the current project we are using Entity Framework for database operations. Entity Framework comes with Visual Studio SP1, which helps you to map tables / views / procedures as entities in C# / VB Code. You can find more details about EF from here : http://msdn.microsoft.com/en-us/library/bb399572.aspx. In this post I am explaining how to [...]]]></description>
			<content:encoded><![CDATA[<p>In the current project we are using Entity Framework for database operations. Entity Framework comes with Visual Studio SP1, which helps you to map tables / views / procedures as entities in C# / VB Code. You can find more details about EF from here : <a title="Entity Framework Overview" href="http://msdn.microsoft.com/en-us/library/bb399572.aspx" target="_blank">http://msdn.microsoft.com/en-us/library/bb399572.aspx</a>. In this post I am explaining how to use Stored Procedures in Entity Framework.</p>
<ol>
<li>Add the Stored Procedure to the Entity Model Designer using Update Model From Database Option.</li>
<div id="attachment_979" class="wp-caption aligncenter" style="width: 546px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/Add_Procedure.png"><img class="size-full wp-image-979" title="Add Procedure" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/Add_Procedure.png" alt="Add Procedure" width="536" height="485" /></a><p class="wp-caption-text">Add Procedure</p></div>
<li>If you are added successfully, you can get the procedure in Model Browser.</li>
<div id="attachment_981" class="wp-caption aligncenter" style="width: 299px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/Model_Browser.png"><img class="size-full wp-image-981" title="Model Browser " src="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/Model_Browser.png" alt="Model Browser " width="289" height="341" /></a><p class="wp-caption-text">Model Browser </p></div>
<li>Right click on the Procedure name and select Create Function Import.</li>
<div id="attachment_980" class="wp-caption aligncenter" style="width: 308px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/create_fn_import.png"><img class="size-full wp-image-980" title="Create Function Import" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/create_fn_import.png" alt="Create Function Import" width="298" height="320" /></a><p class="wp-caption-text">Create Function Import</p></div>
<li>It will popups a Windows with Stored Procedure Name, Function Import Name and Return Type. If the procedure returns nothing, you can choose none. If the procedure is returns single value, like UserId, Number Of Rows etc, then you can choose scalar option, where you need to specify the return type. And if the procedure is returns Table or Number of Rows, you need to choose the last option Entities, which will allow to select entities created in the Model as the Output. Sometimes we need to create a View in the DB and need to import it in the Model, so that we can use the View as the return type entity.  Select the appropriate return type and click Ok. You can use this in code. In this code I am using a View to return the selected users.</li>
</ol>
<div id="attachment_978" class="wp-caption aligncenter" style="width: 399px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/Add_Function_Import.png"><img class="size-full wp-image-978" title="Add Function Import dialog" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/07/Add_Function_Import.png" alt="Add Function Import dialog" width="389" height="278" /></a><p class="wp-caption-text">Add Function Import dialog</p></div>
<pre class="brush: csharp;">

using (SampleEntities context = new SampleEntities())
{
/*
* Thanks to Barry Soetoro.
* I was not calling the GetAllUsers function.
List&lt;Users&gt; Users = null;
Users = (from user in context.Users
             select user).ToList();
this.dataGridView1.DataSource = Users;
*/
//Updated Version.
IEnumerable&lt;UsersView&gt; userview = context.GetAllUsers();
this.dataGridView1.DataSource = userview;
}
</pre>
<p>This will display list of Users in the DataGridView. Happy Coding <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/07/08/how-to-use-stored-procedures-in-entity-framework/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<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>TreeView Population without recursive function</title>
		<link>http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/</link>
		<comments>http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 14:42:56 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Common Table Expressions]]></category>
		<category><![CDATA[CTE]]></category>
		<category><![CDATA[Recursive function]]></category>
		<category><![CDATA[Treeview]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=544</guid>
		<description><![CDATA[If you want to display hierarchical data in a Treeview normally we are using recursion. I was looking for code which helps to avoid recursion using a Single query. But that code was using VB.Net and it was using a class called &#8220;Collection&#8221;, which is not available in C#. So I was looking for a [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to display hierarchical data in a Treeview normally we are using recursion. I was looking for code which helps to avoid recursion using a Single query. But that code was using VB.Net and it was using a class called &#8220;Collection&#8221;, which is not available in C#. So I was looking for a compatable code in C# for long time and today I got the chance to re-write it using C#, but I am using Lamda expressions for this.</p>
<p>Here is the Table structure I want to display in Treeview</p>
<pre class="brush: sql;">

CREATE TABLE [dbo].[tblEmployees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [nvarchar](50) NOT NULL,
[Parent] [int] NOT NULL)
</pre>
<p>And I inserted following Data in it.</p>
<div id="attachment_545" class="wp-caption alignnone" style="width: 299px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/10/Table_Data.JPG" alt="Table Data" title="Table Data" width="289" height="383" class="size-full wp-image-545" /><p class="wp-caption-text">Table Data</p></div>
<p>And the Stored Procedure for getting employees using Common Table Expressions.</p>
<pre class="brush: sql;">
-- usp_GetEmployees
CREATE PROCEDURE [dbo].[usp_GetEmployees]
AS
BEGIN
	WITH SimpleRecursive AS
	(SELECT EmployeeName, EmployeeId, Parent, 0 AS Depth FROM dbo.tblEmployees
	WHERE (EmployeeId IN(SELECT EmployeeId FROM dbo.tblEmployees AS Recursion1
	WHERE (Parent = 0)))
	UNION ALL
	SELECT P.EmployeeName, P.EmployeeId,P.Parent, A.Depth + 1 AS Depth
	FROM dbo.tblEmployees AS P INNER JOIN SimpleRecursive AS A ON A.EmployeeId = P.Parent)
	SELECT EmployeeName, EmployeeId, CONVERT(INT, Parent) AS Parent, Depth
	FROM SimpleRecursive AS SimpleRecursive_1
	ORDER BY Depth
END
</pre>
<p>And the code in C# which adding nodes to Treeview.</p>
<pre class="brush: csharp;">
private void PopulateTreeview()
{
    this.tvEmployees.Nodes.Clear();
    Employees employees = new Employees();
    using (SqlConnection connection = new SqlConnection(@&quot;Server=.\SQLEXPRESS; User Id=SQLUser;Password=SQLPassword;Database=Database&quot;))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(&quot;usp_GetEmployees&quot;, connection))
        {
            command.CommandType = System.Data.CommandType.StoredProcedure;
            SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                employees.Add(new Employees.Employee()
                {
                    Depth = int.Parse(reader[&quot;depth&quot;].ToString()),
                    EmployeeId = int.Parse(reader[&quot;EmployeeId&quot;].ToString()),
                    Parent = int.Parse(reader[&quot;Parent&quot;].ToString()),
                    EmployeeName = reader[&quot;EmployeeName&quot;].ToString(),
                });
            }
        }
    }

    foreach (Employees.Employee employee in employees)
    {
        Employees.Employee parentEmp = employees.Find(o =&gt; o.EmployeeId == employee.Parent);
        if (parentEmp != null)
        {
            this.tvEmployees.Nodes.Find(parentEmp.EmployeeId.ToString(), true)[0].Nodes.Add(employee.EmployeeId.ToString(), employee.EmployeeName);
        }
        else
        {
            this.tvEmployees.Nodes.Add(employee.EmployeeId.ToString(), employee.EmployeeName);
        }
    }
    this.tvEmployees.ExpandAll();
}
</pre>
<p>And the employees class </p>
<pre class="brush: csharp;">
public class Employees : List&lt;Employees.Employee&gt;
{
    public class Employee
    {
        public int EmployeeId
        {
            get;
            set;
        }
        public string EmployeeName
        {
            get;
            set;
        }
        public int Parent
        {
            get;
            set;
        }
        public int Depth
        {
            get;
            set;
        }
    }
}
</pre>
<p>And here is the screenshot</p>
<p><div id="attachment_551" class="wp-caption alignnone" style="width: 345px"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2009/10/treeview_Demo.JPG" alt="Treeview Demo - Screenshot" title="Treeview Demo - Screenshot" width="335" height="447" class="size-full wp-image-551" /><p class="wp-caption-text">Treeview Demo - Screenshot</p></div><br />
Thanks to <strong>Aneesh</strong> and <strong>Anas</strong> for their valuable comments.<br />
Happy Programming <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/10/20/treeview-population-without-recursive-function/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>
	</channel>
</rss>
