<?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>The Art of Software &#187; C#</title>
	<atom:link href="http://orionseven.com/blog/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://orionseven.com/blog</link>
	<description>It takes a lot more than code to make software.</description>
	<lastBuildDate>Thu, 06 Oct 2011 14:06:27 +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 build a Check Box Group Helper with ASP.Net MVC 2.0</title>
		<link>http://orionseven.com/blog/2010/12/15/how-to-build-a-check-box-group-helper-with-asp-net-mvc-2-0/</link>
		<comments>http://orionseven.com/blog/2010/12/15/how-to-build-a-check-box-group-helper-with-asp-net-mvc-2-0/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 00:16:29 +0000</pubDate>
		<dc:creator>Bryan Smith</dc:creator>
				<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://orionseven.com/blog/?p=125</guid>
		<description><![CDATA[ASP.Net MVC 2.0 comes with great HTML helpers right out of the box, which include a check box helper. Unfortunately the way in which the check box helper renders a check box is not the traditional way most web developers use check boxes. Microsoft instead went with a true/false scenario for check boxes, which is [...]]]></description>
			<content:encoded><![CDATA[<p>ASP.Net MVC 2.0 comes with great <a href="http://msdn.microsoft.com/en-us/library/dd410596.aspx">HTML helpers</a> right out of the box, which include a check box helper. Unfortunately the way in which the check box helper renders a check box is not the traditional way most web developers use check boxes. Microsoft instead went with a true/false scenario for check boxes, which is great for many uses of check boxes. However, it does not support a named group of check boxes that many web developer’s use.</p>
<h2>What We Want</h2>
<p>So with that in mind we’re going to create a MVC Check Box Group Helper.</p>
<p>First let’s look at what the well formed html for the check box group with labels looks like:</p>
<div class="codesnip-container" >
<div class="html4strict codesnip" style="font-family:monospace;"><span class="sc2">&lt;<a href="http://december.com/html/4/element/input.html"><span class="kw2">input</span></a> <span class="kw3">id</span><span class="sy0">=</span><span class="st0">&quot;Color1&quot;</span> <span class="kw3">name</span><span class="sy0">=</span><span class="st0">&quot;Colors&quot;</span> <span class="kw3">type</span><span class="sy0">=</span><span class="st0">&quot;checkbox&quot;</span> <span class="kw3">value</span><span class="sy0">=</span><span class="st0">&quot;Blue&quot;</span> <span class="sy0">/</span>&gt;</span> <br />
<span class="sc2">&lt;<a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a> <span class="kw3">for</span><span class="sy0">=</span><span class="st0">&quot;Color1&quot;</span>&gt;</span>Blue<span class="sc2">&lt;<span class="sy0">/</span><a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a>&gt;</span></p>
<p><span class="sc2">&lt;<a href="http://december.com/html/4/element/input.html"><span class="kw2">input</span></a> <span class="kw3">id</span><span class="sy0">=</span><span class="st0">&quot;Color2&quot;</span> <span class="kw3">name</span><span class="sy0">=</span><span class="st0">&quot;Colors&quot;</span> <span class="kw3">type</span><span class="sy0">=</span><span class="st0">&quot;checkbox&quot;</span> <span class="kw3">value</span><span class="sy0">=</span><span class="st0">&quot;Red&quot;</span> <span class="sy0">/</span>&gt;</span> <br />
<span class="sc2">&lt;<a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a> <span class="kw3">for</span><span class="sy0">=</span><span class="st0">&quot;Color2&quot;</span>&gt;</span>Red<span class="sc2">&lt;<span class="sy0">/</span><a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a>&gt;</span></p>
<p><span class="sc2">&lt;<a href="http://december.com/html/4/element/input.html"><span class="kw2">input</span></a> <span class="kw3">id</span><span class="sy0">=</span><span class="st0">&quot;Color3&quot;</span> <span class="kw3">name</span><span class="sy0">=</span><span class="st0">&quot;Colors&quot;</span> <span class="kw3">type</span><span class="sy0">=</span><span class="st0">&quot;checkbox&quot;</span> <span class="kw3">value</span><span class="sy0">=</span><span class="st0">&quot;Green&quot;</span> <span class="sy0">/</span>&gt;</span> <br />
<span class="sc2">&lt;<a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a> <span class="kw3">for</span><span class="sy0">=</span><span class="st0">&quot;Color3&quot;</span>&gt;</span>Green<span class="sc2">&lt;<span class="sy0">/</span><a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a>&gt;</span></p>
<p><span class="sc2">&lt;<a href="http://december.com/html/4/element/input.html"><span class="kw2">input</span></a> <span class="kw3">id</span><span class="sy0">=</span><span class="st0">&quot;Color4&quot;</span> <span class="kw3">name</span><span class="sy0">=</span><span class="st0">&quot;Colors&quot;</span> <span class="kw3">type</span><span class="sy0">=</span><span class="st0">&quot;checkbox&quot;</span> <span class="kw3">value</span><span class="sy0">=</span><span class="st0">&quot;Yellow&quot;</span> <span class="sy0">/</span>&gt;</span> <br />
<span class="sc2">&lt;<a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a> <span class="kw3">for</span><span class="sy0">=</span><span class="st0">&quot;Color4&quot;</span>&gt;</span>Yellow<span class="sc2">&lt;<span class="sy0">/</span><a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a>&gt;</span></p>
<p><span class="sc2">&lt;<a href="http://december.com/html/4/element/input.html"><span class="kw2">input</span></a> <span class="kw3">id</span><span class="sy0">=</span><span class="st0">&quot;Color5&quot;</span> <span class="kw3">name</span><span class="sy0">=</span><span class="st0">&quot;Colors&quot;</span> <span class="kw3">type</span><span class="sy0">=</span><span class="st0">&quot;checkbox&quot;</span> <span class="kw3">value</span><span class="sy0">=</span><span class="st0">&quot;Orange&quot;</span> <span class="sy0">/</span>&gt;</span> <br />
<span class="sc2">&lt;<a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a> <span class="kw3">for</span><span class="sy0">=</span><span class="st0">&quot;Color5&quot;</span>&gt;</span>Orange<span class="sc2">&lt;<span class="sy0">/</span><a href="http://december.com/html/4/element/label.html"><span class="kw2">label</span></a>&gt;</span></div>
</div>
<p>Obviously the check box group is for selecting colors and the values are hex color codes.</p>
<p>The check box group name is “Colors”; each check box has a unique value and a unique ID. The unique ID allows you to use the labels “for” attribute to specify which check box it is for, thus when you click on an associated label it toggles the check box.</p>
<h2>Constraints</h2>
<p>Now for some constraints for the check box group:</p>
<ul>
<li>Easy to use</li>
<li>Maps to an IEnumerable</li>
<li>Does not use JavaScript</li>
<li>Does not use hidden form elements</li>
<li>If possible reuse preexisting MVC classes</li>
</ul>
<p>All of these are pretty straight forward and will come into play as we design this.</p>
<p>If you’re not aware Microsoft released <a href="http://weblogs.asp.net/scottgu/archive/2009/04/01/asp-net-mvc-1-0.aspx">MVC’s source code under the MS-PL open source license</a>. This is great as it lets us peak under the hood and see how they implement things. This is really great if you want to make your own helpers and take into consideration things that the official helpers do as well.</p>
<h2>The Foundation</h2>
<p>Since a check box group will obviously need some data it will need some sort of container which can represent a check box. It will need to keep track of just a few things:</p>
<ul>
<li>The text to display</li>
<li>A value to use</li>
<li>And if it’s checked</li>
</ul>
<p>In fact, just like SelectListItem. Here’s the source from the MVC project for SelectListItem.</p>
<div class="codesnip-container" >
<div class="c codesnip" style="font-family:monospace;">namespace System.<span class="me1">Web</span>.<span class="me1">Mvc</span> <span class="br0">&#123;</span></p>
<p>&nbsp; &nbsp; public class SelectListItem <span class="br0">&#123;</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; public bool Selected <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; get<span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set<span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; public <span class="kw4">string</span> Text <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; get<span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set<span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span></p>
<p>&nbsp; &nbsp; &nbsp; &nbsp; public <span class="kw4">string</span> Value <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; get<span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set<span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
<span class="br0">&#125;</span></div>
</div>
<p>It can’t be much simpler than that, and as it turns out we can make use of this perfectly for our check box. With SelectListItem we can either use SelectList or IEnumerable&lt;SelectListItem&gt; to keep our list.</p>
<p>With that out of the way we now have something to hold the data for our check boxes in that is easy to translate our own data into, people are familiar with it already, and it satisfies our fourth constraint.</p>
<h2>The Helper</h2>
<p>Okay, now for our helper. If you’re not familiar with how to create a basic helper with extension methods you can <a href="http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs">read this great article</a> and then come back here.</p>
<p>Let’s look at the constructor of our new helper whose parameters are quite simple.</p>
<div class="codesnip-container" >
<div class="c codesnip" style="font-family:monospace;">public <span class="kw4">static</span> <span class="kw4">string</span> CheckBoxGroup<span class="br0">&#40;</span>this HtmlHelper htmlHelper<span class="sy0">,</span> <span class="kw4">string</span> name<span class="sy0">,</span> IEnumerable<span class="sy0">&lt;</span>SelectListItem<span class="sy0">&gt;</span> selectList<span class="br0">&#41;</span></div>
</div>
<p>And you’ll use it in your view like so:</p>
<div class="codesnip-container" >
<div class="asp codesnip" style="font-family:monospace;"><span class="sy1">&lt;%</span><span class="sy0">=</span> Html.<span class="me1">CheckBoxGroup</span><span class="br0">&#40;</span><span class="st0">&quot;Colors&quot;</span>, Model.<span class="me1">Colors</span><span class="br0">&#41;</span> <span class="sy1">%&gt;</span></div>
</div>
<p>As you can see, the name of the group will be “Colors” and I’m passing an IEnumerable&lt;Color&gt; from my View’s model (you’re using strongly typed views right?).</p>
<p>Now here’s the actual helper code:</p>
<div class="codesnip-container" >
<div class="c codesnip" style="font-family:monospace;">public <span class="kw4">static</span> <span class="kw4">string</span> CheckBoxGroup<span class="br0">&#40;</span>this HtmlHelper htmlHelper<span class="sy0">,</span> <span class="kw4">string</span> name<span class="sy0">,</span> IEnumerable<span class="sy0">&lt;</span>SelectListItem<span class="sy0">&gt;</span> selectList<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; name <span class="sy0">=</span> htmlHelper.<span class="me1">ViewContext</span>.<span class="me1">ViewData</span>.<span class="me1">TemplateInfo</span>.<span class="me1">GetFullHtmlFieldName</span><span class="br0">&#40;</span>name<span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="kw1">if</span> <span class="br0">&#40;</span><span class="kw4">string</span>.<span class="me1">IsNullOrEmpty</span><span class="br0">&#40;</span>name<span class="br0">&#41;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; throw new ArgumentException<span class="br0">&#40;</span><span class="st0">&quot;Parameter must be specified.&quot;</span><span class="sy0">,</span> <span class="st0">&quot;name&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span></p>
<p>&nbsp; &nbsp; StringBuilder listItemBuilder <span class="sy0">=</span> new StringBuilder<span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span></p>
<p>&nbsp; &nbsp; <span class="kw4">int</span> count <span class="sy0">=</span> <span class="nu0">0</span><span class="sy0">;</span><br />
&nbsp; &nbsp; foreach <span class="br0">&#40;</span>SelectListItem item in selectList<span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; listItemBuilder.<span class="me1">AppendLine</span><span class="br0">&#40;</span>ListItemToCheckBox<span class="br0">&#40;</span>item<span class="sy0">,</span> name<span class="sy0">,</span> count<span class="br0">&#41;</span> <span class="sy0">+</span> ListItemToLabel<span class="br0">&#40;</span>item<span class="sy0">,</span> name<span class="sy0">,</span> count<span class="br0">&#41;</span> <span class="sy0">+</span> <span class="st0">&quot;&lt;br /&gt;&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; count<span class="sy0">++;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">return</span> listItemBuilder.<span class="me1">ToString</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="br0">&#125;</span></div>
</div>
<p>This is obviously modeled after the Drop Down List helper that comes with MVC.</p>
<p>The guts of the helper come down to the for loop. For each of the select list items we’re building a line of HTML that includes both our check box and our label. The code for which is here:</p>
<div class="codesnip-container" >
<div class="c codesnip" style="font-family:monospace;">internal <span class="kw4">static</span> <span class="kw4">string</span> ListItemToCheckBox<span class="br0">&#40;</span>SelectListItem item<span class="sy0">,</span> <span class="kw4">string</span> name<span class="sy0">,</span> <span class="kw4">int</span> count<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; TagBuilder builder <span class="sy0">=</span> new TagBuilder<span class="br0">&#40;</span><span class="st0">&quot;input&quot;</span><span class="br0">&#41;</span><span class="sy0">;</span></p>
<p>&nbsp; &nbsp; builder.<span class="me1">Attributes</span><span class="br0">&#91;</span><span class="st0">&quot;type&quot;</span><span class="br0">&#93;</span> <span class="sy0">=</span> <span class="st0">&quot;checkbox&quot;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; builder.<span class="me1">Attributes</span><span class="br0">&#91;</span><span class="st0">&quot;name&quot;</span><span class="br0">&#93;</span> <span class="sy0">=</span> name<span class="sy0">;</span><br />
&nbsp; &nbsp; builder.<span class="me1">Attributes</span><span class="br0">&#91;</span><span class="st0">&quot;id&quot;</span><span class="br0">&#93;</span> <span class="sy0">=</span> name <span class="sy0">+</span> count<span class="sy0">;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">if</span> <span class="br0">&#40;</span>item.<span class="me1">Value</span> <span class="sy0">!=</span> <span class="kw2">null</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; builder.<span class="me1">Attributes</span><span class="br0">&#91;</span><span class="st0">&quot;value&quot;</span><span class="br0">&#93;</span> <span class="sy0">=</span> item.<span class="me1">Value</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw1">if</span> <span class="br0">&#40;</span>item.<span class="me1">Selected</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; builder.<span class="me1">Attributes</span><span class="br0">&#91;</span><span class="st0">&quot;checked&quot;</span><span class="br0">&#93;</span> <span class="sy0">=</span> <span class="st0">&quot;checked&quot;</span><span class="sy0">;</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><br />
&nbsp; &nbsp; <span class="kw1">return</span> builder.<span class="me1">ToString</span><span class="br0">&#40;</span>TagRenderMode.<span class="me1">Normal</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="br0">&#125;</span></p>
<p>internal <span class="kw4">static</span> <span class="kw4">string</span> ListItemToLabel<span class="br0">&#40;</span>SelectListItem item<span class="sy0">,</span> <span class="kw4">string</span> name<span class="sy0">,</span> <span class="kw4">int</span> count<span class="br0">&#41;</span><br />
<span class="br0">&#123;</span><br />
&nbsp; &nbsp; TagBuilder builder <span class="sy0">=</span> new TagBuilder<span class="br0">&#40;</span><span class="st0">&quot;label&quot;</span><span class="br0">&#41;</span><br />
&nbsp; &nbsp; <span class="br0">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; InnerHtml <span class="sy0">=</span> item.<span class="me1">Text</span><br />
&nbsp; &nbsp; <span class="br0">&#125;</span><span class="sy0">;</span></p>
<p>&nbsp; &nbsp; builder.<span class="me1">Attributes</span><span class="br0">&#91;</span><span class="st0">&quot;for&quot;</span><span class="br0">&#93;</span> <span class="sy0">=</span> name <span class="sy0">+</span> count<span class="sy0">;</span></p>
<p>&nbsp; &nbsp; <span class="kw1">return</span> builder.<span class="me1">ToString</span><span class="br0">&#40;</span>TagRenderMode.<span class="me1">Normal</span><span class="br0">&#41;</span><span class="sy0">;</span><br />
<span class="br0">&#125;</span></div>
</div>
<p>And there you have it. Put the constructor and the two internal static methods in a class and you have a Html.CheckBoxGroup helper.</p>
<h2>What Next?</h2>
<p>There is room for improvement on this model. I didn’t handle everything, if you want to expand it some things I’ve done or looked into are:</p>
<ul>
<li>Custom HTML Attributes</li>
<li>More customization on how check boxes are separated</li>
<li>Creating a Strongly Typed version</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://orionseven.com/blog/2010/12/15/how-to-build-a-check-box-group-helper-with-asp-net-mvc-2-0/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using Table-Valued Parameters in SQL Server 2008 and C#</title>
		<link>http://orionseven.com/blog/2009/09/30/using-table-valued-parameters-in-sql-server-2008-and-c/</link>
		<comments>http://orionseven.com/blog/2009/09/30/using-table-valued-parameters-in-sql-server-2008-and-c/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 20:28:22 +0000</pubDate>
		<dc:creator>Bryan Smith</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://orionseven.com/blog/?p=20</guid>
		<description><![CDATA[Until recently I had not had an opportunity to use Table-Valued Parameters a new feature in SQL Server 2008. I had looked at them briefly, thought they were a nice addition, and then moved on. Finally though, I found a chance to use them. The intended use for Table-Valued Parameters is of course to send [...]]]></description>
			<content:encoded><![CDATA[<p>Until recently I had not had an opportunity to use <a href="http://msdn.microsoft.com/en-us/library/bb510489.aspx">Table-Valued Parameters</a> a new feature in SQL Server 2008. I had looked at them briefly, thought they were a nice addition, and then moved on. Finally though, I found a chance to use them.</p>
<p>The intended use for Table-Valued Parameters is of course to send multiple rows of data to SQL Server from the client. Previous ways to do this involved calling a single stored procedure repeatedly, using XML, using SQLBulkCopy, or my least favorite, creating a stored procedure with many parameters. Each of these methods had draw backs. Calling a single stored procedure over and over works just fine (and was my preferred method) but you are creating a lot of traffic for something that should be simple. XML was nice too, but depending on the complexity of what you are sending you will need a lot of XQuery in your stored procedure; making something simple much more complex. SQLBulkCopy works great, I’ve used it before, but sometimes you may want to do more to your data once it is at the database. Thankfully table-valued parameters solve many of these short comings.</p>
<p>You can use table-valued parameters from your application with DataTables, DbDataReader, or IEnumerable objects. The majority of examples for table-valued parameters are done using DataTables. The problem I have with DataTables is that this seems like too much of an ad-hoc method with more overhead then is needed. Whereas going the IEnumerable route lets you create and use objects that you would likely already be using. This is the route I prefer, and the one I will demonstrate.</p>
<p>For this example assume we have a database of people and each of the people may have one or more aliases. They must be rather shady people. Here is the table for storing the people:</p>
<blockquote>
<pre>CREATE TABLE tbl_Person
(
      [ID] INT IDENTITY(1,1) NOT NULL,
      [FirstName] VARCHAR(20) NOT NULL,
      [LastName] VARCHAR(20) NOT NULL
)</pre>
</blockquote>
<p>It is quite simple, an identity field called ID to give everyone a unique number and a first and last name.</p>
<p>Now we have a table to store their aliases:</p>
<blockquote>
<pre>CREATE TABLE tbl_Alias
(
      [ID] INT NOT NULL,
      [FirstName] VARCHAR(20) NOT NULL,
      [LastName] VARCHAR(20) NULL
)</pre>
</blockquote>
<p>Another simple table to keep our shady people’s aliases; let’s pretend for ease of use there are primary keys and foreign keys shall we?</p>
<p>To add to this table we will use a stored procedure, my favorite mechanism to get data to the database. Why? Because you give the DBA something concrete upon which they can optimize your database, among other reasons. But that’s another post.</p>
<p>Our stored procedure will be an inserting stored procedure which will add our new shady person and their aliases in one call. Thus we will need to<a href="http://msdn.microsoft.com/en-us/library/ms175007.aspx"> create our user-defined table type</a>  first.</p>
<blockquote>
<pre>CREATE TYPE udt_tbl_Alias AS TABLE
(
      [FirstName] VARCHAR(20) NOT NULL,
      [LastName] VARCHAR(20) NULL
)</pre>
</blockquote>
<p>Again, nothing complicated. You will see why I left off the ID field in a bit.</p>
<p>You should note that you cannot use ALTER commands on user-defined table types. So if you want to update the table type later you will have drop it and create it. But if it is being used by a stored procedure you will have to temporarily comment that out of your stored procedure first, then drop the UDT, create the UDT again, and uncomment the UDT in your stored procedure. So plan ahead! Having planned ahead, here is our stored procedure for inserting:</p>
<blockquote>
<pre>CREATE PROCEDURE usp_ins_Person
      @FirstName VARCHAR(20),
      @LastName VARCHAR(20),
      @Aliases udt_tbl_Alias READONLY
AS
BEGIN
      SET NOCOUNT ON

      INSERT INTO tbl_Person VALUES (@FirstName, @LastName)

      INSERT INTO tbl_Alias (ID, FirstName, LastName)
            SELECT @@IDENTITY [ID], FirstName, LastName FROM @Aliases
END</pre>
</blockquote>
<p>The stored procedure requires three parameters: a first name, a last name and the user-defined table-valued parameter. The table type must be marked as READONLY and thus you will not be able to update the table within the stored procedure, only select from it. Otherwise, the stored procedure is rather straight forward. The person is added to tbl_Person and the aliases are added to tbl_Alias. You can see why I chose not to have the ID part of the user-defined table type, since we will not the ID till the person has been inserted.</p>
<p>To use the stored procedure in SQL Server Management Studio you can do the following.</p>
<blockquote>
<pre>DECLARE @Aliases udt_tbl_Alias
DECLARE @FirstName VARCHAR(20) = 'Bryan'
DECLARE @LastName VARCHAR(20) = 'Smith'
 
INSERT INTO @Aliases VALUES ('Database', 'Guy'), ('DBA', NULL)
 
EXEC usp_ins_Person @FirstName, @LastName, @Aliases
 
SELECT * FROM tbl_Person
SELECT * FROM tbl_Alias</pre>
</blockquote>
<p>The output should look like this.</p>
<div id="attachment_19" class="wp-caption alignnone" style="width: 203px"><img class="size-full wp-image-19" title="udt_output" src="http://orionseven.com/blog/wp-content/uploads/2009/09/udt_output.png" alt="Output" width="193" height="139" /><p class="wp-caption-text">Output</p></div>
<p>Great, we’re halfway there! The database side of things is taken care of, now we will need to take care of our client. Within the client code we will create a Person class. The class will have a property for the first name, last name, and aliases. This is why I like the IEnumerable route; it makes sense to store the aliases for a person with the person, and doing so as a list makes sense.</p>
<p>Person Class:</p>
<blockquote>
<pre>
namespace TestUDTApplication
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public AliasCollection Aliases { get; set; }
 
        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
            Aliases = new AliasCollection();
        }
    }
}</pre>
</blockquote>
<p>Alias Class:</p>
<blockquote>
<pre>
namespace TestUDTApplication
{
    class Alias
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
 
        public Alias(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }
}</pre>
</blockquote>
<p>AliasCollection Class:</p>
<blockquote>
<pre>
using System.Collections.Generic;
using System.Data;
using Microsoft.SqlServer.Server;
 
namespace TestUDTApplication
{
    class AliasCollection : List&lt;Alias&gt;, IEnumerable&lt;SqlDataRecord&gt;
    {
        IEnumerator&lt;SqlDataRecord&gt; IEnumerable&lt;SqlDataRecord&gt;.GetEnumerator()
        {
            SqlDataRecord ret = new SqlDataRecord(
                new SqlMetaData("FirstName", SqlDbType.VarChar, 20),
                new SqlMetaData("LastName", SqlDbType.VarChar, 20)
                );
 
            foreach (Alias alias in this)
            {
                ret.SetString(0, alias.FirstName);
                ret.SetString(1, alias.LastName);
                yield return ret;
            }
        }
    }
}</pre>
</blockquote>
<p>Let’s look over this code. First off the Person class has three public properties. FirstName, LastName, and Aliases. The Aliases property is an instance of the AliasCollection class, which inherits the Alias class as a List and then implements the IEnumerable interface. The List&lt;Alias&gt; turns our Alias into a List, which is perfect for handling our aliases within the client code.</p>
<p>The implementation IEnumerable&lt;SqlDataRecord&gt; is what will let us use our List as the input to our user-defined table. Specifically we are implementing IEnumerable with <a href="http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.server.sqldatarecord.aspx">SqlDataRecord</a>, this represents a single row of data and its associated metadata. This is what ADO.Net and SQL Server will need to map our list of aliases to our user-defined table. The <a href="http://msdn.microsoft.com/en-us/library/bb675163.aspx">documentation</a> is not really clear on this part unfortunately, it leads you to believe that anything that implements IEnumerable should suffice, however; what you must have is IEnumerable with SqlDataReader. This does not come out of the box with List&lt;Alias&gt; so we create our own, otherwise we’ll get an InvalidCastException.</p>
<p>Finally, from our client, using the <a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx">Enterprise Library Data Access</a>, we can load people and aliases using a user-defined table type.</p>
<blockquote>
<pre>
Person person = new Person("Bryan", "Smith");
person.Aliases.Add(new Alias("DBA", "Dude"));
person.Aliases.Add(new Alias("Database", "Guy"));
 
SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase("UDTTest");
DbCommand cmd = db.GetStoredProcCommand("usp_ins_Person");
 
db.AddInParameter(cmd, "@FirstName", DbType.String, person.FirstName);
db.AddInParameter(cmd, "@LastName", DbType.String, person.LastName);
db.AddInParameter(cmd, "@Aliases", SqlDbType.Structured, person.Aliases);
 
db.ExecuteNonQuery(cmd);</pre>
</blockquote>
<p>I know personally, I’ll be using this method from now one whenever possible over using user-defined tables with ad-hoc DataTables to load data, or heaven forbid calling the same stored procedure repeatedly.</p>
]]></content:encoded>
			<wfw:commentRss>http://orionseven.com/blog/2009/09/30/using-table-valued-parameters-in-sql-server-2008-and-c/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

