<?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/"
	>

<channel>
	<title>Graeme Hill on .NET development</title>
	<atom:link href="http://graemehill.ca/feed" rel="self" type="application/rss+xml" />
	<link>http://graemehill.ca</link>
	<description></description>
	<pubDate>Thu, 11 Mar 2010 03:30:04 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>CruiseControl.NET: Versioning ccnet.config and integrating it into CI</title>
		<link>http://graemehill.ca/cruisecontrolnet-versioning-ccnetconfig-and-integrating-it-into-ci</link>
		<comments>http://graemehill.ca/cruisecontrolnet-versioning-ccnetconfig-and-integrating-it-into-ci#comments</comments>
		<pubDate>Thu, 11 Mar 2010 03:29:10 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[Continuous Integration]]></category>

		<category><![CDATA[CruiseControl.NET]]></category>

		<category><![CDATA[SVN]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=255</guid>
		<description><![CDATA[Cruise Control is meant to help manage your builds based on the code in source control, and since ccnet config files are basically code, it only makes sense that they should be a part of this process.  Basically, there are two problems I wanted to solve:

If I change ccnet.config and introduce an error, I [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://sourceforge.net/projects/ccnet/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://sourceforge.net/projects/ccnet/');">Cruise Control</a> is meant to help manage your builds based on the code in source control, and since ccnet config files are basically code, it only makes sense that they should be a part of this process.  Basically, there are two problems I wanted to solve:</p>
<ul>
<li>If I change ccnet.config and introduce an error, I want to be able to roll back to a previous version in SVN.</li>
<li>When multiple developers are working on ccnet.config, they should not be fighting over the same file on the CI server.  Instead, each developer should be editing a file in their working copy and then merging changes into the repository.</li>
</ul>
<p>Both of these issues are actually very easy to solve.  Using SVN, you can create a repository with only one file: ccnet.config.  Then add this project to <em>both</em> the ccnet.config in SVN and the one actually used by Cruise Control (probably in C:\Program Files\CruiseControl.NET or something like that):</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;project</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;ccnet config&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sourcecontrol</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;svn&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;executable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>C:\path\to\svn\on\CI\server\svn.exe<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/executable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;workingDirectory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>C:\CI<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/workingDirectory<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;trunkUrl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://localhost/svn/myrepo/trunk<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/trunkUrl<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;autoGetSource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/autoGetSource<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>SVN_USERNAME<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>SVN_PASSWORD<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sourcecontrol<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tasks<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;exec<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;executable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>C:\Windows\System32\xcopy.exe<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/executable<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;buildArgs<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/Y C:\CI\ccnet-config\ccnet.config &quot;C:\Program Files\CruiseControl.NET\server&quot;<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/buildArgs<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/exec<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tasks<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/project<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>All this does is check out the config file and then copy it to the location used by Cruise Control.  Remember to edit all the paths above with the actual ones for your setup.</p>
<p>That&#8217;s all you need to do!  The config file is now versioned and Cruise Control is automatically updating itself every time you commit.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/cruisecontrolnet-versioning-ccnetconfig-and-integrating-it-into-ci/feed</wfw:commentRss>
		</item>
		<item>
		<title>LINQ to SQL Gotcha #5: Column Default Values</title>
		<link>http://graemehill.ca/linq-to-sql-gotcha-5-column-default-values</link>
		<comments>http://graemehill.ca/linq-to-sql-gotcha-5-column-default-values#comments</comments>
		<pubDate>Sat, 06 Mar 2010 17:17:56 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=246</guid>
		<description><![CDATA[A common pattern in database design is to use make a column required, give it a default value and then never think about it when doing INSERTs.  A perfect example would be a createdDate column on the Users with a default value of GetDate().  Here&#8217;s the full table definition:

userID (identity key)
userName
password
ts (timestamp)
createdDate (default [...]]]></description>
			<content:encoded><![CDATA[<p>A common pattern in database design is to use make a column required, give it a default value and then never think about it when doing <code>INSERT</code>s.  A perfect example would be a <code>createdDate</code> column on the <code>Users</code> with a default value of <code>GetDate()</code>.  Here&#8217;s the full table definition:</p>
<ul>
<li>userID (identity key)</li>
<li>userName</li>
<li>password</li>
<li>ts (timestamp)</li>
<li>createdDate (default value = GetDate())</li>
</ul>
<p>In this case we can easily insert into the table without worrying about the <code>createdDate</code>, <code>userID</code>, or <code>ts</code> columns:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> Users <span style="color: #66cc66;">&#40;</span>userName<span style="color: #66cc66;">,</span> password<span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'asdf'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'qwer'</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>However, since this is the 21st century, we don&#8217;t want to do this in SQL, we want to do it with an ORM.  Unfortunately, LINQ to SQL doesn&#8217;t do a very good job with this.</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Using context = <span style="color: #000080;">New</span> TestDataContext
&nbsp;
    <span style="color: #008000;">' Output SQL to the console for debugging
</span>    context.Log = Console.Out
&nbsp;
    <span style="color: #008000;">' Attach a new user and submit the changes
</span>    <span style="color: #000080;">Dim</span> newUser <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> User <span style="color: #000080;">With</span> {.userName = &quot;NewUser&quot;, .password = &quot;password&quot;}
    context.Users.InsertOnSubmit(newUser)
    context.SubmitChanges()
&nbsp;
<span style="color: #000080;">End</span> Using</pre></div></div>

<p>The above code generates the following <code>INSERT</code> statement when <code>SubmitChanges()</code> is called (note: I replaced <code>@p0</code>, <code>@p1</code>, etc with their actual values to make the query more readable):</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">INSERT</span> <span style="color: #993333; font-weight: bold;">INTO</span> <span style="color: #66cc66;">&#91;</span>dbo<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">.</span><span style="color: #66cc66;">&#91;</span>Users<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#91;</span>userName<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>password<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">,</span> <span style="color: #66cc66;">&#91;</span>createdDate<span style="color: #66cc66;">&#93;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">VALUES</span> <span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">'NewUser'</span><span style="color: #66cc66;">,</span> <span style="color: #ff0000;">'password'</span><span style="color: #66cc66;">,</span> <span style="color: #993333; font-weight: bold;">NULL</span><span style="color: #66cc66;">&#41;</span></pre></div></div>

<p>This query fails and we get a <code>SqlTypeException</code> because <code>createdDate</code> is <code>NOT NULL</code> and <code>NULL</code> cannot be converted to a valid date.  Notice that the generated SQL does not attempt to explicitly set a value for <code>userID</code> or <code>ts</code>.  It appears that LINQ to SQL knows how to deal with <code>IDENTITY</code> fields and <code>TIMESTAMP</code>s, but not how to deal with other required columns that happen to have a default value.</p>
<p>I would have expected LINQ to SQL to generate a query that does not explicitly set <code>createdDate</code> so that SQL Server could handle it, but no such luck.  You can easily set the <code>createdDate</code> manually like this:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #000080;">Dim</span> newUser <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> User <span style="color: #000080;">With</span> {.userName = &quot;NewUser&quot;, .password = &quot;password&quot;, .createdDate = <span style="color: #000080;">Date</span>.Now}</pre></div></div>

<p>It really sucks to have to do this every time though, especially if you have many fields to fill in.  A possible alternative is to put a partial class on either your <code>DataContext</code> or just on the <code>User</code> class and write some code that will automatically initialize fields like <code>createdDate</code>.   If you want to make generic behaviour for this (eg: automatically set columns named &#8220;createdDate&#8221; to <code>Date.Now</code> when <code>SubmitChanges</code> is called) you can do something like this in the <code>DataContext</code> partial class:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #000080;">Public</span> Overrides <span style="color: #000080;">Sub</span> SubmitChanges(<span style="color: #000080;">ByVal</span> failureMode <span style="color: #000080;">As</span> ConflictMode)
&nbsp;
    <span style="color: #008000;">' NOTE: this is just a sample to get you started
</span>    <span style="color: #000080;">For</span> <span style="color: #000080;">Each</span> insert <span style="color: #000080;">In</span> GetChangeSet().Inserts
        <span style="color: #000080;">Dim</span> createdDateProp = insert.GetType.GetProperty(&quot;createdDate&quot;)
        <span style="color: #000080;">If</span> createdDateProp IsNot <span style="color: #000080;">Nothing</span> <span style="color: #000080;">Then</span>
            createdDateProp.SetValue(insert, <span style="color: #000080;">Date</span>.Now, <span style="color: #000080;">Nothing</span>)
        <span style="color: #000080;">End</span> <span style="color: #000080;">If</span>
    <span style="color: #000080;">Next</span>
&nbsp;
    MyBase.SubmitChanges(failureMode)
&nbsp;
<span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/linq-to-sql-gotcha-5-column-default-values/feed</wfw:commentRss>
		</item>
		<item>
		<title>Saving changes to stored procedure results in LINQ to SQL</title>
		<link>http://graemehill.ca/saving-changes-to-stored-procedure-results-in-linq-to-sql</link>
		<comments>http://graemehill.ca/saving-changes-to-stored-procedure-results-in-linq-to-sql#comments</comments>
		<pubDate>Wed, 10 Feb 2010 05:23:15 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=238</guid>
		<description><![CDATA[The great thing about fetching data via a LINQ to SQL query is that you get a nice formatted result and you can easily save back any changes you make with SubmitChanges().  Unfortunately, we all inevitably fall into scenarios where we have to make use of stored procedures for performance or other reasons.  [...]]]></description>
			<content:encoded><![CDATA[<p>The great thing about fetching data via a LINQ to SQL query is that you get a nice formatted result and you can easily save back any changes you make with <code>SubmitChanges()</code>.  Unfortunately, we all inevitably fall into scenarios where we have to make use of stored procedures for performance or other reasons.  If you have a stored procedure whose result set contains columns from just a single table then you can easily map the stored procedure to that table, but in most cases the result set involves multiple tables making things a little more tricky.  It&#8217;s easy to execute a stored procedure from LINQ to SQL (just drag the SP from the server explorer into the designer and then execute it like a function on the data context) but you lose some of the benefits of LINQ to SQL.  First of all, you just get a flat result set instead of a hierarchical result set using the auto generated entity classes.  Second, you can&#8217;t just make changes to the result and call <code>SubmitChanges</code>.  Luckily, with a little extra work, the flat, detached result set can be converted into a hierarchical, attached result set where changes can easily be saved.</p>
<p>If you don&#8217;t want to bother reading the whole article and all of the code, here&#8217;s the short answer: use the <code>Attach()</code> method.</p>
<p>Below is an example that runs a stored procedure to return all users in the database joined with their articles.  The results are converted into an attached list of users, each containing a collection of articles.  Notice that not all of the columns need to be known, just the primary key and timestamp are required.  For more info on the timestamp, check out <a href="http://graemehill.ca/linq-to-sql-gotcha-4-changeconflictexception-on-update-of-manually-attached-data" >this article</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Module Module1
&nbsp;
    <span style="color: #000080;">Sub</span> Main()
&nbsp;
        Using testContext <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
&nbsp;
            <span style="color: #008000;">' Print SQL queries to the console for testing purposes
</span>            testContext.Log = Console.Out
&nbsp;
            <span style="color: #008000;">' Get attached entities
</span>            <span style="color: #000080;">Dim</span> users = GetAttachedUsersWithGroups(testContext)
&nbsp;
            <span style="color: #008000;">' Make some random changes to prove the concept
</span>            users.First.userName = &quot;foo&quot;
            users.First.Articles.First.text = &quot;bar&quot;
&nbsp;
            <span style="color: #008000;">' Submit the changes to see what SQL gets executed
</span>            testContext.SubmitChanges()
&nbsp;
        <span style="color: #000080;">End</span> Using
&nbsp;
        Console.ReadKey()
&nbsp;
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
    <span style="color: #000080;">Public</span> <span style="color: #000080;">Function</span> GetAttachedUsersWithGroups(<span style="color: #000080;">ByVal</span> context <span style="color: #000080;">As</span> TestDataContext) <span style="color: #000080;">As</span> IEnumerable(Of User)
&nbsp;
        <span style="color: #008000;">' Get some data from a stored procedure
</span>        <span style="color: #000080;">Dim</span> result = context.GetAllUsersWithArticles
&nbsp;
        <span style="color: #008000;">' Convert flat result set to groups of articles by user
</span>        <span style="color: #000080;">Dim</span> userGroups = From row <span style="color: #000080;">In</span> result _
                         Group row By row.userID, row.userTimestamp _
                         Into articles = Group _
                         <span style="color: #000080;">Select</span> userID, userTimestamp, articles
&nbsp;
        <span style="color: #000080;">Dim</span> users <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> List(Of User)
&nbsp;
        <span style="color: #008000;">' Create LINQ to SQL entities
</span>        <span style="color: #000080;">For</span> <span style="color: #000080;">Each</span> userGroup <span style="color: #000080;">In</span> userGroups
            <span style="color: #000080;">Dim</span> user <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> User <span style="color: #000080;">With</span> {.userID = userGroup.userID, _
                                       .ts = userGroup.userTimestamp}
            <span style="color: #000080;">For</span> <span style="color: #000080;">Each</span> article <span style="color: #000080;">In</span> userGroup.articles
                user.Articles.Add(<span style="color: #000080;">New</span> Article <span style="color: #000080;">With</span> {.articleID = article.articleID, _
                                                    .title = article.title, _
                                                    .ts = article.articleTimestamp})
            <span style="color: #000080;">Next</span>
            users.Add(user)
        <span style="color: #000080;">Next</span>
&nbsp;
        <span style="color: #008000;">' Attach the users to the data context.  This will also attach the articles
</span>        <span style="color: #008000;">' because they have been added to each user's Articles collection.
</span>        context.Users.AttachAll(users)
&nbsp;
        Return users
&nbsp;
    <span style="color: #000080;">End</span> <span style="color: #000080;">Function</span>
&nbsp;
<span style="color: #000080;">End</span> Module</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/saving-changes-to-stored-procedure-results-in-linq-to-sql/feed</wfw:commentRss>
		</item>
		<item>
		<title>LINQ to SQL Gotcha #4: ChangeConflictException on Update of Manually Attached Data</title>
		<link>http://graemehill.ca/linq-to-sql-gotcha-4-changeconflictexception-on-update-of-manually-attached-data</link>
		<comments>http://graemehill.ca/linq-to-sql-gotcha-4-changeconflictexception-on-update-of-manually-attached-data#comments</comments>
		<pubDate>Wed, 10 Feb 2010 05:00:08 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=232</guid>
		<description><![CDATA[LINQ to SQL has built in optimistic concurrency checking.  When you create an unattached entity and then attach it (ie: with the Attach() function) the concurrency check will always fail by throwing a ChangeConflictException unless one of the two are true:

The table that the entity belongs to has a timestamp column and its value [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ to SQL has built in <a href="http://en.wikipedia.org/wiki/Optimistic_concurrency_control" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://en.wikipedia.org/wiki/Optimistic_concurrency_control');">optimistic concurrency</a> checking.  When you create an unattached entity and then attach it (ie: with the <code>Attach()</code> function) the concurrency check will always fail by throwing a <code>ChangeConflictException</code> unless one of the two are true:</p>
<ul>
<li>The table that the entity belongs to has a timestamp column and its value is exactly the same as it appears in the database.</li>
<li>There is no timestamp column but the &#8220;no count&#8221; feature on SQL Server is <em>off</em>.
</ul>
<p>Using a timestamp column seems like the more elegant solution, but it does require that you know the timestamp value.  This usually means that if you&#8217;re attaching the result of a stored procedure so that you can save back the results, your stored procedure needs to return the timestamp in addition to the primary key.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/linq-to-sql-gotcha-4-changeconflictexception-on-update-of-manually-attached-data/feed</wfw:commentRss>
		</item>
		<item>
		<title>LINQ to SQL Gotcha #3: Chaining Where Clauses</title>
		<link>http://graemehill.ca/linq-to-sql-gotcha-3-chaining-where-clauses</link>
		<comments>http://graemehill.ca/linq-to-sql-gotcha-3-chaining-where-clauses#comments</comments>
		<pubDate>Sat, 06 Feb 2010 03:26:57 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=225</guid>
		<description><![CDATA[In LINQ to SQL you can chain multiple where clauses like this:

Module Module1
&#160;
    Sub Main()
&#160;
        Using context As New TestDataContext
            context.Log = Console.Out
            [...]]]></description>
			<content:encoded><![CDATA[<p>In LINQ to SQL you can chain multiple where clauses like this:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Module Module1
&nbsp;
    <span style="color: #000080;">Sub</span> Main()
&nbsp;
        Using context <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
            context.Log = Console.Out
            <span style="color: #000080;">Dim</span> articles = context.Articles.Where(<span style="color: #000080;">Function</span>(a) a.articleID &gt; 10) _
                                           .Where(<span style="color: #000080;">Function</span>(a) a.articleID <span style="color: #000080;">Mod</span> 2 = 0) _
                                           .ToList()
        <span style="color: #000080;">End</span> Using
&nbsp;
        Console.ReadKey()
&nbsp;
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
<span style="color: #000080;">End</span> Module</pre></div></div>

<p>This will generate SQL that looks roughly like this:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">...</span> <span style="color: #993333; font-weight: bold;">FROM</span> Articles <span style="color: #993333; font-weight: bold;">WHERE</span> articleID <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">10</span> <span style="color: #993333; font-weight: bold;">AND</span> articleID % <span style="color: #cc66cc;">2</span> <span style="color: #66cc66;">=</span> <span style="color: #cc66cc;">0</span></pre></div></div>

<p>Since chained where clauses are equivalent to <code>AND</code>ing multiple expressions in a single <code>WHERE</code>, the above SQL is exactly what you would expect to see.  Unfortunately, things get more complicated when one of the expressions cannot be converted to SQL, like in this case:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Module Module1
&nbsp;
    <span style="color: #000080;">Sub</span> Main()
&nbsp;
        Using context <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
            context.Log = Console.Out
            <span style="color: #000080;">Dim</span> articles = context.Articles.Where(<span style="color: #000080;">AddressOf</span> FilterArticle).ToList()
        <span style="color: #000080;">End</span> Using
&nbsp;
        Console.ReadKey()
&nbsp;
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
    <span style="color: #000080;">Function</span> FilterArticle(<span style="color: #000080;">ByVal</span> a <span style="color: #000080;">As</span> Article) <span style="color: #000080;">As</span> <span style="color: #000080;">Boolean</span>
        Return a.articleID <span style="color: #000080;">Mod</span> 2 = 0
    <span style="color: #000080;">End</span> <span style="color: #000080;">Function</span>
&nbsp;
<span style="color: #000080;">End</span> Module</pre></div></div>

<p>The above code generates SQL that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">...</span> <span style="color: #993333; font-weight: bold;">FROM</span> Articles</pre></div></div>

<p>The query has no where clause, it just loads <em>all</em> the articles and then filters them on the client side.  It&#8217;s usually optimal to do the filtering on the SQL side, but the behaviour is reasonable.  I wouldn&#8217;t expect the ORM to be capable of magically converting the contents of the <code>FilterArticle</code> function into SQL (it sure would be nice though).  This is still expected behaviour, but here&#8217;s an example where things get weird:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Module Module1
&nbsp;
    <span style="color: #000080;">Sub</span> Main()
&nbsp;
        Using context <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
            context.Log = Console.Out
            <span style="color: #000080;">Dim</span> articles = context.Articles.Where(<span style="color: #000080;">AddressOf</span> FilterArticle) _
                                           .Where(<span style="color: #000080;">Function</span>(a) a.articleID &gt; 10) _
                                           .ToList()
        <span style="color: #000080;">End</span> Using
&nbsp;
        Console.ReadKey()
&nbsp;
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
    <span style="color: #000080;">Function</span> FilterArticle(<span style="color: #000080;">ByVal</span> a <span style="color: #000080;">As</span> Article) <span style="color: #000080;">As</span> <span style="color: #000080;">Boolean</span>
        Return a.articleID <span style="color: #000080;">Mod</span> 2 = 0
    <span style="color: #000080;">End</span> <span style="color: #000080;">Function</span>
&nbsp;
<span style="color: #000080;">End</span> Module</pre></div></div>

<p>This code generates the same SQL as last time:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">...</span> <span style="color: #993333; font-weight: bold;">FROM</span> Articles</pre></div></div>

<p>It is filtering <em>both</em> where clauses on the client side even though the second one could have been converted to SQL.  If you flip the where clauses like this:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Module Module1
&nbsp;
    <span style="color: #000080;">Sub</span> Main()
&nbsp;
        Using context <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
            context.Log = Console.Out
            <span style="color: #000080;">Dim</span> articles = context.Articles.Where(<span style="color: #000080;">Function</span>(a) a.articleID &gt; 10) _
                                           .Where(<span style="color: #000080;">AddressOf</span> FilterArticle) _
                                           .ToList()
        <span style="color: #000080;">End</span> Using
&nbsp;
        Console.ReadKey()
&nbsp;
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
    <span style="color: #000080;">Function</span> FilterArticle(<span style="color: #000080;">ByVal</span> a <span style="color: #000080;">As</span> Article) <span style="color: #000080;">As</span> <span style="color: #000080;">Boolean</span>
        Return a.articleID <span style="color: #000080;">Mod</span> 2 = 0
    <span style="color: #000080;">End</span> <span style="color: #000080;">Function</span>
&nbsp;
<span style="color: #000080;">End</span> Module</pre></div></div>

<p>then you will still get the expected SQL:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">...</span> <span style="color: #993333; font-weight: bold;">FROM</span> Articles <span style="color: #993333; font-weight: bold;">WHERE</span> articleID <span style="color: #66cc66;">&gt;</span> <span style="color: #cc66cc;">10</span></pre></div></div>

<p>The where clause that can be converted to SQL is filtered in the <code>SELECT</code> statement, but the clause than cannot be converted is filtered on the client side.  I would have hoped that the order of the where clauses would not matter since they are just being <code>AND</code>ed, but that is not the case.</p>
<p>The lesson is that if you need to chain a where clause that cannot be converted to SQL, try to put it at the end of the chain.  This can be a real issue if you are using a data access layer that automatically filters queries (eg: for security) with a function that cannot convert to SQL.  If all of your LINQ to SQL queries have this built in filter then <em>none</em> of them will <em>ever</em> generate <code>WHERE</code> clauses in the SQL, it will just load the entire table every time.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/linq-to-sql-gotcha-3-chaining-where-clauses/feed</wfw:commentRss>
		</item>
		<item>
		<title>WPF Responsiveness: Asynchronous Loading Animations During Rendering</title>
		<link>http://graemehill.ca/wpf-responsiveness-asynchronous-loading-animations-during-rendering</link>
		<comments>http://graemehill.ca/wpf-responsiveness-asynchronous-loading-animations-during-rendering#comments</comments>
		<pubDate>Fri, 05 Feb 2010 04:57:08 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[VB.NET]]></category>

		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=212</guid>
		<description><![CDATA[Download the code here: WpfLoadingOverlay.zip
A common issue in MDI or TDI style user interfaces is that it can take a long time to render new forms when they are opened.  Even a one or two second delay is enough to make an application seem very unresponsive.  If there&#8217;s nothing you can do to [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Download the code here:</strong> <a href="http://graemehill.ca/samples/WpfLoadingOverlay.zip" onclick="javascript:pageTracker._trackPageview('/downloads/samples/WpfLoadingOverlay.zip');">WpfLoadingOverlay.zip</a></p>
<p><img class="alignright size-full wp-image-216" src="http://graemehill.ca/wp-content/uploads/2010/02/asyncloading.png" alt="" width="374" height="271" />A common issue in MDI or TDI style user interfaces is that it can take a long time to render new forms when they are opened.  Even a one or two second delay is enough to make an application seem very unresponsive.  If there&#8217;s nothing you can do to improve the <em>actual</em> performance (ie: the total time to load the form) you can at least improve the <em>perceived</em> performance.  This code sample creates a simple form with a tab control and a button.  Every time you click the button it adds a new tab with 4000 text boxes.  Depending on the speed of your computer the form will probably take around five seconds to load.  As soon as you click the button, the new tab appears with a loading animation that continues until the contents have been rendered.  This is not a trivial task because we want to render a loading animation at the same time that we are waiting for another long rendering operation to complete.  Basically, we need two rendering threads.  You can&#8217;t have multiple rendering threads in a single window, but you <em>can</em> put your loading animation in a new window with its own rendering thread and make it look like it&#8217;s not a separate window.</p>
<p>The loading overlay is a separate, chromeless window that does not appear on the taskbar and disappears as soon as loading is complete.  The window is also semi-transparent and automatically positioned exactly over top of the form that is loading, so it looks like it is a part of the existing window.</p>
<p>Download the <a href="http://graemehill.ca/samples/WpfLoadingOverlay.zip" onclick="javascript:pageTracker._trackPageview('/downloads/samples/WpfLoadingOverlay.zip');">sample project</a> and try it out.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/wpf-responsiveness-asynchronous-loading-animations-during-rendering/feed</wfw:commentRss>
		</item>
		<item>
		<title>LINQ to SQL Gotcha #2: GetChangeSet Weirdness</title>
		<link>http://graemehill.ca/linq-to-sql-gotcha-2-getchangeset-weirdness</link>
		<comments>http://graemehill.ca/linq-to-sql-gotcha-2-getchangeset-weirdness#comments</comments>
		<pubDate>Mon, 01 Feb 2010 04:45:17 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=206</guid>
		<description><![CDATA[If you attach an entity with a required association that is nulled out, you will be unable to call GetChangeSet().  In my opinion, the expected behaviour is that the entity should show up in the change set as though it is valid, but an exception should be thrown when you attempt to call SubmitChanges() [...]]]></description>
			<content:encoded><![CDATA[<p>If you attach an entity with a required association that is nulled out, you will be unable to call <code>GetChangeSet()</code>.  In my opinion, the expected behaviour is that the entity should show up in the change set as though it is valid, but an exception should be thrown when you attempt to call <code>SubmitChanges()</code> because a foreign key constraint has been violated.  In fact, with code like this we will get exactly that result (an exception is thrown on <code>SubmitChanges()</code>):</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Using testData <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
    <span style="color: #000080;">Dim</span> newArticle <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> Article <span style="color: #000080;">With</span> {.title = &quot;Foobar&quot;, _
                                        .text = &quot;blah blah blah&quot;}
    testData.Articles.InsertOnSubmit(newArticle)
    <span style="color: #000080;">Dim</span> changes = testData.GetChangeSet()
    testData.SubmitChanges()
<span style="color: #000080;">End</span> Using</pre></div></div>

<p>There is a required association to the <code>Users</code> table that has not been set at all.  Using the following snippet, with the <code>User</code> property explicitly set to <code>Nothing</code> an exception will be thrown on <code>GetChangeSet()</code> instead of <code>SubmitChanges()</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Using testData <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
    <span style="color: #000080;">Dim</span> newArticle <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> Article <span style="color: #000080;">With</span> {.title = &quot;Foobar&quot;, _
                                        .text = &quot;blah blah blah&quot;, _
                                        .User = <span style="color: #000080;">Nothing</span>}
    testData.Articles.InsertOnSubmit(newArticle)
    <span style="color: #000080;">Dim</span> changes = testData.GetChangeSet()
    testData.SubmitChanges()
<span style="color: #000080;">End</span> Using</pre></div></div>

<p>It gives this error on <code>GetChangeSet()</code>:</p>
<blockquote><p>
An attempt was made to remove a relationship between a User and a Article. However, one of the relationship&#8217;s foreign keys (Article.userID) cannot be set to null.
</p></blockquote>
<p>It appears that the internal implementation of LINQ to SQL distinguishes between an unset relationship, and one that has specifically been set to <code>Nothing</code>.  The awkward thing here is that it is not always easy to avoid this issue since you don&#8217;t even have to call <code>InsertOnSubmit</code>.  Attaching an entity by setting an association to an already attached object gives the same result.</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Using testData <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
    <span style="color: #000080;">Dim</span> existingUser = testData.Users.First
    <span style="color: #000080;">Dim</span> newUserGroup <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> UserGroup <span style="color: #000080;">With</span> {.User = existingUser, .Group = <span style="color: #000080;">Nothing</span>}
    <span style="color: #000080;">Dim</span> changes = testData.GetChangeSet()
    testData.SubmitChanges()
<span style="color: #000080;">End</span> Using</pre></div></div>

<p>In this snippet there are two required associations: <code>User</code> and <code>Group</code>.  As soon as <code>User</code> is set, the <code>UserGroup</code> entity is attached to the <code>DataContext</code>.  However, since <code>Group</code> is <code>Nothing</code> the <code>ChangeSet</code> is now corrupt.</p>
<p>This <em>bug</em> is described in <a href="http://social.msdn.microsoft.com/forums/en-US/linqtosql/thread/78ea42d2-695d-42f3-9680-4698fc7b7030/" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://social.msdn.microsoft.com/forums/en-US/linqtosql/thread/78ea42d2-695d-42f3-9680-4698fc7b7030/');">this forum thread</a> where a Microsoft employee called it a bug and recommended that he post it on Connect (Microsoft&#8217;s bug tracking site).  The bug report on Connect can be found <a href="https://connect.microsoft.com/VisualStudio/feedback/details/343378/getchangeset-throws-exception-when-fk-has-been-nulled-out" onclick="javascript:pageTracker._trackPageview('/outbound/article/https://connect.microsoft.com/VisualStudio/feedback/details/343378/getchangeset-throws-exception-when-fk-has-been-nulled-out');">here</a>.  One hour after it was posted Microsoft replied saying this:</p>
<blockquote><p>
We are currently investigating. The investigation process normally takes 7-14 days.
</p></blockquote>
<p>They then went silent for <em>9 months</em> before posting this:</p>
<blockquote><p>
Hi,</p>
<p>Thank you for taking the time to send this feedback and bug report. We have reviewed the issue and confirmed the behavior, but we will not be fixing this in the next release of LINQ to SQL.</p>
<p>LINQ to SQL Team
</p></blockquote>
<p>That&#8217;s Microsoft for ya.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/linq-to-sql-gotcha-2-getchangeset-weirdness/feed</wfw:commentRss>
		</item>
		<item>
		<title>LINQ to SQL Gotcha #1: Unexpected LoadWith Behaviour</title>
		<link>http://graemehill.ca/linq-to-sql-gotcha-1-unexpected-loadwith-behaviour</link>
		<comments>http://graemehill.ca/linq-to-sql-gotcha-1-unexpected-loadwith-behaviour#comments</comments>
		<pubDate>Mon, 01 Feb 2010 00:48:26 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=196</guid>
		<description><![CDATA[By default, LINQ to SQL uses deferred loading.  When you want to eager load an entity&#8217;s associated data you need to set DataLoadOptions using the LoadOptions property on the DataContext.  If you have a one-to-many relationship between Users and Articles you can force LINQ to SQL to eager load Articles with Users like [...]]]></description>
			<content:encoded><![CDATA[<p>By default, LINQ to SQL uses deferred loading.  When you want to eager load an entity&#8217;s associated data you need to set <code>DataLoadOptions</code> using the <code>LoadOptions</code> property on the <code>DataContext</code>.  If you have a one-to-many relationship between <code>Users</code> and <code>Articles</code> you can force LINQ to SQL to eager load <code>Articles</code> with <code>Users</code> like this:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Using testData <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
&nbsp;
    <span style="color: #008000;">' Log SQL queries to the console
</span>    testData.Log = Console.Out
&nbsp;
    <span style="color: #008000;">' Set LoadOptions
</span>    <span style="color: #000080;">Dim</span> options <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataLoadOptions
    options.LoadWith(<span style="color: #000080;">Function</span>(user <span style="color: #000080;">As</span> User) user.Articles)
    testData.LoadOptions = options
&nbsp;
    <span style="color: #008000;">' Load users with their articles
</span>    <span style="color: #000080;">Dim</span> users = testData.Users.ToList
    <span style="color: #000080;">For</span> <span style="color: #000080;">Each</span> user <span style="color: #000080;">In</span> users
        <span style="color: #000080;">Dim</span> articles = user.Articles.ToList
    <span style="color: #000080;">Next</span>
&nbsp;
<span style="color: #000080;">End</span> Using</pre></div></div>

<p>This will generate a single <code>SELECT</code> statement with a <code>JOIN</code> on the <code>Articles</code> table.  The same goes for for one-to-one relationships.  You can also use <code>LoadWith</code> as many times as you want.  For one-to-one relationships and no more than a single one-to-many relationship this will still generate one query with <code>JOIN</code>s to all the <code>LoadWith</code> tables.  However, if you want to eager load multiple one-to-many relationships you will get into a select N + 1 situation (or worse).  For example, this code eager loads <code>Articles</code> and <code>UserGroups</code> with each <code>User</code> entity:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Using testData <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> TestDataContext
&nbsp;
    <span style="color: #008000;">' Log SQL queries to the console
</span>    testData.Log = Console.Out
&nbsp;
    <span style="color: #008000;">' Set LoadOptions
</span>    <span style="color: #000080;">Dim</span> options <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataLoadOptions
    options.LoadWith(<span style="color: #000080;">Function</span>(user <span style="color: #000080;">As</span> User) user.Articles)
    options.LoadWith(<span style="color: #000080;">Function</span>(user <span style="color: #000080;">As</span> User) user.UserGroups)
    testData.LoadOptions = options
&nbsp;
    <span style="color: #008000;">' Load users with their articles
</span>    <span style="color: #000080;">Dim</span> users = testData.Users.ToList
    <span style="color: #000080;">For</span> <span style="color: #000080;">Each</span> user <span style="color: #000080;">In</span> users
        <span style="color: #000080;">Dim</span> articles = user.Articles.ToList
        <span style="color: #000080;">Dim</span> userGroups = user.UserGroups.ToList
    <span style="color: #000080;">Next</span>
&nbsp;
<span style="color: #000080;">End</span> Using</pre></div></div>

<p>Technically, the behaviour here is correct.  It will successfully eager load both the <code>Articles</code> and <code>UserGroups</code> collections for each <code>User</code>, but it will <em>not</em> do it in a single query.  When I ran this I got one query that fetched the <code>Users</code> and <code>Articles</code> like last time, but then a separate <code>SELECT</code> for each <code>UserGroup</code> rather than another <code>JOIN</code>.  Even though this won&#8217;t alter the behaviour of the code, it will definitely make a major impact on performance, especially if there are a lot of users in the database.</p>
<p>Scott Guthrie confirmed this behaviour in a <a href="http://codebetter.com/blogs/david.hayden/archive/2007/08/06/linq-to-sql-query-tuning-appears-to-break-down-in-more-advanced-scenarios.aspx" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://codebetter.com/blogs/david.hayden/archive/2007/08/06/linq-to-sql-query-tuning-appears-to-break-down-in-more-advanced-scenarios.aspx');">post on David Hayden&#8217;s blog</a>.  This is what he said:</p>
<blockquote><p>
In the case of a 1:n associations, LINQ to SQL only supports joining-in one 1:n association per query.
</p></blockquote>
<p>Lame.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/linq-to-sql-gotcha-1-unexpected-loadwith-behaviour/feed</wfw:commentRss>
		</item>
		<item>
		<title>SQL Server Management Studio and default databases</title>
		<link>http://graemehill.ca/sql-server-management-studio-and-default-databases</link>
		<comments>http://graemehill.ca/sql-server-management-studio-and-default-databases#comments</comments>
		<pubDate>Sun, 31 Jan 2010 05:04:13 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=189</guid>
		<description><![CDATA[There is a really annoying bug (or at least what I would call a bug) in SQL Server Management Studio where you cannot login with a user whose default database does not exist.  Even if you are already logged in and you rename the default database, you will automatically be logged out and will [...]]]></description>
			<content:encoded><![CDATA[<p>There is a really annoying bug (or at least what I would call a bug) in SQL Server Management Studio where you cannot login with a user whose default database does not exist.  Even if you are already logged in and you rename the default database, you will automatically be logged out and will receive an error every time you try to login again.  You can always login as a different user and change the default database, but if you only have access to the one account, you can change the default database using <code>sqlcmd</code>.</p>
<p>First, login with a different database in a command window:<br />
<code><br />
sqlcmd -d master -S server -U username -P password<br />
</code></p>
<p>Then issue the following commands to change the default database:<br />
<code><br />
1> ALTER LOGIN login_name WITH DEFAULT_DATABASE = master<br />
2> GO<br />
</code></p>
<p>You should now be able to login with this account through management studio.</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/sql-server-management-studio-and-default-databases/feed</wfw:commentRss>
		</item>
		<item>
		<title>High performance database rollback in automated tests with SQL Server</title>
		<link>http://graemehill.ca/high-performance-database-rollback-in-automated-tests-with-sql-server</link>
		<comments>http://graemehill.ca/high-performance-database-rollback-in-automated-tests-with-sql-server#comments</comments>
		<pubDate>Sat, 23 Jan 2010 17:15:15 +0000</pubDate>
		<dc:creator>Graeme</dc:creator>
		
		<category><![CDATA[Entity Framework]]></category>

		<category><![CDATA[LINQ To SQL]]></category>

		<category><![CDATA[SQL Server]]></category>

		<category><![CDATA[Unit Testing]]></category>

		<category><![CDATA[VB.NET]]></category>

		<guid isPermaLink="false">http://graemehill.ca/?p=179</guid>
		<description><![CDATA[A couple months ago I wrote this article explaining why I think it is reasonable for unit tests to hit a real database.  Subsequently, I wrote a follow up article describing some techniques for rolling back your database to its original state after each test.  In that article I found that just using [...]]]></description>
			<content:encoded><![CDATA[<p>A couple months ago I wrote <a href="http://graemehill.ca/unit-testing-an-entity-framework-data-access-layer-part-1-just-hit-the-database" >this</a> article explaining why I think it is reasonable for unit tests to hit a real database.  Subsequently, I wrote a <a href="http://graemehill.ca/unit-testing-an-entity-framework-data-access-layer-part-2-rolling-back-the-test-database" >follow up article</a> describing some techniques for rolling back your database to its original state after each test.  In that article I found that just using simple transactions did not solve the problem because you need access to all database connections being used, and they all have to be rolled back.  I have since found a way around this problem using distributed transactions.</p>
<p>With the <a href="http://en.wikipedia.org/wiki/Distributed_Transaction_Coordinator" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://en.wikipedia.org/wiki/Distributed_Transaction_Coordinator');">Microsoft Distributed Transaction Coordinator</a> (MSDTC) the activity over multiple connections can be lumped into a single transaction using the <code>TransactionScope</code> class.  MSDTC needs to be running for this to work, but since this is just for unit tests it doesn&#8217;t need to be enabled on your production environment.</p>
<p>In order to use the <code>TransactionScope</code> class your project will need a reference to <code>System.Transactions</code>.  Here&#8217;s a sample unit test using MSTest and Entity Framework where the database is altered with multiple connections within a transaction and then the changes are rolled back:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Imports System.Transactions
Imports System
Imports System.Text
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
&nbsp;
&lt;TestClass()&gt; _
<span style="color: #000080;">Public</span> Class UnitTestSample
&nbsp;
    &lt;TestMethod()&gt; _
    <span style="color: #000080;">Public</span> <span style="color: #000080;">Sub</span> ProofOfConceptTest()
        Using <span style="color: #000080;">New</span> TransactionScope
            <span style="color: #000080;">Dim</span> conn1 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataTestEntities
            <span style="color: #000080;">Dim</span> conn2 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataTestEntities
&nbsp;
            <span style="color: #000080;">Dim</span> row1 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> Users <span style="color: #000080;">With</span> {.userName = &quot;user1&quot;, .password = &quot;pass&quot;}
            <span style="color: #000080;">Dim</span> row2 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> Users <span style="color: #000080;">With</span> {.userName = &quot;user2&quot;, .password = &quot;pass&quot;}
&nbsp;
            conn1.AddToUsers(row1)
            conn2.AddToUsers(row2)
&nbsp;
            conn1.SaveChanges()
            conn2.SaveChanges()
&nbsp;
            <span style="color: #000080;">Dim</span> conn3 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataTestEntities
            Assert.AreEqual(conn3.Users.Count, 6)
        <span style="color: #000080;">End</span> Using
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
<span style="color: #000080;">End</span> Class</pre></div></div>

<p>Alternatively, if you want every test method inside a test class to be within its own <code>TransactionScope</code> without adding a <code>Using</code> block to every single test, you can use the initialization an cleanup methods like this:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;">Imports System.Transactions
Imports System
Imports System.Text
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
&nbsp;
&lt;TestClass()&gt; _
<span style="color: #000080;">Public</span> Class UnitTestSample
&nbsp;
    <span style="color: #000080;">Private</span> _transaction <span style="color: #000080;">As</span> TransactionScope
&nbsp;
    &lt;TestInitialize()&gt; _
    <span style="color: #000080;">Public</span> <span style="color: #000080;">Sub</span> Setup()
        _transaction = <span style="color: #000080;">New</span> TransactionScope
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
    &lt;TestCleanup()&gt; _
    <span style="color: #000080;">Public</span> <span style="color: #000080;">Sub</span> TearDown()
        _transaction.Dispose()
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
    &lt;TestMethod()&gt; _
    <span style="color: #000080;">Public</span> <span style="color: #000080;">Sub</span> ProofOfConceptTest()
        <span style="color: #000080;">Dim</span> conn1 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataTestEntities
        <span style="color: #000080;">Dim</span> conn2 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataTestEntities
&nbsp;
        <span style="color: #000080;">Dim</span> row1 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> Users <span style="color: #000080;">With</span> {.userName = &quot;user1&quot;, .password = &quot;pass&quot;}
        <span style="color: #000080;">Dim</span> row2 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> Users <span style="color: #000080;">With</span> {.userName = &quot;user2&quot;, .password = &quot;pass&quot;}
&nbsp;
        conn1.AddToUsers(row1)
        conn2.AddToUsers(row2)
&nbsp;
        conn1.SaveChanges()
        conn2.SaveChanges()
&nbsp;
        <span style="color: #000080;">Dim</span> conn3 <span style="color: #000080;">As</span> <span style="color: #000080;">New</span> DataTestEntities
        Assert.AreEqual(conn3.Users.Count, 6)
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
<span style="color: #000080;">End</span> Class</pre></div></div>

<p>As long as the use of MSDTC is an option, I have found this method to be far better than any of those described in the <a href="http://graemehill.ca/unit-testing-an-entity-framework-data-access-layer-part-2-rolling-back-the-test-database" >last article</a>.  It guarantees that the state or your database is maintained and is extremely fast (at least on small amounts of data).</p>
]]></content:encoded>
			<wfw:commentRss>http://graemehill.ca/high-performance-database-rollback-in-automated-tests-with-sql-server/feed</wfw:commentRss>
		</item>
	</channel>
</rss>
