<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DamienG &#187; Development</title>
	<atom:link href="http://damieng.com/blog/category/development/feed" rel="self" type="application/rss+xml" />
	<link>http://damieng.com</link>
	<description>A .NET developer in Redmond</description>
	<lastBuildDate>Mon, 30 Aug 2010 16:23:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Anatomy of a good bug report</title>
		<link>http://damieng.com/blog/2010/06/30/anatomy-of-a-good-bug-report?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=anatomy-of-a-good-bug-report</link>
		<comments>http://damieng.com/blog/2010/06/30/anatomy-of-a-good-bug-report#comments</comments>
		<pubDate>Wed, 30 Jun 2010 19:57:45 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[bug report]]></category>
		<category><![CDATA[bugs]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1644</guid>
		<description><![CDATA[Working on the .NET Framework was an interesting but often difficult time especially when dealing with vague or incomprehensible bug reports. Look before you file Head to Bing, Google, official support sites and bug database if you have access to it (Microsoft Connect, Apple Radar, Bugzilla for Firefox etc.) to see if others have run [...]]]></description>
			<content:encoded><![CDATA[<p>Working on the .NET Framework was an interesting but often difficult time especially when dealing with vague or incomprehensible bug reports.</p>
<h3>Look before you file</h3>
<p>Head to Bing, Google, official support sites and bug database if you have access to it (<a href="http://connect.microsoft.com/">Microsoft Connect</a>, <a href="http://radar.apple.com">Apple Radar</a>, <a href="https://bugzilla.mozilla.org/">Bugzilla for Firefox</a> etc.) to see if others have run into this issue. Searching for the error message can yield good results but remove any elements of the message specific to your project (e.g. class names, property names etc.)</p>
<div class="aside" style="float: right; width: 30%;">
<h4 id="why-workaround">Why accept a workaround?</h4>
<p>Do not underestimate the value of a solid workaround.</p>
<p>A patch is significant effort for both sides and for re-distributable components like .NET Framework getting the components to the right place can be tough. You&#8217;ll need to deploy to your team, build, test and staging environments and, if you distribute software, to all your customers.</p>
<p>This can be especially painful when strictly controlled environments are shared with others and ops teams are hesitant about putting patches or hotfixes into production. Factor in processor architectures, operating systems and language support and weigh it up.</p>
</div>
<p>The reasons for this are:</p>
<ul>
<li>you may have made a mistake (likely if the software has seen considerable use)</li>
<li>behave differently to your expectations (the dreaded &#8216;by design&#8217;)</li>
<li>already be fixed (in the next release and possibly as a patch)</li>
<li>have an acceptable workaround (<a href="#why-workaround">why accept a workaround?</a>)</li>
</ul>
<p>If you are running into problems with developer tools also check out:</p>
<ul>
<li>Official forums (<a href="http://social.msdn.microsoft.com/Forums/">MSDN Forums</a> &amp; <a href="http://forums.asp.net/">ASP.NET Forums</a> for Microsoft tools)</li>
<li>Unofficial respected sites (<a href="http://stackoverflow.com">StackOverflow</a>)</li>
</ul>
<p>Consider how likely it is you&#8217;ve discovered a bug given the complexity of what you are doing, how unusual it is and how mature the software is. Attempting something simple on an established piece of software likely means you&#8217;ve made a mistake or misunderstood the documentation.</p>
<h3>A good bug report</h3>
<p>So you decided to go ahead and report the bug (we all want better software after all).</p>
<p>The essence of a good bug report is having just the right amount of information to identify the bug without any unnecessary detail.</p>
<p>Let&#8217;s break it down.</p>
<h3>What happened</h3>
<p>The most important element is describing what happened and there are four major possibilities.</p>
<h4>Error message</h4>
<p>You told the software to do something and it displayed an error message instead.</p>
<p>On a good day the error message lets you know why it can&#8217;t do what you asked and lets you know what to do to make it work. Given you&#8217;re filing a bug report it isn&#8217;t one of those days.</p>
<p>The error message is likely cryptic, doesn&#8217;t tell you how to get what you want or is just plain wrong. We&#8217;ll need that message in its entirety so:</p>
<ul class="information">
<li>Copy Windows message box contents as text by pressing control-c when it&#8217;s in focus</li>
<li>When there is a lot of text take a screen print (printscreen on Windows, command-shift-3 on Mac OS X)</li>
<li>Localized error messages may slow down support responses &#8211; switch the app back to their language first</li>
</ul>
<h4>Exceptions</h4>
<p>When a piece of a program (called a method or function) can&#8217;t do what it claims it throws an &#8216;exception&#8217; back up to the piece that asked (called) it. This exception is like an error message but with enough lot of technical detail that travels back up the program until something deals with it (known as a catch).</p>
<p>When you see an exception then nothing wanted to deal with it.</p>
<p>You will see an error message that contains the exception and possibly a list of program pieces that couldn&#8217;t deal with it. This is called a stack trace and is invaluable to the person investigating your report so include it.</p>
<p>Developers seeing exceptions in their own program need to determine if they should be catching that exception or whether it shouldn&#8217;t be occurring. Feel frim the stack trace so your own methods aren&#8217;t included but too much is better than too little.</p>
<h4>Unexpected behaviour</h4>
<p>The software should have done what you wanted but did something you didn&#8217;t expect instead.</p>
<p>Report what you thought should happen, what the software did instead, how this is different and the reason why you think it should be that way.</p>
<p>Other people may not agree with your change and in the case of shared programming libraries or frameworks a fix for you can become a break for others that rely on existing behaviour.</p>
<h4>Terminated</h4>
<p>The software just vanished from the screen without a trace. Crashed, terminated or unexpectedly quit and perhaps took some of your work with it :(</p>
<p>If you&#8217;re really unlucky the software that crashed is your operating system. The blue screen of death (BSOD) on Windows, the grey screen on Mac OS X.</p>
<p>Often there are logs left behind you can examine to identify what went wrong.</p>
<p>On Mac OS X fire up <em>Console </em>from <em>Application &gt; Utilities</em> and see what you can find. iPhones, iPods and iPads do this quite often and iTunes will likely offer to send detailed information to Apple who will hopefully share it with the application developer if it&#8217;s not their own.</p>
<p>Windows users will want to head to the <em>Event Viewer</em> and find the error and any additional messages that appear to relate to it and included these too.</p>
<h3>Steps to reproduce</h3>
<p>Ideally the minimal number of steps to reproduce the error every time. You want this to be reliable as possible as companies have limited resources too and won&#8217;t spend days trying to reproduce a low-impact bug.</p>
<p>This can be a very important step in understanding the scope of the problem and it&#8217;s impact. If you can&#8217;t reproduce it in a minimal number of steps there&#8217;s always the possibility you&#8217;re overlooking some other aspect that could be causing the problem &#8211; bad data or rogue code elsewhere!</p>
<p>For an application this may be a data file or a number of manual steps a user must manually perform via the user interface.</p>
<p>For a framework a small self-contained project file with a minimal amount of code to reproduce the failing scenario.</p>
<p>Again here, if you can make the steps clear and ideally in the language of the company producing the software your bug report is not going to hit extra delays.</p>
<h3>Environment</h3>
<p>Bugs are often sensitive to their environment and you should always include the version number of the software you are using as well as pertinent platform details,  including:</p>
<ul>
<li>What operating system, version &amp; service pack</li>
<li>What processor architecture (x86, x64, IA-64)</li>
<li>What language &amp; locale your machine is running in (e.g. US English (en-US), Brazil Portuguese (pr-BR))</li>
</ul>
<p>In the specific case of Visual Studio and .NET bugs:</p>
<ul>
<li>What version of Visual Studio you are using (including any service packs)</li>
<li>What processor architecture you are compiling for</li>
<li>What language and compiler version you are using (e.g. C# compiling for 4.0)</li>
</ul>
<p>You may need to include details for your desktop or developer machine <strong>and </strong>details of the server it is connecting to if any are involved.</p>
<h3>What you&#8217;ve tried</h3>
<p>Chances are you tried several things before filing a bug report. Let us know if you tried:</p>
<ul>
<li>Alternate routes through the user interface</li>
<li>Entering data in a different format or order</li>
<li>A different computer or environment</li>
</ul>
<p>Letting them know this means they can avoid suggesting things you&#8217;ve already tried or waste time trying them too.</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/06/30/anatomy-of-a-good-bug-report/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Include for LINQ to SQL (and maybe other providers)</title>
		<link>http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=include-for-linq-to-sql-and-maybe-other-providers</link>
		<comments>http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers#comments</comments>
		<pubDate>Fri, 21 May 2010 18:24:16 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1684</guid>
		<description><![CDATA[It&#8217;s quite common that when you issue a query you&#8217;re going to want to join some additional tables. In LINQ this can be a big issue as associations are properties and it&#8217;s easy to end up issuing a query every time you hit one. This is referred to as the SELECT N+1 problem and tools [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s quite common that when you issue a query you&#8217;re going to want to join some additional tables.</p>
<p>In LINQ this can be a big issue as associations are properties and it&#8217;s easy to end up issuing a query every time you hit one. This is referred to as the <a href="http://l2sprof.com/Learn/Alerts/SelectNPlusOne">SELECT N+1 problem</a> and tools like <a href="http://l2sprof.com/">LINQ to SQL Profiler</a> can help you find them.</p>
<h3>An example</h3>
<p>Consider the following section of C# code that displays a list of blog posts and also wants the author name.</p>
<pre><code><strong>foreach</strong>(Post post <strong>in</strong> db.Posts)
  Console.WriteLine("{0} {1}", post.Title, post.Author.Name);</code></pre>
<p>This code looks innocent enough and will issue a query like &#8220;SELECT * FROM [Posts]&#8221; but iterating over the posts causes the lazy-loading of the Author property to trigger and each one may well issue a query similar to &#8220;SELECT * FROM [Authors] WHERE [AuthorID] = 1&#8243;.</p>
<p>In the case of LINQ to SQL it&#8217;s not always an extra load as it will check the posts AuthorID foreign key in its internal identity map (cache) to see if it&#8217;s already in-memory before issuing a query to the database.</p>
<h3>LINQ to SQL&#8217;s LoadWith</h3>
<p>Most object-relational mappers have a solution for this &#8211; Entity Framework&#8217;s ObjectQuery has an Include operator (that alas takes a string), and <a href="http://ayende.com/Blog/archive/2006/05/02/CombatingTheSelectN1ProblemInNHibernate.aspx">NHibernate has a fetch</a> mechanism. LINQ to SQL has LoadWith which is used like this:</p>
<pre><code><strong>var </strong>db = <strong>new </strong>MyDataContext();
<strong>var </strong>dlo = <strong>new </strong>DataLoadOptions();
dlo.LoadWith&lt;Posts&gt;(p =&gt; p.Blog);
db.LoadOptions = dlo;</code></pre>
<p>This is a one-time operation for the lifetime of this instance of the data context which can be inflexible and LoadWith has at least <a href="http://connect.microsoft.com/VisualStudio/feedback/details/361683/using-dataloadoptions-with-a-linq-to-sql-inheritance-hierarchy-results-in-multiple-sql-left-joins">one big bug with inheritance issuing multiple joins</a>.</p>
<h3>A flexible alternative</h3>
<p>This got me thinking and I came up with a useful extension method to provide Include-like facilities on-demand in LINQ to SQL (and potentially other LINQ providers depending on what they support) in .NET 4.0.</p>
<pre><code><strong>public static</strong> IEnumerable&lt;T&gt; Include&lt;T, TInclude&gt;(<strong>this </strong>IQueryable&lt;T&gt; query, Expression&lt;Func&lt;T, TInclude&gt;&gt; sidecar) {
   <strong>var </strong>elementParameter = sidecar.Parameters.Single();
   <strong>var </strong>tupleType = <strong>typeof</strong>(Tuple&lt;T, TInclude&gt;);
   <strong>var </strong>sidecarSelector =  Expression.Lambda&lt;Func&lt;T, Tuple&lt;T, TInclude&gt;&gt;&gt;(
      Expression.New(tupleType.GetConstructor(<strong>new</strong>[] { <strong>typeof</strong>(T), <strong>typeof</strong>(TInclude) }),
         <strong>new </strong>Expression[] { elementParameter, sidecar.Body  },
         tupleType.GetProperty("Item1"), tupleType.GetProperty("Item2")), elementParameter);
   <strong>return </strong>query.Select(sidecarSelector).AsEnumerable().Select(t =&gt; t.Item1);
}</code></pre>
<p>To use simply place at the <strong>end </strong>of your query and specify the property you wish to eager-load, e.g.</p>
<pre><code><strong>var</strong> oneInclude = db.Posts.Where(p =&gt; p.Published).Include(p =&gt; p.Blog));
<strong>var</strong> multipleIncludes = db.Posts.Where(p =&gt; p.Published).Include(p =&gt; new { p.Blog, p.Template, p.Blog.Author }));</code></pre>
<div class="alert">This code is very untested although it has worked quite well in the few tests I&#8217;ve thrown at it. Evaluate it properly before you decide to use it!</div>
<h3>How it works</h3>
<p>How it works is actually very simple &#8211; it projects into a Tuple that contains the original item and all additional loaded elements and then just returns the query back the original item. It is a dynamic version of:</p>
<pre><code>var query = db.Posts.Where(p =&gt; p.Published).Select(p =&gt; new Tuple(p, p.Blog)).Select(t =&gt; t.Item1);</code></pre>
<p>This is why it has to return IEnumerable&lt;T&gt; and belong at the end (and the use of Tuple is why it is .NET 4.0 only although that should be easy enough to change). Not all LINQ providers will necessarily register the elements with their identity map to prevent SELECT N+1 on lazy-loading but LINQ to SQL does :)</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Creating RSS feeds in ASP.NET MVC</title>
		<link>http://damieng.com/blog/2010/04/26/creating-rss-feeds-in-asp-net-mvc?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=creating-rss-feeds-in-asp-net-mvc</link>
		<comments>http://damieng.com/blog/2010/04/26/creating-rss-feeds-in-asp-net-mvc#comments</comments>
		<pubDate>Mon, 26 Apr 2010 16:45:48 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[atom]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[rss]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1626</guid>
		<description><![CDATA[ASP.NET&#8217;s MVC -is the technology that brought me to Microsoft and the west-coast and it&#8217;s been fun getting to grips with it these last few weeks. Last week I needed to expose RSS feeds and checked out some examples online but was very disappointed. If you find yourself contemplating writing code to solve technical problems [...]]]></description>
			<content:encoded><![CDATA[<p>ASP.NET&#8217;s MVC -is the technology that brought me to Microsoft and the west-coast and it&#8217;s been fun getting to grips with it these last few weeks.</p>
<p>Last week I needed to expose RSS feeds and checked out some examples online but was very disappointed.</p>
<p>If you find yourself contemplating writing code to solve technical problems rather than the specific business domain you work in you owe it to your employer and fellow developers to see what exists before churning out code to solve it.</p>
<p>The primary excuse (and I admit to using it myself) is &#8220;X is too bloated, I only need a subset. I can write that quicker than learn their solution.&#8221; but a quick reality check:</p>
<ul>
<li>Time &#8211; code always takes longer than you think.</li>
<li>&#8220;Bloat&#8221; &#8211; indicates the problem is more complex than you realize.</li>
<li>Growth &#8211; todays requirements will grow tomorrow.</li>
<li>Maintenance &#8211; fixing code outside your business domain.</li>
<li>Isolation &#8211; nobody coming in will know your home-grown solution.</li>
</ul>
<p>The RSS examples I found had their own &#8216;feed&#8217; and &#8216;items&#8217; classes and implemented flaky XML rendering by themselves or as MVC view pages.</p>
<p>If these people had spent a little time doing some research they would have discovered .NET&#8217;s built in SyndicatedFeed and SyndicatedItem class for content and two classes (Rss20FeedFormatter and Atom10FeedFormatter )  to handle XML generation with correct encoding, formatting and optional fields.</p>
<p>All that is actually required is a small class to wire up these built-in classes to MVC.</p>
<pre><code><strong>using </strong>System;
<strong>using </strong>System.ServiceModel.Syndication;
<strong>using </strong>System.Text;
<strong>using </strong>System.Web;
<strong>using </strong>System.Web.Mvc;
<strong>using </strong>System.Xml;

<strong>namespace </strong>MyApplication.Something
{
    <strong>public class </strong>FeedResult : ActionResult
    {
        <strong>public </strong>Encoding ContentEncoding { <strong>get</strong>; <strong>set</strong>; }
        <strong>public string </strong>ContentType { <strong>get</strong>; <strong>set</strong>; }

        <strong>private readonly </strong>SyndicationFeedFormatter feed;
        <strong>public </strong>SyndicationFeedFormatter Feed{
            <strong>get </strong>{ <strong>return </strong>feed; }
        }

        <strong>public </strong>FeedResult(SyndicationFeedFormatter feed) {
            <strong>this</strong>.feed = feed;
        }

        <strong>public override void</strong> ExecuteResult(ControllerContext context) {
            <strong>if </strong>(context == <strong>null</strong>)
                <strong>throw new</strong> ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = !<strong>string</strong>.IsNullOrEmpty(ContentType) ? ContentType : "application/rss+xml";

            <strong>if </strong>(ContentEncoding != <strong>null</strong>)
                response.ContentEncoding = ContentEncoding;

            <strong>if </strong>(feed != <strong>null</strong>)
                <strong>using </strong>(<strong>var </strong>xmlWriter = <strong>new </strong>XmlTextWriter(response.Output)) {
                    xmlWriter.Formatting = Formatting.Indented;
                    feed.WriteTo(xmlWriter);
                }
        }
    }
}</code></pre>
<p>In a controller that supplies RSS feed simply project your data onto SyndicationItems and create a SyndicationFeed then return a FeedResult with the FeedFormatter of your choice.</p>
<pre><code><strong>public </strong>ActionResult NewPosts() {
    <strong>var </strong>blog = data.Blogs.SingleOrDefault();
    <strong>var </strong>postItems = data.Posts.Where(p =&gt; p.Blog = blog).OrderBy(p =&gt; p.PublishedDate).Take(25)
        .Select(p =&gt; new SyndicationItem(p.Title, p.Content, <strong>new </strong>Uri(p.Url)));

    <strong>var </strong>feed = <strong>new </strong>SyndicationFeed(blog.Title, blog.Description, <strong>new </strong>Uri(blog.Url) , postItems) {
        Copyright = blog.Copyright,
        Language = "en-US"
    };

   <strong> return new </strong>FeedResult(<strong>new </strong>Rss20FeedFormatter(feed));
}</code></pre>
<p>This also has a few additional advantages:</p>
<ol>
<li>Unit tests can ensure the ActionResult is a FeedResult</li>
<li>Unit tests can examine the Feed property to examine results without parsing XML</li>
<li>Switching to Atom format involved just changing the new Rss20FeedFormatter to Atom10FeedFormatter</li>
</ol>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/04/26/creating-rss-feeds-in-asp-net-mvc/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>My top 5 free VS 2010 extension picks</title>
		<link>http://damieng.com/blog/2010/03/22/my-top-5-free-vs-2010-extension-picks?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=my-top-5-free-vs-2010-extension-picks</link>
		<comments>http://damieng.com/blog/2010/03/22/my-top-5-free-vs-2010-extension-picks#comments</comments>
		<pubDate>Mon, 22 Mar 2010 18:32:33 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2010/03/22/my-top-5-free-vs-2010-extension-picks</guid>
		<description><![CDATA[The Visual Studio Gallery is already home to 533 tools, controls and templates for VS 2010 and this number is sure to grow once VS 2010 hits RTM and people get to grips with the extendable new editor. Don’t forget to check out The Visual Studio Blog for more tips, tricks and tools. Theme VS [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/site/search?f[0].Type=VisualStudioVersion&amp;f[0].Value=10.0&amp;f[0].Text=Visual%20Studio%202010%20RC">Visual Studio Gallery is already home to 533 tools, controls and templates for VS 2010</a> and this number is sure to grow once VS 2010 hits RTM and people get to grips with the <a href="http://msdn.microsoft.com/en-us/library/dd885242(VS.100).aspx">extendable new editor</a>.</p>
<p>Don’t forget to check out <a href="http://blogs.msdn.com/visualstudio/">The Visual Studio Blog</a> for more tips, tricks and tools.</p>
<h3><a href="http://damieng.com/wp-content/uploads/2010/03/smallScreenshot.png"><img style="float: right;" src="http://damieng.com/wp-content/uploads/2010/03/smallScreenshot_thumb.png" alt="Small screenshot of Visual Studio 2010" width="114" height="114" /></a>Theme VS itself</h3>
<p>Color themes for the VS editor have been available and popular for some time but the <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/20cd93a2-c435-4d00-a797-499f16402378">Visual Studio Color Theme Editor</a> adds colour themes to the VS shell letting you customize it to the most intimate detail as well as providing a bunch of pre-defined themes like Aero and shades of XP.</p>
<h3>A bucket and a mop</h3>
<p><a href="http://visualstudiogallery.msdn.microsoft.com/en-us/76293c4d-8c16-4f4a-aee6-21f83a571496">CodeMaid</a> lets you clean up your code more thoroughly and quickly including removing extra empty lines and whitespace and automatically triggering VS’s cleanup steps too (format document, remove unused strings, sort usings) as well as quick switching between project sub-items, quick-jump to complex methods etc.</p>
<h3>Ceasefire on indentation war</h3>
<p>The <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/77b317a9-1a94-4ae0-bd15-d46a3195219f">Indentation Matcher Extension</a> detects the indentation style used when you open a file and sets your VS settings to match meaning you can just edit existing projects and solutions without a care in the world.</p>
<p>As it should be – or at least until <a href="http://en.wikipedia.org/wiki/Elastic_tabstop">Elastic tabstops</a> gets ported to VS2010 which might now be possible.</p>
<h3><a href="http://damieng.com/wp-content/uploads/2010/03/italiccomments.png"><img style="float:right" src="http://damieng.com/wp-content/uploads/2010/03/italiccomments_thumb.png" alt="Italic comments in Visual Studio" width="114" height="114" /></a>Stylistic comments</h3>
<p>My hacked-version of Envy Code R marked italic as bold to trick VS into using it which made a lot of people, myself included, happy. But for those who preferred Consolas it wasn’t much help (there was no way I could redistribute a modified version of Consolas but believe me it looked sweet).</p>
<p>VS 2010 curiously still spurns italic fonts but the pluggable editor means extensions like <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/0b439a8a-e21a-4e26-b82b-054fbf0acab7">ItalicComments</a> can get you there although you’ll need to grab the <a href="http://github.com/noahric/italiccomments">source from gitHub</a> to set it to your coding font of choice given the curious decision to hard-code Lucida Sans.</p>
<h3>My Engrish is gud</h3>
<p>Until Windows gets an OS-level spell checker (OS X had one in 2000) we’ll have to be content with each major app having it’s own or in the case of VS, none.</p>
<p>The aptly-named <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/7c8341f1-ebac-40c8-92c2-476db8d523ce">Spell Checker extension</a> adds English spell checking to comments, HTML text, strings etc. and you too can avoid embarrassing mistakes preserved in source control for all to see.</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/03/22/my-top-5-free-vs-2010-extension-picks/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL tips and tricks #3</title>
		<link>http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=linq-to-sql-tips-and-tricks-3</link>
		<comments>http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3#comments</comments>
		<pubDate>Tue, 12 Jan 2010 04:02:37 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1517</guid>
		<description><![CDATA[A few more interesting and lesser-known LINQ to SQL techniques. Lazy loading with stored procedures LINQ to SQL supports stored procedures for retrieving entities, insert, update and delete operations but you can also use them to perform lazy-loading of navigation properties. Lets show an example of a bi-directional relationship between a Post and a Comment. We [...]]]></description>
			<content:encoded><![CDATA[<p>A few more interesting and lesser-known LINQ to SQL techniques.</p>
<h3>Lazy loading with stored procedures</h3>
<p>LINQ to SQL supports stored procedures for retrieving entities, insert, update and delete operations but you can also use them to perform lazy-loading of navigation properties.</p>
<p>Lets show an example of a bi-directional relationship between a Post and a Comment. We have two stored procedures shown below and we bring them into the DBML by dragging them from <em>Server Explorer</em> into the LINQ to SQL designer surface and we set the return type property for each to the expected entity (Post and Comment respectively).</p>
<pre><code><strong>CREATE PROCEDURE</strong> LoadPost (@PostID <strong>int</strong>) <strong>AS SELECT</strong> * <strong>FROM</strong> Posts <strong>WHERE</strong> ID = @PostID
<strong>CREATE PROCEDURE</strong> LoadComments(@PostID <strong>int</strong>) <strong>AS</strong> <strong>SELECT</strong> * <strong>FROM</strong> Comments <strong>WHERE</strong> Parent_Post_ID = @PostID</code></pre>
<p>This generates two method stubs named LoadPost and LoadComments that we can use to programatically retrieve entities:</p>
<pre><code><strong>var</strong> post = dataContext.LoadPost(1).First();
Console.WriteLine("{0}", post.Title);</code></pre>
<p>Now to replace LINQ to SQL&#8217;s lazy-loading query generation we add  methods to the data context subclass with a specific signature.</p>
<pre><code><strong>partial class </strong>DataClasses1DataContext {
    <strong>protected</strong> IEnumerable&lt;Comment&gt; LoadComments(Post post) {
        <strong>return</strong> <strong>this</strong>.LoadComments(post.ID);
    }

    <strong>protected </strong>Post LoadParentPost(Comment comment) {
        <strong>return</strong> <strong>this</strong>.LoadPost(comment.Post_ID).First();
    }
}</code></pre>
<p>To get the signature of the method names right:</p>
<ol>
<li>Visibility can be anything (protected or private is recommended)</li>
<li>Return type must be the type of the other side of the association (wrapped in IEnumerable&lt;T&gt; when that side can be many)</li>
<li>Method name must start with the word &#8220;Load&#8221;</li>
<li>Method name must then continue with the name of the navigation property you want to intercept</li>
<li>Parameter type must be the type that has the named navigation property (step 4)</li>
</ol>
<h3>Storing and retrieving binary files</h3>
<p>LINQ to SQL supports the SQL Server&#8217;s varbinary type but storing something practical like a file in there isn&#8217;t so clear. Map your varbinary(max) column from your table into your entity which will expose the column as the special System.Data.Linq.Binary type (effectively a wrapper for a byte array but better change tracking).</p>
<h4>File to database</h4>
<p>To store a file in the database just read those bytes in and assign them to the property (Binary knows how to create itself from a byte array automatically). e.g.</p>
<pre><code><strong>string</strong> readPath = @"c:\test.jpg";
<strong>var</strong> storedFile = <strong>new</strong> StoredFile();
storedFile.Binary = File.ReadAllBytes(readPath);
storedFile.FileName = Path.GetFileName(readPath);
data.StoredFiles.InsertOnSubmit(storedFile);</code></pre>
<p>I recommend storing the file name as well as the binary contents for two reasons. Firstly writing the file back to disk or streaming it to a browser will require you know the file type (e.g. .jpg or image/jpeg) and secondly nobody likes downloading a a file called &#8216;download&#8217; or &#8217;1&#8242; :)</p>
<h4>Database to file</h4>
<p>Writing the file back to disk is just as easy although you have to use the ToArray() method of System.Data.Linq.Binary to turn it back into a byte array.</p>
<pre><code><strong>string</strong> writePath = @"c:\temp";
<strong>var</strong> storedFile = data.StoredFiles.First();
File.WriteAllBytes(Path.Combine(writePath, storedFile.FileName), storedFile.Binary.ToArray());
</code></pre>
<div class="alert">Always ensure when writing to the file system based on data that your filenames are sanitized! You don&#8217;t want users overwriting important files on your system.</div>
<h3>Multiple databases with a single context</h3>
<p>Contrary to popular belief you can in fact access entities from multiple databases with a single data context providing they live on the same server. This isn&#8217;t supported but I&#8217;ve used it on my own projects without issue :)</p>
<p>The first part is the tricky bit which involves getting the definition of your entity into your DBML. You have two options here:</p>
<h4>Create a temporary view</h4>
<p>If you have the rights you can temporarily create views in your primary database for each table in your non-primary database.</p>
<pre><code><strong>CREATE VIEW </strong>MyOtherTable <strong>AS SELECT </strong>* <strong>FROM</strong> MyOtherDatabase.dbo.MyOtherTable</code></pre>
<p>Once the views are created add them to your DBML by dragging them from Server Explorer into the LINQ to SQL designer surface and delete the views you created from the database.</p>
<h4>Create a temporary DBML</h4>
<p>If you can&#8217;t or don&#8217;t want to create temporary views then add a second (temporary) LINQ to SQL classes file (DBML) to your project. Use <em>Server Explorer</em> to find your secondary database and drag all the tables you will want to access to the LINQ to SQL designer surface.</p>
<p>Now save &amp; close open files and use the right-mouse-button context menu to <em>Open With&#8230;</em> and choose <em>XML Editor</em> on your original DBML and the new temporary one. Head to the <em>Window</em> menu and select <em>New Vertical Tab Group</em> to make the next step easier.</p>
<p>Looking through the DBML you will see each entity has a &lt;Table&gt; block inside the &lt;Database&gt;. Select all the Table tags and their children (but not Database or Connection) and copy/paste them into your existing DBML file. Then close the files and check all looks well in the designer again.</p>
<p>If it does, delete the temporary DBML file you created. If not go back and check the DBML file for duplicate names, mismatched XML etc.</p>
<h4>Finally, the easy bit</h4>
<p>Open the designer and for each table that comes from the other database select it and change the <em>Source</em> property in the <em>Properties</em> window from <em>dbo.MyOtherTable</em> to <em>MyOtherDatabase.dbo.MyOtherTable</em>.</p>
<p>Hit play and run! <em> </em></p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>SQL Server query plan cache &#8211; what is it and why should you care?</title>
		<link>http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=sql-server-query-plan-cache</link>
		<comments>http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache#comments</comments>
		<pubDate>Mon, 14 Dec 2009 00:55:42 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[sql-server]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1487</guid>
		<description><![CDATA[What is a query plan? SQL Server like all databases goes through a number of steps when it receives a command. Besides parsing and validating the command text and parameters it looks at the database schema, statistics and indexes to come up with a plan to efficiently query or change your data. You can view [...]]]></description>
			<content:encoded><![CDATA[<h3>What is a query plan?</h3>
<p>SQL Server like all databases goes through a number of steps when it receives a command. Besides parsing and validating the command text and parameters it looks at the database schema, statistics and indexes to come up with a plan to efficiently query or change your data.</p>
<p>You can view the plan SQL Server comes up with for a given query in SQL Management Studio by selecting Include Actual Execution Plan from the Query menu before running your query.</p>
<div id="attachment_1488" class="wp-caption alignnone" style="width: 310px"><img class="size-medium wp-image-1488" title="A query plan in SQL Managment Studio" src="http://damieng.com/wp-content/uploads/2009/12/QueryPlan-300x141.PNG" alt="A query plan in SQL Managment Studio" width="300" height="141" /><p class="wp-caption-text">A query plan in SQL Managment Studio</p></div>
<h3>Show me the cache!</h3>
<p>Query plans are cached so subsequent identical operations can reuse them for further performance gains. You can see the query plans in use on your server with the following SQL:</p>
<pre><code class="sql">SELECT objtype, p.size_in_bytes, t.[text], usecounts
     FROM sys.dm_exec_cached_plans p
     OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) t
     WHERE objtype IN ('Prepared', 'Adhoc')
     ORDER BY usecounts DESC</code></pre>
<h3>Hitting the cache</h3>
<p>DBAs know the value in hitting the query plan often and this is one of the reasons they like stored procedures. You can however achieve the same thing with parameterized queries providing the query text and the parameter definitions are identical so you can execute the same thing over and over again just with different parameters.</p>
<p>If your ORM uses parameterized queries then it too can take advantage of it but it is important to remember the query definition and parameters need to be identical for this to happen.</p>
<h3>How this applies to ORMs</h3>
<p>In .NET 3.5SP1 both LINQ to SQL and Entity Framework did not set the length of variable type parameters (varchar, nvarchar, text, ntext and varbinary) so SQL Client sets it to the actual content length. This means the cache is often missed and instead populated with plans that are different only in the parameter lengths.</p>
<p>In .NET 4.0 variable length parameters now honour the defined length in both LINQ to SQL and Entity Framework where possible or fall back to the maximum length when the actual content doesn&#8217;t fit in the defined length.</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Multiple outputs from T4 made easy &#8211; revisited</title>
		<link>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=multiple-outputs-from-t4-made-easy-revisited</link>
		<comments>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited#comments</comments>
		<pubDate>Fri, 06 Nov 2009 08:20:37 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1457</guid>
		<description><![CDATA[My multiple outputs from t4 made easy post contained a class making it easy to produce multiple files from Visual Studio’s text templating engine (T4). While useful it had a few issues: Getting start/end blocks mixed up resulted in unpredictable behaviour Files were rewritten even when content did not change Did not play well with [...]]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy">multiple outputs from t4 made easy</a> post contained a class making it easy to produce multiple files from Visual Studio’s text templating engine (T4).</p>
<p>While useful it had a few issues:</p>
<ul>
<li>Getting start/end blocks mixed up resulted in unpredictable behaviour</li>
<li>Files were rewritten even when content did not change</li>
<li>Did not play well with source control</li>
<li>Files not always deleted in VS</li>
<li>Failed in Visual Studio&#8217;s project-less Web Sites</li>
</ul>
<p>This helper class forms the basis of multiple file output for Entity Framework templates in .NET 4.0 and the <a href="http://l2st4.codeplex.com">LINQ to SQL templates</a> on CodePlex so we (Jeff Reed, <a href="http://andrewpeters.net/">Andrew Peters</a> and myself) made the following changes.</p>
<h3>Improvements</h3>
<h4>Simpler block handling</h4>
<p>The header, footer and file blocks can now be completed with EndBlock (EndHeader and EndFooter are gone), although it will automatically end the previous block when it hits a new one or the final Process method.</p>
<h4>Skip unchanged files</h4>
<p>Files are now only written to disk if the contents are different with the exception of the original T4 output file (we can&#8217;t stop that, sorry).</p>
<p>There is additional overhead reading and comparing files we believe unmodified files keeping their dates and source control status are worth it.</p>
<h4>Automatic checkout</h4>
<p>When the template detects it is running in Visual Studio and that the file it needs to write to is currently in source control but not checked out it will check the file out for you.</p>
<h4>Predictable clean-up</h4>
<p>All files that were not part of the generation process but are nested under the project item will now be deleted when running inside Visual Studio.</p>
<p>Outside of Visual Studio files are no longer deleted &#8211; this was destructive and it couldn&#8217;t know which files it generated on a previous run to clean-up correctly anyway.</p>
<h4>Website projects fall back to single file generation</h4>
<p>Visual Studio has both <a href="http://damieng.com/blog/2008/02/07/web-site-vs-web-application">web sites and web applications</a> with the former being project-less leading to very messy multi-file generation so it forces single file generation.</p>
<h4>Internal improvements</h4>
<p>Source is now simpler to read and understand with less public visibility and faster and more robust VS interop by batching the files &amp; deletes to a single invoke at the end to avoid conflicts with other add-in&#8217;s that might be triggered by the changes.</p>
<h3>Usage</h3>
<h4>Initialization</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. (For Visual Studio 2010 remove the #v3.5 portion from the language attribute)</p>
<pre><code>&lt;#@ template language="C#v3.5" hostspecific="True"
#&gt;&lt;#@include file="Manager.ttinclude"
#&gt;&lt;# var manager = Manager.Create(Host, GenerationEnvironment); #&gt;</code></pre>
<h4>File blocks</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. The EndBlock is optional if you want it to carry through to the next one :)</p>
<pre><code>&lt;# manager.StartNewFile("Employee.generated.cs"); #&gt;
public class Employee { … }
&lt;# manager.EndBlock(); #&gt;</code></pre>
<h4>Headers &amp; 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 and StartFooter and the blocks will be emitted to the start and end of all split files as well as being left in the original output file.</p>
<pre><code>&lt;# manager.StartHeader(); #&gt;
// Code generated by a template
using System;

&lt;# manager.EndBlock(); #&gt;</code></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 StartNewFile block will remain in the original output file.</p>
<pre><code>&lt;# manager.Process(true); #&gt;</code></pre>
<h3>Revised Manager class</h3>
<pre><code>&lt;#@ assembly name="System.Core"
#&gt;&lt;#@ assembly name="System.Data.Linq"
#&gt;&lt;#@ assembly name="EnvDTE"
#&gt;&lt;#@ assembly name="System.Xml"
#&gt;&lt;#@ assembly name="System.Xml.Linq"
#&gt;&lt;#@ import namespace="System"
#&gt;&lt;#@ import namespace="System.CodeDom"
#&gt;&lt;#@ import namespace="System.CodeDom.Compiler"
#&gt;&lt;#@ import namespace="System.Collections.Generic"
#&gt;&lt;#@ import namespace="System.Data.Linq"
#&gt;&lt;#@ import namespace="System.Data.Linq.Mapping"
#&gt;&lt;#@ import namespace="System.IO"
#&gt;&lt;#@ import namespace="System.Linq"
#&gt;&lt;#@ import namespace="System.Reflection"
#&gt;&lt;#@ import namespace="System.Text"
#&gt;&lt;#@ import namespace="System.Xml.Linq"
#&gt;&lt;#@ import namespace="Microsoft.VisualStudio.TextTemplating"
#&gt;&lt;#+

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

    <strong>private</strong> Block currentBlock;
    <strong>private</strong> List&lt;Block&gt; files = <strong>new</strong> List&lt;Block&gt;();
    <strong>private</strong> Block footer = <strong>new</strong> Block();
    <strong>private</strong> Block header = <strong>new</strong> Block();
    <strong>private</strong> ITextTemplatingEngineHost host;
    <strong>private</strong> StringBuilder template;
    <strong>protected</strong> List&lt;String&gt; generatedFileNames = <strong>new</strong> List&lt;String&gt;();

    <strong>public static </strong>Manager Create(ITextTemplatingEngineHost host, StringBuilder template) {
        <strong>return</strong> (host <strong>is</strong> IServiceProvider) ? <strong>new</strong> VSManager(host, template) : <strong>new</strong> Manager(host, template);
    }

    <strong>public void</strong> StartNewFile(String name) {
        <strong>if</strong> (name == <strong>null</strong>)
            <strong>throw new</strong> ArgumentNullException("name");
        CurrentBlock = <strong>new</strong> Block { Name = name };
    }

    <strong>public void</strong> StartFooter() {
        CurrentBlock = footer;
    }

    <strong>public void</strong> StartHeader() {
        CurrentBlock = header;
    }

    <strong>public void</strong> EndBlock() {
        <strong>if</strong> (CurrentBlock == <strong>null</strong>)
            <strong>return</strong>;
        CurrentBlock.Length = template.Length - CurrentBlock.Start;
        <strong>if</strong> (CurrentBlock != header &amp;&amp; CurrentBlock != footer)
            files.Add(CurrentBlock);
        currentBlock = <strong>null</strong>;
    }

    <strong>public virtual void</strong> Process(<strong>bool</strong> split) {
        <strong>if</strong> (split) {
            EndBlock();
            String headerText = template.ToString(header.Start, header.Length);
            String footerText = template.ToString(footer.Start, footer.Length);
            String outputPath = Path.GetDirectoryName(host.TemplateFile);
            files.Reverse();
            <strong>foreach</strong>(Block block <strong>in</strong> files) {
                String fileName = Path.Combine(outputPath, block.Name);
                String content = headerText + template.ToString(block.Start, block.Length) + footerText;
                generatedFileNames.Add(fileName);
                CreateFile(fileName, content);
                template.Remove(block.Start, block.Length);
            }
        }
    }

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

    <strong>public virtual</strong> String GetCustomToolNamespace(String fileName) {
        <strong>return null</strong>;
    }

    <strong>public virtual</strong> String DefaultProjectNamespace {
        <strong>get</strong> { <strong>return null</strong>; }
    }

    <strong>protected bool</strong> IsFileContentDifferent(String fileName, String newContent) {
        <strong>return</strong> !(File.Exists(fileName) &amp;&amp; File.ReadAllText(fileName) == newContent);
    }

    <strong>private</strong> Manager(ITextTemplatingEngineHost host, StringBuilder template) {
        <strong>this.</strong>host = host;
        <strong>this</strong>.template = template;
    }

    <strong>private</strong> Block CurrentBlock {
        <strong>get</strong> { <strong>return</strong> currentBlock; }
        <strong>set</strong> {
            <strong>if</strong> (CurrentBlock != <strong>null</strong>)
                EndBlock();
            if<strong> </strong>(value != <strong>null</strong>)
                value.Start = template.Length;
            currentBlock = <strong>value</strong>;
        }
    }

    <strong>private class</strong> VSManager: Manager {
        <strong>private</strong> EnvDTE.ProjectItem templateProjectItem;
        <strong>private</strong> EnvDTE.DTE dte;
        <strong>private</strong> Action&lt;String&gt; checkOutAction;
        <strong>private</strong> Action&lt;IEnumerable&lt;String&gt;&gt; projectSyncAction;

        <strong>public override</strong> String DefaultProjectNamespace {
            <strong>get</strong> {
                <strong>return</strong> templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString();
            }
        }

        <strong>public override</strong> String GetCustomToolNamespace(string fileName) {
            <strong>return</strong> dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
        }

        <strong>public override void</strong> Process(<strong>bool</strong> split) {
            <strong>if</strong> (templateProjectItem.ProjectItems == <strong>null</strong>)
                <strong>return</strong>;
            <strong>base</strong>.Process(split);
            projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, <strong>null</strong>, <strong>null</strong>));
        }

        <strong>protected override void</strong> CreateFile(String fileName, String content) {
            <strong>if</strong> (IsFileContentDifferent(fileName, content)) {
                CheckoutFileIfRequired(fileName);
                File.WriteAllText(fileName, content);
            }
        }

        <strong>internal</strong> VSManager(ITextTemplatingEngineHost host, StringBuilder template)
            : <strong>base</strong>(host, template) {
            <strong>var</strong> hostServiceProvider = (IServiceProvider) host;
            <strong>if</strong> (hostServiceProvider == <strong>null</strong>)
                <strong>throw new</strong> ArgumentNullException("Could not obtain IServiceProvider");
            dte = (EnvDTE.DTE) hostServiceProvider.GetService(<strong>typeof</strong>(EnvDTE.DTE));
            <strong>if</strong> (dte == <strong>null</strong>)
                <strong>throw new</strong> ArgumentNullException("Could not obtain DTE from host");
            templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
            checkOutAction = (String fileName) =&gt; dte.SourceControl.CheckOutItem(fileName);
            projectSyncAction = (IEnumerable&lt;String&gt; keepFileNames) =&gt; ProjectSync(templateProjectItem, keepFileNames);
        }

        <strong>private static void</strong> ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable&lt;String&gt; keepFileNames) {
            <strong>var</strong> keepFileNameSet = <strong>new</strong> HashSet&lt;String&gt;(keepFileNames);
            <strong>var</strong> projectFiles = <strong>new</strong> Dictionary&lt;String, EnvDTE.ProjectItem&gt;();
            <strong>var</strong> originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.get_FileNames(0)) + ".";
            <strong>foreach</strong>(EnvDTE.ProjectItem projectItem <strong>in</strong> templateProjectItem.ProjectItems)
                projectFiles.Add(projectItem.get_FileNames(0), projectItem);

            // Remove unused items from the project
            <strong>foreach</strong>(<strong>var</strong> pair <strong>in</strong> projectFiles)
                <strong>if</strong> (!keepFileNames.Contains(pair.Key) &amp;&amp; !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix))
                    pair.Value.Delete();

            // Add missing files to the project
            <strong>foreach</strong>(String fileName <strong>in</strong> keepFileNameSet)
                <strong>if</strong> (!projectFiles.ContainsKey(fileName))
                    templateProjectItem.ProjectItems.AddFromFile(fileName);
        }

        <strong>private void</strong> CheckoutFileIfRequired(String fileName) {
            <strong>var</strong> sc = dte.SourceControl;
            <strong>if</strong> (sc != <strong>null </strong>&amp;&amp; sc.IsItemUnderSCC(fileName) &amp;&amp; !sc.IsItemCheckedOut(fileName))
                checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, <strong>null</strong>, <strong>null</strong>));
        }
    }
} #&gt;</code></pre>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>When an object-relational mapper is too much, DataReader too little</title>
		<link>http://damieng.com/blog/2009/09/22/when-an-object-relational-mapper-is-too-much-datareader-too-little?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=when-an-object-relational-mapper-is-too-much-datareader-too-little</link>
		<comments>http://damieng.com/blog/2009/09/22/when-an-object-relational-mapper-is-too-much-datareader-too-little#comments</comments>
		<pubDate>Wed, 23 Sep 2009 06:57:28 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/09/22/when-an-object-relational-mapper-is-too-much-datareader-too-little</guid>
		<description><![CDATA[I fired up Visual Studio this evening to write a proof-of-concept app and found myself wanting strongly typed domain objects from a database but without the overhead of an object-relational mapper  (the application is read-only). One solution is to write methods by hand, another is to code generate them but it would be nice to [...]]]></description>
			<content:encoded><![CDATA[<p>I fired up Visual Studio this evening to write a proof-of-concept app and found myself wanting strongly typed domain objects from a database but without the overhead of an object-relational mapper  (the application is read-only).</p>
<p>One solution is to write methods by hand, another is to code generate them but it would be nice to be able to do:</p>
<pre><code><strong>var</strong> customers = <strong>new</strong> SqlCommand("SELECT ID, Name FROM Customer", connection)
  .As(r =&gt; <strong>new</strong> Customer { CustomerID = r.GetInt32(0), Name = r.GetString(1) }).ToList();</code></pre>
<p>So for any DbCommand object you can turn it into a bunch of classes by specifying the new pattern.</p>
<p>The tiny helper class to achieve this is:</p>
<pre><code><strong>public static class</strong> DataHelpers {
    <strong>public static</strong> List&lt;T&gt; ToList&lt;T&gt;(<strong>this</strong> IEnumerable&lt;T&gt; enumerable) {
        <strong>return new</strong> List&lt;T&gt;(enumerable);
    }

    <strong>public static</strong> IEnumerable&lt;T&gt; As&lt;T&gt;(<strong>this</strong> DbCommand command, Func&lt;IDataRecord, T&gt; map) {
        <strong>using</strong> (<strong>var</strong> reader = command.ExecuteReader())
            <strong>while</strong> (reader.Read())
                <strong>yield return</strong> map(reader);
    }
}</code></pre>
<p>It might even be possible to do some cool caching/materialization. I should look into that :)</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/09/22/when-an-object-relational-mapper-is-too-much-datareader-too-little/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL cheat sheet</title>
		<link>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=linq-to-sql-cheat-sheet</link>
		<comments>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet#comments</comments>
		<pubDate>Thu, 13 Aug 2009 07:55:33 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[cheat sheet]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1248</guid>
		<description><![CDATA[A few short words to say I&#8217;ve put together a cheat sheet for LINQ to SQL with one page for C# and another for VB.NET. It shows the syntax for a number of common query operations, manipulations and attributes and can be a very useful quick reference :) Download LINQ to SQL cheat sheet (PDF) [...]]]></description>
			<content:encoded><![CDATA[<p>A few short words to say I&#8217;ve put together a cheat sheet for LINQ to SQL with one page for C# and another for VB.NET.</p>
<p><img src="http://images.damieng.com/blog/LINQToSQLCheatSheet.png" alt="Thumbnail of the LINQ to SQL Cheat Sheet PDF" /></p>
<p>It shows the syntax for a number of common query operations, manipulations and attributes and can be a very useful quick reference :)</p>
<p class="download">Download <a href="http://download.damieng.com/dotnet/LINQToSQLCheatSheet.pdf">LINQ to SQL cheat sheet (PDF)</a> (76 KB)</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Dictionary look-up or create made simpler</title>
		<link>http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=dictionaryt-look-up-or-create-made-simpler</link>
		<comments>http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler#comments</comments>
		<pubDate>Wed, 05 Aug 2009 00:24:04 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler</guid>
		<description><![CDATA[The design of a Dictionary&#60;T&#62; lends itself well to a caching or identification mechanism and as a result you often see code that looks like this: private static Dictionary&#60;string,Employee&#62; employees; … public static Employee GetByName(string name) { Employee employee; if (!employees.TryGetValue(name, out employee)) { employee = new Employee(whatever); employees.Add(name, employee); } return employee; } It&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<p>The design of a Dictionary&lt;T&gt; lends itself well to a caching or identification mechanism and as a result you often see code that looks like this:</p>
<pre><code><strong>private static</strong> Dictionary&lt;<strong>string</strong>,Employee&gt; employees;
…
<strong>public static</strong> Employee GetByName(<strong>string</strong> name) {
    Employee employee;
    <strong>if</strong> (!employees.TryGetValue(name, <strong>out</strong> employee)) {
        employee = <strong>new</strong> Employee(whatever);
        employees.Add(name, employee);
    }
    <strong>return</strong> employee;
}</code></pre>
<p>It&#8217;s not that it is particularly difficult but it can be a bit error prone and when you’re doing it over and over. What would be nicer is something that let you do:</p>
<pre><code><strong>public static</strong> Employee GetByName(<strong>string</strong> name) {
    <strong>return</strong> employees.GetOrAdd(name, () =&gt; <strong>new</strong> Employee(whatever));
}</code></pre>
<p>Here&#8217;s an extension method to drop-in to a static class of your choosing that achieves just that.</p>
<pre><code><strong><strong>public </strong>static</strong> TDictionaryValue GetOrAdd&lt;TKey, TDictionaryValue&gt;(<strong>this</strong> IDictionary&lt;TKey, TDictionaryValue&gt; dictionary, TKey key, Func&lt;TDictionaryValue&gt; newValue)
{
    TDictionaryValue value;
    <strong>if</strong> (!dictionary.TryGetValue(key, <strong>out</strong> value)) {
        value = newValue.Invoke();
        dictionary.Add(key, value);
    }
    <strong>return</strong> value;
}</code></pre>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<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?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=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[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1202</guid>
		<description><![CDATA[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 [...]]]></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, <a href="http://blogs.msdn.com/meek/">Colin Meek</a> 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><code><strong>partial class</strong> Employee {
	<strong>public string</strong> FullName {
		<strong>get</strong> { <strong>return</strong> Forename + " " + 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("da")).GroupBy(e =&gt; e.Age);</code></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><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 + " " + 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; 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("da")).GroupBy(e =&gt; e.Age).WithTranslations();</code></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><code>...
DefaultTranslationOf&lt;Employee&gt;.Property(e =&gt; e.FullName).Is(e =&gt; e.Forename + " " + e.Surname);
<strong>var</strong> employees = db.Employees.Where(e =&gt; e.FullName.Contains("da")).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());} }
}</code></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><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 + " " + e.LastName);
<strong>var</strong> results = (<strong>from</strong> e <strong>in</strong> db.Employees <strong>where</strong> e.Name.Contains("martin") <strong>select</strong> e).WithTranslations(myTranslationMap).ToList();</code></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><code><strong>using</strong> Microsoft.Linq.Translations.Auto;</code></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><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()); } }</code></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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL resources</title>
		<link>http://damieng.com/blog/2009/06/04/linq-to-sql-resources?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=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[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1224</guid>
		<description><![CDATA[A quick round-up of some useful LINQ to SQL related resources that are available for developers. I&#8217;ve not used everything on this list myself so don&#8217;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 This ORM templating and design [...]]]></description>
			<content:encoded><![CDATA[<p>A quick round-up of some useful LINQ to SQL related resources that are available for developers. I&#8217;ve not used everything on this list myself so don&#8217;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&#8217;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&#8217;s ever-popular CodeSmith templating environment include a whole host of extra functionality beyond the standard generation including entity clone &amp; detach, enum&#8217;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&#8217;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>
<li><em><span style="font-style: normal;"><a href="http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet">LINQ to SQL Cheat Sheet</a></span><br />
PDF download of the most popular query and update syntax for C# and VB.NET. </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>
<li><em><span style="font-style: normal;"><a href="http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40">Changes in .NET 4.0</a></span><br />
List of the changes made to LINQ to SQL to .NET 4.0 including some possible breaking changes </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>
<li><a href="http://www.amazon.com/Programming-Microsoft®-PRO-Developer-Paolo-Pialorsi/dp/0735624003?tag=dam-20">Programming Microsoft LINQ</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><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/linq-to-sql">StackOverflow&#8217;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&#8217;s data access too!)</em></li>
</ul>
<p><em>[)amien</em></p>
]]></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?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=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><![CDATA[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. 25 Aug 2009 – Updated with additional changes, some of which are new in beta 2. Change list Performance Query plans are reused more often by specifically [...]]]></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>
<p class="new"><strong>25 Aug 2009</strong> – Updated with additional changes, some of which are new in beta 2. </p>
<h3>Change list</h3>
<h4>Performance</h4>
<ul>
<li>Query plans are reused more often by specifically defining text parameter lengths (when connecting to SQL 2005 or later)</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)</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&#8217;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 (regular &amp; compiled queries)</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&#8217;t match underlying column name </li>
<li>Server-generated columns and SQL replication/triggers now work instead of throwing SQL exception </li>
<li>Improved binding support with the MVC model binder</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>Database&#160; control</h4>
<ul>
<li>DeleteDatabase no longer fails with case-sensitive database servers</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 &amp; computed columns</li>
<li>Foreign key changes will be picked up when bringing tables back into the designer without a restart </li>
<li>Can edit the return value type of unidentified stored procedure types</li>
<li>Stored procedure generated classes do not localize the word “Result” in the class name</li>
<li>Opening a DBML file no longer causes it to be checked out of source control</li>
<li>Changing a FK for a table and re-dragging it to the designer surface will show new FK’s</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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40/feed</wfw:commentRss>
		<slash:comments>83</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?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=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><![CDATA[A few more useful and lesser-known techniques for using LINQ to SQL. Take full control of  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 [...]]]></description>
			<content:encoded><![CDATA[<p>A few more useful and lesser-known techniques for using LINQ to SQL.</p>
<h3>Take full control of  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>
<pre><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("[People] AS [t0]", "[People] AS [t0] WITH (NOLOCK)");
<strong>var</strong> results = db.Translate&lt;Person&gt;(cmd.ExecuteReader());</code></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 dynamic 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><code><strong>SET</strong> FMTONLY <strong>OFF</strong></code></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><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);
    }
}</code></pre>
<p>And then to clone simply:</p>
<pre><code><strong>var</strong> source = myQuery.First();
<strong>var</strong> cloned = Clone(source);</code></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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2/feed</wfw:commentRss>
		<slash:comments>6</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?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=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><![CDATA[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 [...]]]></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><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;</code></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><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</code></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><code>[Function(Name=@"dbo.DynamicContractsActiveBetween")]
[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;
}</code></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><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);
   }
}</code></pre>
<p><em>[)amien</em></p>
]]></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>
	</channel>
</rss>
