<?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 silicon valley</description>
	<lastBuildDate>Wed, 16 May 2012 22:46:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Designing a great API</title>
		<link>http://damieng.com/blog/2011/11/29/designing-a-great-api?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=designing-a-great-api</link>
		<comments>http://damieng.com/blog/2011/11/29/designing-a-great-api#comments</comments>
		<pubDate>Tue, 29 Nov 2011 09:16:44 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=2311</guid>
		<description><![CDATA[Several years ago I worked on a payroll package developing a core engine that required an API to let third parties write calculations, validations and security gates that would execute as part of it&#8217;s regular operation. We were a small team and I had many conversations with another developer tasked with building a payroll using ]]></description>
			<content:encoded><![CDATA[<p>Several years ago I worked on a payroll package developing a core engine that required an API to let third parties write calculations, validations and security gates that would execute as part of it&#8217;s regular operation.</p>
<p>We were a small team and I had many conversations with another developer tasked with building a payroll using the API I would provide. Some methods here, classes there, the odd helper function and I had an API and then we had a mini payroll running.</p>
<p>Then he showed me the code he had written and that smug grin dropped off my face. It was awful.</p>
<p>Perhaps this other developer wasn&#8217;t as great as I&#8217;d thought? Looking at the code though made me realise he had done the best anyone could with a terrible API. I&#8217;d exposed parts of this core payroll engine with hooks when it needed a decision. Its job was to run the payroll &#8211; a very complex task that involved storage, translation, time periods, users and companies. That complexity and context had leaked out.</p>
<p>Unfortunately it&#8217;s not a unique story &#8211; many API&#8217;s are terrible to use. They&#8217;re concerned with their own terminology, limitations and quirks because they are exposed sections of an underlying system developed by those responsible for the underlying system.</p>
<p>If you want others to have a good experience with your product you have to put yourself in their shoes. Whether it&#8217;s a UI or an API makes no difference.</p>
<h3>You are not the user</h3>
<p>That&#8217;s the real difference between writing the classes that form your regular implementation and those that make up your public API.</p>
<p>We had time to fix our payroll API. Instead of refining and polishing here and there we took the 20 or so snippets developed for the mini payroll and pruned, cleaned and polished until they looked beautiful. They scanned well and made sense to payroll developers unfamiliar with our package. When a third developer familiar with payrolls but unfamiliar with out package developed the necessary code for a fully-functional jurisdiction in record time with minimal assistance we knew we had hit our goal.</p>
<p>Sure implementing that new API was hard work. Instead of simple methods sticking out of the engine we had a <a href="http://en.wikipedia.org/wiki/Facade_pattern">facade</a> over our engine but it was justified. They were two different systems for two different types of user with distinct ideas about what the system was and how it was going to be used.</p>
<h3>Code First</h3>
<p>Many years later I found myself on a small team of 3 people tasked with putting a brand new API on top of Entity Framework for configuring models with code the .NET world would come to know as Code First. I was determined to use my experience and avoid another complex API surface littered with terminology and leaky abstractions. Parts of EF already suffered from that problem.</p>
<p>So for the first few weeks of that project we didn&#8217;t write any of the code that would in fact become Code First.</p>
<p>Instead we decided who our user was &#8211; in this case a C# developer who likes writing code, knows LINQ and some database concepts but doesn&#8217;t know Entity Framework as people who did were already using Model First or Database First.</p>
<p>Then we wrote tiny sample apps and tried to find simpler and simpler ways to describe them in code. We&#8217;d often start on a whiteboard with a scenario and write the complete mapping. We&#8217;d then try and find conventions that would remove the need for most of it and then try to write succinct code to configure the rest. As the newest guy to the team I&#8217;d fight to keep EF terms away from the main API surface in order to reduce that barrier to entry and help drive adoption.</p>
<p>Finally we&#8217;d hit the computer and develop stub classes and methods to make samples compile and let us try the IntelliSense. This isn&#8217;t always necessary but if you want to develop a fluent API or provide lots of type-safety such as Code First&#8217;s relationship mapping it&#8217;s highly recommended.</p>
<p>We&#8217;d then revisit the samples later and see if they could be read as easily as they were written and figure out what problems people were likely to run into and whether we could solve them without too much noise. Sometimes this meant having more than one way to do things such as chaining the fluent methods or allowing a bunch of properties to be set (solved with an extension method class providing the fluent API) and how users could manage larger models (solved by subclassing EntityConfiguration&lt;T&gt; &#8211; now EntityTypeConfiguration&lt;T&gt; sigh &#8211; and allowing redundant specification for things like relationships that span more than one class).</p>
<p>We finally ended up with succinct code like this with IntelliSense guiding you along the way and preventing you from even being able to specify invalid combinations. The HasMany prompts the properties on Customer and it won&#8217;t show you WithRequired unless it is valid. In the case of Required to Required it will ensure that the WithRequired specified which end is principle and dependent. In short it guides you through the process and results in highly readable code.</p>
<pre><code>Entity&lt;Customer&gt;().HasMany(c =&gt; c.Orders).WithRequired(o =&gt; o.Customer).WillCascadeOnDelete();</code></pre>
<p>This process took a little longer but given the amount of use the API will get that time will be saved by users countless times over.</p>
<p>Code First went down incredibly well with both the target audience and existing EF users and inspired the simpler DbContext interface that became the recommended way of accessing EF.</p>
<p>I think it&#8217;s one of the nicest API&#8217;s to come out of Microsoft and .NET.</p>
<p><em>[)amien</em></p>
<p>PS. Martin Fowler has some great guidance in his book <a href="http://www.amazon.com/gp/product/0321712943/ref=as_li_ss_tl?ie=UTF8&amp;tag=dam-20&amp;linkCode=as2&amp;camp=217145&amp;creative=399369&amp;creativeASIN=0321712943">Domain Specific Languages</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2011/11/29/designing-a-great-api/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Behind the scenes at xbox.com &#8211; RSS enabling web marketplace</title>
		<link>http://damieng.com/blog/2011/07/07/behind-the-scenes-at-xbox-com-rss-enabling-web-marketplace?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behind-the-scenes-at-xbox-com-rss-enabling-web-marketplace</link>
		<comments>http://damieng.com/blog/2011/07/07/behind-the-scenes-at-xbox-com-rss-enabling-web-marketplace#comments</comments>
		<pubDate>Thu, 07 Jul 2011 20:05:44 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[rss]]></category>
		<category><![CDATA[xbox]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=2178</guid>
		<description><![CDATA[A number of people were requesting additional RSS feeds for the xbox.com web marketplace. (We had just one that included all new arrivals) Looking across our site as the various lists of products we display today the significant views are: Browse games by department Search results Promotions (e.g. Deal of the week) Game detail (shows ]]></description>
			<content:encoded><![CDATA[<p>A number of people were requesting additional RSS feeds for the xbox.com web marketplace. (We had just one that included all new arrivals)</p>
<p>Looking across our site as the various lists of products we display today the significant views are:</p>
<ul>
<li>Browse games by department</li>
<li>Search results</li>
<li>Promotions (e.g. Deal of the week)</li>
<li>Game detail (shows downloads available beneath it)</li>
<li>Avatar item browse</li>
</ul>
<p>These views also have sorting options and a set of filters available for things like product type, game genre, content rating etc.</p>
<p>So we had a couple of options:</p>
<ol>
<li>Write controller actions that expose the results of specific queries as RSS</li>
<li>Introduce a mechanism whereby any of our product result pages can render as RSS including any user-defined filtering</li>
</ol>
<p>Our web marketplace is written in ASP.NET MVC (like most of xbox.com) so while option 1 sounds simpler MVC really helps us make option 2 more attractive by way of a useful feature called ActionFilters that let us jump in and reshape the way existing actions behave.</p>
<h3>ActionFilters</h3>
<p><a href="http://msdn.microsoft.com/en-us/library/gg416513%28VS.98%29.aspx">ActionFilters</a> can be applied to either to an individual action method on a controller or to the controller class itself which applies it to all the actions on that controller. They provide hooks into the processing pipeline where you can jump in and perform additional processing.</p>
<p>The most interesting events are:</p>
<ul>
<li>OnActionExecuting</li>
<li>OnActionExecuted</li>
<li>OnResultExecuting</li>
<li>OnResultExecuted</li>
</ul>
<div>We&#8217;re going to hook in to the OnActionExecuted step &#8211; this is because we always want to run after the code in the controller action has executed but before the ActionResult has done it&#8217;s work &#8211; i.e. before page or RSS rendering.</div>
<h3>Writing our ActionFilter</h3>
<p>The first thing we want to do is identify that a request wants the RSS version. One way is to read the accepts header and switch when it requests mime/type but this can be a little trickier to test,  another is to append a query parameter on the url which is very easy to test.</p>
<p>Once we&#8217;ve identified the incoming request should be for RSS we need to identify the data we want to turn into RSS and repurpose it.</p>
<p>All the views we identified at the start of this post share a common rendering mechanism and each view model subclasses from one of our base models. For simplicity though we&#8217;ll imagine an interface that just exposes an IEnumerable&lt;Product&gt; property.</p>
<pre><code><strong>public class</strong> RssEnabledAttribute : ActionFilterAttribute
{
    <strong>public override void</strong> OnActionExecuted(ActionExecutedContext filterContext) {
        <strong>var</strong> viewModel = filterContext.Controller.ViewData.Model <strong>as</strong> IProductResultViewModel;
        if (viewModel == <strong>null</strong>)
            <strong>return</strong>;

        <strong>var</strong> rssFeedTitle = FeedHelper.MakeTitle(viewModel.Results);
        filterContext.Controller.ViewData.Add("RssFeedTitle", rssFeedTitle);

        <strong>var</strong> format = filterContext.RequestContext.HttpContext.Request.QueryString["format"];
        <strong>if</strong> (format == "rss" &amp;&amp; rssFeedTitle != <strong>null</strong>) {
            <strong>var</strong> urlHelper = <strong>new</strong> UrlHelper(filterContext.RequestContext);
            <strong>var</strong> url = QueryStringUtility.RemoveQueryStringParameter(filterContext.RequestContext.HttpContext.Request.Url.ToString(), "format");
            <strong>var</strong> feedItems = FeedHelper.GetSyndicationItems(viewModel.Results, urlHelper);
            filterContext.Result = FeedHelper.CreateProductFeed(rssFeedTitle, viewModel.Description, <strong>new</strong> Uri(url), feedItems);
        }

        <strong>base</strong>.OnActionExecuted(filterContext);
    }
}</code></pre>
<p>This class relies on our FeedHelper class to achieve three things it needs:</p>
<ol>
<li><strong>MakeTitle</strong> takes the request details &#8211; i.e. which page, type of products, filtering and sorting is selected and makes a title by re-using our breadcrumbs</li>
<li><strong>GetSyndicationItems</strong> takes the IEnumerable&lt;Product&gt; and turns it into IEnumerable&lt;SyndicationItem&gt; by way of a foreach projecting Product into SyndicationItem with some basic HTML formatting, combining the product image and setting the correct category (with a yield thrown in for good measure)</li>
<li><strong>CreateProductFeed</strong> then creates a Syndication feed with the appropriate Copyright and Language set and chooses the formatter &#8211; in our case <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.rss20feedformatter.aspx">RSS 2.0</a> but could easily be <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.atom10feedformatter.aspx">Atom 1.0</a>, e.g.</li>
</ol>
<pre><code><strong>public static</strong> SyndicationFeedResult CreateProductFeed(<strong>string</strong> title, <strong>string</strong> description, Uri link, IEnumerable&lt;SyndicationItem&gt; syndicationItems)
{
    <strong>var</strong> feed = new SyndicationFeed(title, description, link, syndicationItems) {
        Copyright = new TextSyndicationContent(String.Format(Resources.FeedCopyrightFormat, DateTime.Now.Year)),
        Language = CultureInfo.CurrentUICulture.Name
    };

    <strong>return new</strong> FeedResult(<strong>new</strong> Rss20FeedFormatter(feed, <strong>false</strong>));
}</code></pre>
<p>The <a href="http://damieng.com/blog/2010/04/26/creating-rss-feeds-in-asp-net-mvc">FeedResult</a> class is a simple one that takes the built-in .NET SyndicationFeed class and wires it up to MVC by implementing an ActionResult that writes the XML of the SyndicationFeedFormatter into the response as well as setting the application/rss+xml content type and encoding.</p>
<h3>Advertising the feed in the head</h3>
<p>Now that we have the ability to serve up RSS we need to let browsers know it exists.</p>
<p>The ActionFilter we wrote above needs to know the title of the RSS feed regardless of whether it is rendering the RSS (which needs a title) or rendering the page (which will need to advertise the RSS title) so it always calculates it and then puts it into the ViewData dictionary with the key RssFeedTitle.</p>
<p>Now finally our site&#8217;s master page can check for the existence of that key/value pair and advertise it out with a simple link tag:</p>
<pre><code><strong>var</strong> rssFeedTitle = ViewData["RssFeedTitle"] <strong>as string</strong>;
<strong>if</strong> (!String.IsNullOrEmpty(rssFeedTitle)) { %&gt;
&lt;link rel="alternate" type="application/rss+xml" title="&lt;%:rssFeedTitle%&gt;" href="&lt;%:Url.ForThisAsRssFeed%&gt;" /&gt;
&lt;% }</code></pre>
<p>This code requires just one more thing &#8211; a very small UrlHelper which will append &#8220;format=rss&#8221; to the query string (taking into account whether there existing query parameters or not).</p>
<p>The result of this is we can now just add [RssEnabled] in front of any controller or action to turn on RSS feeds for that portion of our marketplace! :)</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2011/07/07/behind-the-scenes-at-xbox-com-rss-enabling-web-marketplace/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Enums &#8211; Better syntax, improved performance and TryParse in NET 3.5</title>
		<link>http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=enums-better-syntax-improved-performance-and-tryparse-in-net-3-5</link>
		<comments>http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5#comments</comments>
		<pubDate>Mon, 18 Oct 2010 05:58:18 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[enum]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1745</guid>
		<description><![CDATA[Recently I needed to map external data into in-memory objects. In such scenarios the TryParse methods of Int and String are useful but where is Enum.TryParse? TryParse exists in .NET 4.0 but like a lot of people I&#8217;m on .NET 3.5. A quick look at Enum left me scratching my head. Why didn&#8217;t enums receive ]]></description>
			<content:encoded><![CDATA[<p>Recently I needed to map external data into in-memory objects. In such scenarios the TryParse methods of Int and String are useful but where is Enum.TryParse? TryParse exists in .NET 4.0 but like a lot of people I&#8217;m on .NET 3.5.</p>
<p>A quick look at Enum left me scratching my head.</p>
<ul>
<li>Why didn&#8217;t enums receive the generic love that collections received in .NET 2.0?</li>
<li>Why do I have to pass in typeof(MyEnum) everywhere?</li>
<li>Why do I have to the cast results back to MyEnum all the time?</li>
<li>Can I write TryParse and still make quick &#8211; i.e. without try/catch?</li>
</ul>
<p>I found myself with a small class, Enum&lt;T&gt; that solved all these. I was surprised when I put it through some benchmarks that also showed the various methods were significantly faster when processing a lot of documents. Even my TryParse was quicker than that in .NET 4.0.</p>
<p>While there is some small memory overhead with the initial class (about 5KB for the first, a few KB per enum after) the performance benefits came as an additional bonus on top of the nicer syntax.</p>
<h3>Before (System.Enum)</h3>
<pre><code><strong>var</strong> getValues = Enum.GetValues(<strong>typeof</strong>(MyEnumbers)).OfType();
<strong>var</strong> parse = (MyEnumbers)Enum.Parse(<strong>typeof</strong>(MyEnumbers), "Seven");
<strong>var</strong> isDefined = Enum.IsDefined(<strong>typeof</strong>(MyEnumbers), 3);
<strong>var</strong> getName = Enum.GetName(<strong>typeof</strong>(MyEnumbers), MyEnumbers.Eight);
MyEnumbers tryParse;
Enum.TryParse&lt;MyEnumbers&gt;("Zero", <strong>out</strong> tryParse);</code></pre>
<h3>After (Enum&lt;T&gt;)</h3>
<pre><code><strong>var</strong> getValues = Enum&lt;MyEnumbers&gt;.GetValues();
<strong>var</strong> parse = Enum&lt;MyEnumbers&gt;.Parse("Seven");
<strong>var</strong> isDefined = Enum&lt;MyEnumbers&gt;.IsDefined(MyEnumbers.Eight);
<strong>var</strong> getName = Enum&lt;MyEnumbers&gt;.GetName(MyEnumbers.Eight);
MyEnumbers tryParse;
Enum&lt;MyEnumbers&gt;.TryParse("Zero", <strong>out</strong> tryParse);
</code></pre>
<p>I also added a useful ParseOrNull method that lets you either return null or default using the coalesce so you don&#8217;t have to mess around with out parameters, e.g.</p>
<pre><code>MyEnumbers myValue = Enum&lt;MyEnumbers&gt;.ParseOrNull("Nine-teen") ?? MyEnumbers.Zero;</code></pre>
<h3>The class</h3>
<pre><code><strong>using<span style="font-weight: normal;"> System;</span>
using <span style="font-weight: normal;">System.Collections.Generic;</span>
using <span style="font-weight: normal;">System.Linq;</span>

public static class</strong> Enum&lt;T&gt; <strong>where</strong> T : <strong>struct</strong> {
    <strong>private static readonly</strong> IEnumerable&lt;T&gt; All = Enum.GetValues(<strong>typeof</strong>(T)).Cast&lt;T&gt;();
    <strong>private static readonly</strong> Dictionary&lt;<strong>string</strong>, T&gt; InsensitiveNames = All.ToDictionary(k =&gt; Enum.GetName(typeof(T), k).ToLowerInvariant());
    <strong>private static readonly</strong> Dictionary&lt;<strong>string</strong>, T&gt; SensitiveNames = All.ToDictionary(k =&gt; Enum.GetName(typeof(T), k));
    <strong>private static readonly</strong> Dictionary&lt;<strong>int</strong>, T&gt; Values = All.ToDictionary(k =&gt; Convert.ToInt32(k));
    <strong>private static readonly</strong> Dictionary&lt;T, <strong>string</strong>&gt; Names = All.ToDictionary(k =&gt; k, v =&gt; v.ToString());

    <strong>public static bool</strong> IsDefined(T value) {
        <strong>return</strong> Names.Keys.Contains(value);
    }

    <strong>public static bool</strong> IsDefined(<strong>string</strong> value) {
        <strong>return</strong> SensitiveNames.Keys.Contains(value);
    }

    <strong>public static bool</strong> IsDefined(<strong>int</strong> value) {
        <strong>return</strong> Values.Keys.Contains(value);
    }

    <strong>public static</strong> IEnumerable&lt;T&gt; GetValues() {
        <strong>return</strong> All;
    }

    <strong>public static string</strong>[] GetNames() {
        <strong>return</strong> Names.Values.ToArray();
    }

    <strong>public static string</strong> GetName(T value) {
        <strong>string</strong> name;
        Names.TryGetValue(value, <strong>out</strong> name);
        <strong>return</strong> name;
    }

    <strong>public static </strong>T Parse(<strong>string</strong> value) {
        T parsed = <strong>default</strong>(T);
        <strong>if</strong> (!SensitiveNames.TryGetValue(value, <strong>out</strong> parsed))
            <strong>throw new </strong>ArgumentException("Value is not one of the named constants defined for the enumeration", "value");
        <strong>return</strong> parsed;
    }

    <strong>public static</strong> T Parse(<strong>string</strong> value, <strong>bool</strong> ignoreCase) {
        <strong>if</strong> (!ignoreCase)
            <strong>return</strong> Parse(value);

        T parsed = <strong>default</strong>(T);
        <strong>if</strong> (!InsensitiveNames.TryGetValue(value.ToLowerInvariant(), <strong>out</strong> parsed))
            <strong>throw new</strong> ArgumentException("Value is not one of the named constants defined for the enumeration", "value");
        <strong>return</strong> parsed;
    }

    <strong>public static bool</strong> TryParse(<strong>string</strong> value, <strong>out</strong> T returnValue) {
        <strong>return</strong> SensitiveNames.TryGetValue(value, <strong>out</strong> returnValue);
    }

    <strong>public static bool </strong>TryParse(<strong>string</strong> value, <strong>bool</strong> ignoreCase, <strong>out</strong> T returnValue) {
        <strong>if</strong> (!ignoreCase)
            <strong>return</strong> TryParse(value, <strong>out</strong> returnValue);

        <strong>return</strong> InsensitiveNames.TryGetValue(value.ToLowerInvariant(), <strong>out</strong> returnValue);
    }

    <strong>public static</strong> T? ParseOrNull(<strong>string</strong> value) {
        <strong>if</strong> (String.IsNullOrEmpty(value))
            <strong>return null</strong>;

        T foundValue;
        <strong>if</strong> (InsensitiveNames.TryGetValue(value.ToLowerInvariant(), <strong>out</strong> foundValue))
            <strong>return</strong> foundValue;

        <strong>return</strong> null;
    }

    <strong>public static</strong> T? CastOrNull(<strong>int</strong> value) {
        T foundValue;
        <strong>if</strong> (Values.TryGetValue(value, <strong>out</strong> foundValue))
            <strong>return</strong> foundValue;

        <strong>return null</strong>;
    }
}</code></pre>
<h3>Usage notes</h3>
<ul>
<li>This class as-is only works for Enum&#8217;s backed by an int (the default) although you could modify the class to use longs etc.</li>
<li>I doubt very much this class is of much use for flag enums</li>
<li>Casting from long can be done using the CastOrNull function instead of just putting (T)</li>
<li>GetName is actually much quicker than ToString on the Enum&#8230; (e.g. Enum&lt;MyEnumbers&gt;.GetName(a) over a.ToString())</li>
<li>IsDefined doesn&#8217;t take an object like Enum and instead has three overloads which map to the actual types Enum.IsDefined can deal with and saves runtime lookup</li>
<li>Some of the method may not behave exactly like their Enum counterparts in terms of exception messages, nulls etc.</li>
</ul>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<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&#038;utm_medium=rss&#038;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&#038;utm_medium=rss&#038;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>
<p class="alert">This technique only works for to-one relationships not to-many. It is also quite untested so evaluate it properly before using it.</p>
<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><strong>var</strong> query = db.Posts.Where(p =&gt; p.Published)
   .Select(p =&gt; new Tuple&lt;Post, Blog&gt;(p, p.Blog))
   .AsEnumerable()
   .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>12</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&#038;utm_medium=rss&#038;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 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 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>Bloat &#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>10</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&#038;utm_medium=rss&#038;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>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><img style="float:right" src="http://images.damieng.com/blog/italiccomments.png" alt="Italic comments in Visual Studio" width="114" height="114" />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&#038;utm_medium=rss&#038;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&#038;utm_medium=rss&#038;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>
<p><img src="http://images.damieng.com/blog/queryplan.png" alt="A query plan in SQL Managment Studio" /></p>
<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&#038;utm_medium=rss&#038;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>18</slash:comments>
		</item>
	</channel>
</rss>

