<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feed.damieng.com/~d/styles/itemcontent.css"?><rss 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/" version="2.0">

<channel>
	<title>DamienG</title>
	
	<link>http://damieng.com</link>
	<description>A .NET developer in Redmond</description>
	<lastBuildDate>Fri, 03 Jul 2009 05:00:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feed.damieng.com/DamienG" type="application/rss+xml" /><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.bloglines.com/sub/http://feed.damieng.com/DamienG" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.live.com/?add=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Client-side properties and any remote LINQ provider</title>
		<link>http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider</link>
		<comments>http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider#comments</comments>
		<pubDate>Wed, 24 Jun 2009 20:05:00 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[LinqToSql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1202</guid>
		<description>David Fowler on the ASP.NET team and I have been bouncing ideas about on how to solve an annoyance using LINQ:
If you write properties on the client you can’t use them in remote LINQ operations.

The problem occurs because these properties can’t be translated and sent to the server as they have been compiled into intermediate [...]</description>
			<content:encoded><![CDATA[<p><a href="http://weblogs.asp.net/davidfowler/">David Fowler</a> on the ASP.NET team and I have been bouncing ideas about on how to solve an annoyance using LINQ:</p>
<blockquote><p>If you write properties on the client you can’t use them in remote LINQ operations.</p>
</blockquote>
<p>The problem occurs because these properties can’t be translated and sent to the server as they have been compiled into intermediate language (IL) and not LINQ expression trees that are required for translation by IQueryable implementations. There is nothing available in .NET to let us reverse-engineer the IL back into the methods and syntax that would allow us to translate the intended operation into a remote query.</p>
<p>This means you end up having to write your query in two parts; firstly the part the server can do, a ToList or AsEnumerable call to force that to happen and bring the intermediate results down to the client, and then the operations that can only be evaluated locally. This can hurt performance if you want to reduce or transform the result set significantly.</p>
<p>What we came up (David, Colin Meek and myself) is a provider-independent way of declaring properties just once so they can be used in both scenarios. Computed properties for LINQ to SQL, LINQ to Entities and anything else LINQ enabled with little effort and it works great on .NET 3.5 SP1 :)</p>
<h3>Before example</h3>
<p>Here we have extended the Employee class to add Age and FullName. We only wanted to people with “da” in their name but we are forced to pull down everything to the client in order to the do the selection.</p>
<pre class="code"><strong>partial class</strong> Employee {
	<strong>public string</strong> FullName {
		<strong>get</strong> { <strong>return</strong> Forename + &quot; &quot; + Surname; }
	}

	<strong>public int</strong> Age {
		<strong>get</strong> { <strong>return</strong> DateTime.Now.Year - BirthDate.Year -
			(DateTime.Now.Month &lt; BirthDate.Now.Month
			|| DateTime.Now.Month == BirthDate.Now.Month &amp;&amp; DateTime.Now.Day &lt; BirthDate.Now.Day) ? 1 : 0);
		}
	}
}...<strong>var</strong> employees = db.Employees.ToList().Where(e =&gt; e.FullName.Contains(&quot;da&quot;)).GroupBy(e =&gt; e.Age);</pre>
<h3>After example</h3>
<p>Here using our approach it all happens server side… and works on both LINQ to Entities and LINQ to SQL.</p>
<pre class="code"><strong>partial class</strong> Employee {
    <strong>private static readonly</strong> CompiledExpression&lt;Employee,string&gt; fullNameExpression =       DefaultTranslationOf&lt;Employee&gt;.Property(e =&gt; e.FullName).Is(e =&gt; e.Forename + &quot; &quot; + e.Surname);
    <strong>private static readonly</strong> CompiledExpression&lt;Employee,int&gt; ageExpression =       DefaultTranslationOf&lt;Employee&gt;.Property(e =&gt; e.Age).Is(e =&gt; <employees  , int(e="">DateTime.Now.Year - e.BirthDate.Value.Year - ((DateTime.Now.Month &lt; e.BirthDate.Value.Month || (DateTime.Now.Month == e.BirthDate.Value.Month &amp;&amp; DateTime.Now.Day &lt; e.BirthDate.Value.Day)) ? 1 : 0)));

    <strong>public string</strong> FullName {
        <strong>get</strong> { <strong>return</strong> fullNameExpression.Evaluate(<strong>this</strong>); }
    }

    <strong>public int</strong> Age {
        <strong>get</strong> { <strong>return</strong> ageExpression.Evaluate(<strong>this</strong>); }
    }
}...

<strong>var</strong> employees = db.Employees.Where(e =&gt; e.FullName.Contains(&quot;da&quot;)).GroupBy(e =&gt; e.Age).WithTranslations();</pre>
<h3>Getting started</h3>
<p>Check out this download which includes the necessary project to drop-in to your solution. The caveat to the usage technique shown above is you need to ensure your class has been initialized before you write queries to it. If this is a problem check out the usage considerations section below.</p>
<p>The other major caveat is obviously the expression you register for a property must be able to be translated to the remote store so you will need to constrain yourself to the methods and operators your IQueryable provider supports.</p>
<div class="download">Download <a href="http://download.damieng.com/dotnet/Microsoft.LINQ.Translations.zip">Microsoft.LINQ.Translations.zip</a> (9.6KB)</div>
<div class="information">Licensed under the <a href="http://www.microsoft.com/opensource/licenses.mspx">Microsoft Public License (MS-PL)</a></div>
<h3>Usage considerations</h3>
<p>There are a few alternative ways to use this rather than the specific examples above.</p>
<h4>Registering the expressions</h4>
<p>You can register the properties in the class itself as shown in the examples which means the properties themselves can evaluate the expressions without any reflection calls. Alternatively if performance is less critical you can register them elsewhere and have the methods look up their values dynamically via reflection. e.g.</p>
<pre class="code">…
DefaultTranslationOf&lt;Employee&gt;.Property(e =&gt; e.FullName).Is(e =&gt; e.Forename + &quot; &quot; + e.Surname);
<strong>var</strong> employees = db.Employees.Where(e =&gt; e.FullName.Contains(&quot;da&quot;)).GroupBy(e =&gt; e.Age).WithTranslations();
…
<strong>partial class</strong> Employee {
<strong>    public string</strong> FullName { <strong>get</strong> { <strong>return</strong> DefaultTranslationOf&lt;Employees&gt;.Evaluate&lt;<strong>string</strong>&gt;(<strong>this</strong>, MethodInfo.GetCurrentMethod());} }
}
</pre>
<p>If performance of the client-side properties is critical then you can always have them as regular get properties with the full code in there at the expense of having the calculation duplicated, once in IL in the property and once as an expression for the translation.</p>
<h4>Different maps for different scenarios</h4>
<p>Sometimes certain parts of your application may want to run with different translations for different scenarios, performance etc. No problem!</p>
<p>The WithTranslations method normally operates against the default translation map (accessed with DefaultTranslationOf) but there is also another overload that takes a TranslationMap you can build for specific scenarios, e.g.</p>
<pre class="code"><strong>var</strong> myTranslationMap = <strong>new</strong> TranslationMap();
myTranslationMap.Add&lt;Employees, <strong>string</strong>&gt;(e =&gt; e.Name, e =&gt; e.FirstName + &quot; &quot; + e.LastName);
<strong>var</strong> results = (<strong>from</strong> e <strong>in</strong> db.Employees <strong>where</strong> e.Name.Contains(&quot;martin&quot;) <strong>select</strong> e).WithTranslations(myTranslationMap).ToList();</pre>
<h4>Not specifying WithTranslation everywhere</h4>
<p>If you are happy to always have the default translation applied simply add the following statement to the top of your file which will bring in a bunch of extensions methods for the usual LINQ query operators that already apply WithTranslation for you :)</p>
<pre class="code"><strong>using</strong> Microsoft.Linq.Translations.Auto;</pre>
<h4>With .NET 4.0</h4>
<p>You should be able to drop the ExpressionVisitor class in the download and reference the built-in one.</p>
<h3>How it works</h3>
<h4>CompiledExpression&lt;T, TResult&gt;</h4>
<p>The first thing we needed to do was get the user-written client-side “computed” properties out of IL and back into expression trees so we could translate them. Given that we also want to evaluate them on the client we need to compile them at run time so CompiledExpression exists which just takes an expression of Func&lt;T, TResult&gt;, compiles it and allows evaluation of objects against the compiled version.</p>
<h4>ExpressiveExtensions</h4>
<p>This little class provides both the WithTranslations extensions methods and the internal TranslatingVisitor that unravels the property accesses into their actual registered Func&lt;T, TResult&gt; expressions via the TranslationMap so that the underlying LINQ provider can deal with that instead.</p>
<h4>TranslationMap</h4>
<p>We need to have a map of properties to compiled expressions and for that purpose TranslationMap exists. You can create a TranslationMap by hand and pass it in to WithTranslations if you want to programmatically create them at runtime or have different ones for different scenarios but generally you will want to use…</p>
<h4>DefaultTranslationOf</h4>
<p>This helper class lets you register properties against the default TranslationMap we use when nothing is passed to WithTranslations. It also allows you to lookup what is already registered so you can evaluate to that although there is a small reflection performance penalty for that:</p>
<pre class="code"><strong>public int</strong> Age { <strong>get</strong> { <strong>return</strong> DefaultTranslationOf&lt;Employees&gt;.Evaluate&lt;<strong>int</strong>&gt;(<strong>this</strong>, MethodInfo.GetCurrentMethod()); } }</pre>
<h4>AutoTranslation</h4>
<p>Remembering to specify WithTranslations everywhere can be a pain so if you always want to go via translation and use the default TranslationMap you can include the Microsoft.Linq.Translations.Auto namespace in your code which includes extension methods for all the regular LINQ operations that saves you having to remember.</p>
<p>Have fun!</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=hSu88MxihGM:Rs8sjBjw6TU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=hSu88MxihGM:Rs8sjBjw6TU:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/hSu88MxihGM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL resources</title>
		<link>http://damieng.com/blog/2009/06/04/linq-to-sql-resources</link>
		<comments>http://damieng.com/blog/2009/06/04/linq-to-sql-resources#comments</comments>
		<pubDate>Fri, 05 Jun 2009 05:33:51 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[LinqToSql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1224</guid>
		<description>A quick round-up of some useful LINQ to SQL related resources that are available for developers. I've not used everything on this list myself so don't take this as personal endorsement.
Templates

Entity Developer       Add-in for Visual Studio that provides a replacement designer with code templates. Commercial ($99.95) 
LLBLGen Pro  [...]</description>
			<content:encoded><![CDATA[<p>A quick round-up of some useful LINQ to SQL related resources that are available for developers. I've not used everything on this list myself so don't take this as personal endorsement.</p>
<h3>Templates</h3>
<ul>
<li><a href="http://www.devart.com/entitydeveloper/">Entity Developer</a>       <br /><em>Add-in for Visual Studio that provides a replacement designer with code templates. Commercial ($99.95)</em> </li>
<li><a href="http://www.llblgen.com">LLBLGen Pro</a>       <br /><em>This ORM templating and design tool has a set of LINQ to SQL templates available for generating C# code including file per entity that can be used in conjunction with their designer. Templates are free but require LLBLGen Pro licence (€179-249).</em> </li>
<li><a href="http://l2st4.codeplex.com/">L2ST4</a>       <br /><em>My templates use Visual Studio's built in T4 engine and provide a great starting point to customizing the code generation process. Everything that SQL Metal/LINQ to SQL designer can generate is handled including C# and VB.NET generation and are freely licensed under the MS-PL. </em></li>
<li><a href="http://plinqo.com/default.aspx?AspxAutoDetectCookieSupport=1">PLINQO</a>       <br /><em>These templates for Eric Smith's ever-popular CodeSmith templating environment include a whole host of extra functionality beyond the standard generation including entity clone &amp; detach, enum's from tables, data annotations, batching, auditing and more. Templates are free but require CodeSmith licence ($79-$299).</em> </li>
<li><a href="http://t4toolbox.codeplex.com/">T4 Toolbox</a>       <br /><em>Oleg Sych has put together a suite of useful T4 templates including ones for producing LINQ to SQL entities, data contexts as well as SQL scripts for altering the schema to reflect changes. C# only, MS-RL.</em> </li>
</ul>
<p>Note: While the T4 templating language is built-in to Visual Studio 2008/2010 it does not come with syntax highlighting or IntelliSense. Check out either:</p>
<ul>
<li><a href="http://www.visualt4.com/">Clarius Visual T4</a><em>       <br />Basic ‘community’ version available for free, commercial ‘pro’ version with IntelliSense, sub-templates, preview, user preferences etc. is $99.</em></li>
<li><a href="http://t4-editor.tangible-engineering.com/">Tangible T4</a>      <br /><em>Free version available with limited IntelliSense, commercial ‘pro’ version with UML modelling etc. available for $99.</em></li>
</ul>
<h3>Blogs</h3>
<ul>
<li><a href="http://blogs.rev-net.com/ddewinter/category/linq-to-sql/">David DeWinter</a>       <br /><em>David is a dev in test who recently joined our team and hit the ground running with testing, blogging and helping out on the forums.</em> </li>
<li><a href="http://oakleafblog.blogspot.com/">Roger Jennings</a>       <br /><em>Roger over at OakLeaf Systems publishes regular articles and roundups of some of the best .NET data access content from around the web including LINQ to SQL.</em> </li>
<li><a href="http://weblogs.asp.net/scottgu/archive/tags/LINQ/default.aspx">Scott Guthrie</a>       <br /><em>Our Corporate Vice President for the .NET Developer Platform takes a very active role in getting his hands dirty and publishes a series of useful LINQ to SQL articles.</em> </li>
<li><a href="http://www.sidarok.com/web/blog/">Sidar Ok</a>       <br /><em>Sidar is a regular forum helper and has written a number of great posts on LINQ to SQL including some good POCO coverage.</em> </li>
</ul>
<h3>Tools</h3>
<ul>
<li><a href="http://www.devart.com/dotconnect/">Devart dotConnect</a>       <br /><em>Devart's dotConnect family are database providers for Oracle, MySQL, Postgres and SQLite that also include LINQ support to enable LINQ to SQL like functionality on other platforms. Some database basic versions are free, professional versions are commercial and vary in price (~$99-$209).</em> </li>
<li><a href="http://www.huagati.com/dbmltools/">Hugati DBML/EDMX Tools</a>       <br /><em>Add-in for Visual Studio that provides comparison/update facilities between the database and the DBML as well as standardising names and generating interfaces. Commercial ($49-$119, free 30 day trial).</em></li>
<li><a href="http://www.huagati.com/L2SProfiler/">Hugati LINQ to SQL Profiler</a>      <br /><em>Profiling tool to help optimize your LINQ to SQL based applications. Commercial ($49-$119, free 45 day trial).</em></li>
<li><a href="http://www.linqpad.net/">LINQpad</a>       <br /><em>This invaluable tool helps you write and visualise your LINQ queries in a test-bench without compilation and includes a version for the .NET 4.0 beta.</em><em> Free to use, auto-completion add-on available ($19).</em> </li>
</ul>
<h3>Official guides</h3>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx">Samples</a>       <br /><em>The official samples includes a whopping 101 snippets showing how to use many of the features and syntax.</em> </li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb399408.aspx">Programming Guide</a>       <br /><em>Includes steps on how to get started, querying, making changes, debugging and background information.</em> </li>
<li><a href="http://msdn.microsoft.com/en-gb/library/bb425822.aspx">Whitepaper</a>       <br /><em>Single document describing the architecture, query capabilities, change tracking and lifecycle, multi-tier entities, external mapping etc.</em> </li>
</ul>
<h3>Books</h3>
<ul>
<li><a href="http://www.amazon.com/gp/product/0321564162?tag=dam-20">Essential LINQ</a> </li>
<li><a href="http://www.amazon.com/gp/product/1933988169?tag=dam-20">LINQ in Action</a> </li>
<li><a href="http://www.amazon.com/gp/product/047018261X?tag=dam-20">Pro ADO.NET 3.5 with LINQ</a> </li>
<li><a href="http://www.amazon.com/gp/product/1590599659?tag=dam-20">Pro LINQ Object Relational Mapping</a> </li>
</ul>
<h3>Support</h3>
<ul>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/linqtosql/threads">Official MSDN forums</a>       <br /><em>Great way to get access to the product team directly as well as knowledgeable and experienced users if you have a question or a problem.</em> </li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb386929.aspx">Official LINQ to SQL FAQ</a>&#160; <br /><em>Coverage is a little thin on the ground but it has some useful tips.</em> </li>
<li><a href="http://stackoverflow.com/questions/tagged/linqtosql">StackOverflow's LINQ to SQL tag</a>       <br /><em>StackOverflow has rapidly become a leader in questions and answers for a wide variety of developer topics and covers LINQ to SQL (which the site uses for it's data access too!)</em> </li>
</ul>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=B5lHIDKfsF4:vCc-FVct4ss:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=B5lHIDKfsF4:vCc-FVct4ss:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/B5lHIDKfsF4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/04/linq-to-sql-resources/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL changes in .NET 4.0</title>
		<link>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40</link>
		<comments>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40#comments</comments>
		<pubDate>Mon, 01 Jun 2009 22:15:29 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40</guid>
		<description>People have been asking via Twitter and the LINQ to SQL forums so here’s a list I put together on a number of the changes made for 4.0.
Change list
Performance

Query plans are reused more often by specifically defining text parameter lengths 
Identity cache lookups for primary key with single result now includes query.Where(predicate).Single/SingleOrDefault/First/FirstOrDefault 
Reduced query execution [...]</description>
			<content:encoded><![CDATA[<p>People have been asking via Twitter and the LINQ to SQL forums so here’s a list I put together on a number of the changes made for 4.0.</p>
<h3>Change list</h3>
<h4>Performance</h4>
<ul>
<li>Query plans are reused more often by specifically defining text parameter lengths </li>
<li>Identity cache lookups for primary key with single result now includes query.Where(predicate).Single/SingleOrDefault/First/FirstOrDefault </li>
<li>Reduced query execution overhead when DataLoadOptions specified (cache lookup considers DataLoadOptions value equivalency – post beta 1) </li>
</ul>
<h4>Usability</h4>
<ul>
<li>ITable&lt;T&gt; interface for additional mocking possibilities </li>
<li>Contains with enums automatically casts to int or string depending on column type </li>
<li>Associations can now specify non-primary-key columns on the other end of the association for updates </li>
<li>Support list initialization syntax for queries </li>
<li>LinqDataSource now supports inherited entities </li>
<li>LinqDataSource support for ASP.NET query extenders added </li>
</ul>
<h4>Query stability</h4>
<ul>
<li>Contains now detects self-referencing IQueryable and doesn't cause a stack overflow </li>
<li>Skip(0) no longer prevents eager loading </li>
<li>GetCommand operates within SQL Compact transactions </li>
<li>Exposing Link&lt;T&gt; on a property/field is detected and reported correctly </li>
<li>Compiled queries now correctly detect a change in mapping source and throw </li>
<li>String.StartsWith, EndsWith and Contains now correctly handles ~ in the search string </li>
<li>Now detects multiple active result sets (MARS) better </li>
<li>Associations are properly created between entities when using eager loading with Table-Valued Functions (TVFs) </li>
<li>Queries that contain sub-queries with scalar projections now work better </li>
</ul>
<h4>Update stability</h4>
<ul>
<li>SubmitChanges no longer silently consumes transaction rollback exceptions </li>
<li>SubmitChanges deals with timestamps in a change conflict scenario properly </li>
<li>IsDbGenerated now honors renamed properties that don't match underlying column name </li>
<li>Server-generated columns and SQL replication/triggers now work instead of throwing SQL exception </li>
</ul>
<h4>General stability</h4>
<ul>
<li>Binary types equate correctly after deserialization </li>
<li>EntitySet.ListChanged fired when adding items to an unloaded entity set </li>
<li>Dispose our connections upon context disposal (ones passed in are untouched) </li>
</ul>
<h4>SQL Metal</h4>
<ul>
<li>Foreign key property setter now checks all affected associations not just the first </li>
<li>Improved error handling when primary key type not supported </li>
<li>Now skips stored procedures containing table-valued parameters instead of aborting process </li>
<li>Can now be used against connections that use AttachDbFilename syntax </li>
<li>No longer crashes when unexpected data types are encountered </li>
</ul>
<h4>LINQ to SQL class designer</h4>
<ul>
<li>Now handles a single anonymously named column in SQL result set </li>
<li>Improved error message for associations to nullable unique columns </li>
<li>No longer fails when using clauses are added to the partial user class </li>
<li>VarChar(1) now correctly maps to string and not char </li>
<li>Decimal precision and scale are now emitted correctly in the DbType attributes for stored procedures </li>
<li>Foreign key changes will be picked up when bringing tables back into the designer without a restart </li>
</ul>
<h4>Code generation (SQL Metal + LINQ to SQL class designer)</h4>
<ul>
<li>Stored procedures using original values now compiles when the entity and context namespaces differ </li>
<li>Virtual internal now generates correct syntax </li>
<li>Mapping attributes are now fully qualified to prevent conflicts with user types </li>
<li>KnownTypeAttributes are now emitted for DataContractSerializer with inheritance </li>
<li>Delay-loaded foreign keys now have the correct, compilable, code generated </li>
<li>Using stored procedures with concurrency no longer gets confused if entities in different namespace to context </li>
<li>ForeignKeyReferenceAlreadyHasValueException is now thrown if any association is loaded not just the first </li>
</ul>
<h3></h3>
<h3>Potentially breaking changes</h3>
<p>We worked very hard to avoid breaking changes but of course any potential bug fix is a breaking change if your application was depending on the wrong behavior. The ones I specifically want to call out are:</p>
<h4>Skip(0) is no longer a no-op</h4>
<p>The special-casing of 0 for Skip to be a no-op was causing some subtle issues such as eager loading to fail and we took the decision to stop special casing this. This means if you had syntax that was invalid for a Skip greater than 0 it will now also be invalid for skip with a 0. This makes more sense and means your app would break on the first page now instead of subtlety breaking on the second page. Fail fast :)</p>
<h4>ForeignKeyReferenceAlreadyHasValue exception</h4>
<p>If you are getting this exception where you weren’t previously it means you have an underlying foreign key with multiple associations based on it and you are trying to change the underlying foreign key even though we have associations loaded.Best thing to do here is to set the associations themselves and if you can’t do that make sure they aren’t loaded when you want to set the foreign key to avoid inconsistencies.</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=IJdrMERKFc0:YPjtMVuFce0:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=IJdrMERKFc0:YPjtMVuFce0:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/IJdrMERKFc0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40/feed</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
		<item>
		<title>Font hinting and instructing – a primer</title>
		<link>http://damieng.com/blog/2009/05/07/font-hinting-and-instructing-a-primer</link>
		<comments>http://damieng.com/blog/2009/05/07/font-hinting-and-instructing-a-primer#comments</comments>
		<pubDate>Fri, 08 May 2009 04:11:00 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Fonts]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[fontforge]]></category>
		<category><![CDATA[fontlab]]></category>
		<category><![CDATA[hinting]]></category>
		<category><![CDATA[truetype]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1164</guid>
		<description>Taking my bitmap font Envy Code B into the vector TrueType Envy Code R was a long process, the most difficult being hinting.
Bitmap v scalable fonts
Bitmap fonts are incredibly easy to make. Using a program like Softy or BitFonter you decide the size of your letters and start plotting pixels. You can see exactly how [...]</description>
			<content:encoded><![CDATA[<p>Taking my bitmap font <a href="http://damieng.com/creative/typography/envy-code-b">Envy Code B</a> into the vector TrueType <a href="damieng.com/fonts/envy-code-r">Envy Code R</a> was a long process, the most difficult being hinting.</p>
<h3>Bitmap v scalable fonts</h3>
<p>Bitmap fonts are incredibly easy to make. Using a program like <a href="http://users.breathe.com/l-emmett/">Softy</a> or <a href="http://www.fontlab.com/photofont/bitfonter/">BitFonter</a> you decide the size of your letters and start plotting pixels. You can see exactly how it will look because you draw every glyph (letter/symbol/number) in every size you want to support. This can obviously be very time consuming and doesn’t let you take full advantage of the resolution of the device and the capabilities it offers. A printer can handle in excess of 300 dpi while a display is typically 72 dpi (Mac) or 96 dpi (Windows) with LCD’s supporting sub-pixels due to the individual layout of the red-green and blue elements you can’t feasibly pre-plot every single combination and even if you could the file size would be rather large.</p>
<p>Rather than having specific set of pixels to turn on or off TrueType, OpenType and PostScript fonts contain a series of instructions that tell the computer the shape using a series of points, lines and curves. This means the computer can scale the glyph to the size that is required and then take full advantage of the device being rendered honoring the users preferences for anti-aliasing (smoothing using shades of grey), sub-pixel precision (smoothing using hints of red, green and blue to take advantage of the layout of colour elements in an LCD display), desired contrast and gamma settings etc.</p>
<h3>Grid fitting</h3>
<p>Such a scaled glyph won’t fit perfectly within a pixel grid and a small sizes and low resolution it can look awful. It is also necessary to ensure that the vertical part of the letter I (known as a stem) looks very similar to the stem of other letters at the same size – we don’t want some letters looking bold – and that the top of the letter o aligns nicely with the top of the i etc. (in most fonts). The glyphs themselves don’t know what is a stem, what should align with other glyphs etc.</p>
<p>Many renders include logic to try and improve un-hinted fonts such as the drop-out control in Windows through to the full auto-hinter in <a href="http://freetype.sourceforge.net/index2.html">FreeType</a>. If you’ve ever used free fonts from any of the numerous web sites around you’ve probably seen that it doesn’t get it right and it looks like this:<font size="2">&#160;<img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Envy Code R unhinted" border="0" alt="Envy Code R unhinted" src="http://damieng.com/wp-content/uploads/2009/05/envycoderunhinted-thumb.png" width="376" height="21" /></font></p>
<p>The first few versions of Envy Code R looked like that because to address this problem you need to learn a process called hinting, which let’s the designer give the renderer “hints” on how to choose the pixels.</p>
<h3>Hinting</h3>
<p>Font hinting started off as stem and edge identification so that glyphs would maintain the right proportions when sized and rendered on these low-DPI devices. It became apparent that a much more fine-grained level of control was required and so a stack-based byte-code language was developed as part of the TrueType specification to allow designers finer control in how points are adjusted to better take advantage of the display characteristics.</p>
<p>A TrueType font can contain extra blocks which describes, using a sequence of bytes that represent instructions and their arguments, the process by which to align the points and therefore make decisions about how best to fit the letter into the grid by retaining and adjusting various elements.</p>
<p>The important blocks are:</p>
<table border="0" cellspacing="0" cellpadding="2" width="410">
<tbody>
<tr>
<th valign="top" width="10">Block</th>
<th valign="top" width="70">Name</th>
<th valign="top" width="328">Description</th>
</tr>
<tr>
<td valign="top" width="10">fpgm</td>
<td valign="top" width="70">Font program</td>
<td valign="top" width="328">Run once when font first used to setup the tables.</td>
</tr>
<tr>
<td valign="top" width="10">gasp</td>
<td valign="top" width="70">Grid-fitting and scan conversion</td>
<td valign="top" width="328">Table specifying when to apply smoothing and grid-fitting based on size ranges.</td>
</tr>
<tr>
<td valign="top" width="10">prep</td>
<td valign="top" width="70">Control value program</td>
<td valign="top" width="328">Run every time the font needs to be drawn differently (e.g. change of size, changing anti-aliasing etc)</td>
</tr>
<tr>
<td valign="top" width="10">cvt</td>
<td valign="top" width="70">Control value table</td>
<td valign="top" width="328">Set of tables that can be used to specify various heights, widths, spacing, positions etc. that glyphs can relate to.</td>
</tr>
</tbody>
</table>
<p>Each instruction (<a href="http://en.wikipedia.org/wiki/Opcode">opcode</a>) has a <a href="http://en.wikipedia.org/wiki/Mnemonic">mnemonic</a> that is representative of what it does and these are documented in Chapters 5 through 6 of the <a href="http://www.microsoft.com/typography/SpecificationsOverview.mspx">TrueType specification</a> (along with much other useful relevant information). Actual per-glyph instructions are stored with each glyph outline in the glyp block.</p>
<h3>Rasterizing &amp; rendering</h3>
<p>There are many <a href="http://fortes.com/2007/05/font-rendering-in-across-rich-platforms/">different ways a TrueType font can end up on your screen</a> with a lot of variants between how vendors chose to render the font and what options they expose to developers and users to fine-tune the experience.</p>
<ul>
<li>Windows – User choice of 1-bit, 4-bit grey-scale anti-aliasing, ClearType, ClearType tuning and display DPI plus WPF and DirectWrite per-app options </li>
<li>Mac OS X – User choice of sub-pixel anti-aliasing strength and 1-bit cut-off plus per-app 1-bit option (e.g. Terminal) </li>
<li>Java – Per-application choice of 1-bit, grey-scale or sub-pixel rendering </li>
<li>Flash – Per-application choice of 1-bit or grey-scale </li>
<li>FreeType – Rendering library that exposes a number of runtime and compile-time settings </li>
</ul>
<p>This is of course ignoring the other rendering engines out there such as the Adobe’s Photoshop, RiscOS, <a href="http://www.d-type.com/about/comparison.htm">D-Type rendering engine</a>, <a href="http://www.bitstream.com/font_rendering/products/font_fusion/">Font Fusion</a> (used on BeOS) etc. and prior versions of those renderers listed above (Flash and Mac OS changed significantly). Getting it pixel-perfect on every combination is impossible but we can try :)</p>
<h3>Tools</h3>
<p>Instructing fonts is a painstaking process at the best of times and few people deal directly with the low-level instructions instead relying on tools, stem identification and higher-level languages to achieve the same result. Some tools that have support for hinting instructions are:</p>
<ul>
<li><a href="http://www.fontlab.com/font-editor/fontlab-studio/">FontLab Studio 5</a>       <br />Comprehensive font-production package for Windows and Mac that includes auto-hinting and it’s own higher-level link language that it can generate TrueType instructions from but it does not support viewing or modifying existing TrueType instructions and does not handle diagonals well. Rendering preview includes mono, grey-scale and ClearType. <em>(Commercial $649)</em> </li>
<li><a href="http://www.fontlab.com/font-editor/fontographer/">Fontographer 4.1</a>       <br />Rather dated font-production package for Windows and Mac. <em>(Commercial $349)</em> </li>
<li><a href="http://fontforge.sourceforge.net">FontForge</a>       <br />Comprehensive font-production package that runs on X11 that includes auto-hinting and the ability to disassemble and edit existing TrueType instructions as well as debug them with stepping. Includes basic mono/grey-scale rendering options. <em>(Open source)</em> </li>
<li><a href="http://www.microsoft.com/typography/tools/vtt.aspx">Microsoft Visual TrueType</a>       <br />Hinting instruction tool from Microsoft that uses it’s own higher-level VTT Talk language that compiles down to TrueType instructions that you can further edit. Includes a comprehensive set of preview rendering options but is not capable of disassembling existing instructions.<em> (Commercial, free with signed licence agreement)</em> </li>
<li><a href="http://www.letterror.com/code/ttx/">TTX</a>       <br />Python scripts that can convert a font into an editable XML representation and back including disassembly and assembly of TrueType hinting instructions. <em>(BSD)</em> </li>
<li><a href="http://home.kabelfoon.nl/~slam/fonts/tticomp.html">TTIComp</a>       <br />Command-line tool that provides an alternative C-like hinting language. (<em>GPL)</em> </li>
<li><a href="http://xgridfit.sourceforge.net/">Xgridfit</a>       <br />FontForge scripts to provide an alternative XML-based hinting language. <em>(GPL)</em></li>
<li><a href="http://home.kabelfoon.nl/~slam/fonts/truetypeviewer.html">TrueTypeViewer</a>      <br />Windows tool for displaying TrueType fonts and glyphs including debugging and descriptive disassembly of instructions. <em>(GPL)</em></li>
<li><a href="http://www.cr8.netfirms.com/tthmachine.html">TTHMachine</a>       <br />Real-time editing of hinting instruction mnemonics and observing their effects which is useful for learning. <em>(Free, no longer supported)</em> </li>
</ul>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=eVgIJBxh930:zWNsNsrCGrU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=eVgIJBxh930:zWNsNsrCGrU:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/eVgIJBxh930" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/05/07/font-hinting-and-instructing-a-primer/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL tips and tricks #2</title>
		<link>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2</link>
		<comments>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2#comments</comments>
		<pubDate>Mon, 13 Apr 2009 07:21:05 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2</guid>
		<description>A few more useful and lesser-known techniques for using LINQ to SQL.
Take full control of&amp;#160; the TSQL
There are times when LINQ to SQL refuses to cook up the TSQL you wanted either because it doesn’t support the feature or because it has a different idea what makes an optimal query.
In either case the Translate method [...]</description>
			<content:encoded><![CDATA[<p>A few more useful and lesser-known techniques for using LINQ to SQL.</p>
<h3>Take full control of&#160; the TSQL</h3>
<p>There are times when LINQ to SQL refuses to cook up the TSQL you wanted either because it doesn’t support the feature or because it has a different idea what makes an optimal query.</p>
<p>In either case the Translate method allows you to deliver your own TSQL to LINQ to SQL to process as if it were its own with execution, materialization and identity mapping still honored. For example:</p>
</p>
<pre class="code"><strong>var</strong> db = <strong>new</strong> PeopleContext();
<strong>if</strong> (db.Connection.State == System.Data.ConnectionState.Closed)
    db.Connection.Open();
<strong>var</strong> cmd = db.GetCommand(db.Persons.Where(p =&gt; p.CountryID == 1));
cmd.CommandText = cmd.CommandText.Replace(&quot;[People] AS [t0]&quot;, &quot;[People] AS [t0] WITH (NOLOCK)&quot;);
<strong>var</strong> results = db.Translate&lt;Person&gt;(cmd.ExecuteReader());</pre>
<h3>Complex stored procedures</h3>
<p>When working with stored procedures the LINQ to SQL designer and SQLMetal tools need a way of figuring out what the return type will be. In order to do this without actually running the stored procedure itself they use the SET FMTONLY command set to ON so that SQL Server will just parse the stored procedure instead.</p>
<p>Unfortunately this parsing does not extend to tdynamic SQL or temporary tables so you must change the return type from the scalar integer to one of the known entity types by hand. You could use the following command at the start to let it run regardless given the subsequent warning.</p>
<pre class="code"><strong>SET</strong> FMTONLY <strong>OFF</strong></pre>
<p class="alert">If your stored procedure can not safely handle being called at any time with null parameters set the return type by hand instead. </p>
<h3>Cloning an entity</h3>
<p>There are many reasons you might want to clone an entity – you may want to create many similar ones, you could want to keep it around longer than the DataContext it came from – whatever your reason implementing a Clone method can be a pain but taking advantage of the DataContractSerializer can make light work of this providing your DBML is set to enable serialization.</p>
<p>If you use discriminator subclassing you will need to either ensure your type is cast to its concrete type or use my <a href="http://l2st4.codeplex.com">L2ST4 templates</a> for now as .NET 3.5 SP1 doesn’t emit the necessary KnownType attributes to make this automatically happen (fixed in .NET 4.0). Add a simple method to serialize in-memory like this:</p>
<pre class="code"><strong>public static</strong> T Clone&lt;T&gt;(T source) {
    <strong>var</strong> dcs = <strong>new</strong> System.Runtime.Serialization.DataContractSerializer(<strong>typeof</strong>(T));
    <strong>using</strong> (<strong>var</strong> ms = <strong>new</strong> System.IO.MemoryStream()) {
        dcs.WriteObject(ms, source);
        ms.Seek(0, System.IO.SeekOrigin.Begin);
        <strong>return</strong> (T)dcs.ReadObject(ms);
    }
}</pre>
<p>And then to clone simply:</p>
<pre class="code"><strong>var</strong> source = myQuery.First();<strong>var</strong> cloned = Clone(source);</pre>
<p>Be aware that this comes with a little overhead in the serialization and deserialization process.</p>
<p>If that is a problem for you then why not grab those templates and make your entities implement ICloneable!</p>
<p><em>[</em><em>)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=xZkyeHyeZPk:yAWuPbb6h7M:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=xZkyeHyeZPk:yAWuPbb6h7M:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/xZkyeHyeZPk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL tips and tricks #1</title>
		<link>http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1</link>
		<comments>http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1#comments</comments>
		<pubDate>Mon, 16 Mar 2009 22:01:51 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1</guid>
		<description>Being on the inside of a product team often leads to uncovering or stumbling upon lesser known techniques and here are a few little nuggets I found interesting – I have more if there is interest. 
Loading a delay-loaded property
LINQ to SQL lets you specify that a property is delay-loaded meaning that it is not [...]</description>
			<content:encoded><![CDATA[<p>Being on the inside of a product team often leads to uncovering or stumbling upon lesser known techniques and here are a few little nuggets I found interesting – I have more if there is interest. </p>
<h3>Loading a delay-loaded property</h3>
<p>LINQ to SQL lets you specify that a property is delay-loaded meaning that it is not normally retrieved as part of normal query operations against that entity. This is particularly useful for binary and large text fields such as a photo property on an employee object that is rarely used and would cause a large amount of memory to be consumed on the client not to mention traffic between the SQL and application.</p>
<p>There are times however when you want all these binaries returned in a single query, say for example returning all the photos for the company photo intranet page:</p>
<pre class="code"><strong>var</strong> db = <strong>new</strong> NorthwindContext();
<strong>var</strong> loadOptions = <strong>new</strong> DataLoadOptions();
loadOptions.LoadWith&lt;Employee&gt;(e =&gt; e.Photo);
db.LoadOptions = loadOptions;</pre>
<h3>Multiple entity types from a single stored procedure</h3>
<p>It is actually possible to return multiple entity types from a single stored procedure in LINQ to SQL although this is not well known as the LINQ to SQL designer doesn’t actually support it. Indeed to generate the code it is necessary to hand-edit the DBML and then use SQL Metal (or my T4 template) to generate the required method signature.</p>
<p>In fact it is just much easier to write the code yourself and add it to the non-generated portion of your data context. If you imagine a stored procedure GetStaticData that looks like this:</p>
<pre class="code"><strong>CREATE PROCEDURE</strong> GetStaticData <strong>AS
SELECT</strong> * <strong>FROM</strong> Region
<strong>SELECT</strong> * <strong>FROM</strong> Categories
<strong>SELECT</strong> * <strong>FROM</strong> Territories</pre>
<p>Then all you need to do is write a method signature that looks like this (the sequence of result type attributes must match the order in the stored procedure):</p>
<pre class="code">[Function(Name=@&quot;dbo.DynamicContractsActiveBetween&quot;)]
[ResultType(<strong>typeof</strong>(Region))]
[ResultType(<strong>typeof</strong>(Category))]
[ResultType(<strong>typeof</strong>(Territory))]
<strong>public</strong> IMultipleResults GetStaticData() {
	<strong>return</strong> (IMultipleResults) ExecuteMethodCall(<strong>this</strong>, (MethodInfo) MethodInfo.GetCurrentMethod()).ReturnValue;
}</pre>
<h3>Intercepting create, update and delete operations</h3>
<p>There are times it is useful to be able to listen in to when these events happen and perform your own logic, perhaps auditing or logging for some scenarios. The easiest way to do this is to implement some specially-named methods on your data context, perform your action and then to dispatch the call back to LINQ to SQL.</p>
<p>The format of these specially-named methods is [Action][Entity] and then you should pass back control to LINQ to SQL using ExecuteDynamic[Action] where [Action] is either Insert, Update or Delete. One example of such usage might be:</p>
<pre class="code"><strong>partial class</strong> NorthwindContext {
   <strong>partial void</strong> InsertEmployee(Employee instance) {
      instance.CreatedBy = CurrentUser;
      instance.CreatedAt = DateTime.Now;
      ExecuteDynamicInsert(instance);
   }

   <strong>partial void</strong> UpdateEmployee(Employee instance) {
      AuditEmployeeOwnerChange(instance);
      instance.LastModifiedAt = DateTime.Now;
      ExecuteDynamicUpdate(instance);
   }

   <strong>partial void</strong> DeleteEmployee(Employee instance) {
      AuditDelete(instance, CurrentUser);
      ExecuteDynamicDelete(instance);
   }
}</pre>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=QghgCt_yIM0:y3Dxz8MHC2k:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=QghgCt_yIM0:y3Dxz8MHC2k:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/QghgCt_yIM0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The secret driven-development/design acronyms</title>
		<link>http://damieng.com/blog/2009/02/18/the-secret-driven-developmentdesign-acronyms</link>
		<comments>http://damieng.com/blog/2009/02/18/the-secret-driven-developmentdesign-acronyms#comments</comments>
		<pubDate>Wed, 18 Feb 2009 23:20:46 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Entertainment]]></category>
		<category><![CDATA[programmer humor]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/02/18/the-secret-driven-developmentdesign-acronyms</guid>
		<description>We’ve all heard of BDD, DDD and TDD but that still leaves 23 letters unaccounted for.
I can now exclusively reveal more! You may recognize some from projects you’ve already worked on but didn’t know had a name much less a recognized methodology.
ADD, Agro Driven Development
Developers code features directly proportional to the amount of heat they [...]</description>
			<content:encoded><![CDATA[<p>We’ve all heard of BDD, DDD and TDD but that still leaves 23 letters unaccounted for.</p>
<p>I can now exclusively reveal more! You may recognize some from projects you’ve already worked on but didn’t know had a name much less a recognized methodology.</p>
<h3>ADD, Agro Driven Development</h3>
<p>Developers code features directly proportional to the amount of heat they are getting from users, sales or managers. Results in a jack-of-all-trades, master of none.</p>
<h3>CDD, Clone Driven Design</h3>
<p>Features and design are achieved by cloning somebody else's product thereby removing the pesky overhead of having to come up with ideas of your own. Sure fire way to stay firmly behind the leader.</p>
<h3>EDD, Ego Driven Design</h3>
<p>Where the direction of the project is dictated purely on an individuals ego and their ability to shout long and hard until they get their own way. The individual involved is rarely the target audience for the product which is often the ego-bruising trigger in the first place.</p>
<h3>GDD, Golf Driven Design</h3>
<p>Where features and specifications are agreed on the golf course by people who neither use the software nor are responsible for implementing it but want to write off the whole trip as a business expense. With any luck they won’t check the final product.</p>
<h3>LDD, Lunch Driven Development</h3>
<p>Where features, goals and APIs are decided over lunch by the developers and users who care enough to meet up over their lunch-time. Lunch must not be provided or you stray into Golf Driven Design instead.</p>
<h3>PDD, Psychic Driven Development</h3>
<p>Where specifications are not so much decided through real communication but rather obtained via a psychic link with potential users with mixed results. Often seen in conjunction with Ego Driven Design.</p>
<h3>QDD, Query Driven Development</h3>
<p>Every page or screen starts with a question to the user what they want to see, writing that as a SQL/LINQ query statement and then dumping results out via a simple UI. Would likely be better off in Access or Excel but people involved want to claim they have intraweb experience.</p>
<h3>XDD, Xenophobic Driven Development</h3>
<p>Where the majority of development time is given over to making sure others can't do anything BUT what the original developers wanted. Typically observed by large sets of exception messages, the absence of hooks and a sprinkling of the sealed keyword.</p>
<h3>YDD, Yesterday Driven Development</h3>
<p>Features added today are the ones the customers thought they were getting yesterday. Generally used in very-tight rapid methodologies.</p>
<h3>ZDD, Zzzzz Driven Development</h3>
<p>Every waking hour is given over to the development process at the expense of quality and design ideas that are only appreciated by the sleep-deprived. Normally observed on tight schedules such as those in the gaming industry.</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=z2eUijqU"><img src="http://feeds.feedburner.com/~f/DamienG?i=z2eUijqU" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/oKomF8XN0Sw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/02/18/the-secret-driven-developmentdesign-acronyms/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Multiple outputs from T4 made easy</title>
		<link>http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy</link>
		<comments>http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy#comments</comments>
		<pubDate>Thu, 22 Jan 2009 19:53:13 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy</guid>
		<description>10 March 2009 Updated to dispatch calls to Visual Studio in a way that doesn't cause issues with third-party plugin's loaded such as VisualSVN etc.
One of the things I wanted my LINQ to SQL T4 templates to do was be able to split the output into a file-per-entity. Existing solutions used either a separate set [...]</description>
			<content:encoded><![CDATA[<p class="new"><strong>10 March 2009</strong> Updated to dispatch calls to Visual Studio in a way that doesn't cause issues with third-party plugin's loaded such as VisualSVN etc.</p>
<p>One of the things I wanted my <a href="http://l2st4.codeplex.com/">LINQ to SQL T4 templates</a> to do was be able to split the output into a file-per-entity. Existing solutions used either a separate set of templates with duplicate code or intrusive handling code throughout the template. Here’s my helper class to abstract the problem away from what is already complicated enough template code.</p>
<h3>Using the Manager class</h3>
<h4>Setup</h4>
<p>You’ll need to get the code into your template – either copy the code in or reference it with an include directive. Then declare an instance of the Manager class passing in some environmental options such as the desired default output path.</p>
<pre class="code">&lt;#@ template language="C#v3.5" hostspecific="True"
#&gt;&lt;#@ include file=&quot;Manager.ttinclude&quot;
#&gt;&lt;# <strong>var</strong> manager = <strong>new</strong> Manager(Host, GenerationEnvironment, <strong>true</strong>) { OutputPath = Path.GetDirectoryName(Host.TemplateFile) }; #&gt;</pre>
<h4>Define a block</h4>
<p>Then add one line before and one line after each block which could be split out into it’s own file passing in what the filename would be if split.</p>
<pre class="code">&lt;# manager.StartBlock(&quot;Employee.generated.cs&quot;); #&gt;
public class Employee { … }
&lt;# manager.EndBlock(); #&gt;</pre>
<h4>Headers and footers</h4>
<p>Many templates need to share a common header/footer for such things as comments or using/import statements or turning on/off warnings. Simply use StartHeader/EndHeader and StartFooter/EndFooter. The resulting blocks will be emitted into all split files and left in the original output to.</p>
<pre class="code">&lt;# manager.StartHeader(); #&gt;
// Code generated template
using System;

&lt;# manager.EndHeader(); #&gt;</pre>
<h4>Process</h4>
<p>At the end of the template call Process to handle splitting the files (true) or not (false). Anything not included in a specific start/end block will remain in the original output file.</p>
<pre class="code">&lt;# manager.Process(<strong>true</strong>); #&gt;</pre>
<p class="alert">When processing each block name in the Output path will either be overwritten or deleted to enable proper clean-up. It will also add and remove the files from Visual Studio so <strong>make sure your generated names aren’t going to collide with hand-written ones</strong>!</p>
<h3>Manager classes </h3>
<p>Here is the Manger class itself as well as the small ManagementStrategy classes that determines what to do with the files within Visual Studio (add/remove project items) and outside of Visual Studio (create/delete files).</p>
<p class="download">Download <a href="http://download.damieng.com/dotnet/Manager.ttinclude">Manager.ttinclude</a> (4KB)</p>
<div class="information">Licensed under the <a href="http://www.microsoft.com/opensource/licenses.mspx">Microsoft Public License (MS-PL)</a></div>
<pre class="code">&lt;#@ assembly name=&quot;System.Core&quot;
#&gt;&lt;#@ assembly name=&quot;EnvDTE&quot;
#&gt;&lt;#@ import namespace=&quot;System.Collections.Generic&quot;
#&gt;&lt;#@ import namespace=&quot;System.IO&quot;
#&gt;&lt;#@ import namespace=&quot;System.Text&quot;
#&gt;&lt;#@ import namespace=&quot;Microsoft.VisualStudio.TextTemplating&quot;
#&gt;&lt;#+

// T4 Template Block manager for handling multiple file outputs more easily.
// Copyright (c) Microsoft Corporation.  All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)

// Manager class records the various blocks so it can split them up
<strong>class Manager
</strong>{
	<strong>private struct</strong> Block {
		<strong>public</strong> String Name;
		<strong>public int</strong> Start, Length;
	}

	<strong>private</strong> List&lt;Block&gt; blocks = <strong>new</strong> List&lt;Block&gt;();
	<strong>private</strong> Block currentBlock;
	<strong>private</strong> Block footerBlock = <strong>new</strong> Block();
	<strong>private</strong> Block headerBlock = <strong>new</strong> Block();
	<strong>private</strong> ITextTemplatingEngineHost host;
	<strong>private</strong> ManagementStrategy strategy;
	<strong>private</strong> StringBuilder template;
	<strong>public</strong> String OutputPath { <strong>get</strong>; <strong>set</strong>; }

	<strong>public</strong> Manager(ITextTemplatingEngineHost host, StringBuilder template, <strong>bool</strong> commonHeader) {
		<strong>this</strong>.host = host;
		<strong>this</strong>.template = template;
		OutputPath = String.Empty;
		strategy = ManagementStrategy.Create(host);
	}

	<strong>public void</strong> StartBlock(String name) {
		currentBlock = <strong>new</strong> Block { Name = name, Start = template.Length };
	}

	<strong>public void</strong> StartFooter() {
		footerBlock.Start = template.Length;
	}

	<strong>public void</strong> EndFooter() {
		footerBlock.Length = template.Length - footerBlock.Start;
	}

	<strong>public void</strong> StartHeader() {
		headerBlock.Start = template.Length;
	}

	<strong>public void</strong> EndHeader() {
		headerBlock.Length = template.Length - headerBlock.Start;
	}	

	<strong>public void</strong> EndBlock() {
		currentBlock.Length = template.Length - currentBlock.Start;
		blocks.Add(currentBlock);
	}

	<strong>public void</strong> Process(bool split) {
		String header = template.ToString(headerBlock.Start, headerBlock.Length);
		String footer = template.ToString(footerBlock.Start, footerBlock.Length);
		blocks.Reverse();
		<strong>foreach</strong>(Block block <strong>in</strong> blocks) {
			String fileName = Path.Combine(OutputPath, block.Name);
			<strong>if</strong> (split) {
				String content = header + template.ToString(block.Start, block.Length) + footer;
				strategy.CreateFile(fileName, content);
				template.Remove(block.Start, block.Length);
			} <strong>else</strong> {
				strategy.DeleteFile(fileName);
			}
		}
	}
}

<strong>class</strong> ManagementStrategy
{
	<strong>internal static</strong> ManagementStrategy Create(ITextTemplatingEngineHost host) {
		<strong>return</strong> (host <strong>is</strong> IServiceProvider) ? <strong>new</strong> VSManagementStrategy(host) : <strong>new</strong> ManagementStrategy(host);
	}

	<strong>internal</strong> ManagementStrategy(ITextTemplatingEngineHost host) { }

	<strong>internal virtual void</strong> CreateFile(String fileName, String content) {
		File.WriteAllText(fileName, content);
	}

	<strong>internal virtual void</strong> DeleteFile(String fileName) {
		<strong>if</strong> (File.Exists(fileName))
			File.Delete(fileName);
	}
}

<strong>class</strong> VSManagementStrategy : ManagementStrategy
{
	<strong>private</strong> EnvDTE.ProjectItem templateProjectItem;

	<strong>internal</strong> VSManagementStrategy(ITextTemplatingEngineHost host) : <strong>base</strong>(host) {
		IServiceProvider hostServiceProvider = (IServiceProvider)host;
		<strong>if</strong> (hostServiceProvider == <strong>null</strong>)
			<strong>throw new</strong> ArgumentNullException(&quot;Could not obtain hostServiceProvider&quot;);

		EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(<strong>typeof</strong>(EnvDTE.DTE));
		<strong>if</strong> (dte == <strong>null</strong>)
			<strong>throw new</strong> ArgumentNullException(&quot;Could not obtain DTE from host&quot;);

		templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
	}

	<strong>internal override void</strong> CreateFile(String fileName, String content) {
		<strong>base</strong>.CreateFile(fileName, content);
		((EventHandler)<strong>delegate</strong> { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(<strong>null</strong>, <strong>null</strong>, <strong>null</strong>, <strong>null</strong>);
	}

	<strong>internal override void</strong> DeleteFile(String fileName) {
		((EventHandler)<strong>delegate</strong> { FindAndDeleteFile(fileName); }).BeginInvoke(<strong>null</strong>, <strong>null</strong>, <strong>null</strong>, <strong>null</strong>);
	}

	<strong>private void</strong> FindAndDeleteFile(String fileName) {
		<strong>foreach</strong>(EnvDTE.ProjectItem projectItem <strong>in</strong> templateProjectItem.ProjectItems) {
			<strong>if</strong> (projectItem.get_FileNames(0) == fileName) {
				projectItem.Delete();
				<strong>return</strong>;
			}
		}
	}
}#&gt;</pre>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=36mEELzc"><img src="http://feeds.feedburner.com/~f/DamienG?i=36mEELzc" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/1cutyuac7bk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL templates updated, now on CodePlex</title>
		<link>http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex</link>
		<comments>http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex#comments</comments>
		<pubDate>Tue, 20 Jan 2009 01:48:27 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex</guid>
		<description>My templates that allow you to customize the LINQ to SQL code-generation process (normally performed by SQLMetal/LINQ to SQL classes designer) have been updated once again.
Updates

Now licensed under the Microsoft Public License and hosted at CodePlex
User options specified with a var options block at the start of the template
Option for each class to be a [...]</description>
			<content:encoded><![CDATA[<p>My templates that allow you to customize the LINQ to SQL code-generation process (normally performed by SQLMetal/LINQ to SQL classes designer) have been updated once again.</p>
<h3>Updates</h3>
<ul>
<li>Now licensed under the <a href="http://www.codeplex.com/l2st4/license">Microsoft Public License</a> and <a href="http://l2st4.codeplex.com/">hosted at CodePlex</a></li>
<li>User options specified with a <em>var options</em> block at the start of the template</li>
<li>Option for each class to be a separate file that is reflected in the VS project (EntityPerFile=true)</li>
<li>Detection and support of IsComposable functions</li>
<li>General code clean-up and better error handling such as missing DBML file</li>
</ul>
<h3>In action!</h3>
<p>To show just how easy the templates are to use (they require nothing more than Visual Studio 2008) here is a short (2m30s) screen-cast of them in action!<br />
<iframe style="width: 640px; height: 480px" src="http://silverlight.services.live.com/invoke/89084/LINQ%20to%20SQL%20templates%20introduction/iframe.html" frameborder="0" scrolling="no"></iframe></p>
<p class="download">Download <a href="http://silverlight.services.live.com/89084/LINQ%20to%20SQL%20templates%20introduction/video.wmv">LINQ to SQL T4 screen-cast (WMV)</a> (5MB).</p>
<p class="warning">If you decide you want to go back to the built-in code generation just set the .template.cs/.vb Build Action property to None and the .generated.cs/.vb file back to Compile. You can then remove the .tt and .ttinclude files.</p>
<p class="warning">Please remember that these templates are a work-in-progress and you should ensure the generated code is suitably tested with your application.</p>
<h3>CodePlex</h3>
<p>CodePlex makes it easier for people to be able to see and merge updates in with their own modified versions as well as report issues via the issue tracker etc. There is also an RSS feed that lets you keep track of releases, source updates or whatever else you are interested in.</p>
<p>For now it is a grab-the-source style release but I hope to publish downloadable tested releases wrapped up in a Visual Studio Installer (VSI) package to make getting started easier soon.  Feel free to grab the sources directly via TFS/Subversion to be able to diff them with your own modified versions.</p>
<p>Enjoy!</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=LXfQhQB5"><img src="http://feeds.feedburner.com/~f/DamienG?i=LXfQhQB5" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/wsHEi6bnt84" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
<enclosure url="http://silverlight.services.live.com/89084/LINQ%20to%20SQL%20templates%20introduction/video.wmv" length="5418479" type="audio/x-ms-wmv" />
		</item>
		<item>
		<title>Changing type, the state pattern and LINQ to SQL</title>
		<link>http://damieng.com/blog/2009/01/05/changing-type-the-state-pattern-and-linq-to-sql</link>
		<comments>http://damieng.com/blog/2009/01/05/changing-type-the-state-pattern-and-linq-to-sql#comments</comments>
		<pubDate>Tue, 06 Jan 2009 03:24:18 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design-Patterns]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[state pattern]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1126</guid>
		<description>A question I see from time-to-time on LINQ to SQL relates to changing an entity’s class.
C# and VB.NET don’t allow a class to change its type at runtime and LINQ to SQL specifically doesn’t provide a mechanism for changing the underlying discriminator for this reason.
Discarding the current object and creating a new one is fraught [...]</description>
			<content:encoded><![CDATA[<p>A question I see from time-to-time on LINQ to SQL relates to changing an entity’s class.</p>
<p>C# and VB.NET don’t allow a class to change its type at runtime and LINQ to SQL specifically doesn’t provide a mechanism for changing the underlying discriminator for this reason.</p>
<p>Discarding the current object and creating a new one is fraught with issues. What do we do about existing references, unsaved data, established associations and caches?</p>
<h3>Start with an example</h3>
<p>Consider an abstract Account class with SavingsAccount and CurrentAccount sub-classes. Bank accounts don’t change type once created (in my experience) so that’s good so far.</p>
<p>When we get into processing and validation logic its tempting to create ClosedAccount and OpenAccount classes but what happens during execution when closing an account?</p>
<p>A further consideration is how exactly ClosedAccount and OpenAccount fit into the hierarchy given the single-inheritance limitation of C# and VB.NET.</p>
<h3>Enter the State Pattern</h3>
<p>The ever-resourceful <a href="http://en.wikipedia.org/wiki/Gang_of_Four_(software)">Gang of Four</a> describe the <a href="http://en.wikipedia.org/wiki/State_pattern">State Pattern</a> as:</p>
<blockquote><p>Allow an object to alter its behavior when its internal state changes.<br />
The object will appear to change its class.</p></blockquote>
<p>Taking the bank accounts example and applying the state pattern gives:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="StatePattern" src="http://damieng.com/wp-content/uploads/2009/01/statepattern1.png" border="0" alt="StatePattern" width="739" height="372" /></p>
<p>Account no longer needs to change type at run-time yet is still able to have clients call Validate and process Methods that end up in discrete methods as if inheritance had been used.</p>
<p>To achieve this we have:</p>
<ol>
<li>Created a State hierarchy that contains the logic we need to change at run-time</li>
<li>Introduced a private member in Account that points to the current state instance</li>
<li>Ensured the Account methods call the current state class via the private member</li>
</ol>
<p>Because the state member is private and only accessed by Account itself we can happily create and dispose it as the conditions that affect the state change as much as we like without worrying about references to it.</p>
<p>This is best illustrated with code. Here rather than just calling the state’s validation logic there is a combination of core Account validation (balance), state validation (closed) and CheckingAccount validation (transaction limits):</p>
<pre class="code"><strong>public abstract class</strong> Account {
    <strong>private</strong> AccountState state;

    <strong>public virtual</strong> Status Validate(ITransaction tx) {
        Status result = state.Validate(tx);
        <strong>if</strong> (tx.Amount &gt; Balance)
            result.Add(TransactionFailures.InsufficientFunds);
        <strong>return</strong> result;
    }
}
<strong>public class </strong>SavingsAccount : Account {
    <strong>public override</strong> Status Validate(ITransaction tx) {
        Status result = <strong>base</strong>.Validate(tx);
        <strong>if</strong> (Transactions.Count &gt; TransactionLimit)
            result.Add(TransactionFailures.TransactionLimitReached);
        <strong>return</strong> result;
    }
}<strong>
public class</strong> ClosedAccountState : AccountState {
<strong>    public override</strong> Status Validate(ITransaction tx) {
        <strong>return new </strong>Status(TransactionFailures.InvalidSourceAccount);
    }
}</pre>
<p>This is less complex than selectively replacing objects within our application at run-time and can bring additional benefits:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single responsibility principle</a> – logic relating to a specific state has its own class to live in</li>
<li><a href="http://www.artima.com/lejava/articles/designprinciples4.html">Favor composition over inheritance</a> – inheritance for OpenSavingsAccount, ClosedCheckingAccount etc. is complex</li>
</ul>
<p>Like all guidance, patterns and principles do not blindly follow these guidelines or patterns but consider how it affects and fits with your application. For this particular example it not only solves the problem but helps maintainability – at least at this simple stage. Once Validation becomes sufficiently complex it would likely move out entirely into a new set of orchestrated classes just for that.</p>
<h3>With LINQ to SQL (and other mappers)</h3>
<p>Moving this example into an object-relational mapper requires two - not unexpected - database-mapped properties.</p>
<ol>
<li>The inheritance discriminator (Type)</li>
<li>A state indicator (Active)</li>
</ol>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Dbml" src="http://damieng.com/wp-content/uploads/2009/01/dbml1.png" border="0" alt="Dbml" width="599" height="337" /></p>
<p>The only thing we need to ensure is the Account’s state member always refers to either a ClosedAccountState or OpenedAccountState depending upon the Active flag.</p>
<p>Given that LINQ to SQL code-generates the property for Active we could:</p>
<ol>
<li>Make Active private, wrap it in another property and set the state member when it changes and at initialization</li>
<li>Make the state member a read-only property instead of an instance variable</li>
</ol>
<p>The second works well here and given that AccountState is itself stateless (perhaps not the best choice of name) we can use a singleton to avoid multiple instances. The state instance variable in the Account class is replaced with:</p>
<pre class="code"><strong>private</strong> AccountState State {
    <strong>get</strong> {
        <strong>if</strong> (Active)
            <strong>return</strong> OpenAccountState.Instance;
        <strong>else</strong>
            <strong>return</strong> ClosedAccountState.Instance;
    }
}</pre>
<p>The code continues to work and now changing the Active flag results in different behavior.</p>
<p>Best of all we still have the code in separate classes, no switch/case/if statements relating to validation or account types, a clean inheritance hierarchy and no running around trying to invalidate existing references.</p>
<h3>Hitting the discriminator directly</h3>
<p>There may be times when claims are made that a type has to change - perhaps data was entered incorrectly.</p>
<p>Before delving into the database or providing a tool to flip the underlying discriminator value consider:</p>
<ol>
<li>Does the new class interpret the same data in a different manner?<em><br />
Has a $1,000 credit limit just become a 1,000 transactions per-month limit?</em></li>
<li>Would the object be valid in the new class?<em><br />
Did a ProposedCustomer just become ApprovedCustomer without a policy-enforced credit check?</em></li>
<li>Are associations still honored?<em><br />
Are 300 unshipped orders for a GameProduct still honored for a BookProduct?</em></li>
</ol>
<p>If in doubt don’t do it.</p>
<p>An inconsistent database bleeding through your application isn’t good for anyone and will take a lot longer to sort out than setting up a new entity.</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=cpOsocN8"><img src="http://feeds.feedburner.com/~f/DamienG?i=cpOsocN8" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/bLW6WRtY8oA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/05/changing-type-the-state-pattern-and-linq-to-sql/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>ALT.NET Seattle</title>
		<link>http://damieng.com/blog/2009/01/03/altnet-seattle</link>
		<comments>http://damieng.com/blog/2009/01/03/altnet-seattle#comments</comments>
		<pubDate>Sun, 04 Jan 2009 03:32:25 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[alt.net]]></category>
		<category><![CDATA[seattle]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1108</guid>
		<description>One of the cool things about living in Seattle is the sheer number of passionate developers around. Whether you're dropping into offices, heading across campus for lunch, meeting downtown for music and beer or in my case last month taking a Saturday out to participate in ALT.NET Seattle, there are ideas, enthusiasm and discussions with [...]</description>
			<content:encoded><![CDATA[<p>One of the cool things about living in Seattle is the sheer number of passionate developers around. Whether you're dropping into offices, heading across campus for lunch, meeting downtown for music and beer or in my case last month taking a Saturday out to participate in ALT.NET Seattle, there are ideas, enthusiasm and discussions with great developers to be had everywhere.</p>
<p>The <a href="http://laribee.com/blog/2007/04/10/altnet/">ALT.NET</a> event was particularly interesting. If you didn't already know the name encapsulates:</p>
<ul>
<li>the desire to improve the art, process, individual and product</li>
<li>the understanding that the right tool for the job doesn't always ship with the .NET</li>
</ul>
<p>The event follows the same minimal up-front planning modern development practices enjoy relying on talented people and simple structure to achieving something great in a short space of time.<sup>1</sup></p>
<p>This open-spaces format involves a small deck of cards to write topics you'd like to talk about on and a board with rooms and times to drop them into. I was surprised at how well the event unfolded (bar one session that veered off-course) given our unplanned attempts at the <a href="http://developers.org.gg">Guernsey developer group</a> always resulted in five people having dinner in a bar :)</p>
<p>I had an enjoyable day and my thanks go to <a href="http://bradwilson.typepad.com/">Brad Wilson</a> (ASP.NET) for driving and listening to my nostalgic 8-bit discussion with fellow brit <a href="http://www.ademiller.com/blogs/tech/">Ade Miller</a> (p&amp;p) who previously worked at Future Publishing (<a href="http://en.wikipedia.org/wiki/Your_Sinclair">Your Sinclair</a> magazine). I'm now messing around with a .NET based Spectrum emulator I started years ago and I'm going to blame him for that.</p>
<p>The best news is that there are more events planned for the coming months:</p>
<ul>
<li>January 17th normal format, location TBA</li>
<li>February -  provisionally the 7th, regular format, location TBA</li>
</ul>
<h3>ALT.NET Seattle 2009 Conference</h3>
<p>This is the big one immediately preceding the MVP Summit by running February 27th to March 1st at <a href="https://www.digipen.edu/">Digipen</a> in Redmond. <a href="http://codebetter.com/blogs/glenn.block/archive/2009/01/02/alt-net-seattle-2009-is-happening.aspx">Glenn Block has more details</a>.</p>
<p>Registration will open on Tuesday, 6pm (GMT-8), attendance is free and spaces are limited so get in quick!</p>
<p>Consider joining the <a href="http://groups.google.com/group/altnetseattle?hl=en&#038;pli=1">Seattle area ALT.NET group</a> or <a href="http://www.facebook.com/group.php?gid=111345965570">ALT.NET Facebook group</a> for more details or to get involved.</p>
<p><em>[)amien</em><br />
<sup>1</sup>And as either Glen or Brad said with a nod to the end-of-credits bit in Ferris Bueller - "When it's over it's over. Go home already."</p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=q3j9RQLO"><img src="http://feeds.feedburner.com/~f/DamienG?i=q3j9RQLO" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/kmMu2Xub_F4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/03/altnet-seattle/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC open-source content management system</title>
		<link>http://damieng.com/blog/2008/12/08/aspnet-mvc-open-source-content-management-system</link>
		<comments>http://damieng.com/blog/2008/12/08/aspnet-mvc-open-source-content-management-system#comments</comments>
		<pubDate>Mon, 08 Dec 2008 19:36:25 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[cms]]></category>
		<category><![CDATA[oxite]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1100</guid>
		<description>The nice bunch of people over at Mix Online have released an open-source content management system called Oxite that is built on top of ASP.NET MVC!
As well as providing the usual blog facilities it also boasts standards compliance, extensibility and a test suite. Nice!
Oxite joins the group of .NET blogging platforms including:

Subtext
Dasblog
BlogEngine.NET
Graffiti CMS

[)amien</description>
			<content:encoded><![CDATA[<p>The nice bunch of people over at Mix Online have released an open-source content management system called <a href="http://visitmix.com/lab/oxite/">Oxite</a> that is built on top of ASP.NET MVC!</p>
<p>As well as providing the usual blog facilities it also boasts standards compliance, extensibility and a test suite. Nice!</p>
<p>Oxite joins the group of .NET blogging platforms including:</p>
<ul>
<li><a href="http://subtextproject.com/">Subtext</a></li>
<li><a href="http://www.dasblog.info/">Dasblog</a></li>
<li><a href="http://www.dotnetblogengine.net/">BlogEngine.NET</a></li>
<li><a href="http://graffiticms.com/">Graffiti CMS</a></li>
</ul>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=1ytvmbRR"><img src="http://feeds.feedburner.com/~f/DamienG?i=1ytvmbRR" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/eV0S5eFn7vM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2008/12/08/aspnet-mvc-open-source-content-management-system/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL next steps</title>
		<link>http://damieng.com/blog/2008/10/31/linq-to-sql-next-steps</link>
		<comments>http://damieng.com/blog/2008/10/31/linq-to-sql-next-steps#comments</comments>
		<pubDate>Sat, 01 Nov 2008 00:15:14 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[LinqToSql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1082</guid>
		<description>There has been a flurry of posts and comments in the last 24 hours over the future of LINQ to SQL so I thought it would be interesting to provide some information on what the LINQ to SQL team have been up to and what we’re working on for .NET Framework 4.0.
A little background
LINQ was [...]</description>
			<content:encoded><![CDATA[<p>There has been a flurry of posts and comments in the last 24 hours over the future of LINQ to SQL so I thought it would be interesting to provide some information on what the LINQ to SQL team have been up to and what we’re working on for .NET Framework 4.0.</p>
<h3>A little background</h3>
<p>LINQ was a new feature in .NET 3.5 that provides a store-agnostic query language syntax using a provider model.</p>
<p>As part of that initiative the C# team delivered LINQ to SQL – a LINQ provider to SQL Server with additional update and access management via DataContext and mapping tools such as the designer and SQL Metal. The result is a great lightweight solution that is easy to get started with and a good data access solution where your database and objects are closely aligned.</p>
<p>Meanwhile Data Programmability worked on an initiative to provide abstraction between conceptual and physical models of databases to allow applications to operate independently of the database vendor and underlying physical schema. LINQ support was also added in the form of LINQ to Entities and it shipped with it’s management tools in .NET 3.5 SP1.</p>
<p>Which now means we have two object-relational mapping options that overlap in some areas but with very different backgrounds.</p>
<h3>The story so far</h3>
<p>Some time before I started in May LINQ to SQL was handed over to Data Programmability.</p>
<p>One of the first things you notice is that the overlap between the two object-relational mapping solutions Microsoft causes confusion and hesitation.</p>
<blockquote><p>Do I want something lightweight and easy or do I need the extra abstraction with a richer feature set?     <br /> If I want to start with LINQ to SQL today but know that the database won’t stay under my control how would I move to Entity Framework?</p>
</blockquote>
<p>These are the questions that many developers face and our team spent a lot of time looking at the differences between the two stacks, how they behave and which features were missing if you wanted to migrate from LINQ to SQL to Entity Framework v1. We put together code samples, some helpers and documentation which are now being <a href="http://blogs.msdn.com/adonet/">serialized on the ADO.NET blog</a> and left us with a better understanding of the disparity – some of which the EF team have already addressed in v2.</p>
<h3>Where next</h3>
<p>The decision has been made that <a href="http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx">Entity Framework is the recommended solution for LINQ to relational scenarios</a> but we are committed to looking after our users and are approaching this in two ways.</p>
<p>Firstly we are going to make sure LINQ to SQL continues to operate as it should. This doesn’t just mean making sure what we had works in .NET 4.0 but also fixing a number of issues that have arisen as people pick it up for more advanced projects and put it into production environments.</p>
<p>Secondly we will evolve LINQ to Entities to encompass the features and ease of use that people have come to expect from LINQ to SQL. In .NET 4.0 this already includes additional LINQ operators and better persistence-ignorance.</p>
<p>This isn’t to say LINQ to SQL won’t ever get new features. The communities around LINQ to SQL are a continuous source of ideas and we need to consider how they fit the minimalistic lightweight approach LINQ to SQL is already valued for. Where these suggestions fit with this strategy we will be working hard to get them into the product. Some enhancements like the T4 templates can be released independently but runtime elements need to stick to the .NET Framework schedule.</p>
<h3>In conclusion</h3>
<p><font size="5">DON’T PANIC     <br /></font> (in large, friendly letters)</p>
<p>LINQ to SQL will continue to work and EF will better address the needs of LINQ to SQL users with each new release.</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=QiXQkNs5"><img src="http://feeds.feedburner.com/~f/DamienG?i=QiXQkNs5" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/rJmC1LsO5OI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2008/10/31/linq-to-sql-next-steps/feed</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Disappointing new MacBook Pros</title>
		<link>http://damieng.com/blog/2008/10/14/disappointing-new-macbook-pros</link>
		<comments>http://damieng.com/blog/2008/10/14/disappointing-new-macbook-pros#comments</comments>
		<pubDate>Tue, 14 Oct 2008 19:16:01 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[MacBook-Pro]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1070</guid>
		<description>Like many other MacBook Pro owners I've been waiting for the October 14th event with some excitement. The highlights include:

Stronger aluminium block casing
NVidia dual graphics for low-power or high-performance
Glass multi-touch/multi-press trackpad

But the downsides are also worth noting, all of which make me think when I replace my 2.6GHz 17" MBP in a year Apple aren't going to [...]</description>
			<content:encoded><![CDATA[<p>Like many other MacBook Pro owners I've been waiting for the October 14th event with some excitement. The highlights include:</p>
<ul>
<li>Stronger aluminium block casing</li>
<li>NVidia dual graphics for low-power or high-performance</li>
<li>Glass multi-touch/multi-press trackpad</li>
</ul>
<p>But the downsides are also worth noting, all of which make me think when I replace my 2.6GHz 17" MBP in a year Apple aren't going to have something I want to replace it with.</p>
<ul>
<li>No 17" model</li>
<li>4GB RAM limit</li>
<li>Glossy screen only</li>
<li>1440x900 resolution</li>
<li><span style="text-decoration: line-through;">Firewire gone</span></li>
</ul>
<p class="new"><a href="http://blogs.technet.com/keithcombs/archive/2008/10/14/thumbs-up-or-down-for-the-new-macs.aspx">Keith Combs</a> has some similar observations in more depth while AppleInsider is suggesting a <a href="http://www.appleinsider.com/articles/08/10/15/apples_next_gen_17_inch_macbook_pro_due_in_a_few_months.html">January refresh for the 17"</a></p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=JE3QpQfi"><img src="http://feeds.feedburner.com/~f/DamienG?i=JE3QpQfi" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/MDjZdrZYr1c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2008/10/14/disappointing-new-macbook-pros/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Friday Fill-Ins #91</title>
		<link>http://damieng.com/blog/2008/09/27/friday-fill-ins-91</link>
		<comments>http://damieng.com/blog/2008/09/27/friday-fill-ins-91#comments</comments>
		<pubDate>Sat, 27 Sep 2008 05:26:07 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[meme]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1050</guid>
		<description>Started by Janet, picked up via Brad.

Settling down in the Redmond area and being with my team are some of the things I'm most looking forward to in October.
Sometimes I am so deep in thought when people ask me a question I look dazed and confused, failing to answer them.
People grow and situations change and that's [...]</description>
			<content:encoded><![CDATA[<p>Started by <a href="http://fridayfillins.blogspot.com/2008/09/friday-fill-ins-91.html">Janet</a>, picked up via <a href="http://bradwilson.typepad.com/blog/2008/09/friday-fill-ins.html">Brad</a>.</p>
<ol>
<li><em>Settling down in the Redmond area and being with my team</em> are some of the things I'm most looking forward to in October.</li>
<li>Sometimes I <em>am so deep in thought when people ask me a question I look dazed and confused, failing to answer them.</em></li>
<li><em>People grow and situations change</em> and that's why there is a saying, "never say never"!</li>
<li>When I'm down, I <em>take a nap, wake up and do something different or creative</em>.</li>
<li><em>Microsoft Building 35</em> is where you'll find me most often.</li>
<li>A rainy day is good for <em>splashing in puddles, getting wet and drying off near something warm with cocoa</em>.</li>
<li>And as for the weekend, tonight I’m looking forward to <em>wrapping things up</em>, tomorrow my plans include <em>going out with my Vancouver friends one last time</em> and Sunday, I want to <em>go parkouring and start packing</em>!</li>
</ol>
<div><em>[)amien</em></div>
<div class="feedflare">
<a href="http://feed.damieng.com/~f/DamienG?a=4wDqQlXH"><img src="http://feeds.feedburner.com/~f/DamienG?i=4wDqQlXH" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/oA8gtaa9EF8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2008/09/27/friday-fill-ins-91/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic page generated in 1.303 seconds. --><!-- Cached page generated by WP-Super-Cache on 2009-07-11 01:19:49 -->
