<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feed.damieng.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>DamienG</title>
	
	<link>http://damieng.com</link>
	<description>A .NET developer in Redmond</description>
	<lastBuildDate>Thu, 28 Jan 2010 07:44:37 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feed.damieng.com/DamienG" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="damieng" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.bloglines.com/sub/http://feed.damieng.com/DamienG" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" href="http://www.live.com/?add=http%3A%2F%2Ffeed.damieng.com%2FDamienG" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><item>
		<title>MacBook Pro two year check-in</title>
		<link>http://damieng.com/blog/2010/01/27/macbook-pro-two-year-check-in</link>
		<comments>http://damieng.com/blog/2010/01/27/macbook-pro-two-year-check-in#comments</comments>
		<pubDate>Thu, 28 Jan 2010 07:44:36 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[freeware]]></category>
		<category><![CDATA[MacBook-Pro]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1546</guid>
		<description>It&amp;#8217;s been an interesting couple of years with nothing but a maxed-out MacBook Pro 17&amp;#8243; as my only home machine.
Failures
The hard drive died but time machine held my hand. At ALT.NET Seattle 2009 my backpack took a dive that left a dent in one corner. The battery was replaced and I roped GrinGod into obtaining [...]</description>
			<content:encoded><![CDATA[<p>It&#8217;s been an interesting couple of years with nothing but a maxed-out MacBook Pro 17&#8243; as my only home machine.</p>
<h3>Failures</h3>
<p>The hard drive died but time machine held my hand. At <a href="http://www.altnetseattle.org/">ALT.NET Seattle</a> 2009 my backpack took a dive that left a dent in one corner. The battery was replaced and I roped GrinGod into obtaining a replacement UK-style \ key from the UK after some frantic typing.</p>
<p>A friend cracked the display when his keyfob sprang from his Batbelt culminating in a visit of the Apple Store in Bellevue. Ten days and $700 later got that fixed and included a bonus disconnected thermal sensor, a couple of new scratches, an extra screw to rattle around inside and a line of grease around the Apple logo.</p>
<h3>Sticking with it</h3>
<p>When I find myself eying the unibody I wince at the glossy &#8216;matt finish&#8217; screen, the multi-touch trackpad clicks that sound like Robocop is nearby and a US keyboard that requires my pinky to hit a single-height enter key. That little pink dog won&#8217;t learn any new tricks. I&#8217;ve tried.</p>
<p>Still the OpenCL benchmark show the 8600M outperforming the newer 9400M and it does everything I need and at least one thing I don&#8217;t (gets hot enough to bake bread on). Short of switching the hard disk out for an SSD &#8211; I&#8217;ve ordered twice and then recalled after a Twitter volley of &#8220;no, you don&#8217;t want THAT one&#8221; &#8211; it&#8217;s here to stay for at least another year.</p>
<h3>Applications</h3>
<p>One thing that is always changing is the bunch of installed applications as I search for a combination that deliver a nirvana between productivity and enjoyment. Apps that perform a set of focused useful tasks with a shiny, eminently lick-able user interface, score highly.</p>
<p>I&#8217;ve rounded up my favourite apps before but here&#8217;s the latest specials on the menu.</p>
<h4>CleanMyMac</h4>
<p>This great-looking app helps <a href="http://www.macpaw.com/cleanmymac">reclaim wasted space</a> making it a pre-requisite for SSD switchers.</p>
<p>Combining the PowerPC and foreign language code-purging of XSlimmer &amp; TrimTheFat is also adds cache &amp; log purging in with application uninstalls ala AppZapper etc.</p>
<p>Despite using XSlimmer already on my machine it was able to reclaim another 1.8GB and V2 is out soon which I hope will remove &amp; alias duplicates given we&#8217;re not getting ZFS which had this feature (how many copies of Sparkle.framework do I have on my machine&#8230;.)</p>
<h4>Coda</h4>
<p>This year I rewrote my blog&#8217;s WordPress theme from scratch and given the PHP requirement I found myself looking for an alternate IDE to Visual Studio. I already own TextMate but the feel of a raw text editor with bundles of extra bits feel didn&#8217;t have the gloss and usability I wanted such as fast preview, remote FTP sync etc. with a minimal of setup fuss.</p>
<p>I briefly toyed with Espresso during the early development cycle but <a href="http://www.panic.com/coda/">Coda</a> won me over in the end with it&#8217;s sheer simplicity and elegance plus the addition of built-in documentation for PHP was very helpful when working offline.</p>
<h4>BetterTouchTool</h4>
<p>Yes, when the <a href="http://www.apple.com/magicmouse/">Magic Mouse</a> hit the street I picked one up. The idea of a mouse with trackpad multi-touch technology was appealing but a few minutes of use and no amount of twiddling would make it track  or let me configure it to take full advantage of what it should be able to do.</p>
<p>Until Apple sort this out <a href="http://blog.boastr.net/">BetterTouchTool</a> is your friend letting you speed up the tracking of the Magic Mouse, or indeed your trackpad, and assign all sorts of interesting shortcuts and abilities to combinations of finger gestures.</p>
<h4>Secrets</h4>
<p>Mac apps tend to expose only the common options in their user interfaces but sometimes developers add some additional tweaks and settings behind the scenes that live in the Mac&#8217;s equivalent of the registry (known as &#8220;<a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/defaults.1.html">defaults</a>&#8220;). While you can set these manually using the defaults command-line tool you still need to know the setting exists, it&#8217;s name and what options are available and so secrets exposes this.</p>
<p><a href="http://secrets.blacktree.com/">Secrets</a> is similar to Deeper and TinkerTool but the difference is that the secrets web site lets people add new options which then are automatically available within the installed preferences pane making them easily discoverable, searchable, applied&#8230; and occasionally undone.</p>
<h4>Machinarium</h4>
<p><a href="http://damieng.com/wp-content/uploads/2010/01/machinarium2.jpg"><img style="float: right;" title="Machinarium" src="http://damieng.com/wp-content/uploads/2010/01/machinarium2.jpg" alt="Screenshot of the game Machinarium" width="256" height="162" /></a>This <a href="http://machinarium.net/">point-and-click adventure game</a> will appeal to people who enjoyed Monkey Island although it feels more like the gorgeously submerging <a href="http://www.revolution.co.uk/_display.php?id=16">Beneath a Steel Sky</a>.</p>
<p>The scenery is brilliantly imagined, stylistic and shows that very real lived-in cities can be beautiful especially when populated by cute robots capable of assembling themselves from their own body-parts (just like a <a href="http://terminator.wikia.com/wiki/Series_888">triple 8</a> but infinitely cuter).</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=2y7K-wrEopY:H3GW61bztY0:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=2y7K-wrEopY:H3GW61bztY0:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/2y7K-wrEopY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/01/27/macbook-pro-two-year-check-in/feed</wfw:commentRss>
		<slash:comments>2</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</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>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 have two stored [...]</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 &#8216;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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=k1g4nuv8BfY:vlqHLFW-xZY:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=k1g4nuv8BfY:vlqHLFW-xZY:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/k1g4nuv8BfY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Origins of a love affair</title>
		<link>http://damieng.com/blog/2009/12/29/origins-of-a-love-affair</link>
		<comments>http://damieng.com/blog/2009/12/29/origins-of-a-love-affair#comments</comments>
		<pubDate>Tue, 29 Dec 2009 20:06:51 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[bbc micro]]></category>
		<category><![CDATA[sinclair]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1502</guid>
		<description>From an earliest memory of a cream coloured box emblazoned with letters, mostly black &amp;#8211; some red, came an owl proclaiming allegiance to the BBC.
This small box sat silently, patiently even, in our classroom for the best part of a year. On the few occasions our teacher was brave enough to flip the switch the [...]</description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/BBC_Micro"><img style="float: right; padding-left: 1em" title="BBC Micro Computer's Owl" src="http://damieng.com/wp-content/uploads/2009/12/bbc-owl.jpg" alt="BBC Micro Computer's Owl" width="147" height="156" /></a>From an earliest memory of a cream coloured box emblazoned with letters, mostly black &#8211; some red, came an owl proclaiming allegiance to the BBC.</p>
<p>This small box sat silently, patiently even, in our classroom for the best part of a year. On the few occasions our teacher was brave enough to flip the switch the machine would chirp into life with it&#8217;s two-tone beep and would state on capital white letters on a black background that it was BASIC. At this point the teacher would key-in the mythical incantation of CHAIN &#8220;&#8221; &#8211; handily jotted on a nearby note &#8211; and feed the beast a cassette tape.</p>
<p>Some time later the machine would announce it&#8217;s vague disappointment with the contents of the tape and be put back to sleep.  One time, and one time only, I recall a screen full of bright colours masquerading as pirates looking for treasure.</p>
<p>I was 11.</p>
<p>Such a tantalising taste of computing left me hungry for more. I knew precisely two people who owned computers. One possessed a cut-down version of the BBC Micro from my classroom called the Acorn Electron and guarded it like a sacred treasure, the other was a friend and more accommodating so much so that he agreed, with little optimism, we could type my program listing into his computer.</p>
<p>What combination of childish scrawl, lack of understanding of programming concepts or the cobbled-together dialect of BASIC was responsible for his <a href="http://en.wikipedia.org/wiki/Texas_Instruments_TI-99/4A">Texas Instruments TI-99</a> rejecting my program I would never know. However neither that failure nor the subsequent arrival and rapid departure of a &#8216;programmable&#8217; <a href="http://computermuseum.50megs.com/brands/g7000.htm">Philips G7000 Videopac</a> from my home would quench my thirst.</p>
<p>A new school year started and for me that meant a new school and new subjects the most interesting of these was named Information Technology or IT for short. I don&#8217;t recall much of these early lessons other than some exposure to word processing, videotext and a simplified geometry-base programming language for drawing shapes called <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)">Logo</a>.</p>
<p>This fixed schedule held little interest to me although the machines themselves did and the teacher opened the room of fifteen or so BBC Micro&#8217;s equipped with 5.25&#8243; floppy drives to the ever-changing line of misfits queued outside to play games. But unlike my old school a few people here actually knew a little about these machines.</p>
<p><a href="http://www.mobygames.com/game/chuckie-egg/">Chuckie Egg</a> and Mr. E were favourites while masochists would fire up <a href="http://video.google.co.uk/videoplay?docid=7967989481850456319&amp;q=castle+quest#">Castle Quest</a>, <a href="http://www.strafom.force9.co.uk/bbc/Retrobbc/Citadel/index.html">Citadel</a> and <a href="http://en.wikipedia.org/wiki/Repton_(video_game)">Repton 2</a> despite being impossible to complete and lacking a crucial save-game option. Fewer still braved the open-ended and <a href="http://en.wikipedia.org/wiki/Elite_(video_game)">Elite</a> space trading/combat game which would let you resume your position each day. Right on commander!</p>
<p>Games consisted of a few files passed between easily damaged 5.25&#8243; floppy disks that students had mysteriously acquired. Remembering which file to CHAIN, *EXEC or *LOAD was a task in itself made worse by the ever-changing scene of kids and games. Now I finally had a machine to myself for a brief period each day I set about solving the first real world problem I encountered here and wanted to create something that would automatically boot and let you select a game by pressing a letter or a number.</p>
<p>Scouring magazines, loaning one of the few <a href="http://mdfs.net/Software/BBCBasic/">BBC BASIC</a> programming manuals from the teacher and occasionally LISTing other people&#8217;s I came up with something that worked. Before long it had double height text, colours and some basic animation. Included in the program were some basic instructions on how to edit the program to fit the games on your own disk and it spread like wildfire.</p>
<p><a href="http://www.worldofspectrum.org"><img style="float: left; padding-right: 1em" title="Spectrum" src="http://damieng.com/wp-content/uploads/2009/12/Spectrum.jpg" alt="" width="202" height="142" /></a>Shortly after my father, who made gadget trading one of his hobbies, brought home a <a href="http://worldofspectrum.org">Sinclair ZX Spectrum</a> 16KB. It was less powerful than the BBC&#8217;s at school and had to be hooked up to a television and cassette record to be of any use and had small rubber keys that were hard to type on. I played and programmed on it for hours without interruption and it finally became mine when my mother made it clear to my father it couldn&#8217;t be traded out for the next gadget. Within a few months the machine had died after something metallic got in through the edge connector.</p>
<p>I was heartbroken but found a neighbour was selling his Spectrum 48K and persuaded my parents to buy it. The extra memory was useful but even better was the hard-key keyboard and the original Sinclair BASIC programming manual I&#8217;d been missing. That year my parents split, my father moved out and we moved to a new parish on our little island of Guernsey which meant new friends and a new school. A school that had IT sharing lessons with technical drawing.</p>
<p>My hopes weren&#8217;t high&#8230;</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=u42h154VgrE:c0RO2Zw3CDs:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=u42h154VgrE:c0RO2Zw3CDs:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/u42h154VgrE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/12/29/origins-of-a-love-affair/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>SQL Server query plan cache – what is it and why should you care?</title>
		<link>http://damieng.com/blog/2009/12/13/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>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 the plan [...]</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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=jAgBc7SC47g:uoTUhkElz18:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=jAgBc7SC47g:uoTUhkElz18:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/jAgBc7SC47g" height="1" width="1"/>]]></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 – revisited</title>
		<link>http://damieng.com/blog/2009/11/06/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>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 source control
Files not always [...]</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>));
        }
    }
}</code></pre>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=c5ytF6NSG-E:-hPQfCvQv2I:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=c5ytF6NSG-E:-hPQfCvQv2I:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/c5ytF6NSG-E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited/feed</wfw:commentRss>
		<slash:comments>3</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</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>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 be [...]</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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=ubzw0vAjfW4:wHxMqz88zbE:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=ubzw0vAjfW4:wHxMqz88zbE:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/ubzw0vAjfW4" height="1" width="1"/>]]></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>18</slash:comments>
		</item>
		<item>
		<title>Five steps to blog (re)design</title>
		<link>http://damieng.com/blog/2009/09/11/5-steps-to-blog-redesign</link>
		<comments>http://damieng.com/blog/2009/09/11/5-steps-to-blog-redesign#comments</comments>
		<pubDate>Fri, 11 Sep 2009 09:10:28 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[960 grid]]></category>
		<category><![CDATA[web design]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1336</guid>
		<description>For some time I&amp;#8217;ve wanted to refresh the design here at damieng.com which evolved out of the Redoable theme with my own tweaks to colours, typography, images and background until it was almost my own.
Almost, but not quite.
As an engineer I prefer incremental improvement over a complete redesign but I was at the point where [...]</description>
			<content:encoded><![CDATA[<p>For some time I&#8217;ve wanted to refresh the design here at damieng.com which evolved out of the <a href="http://deanjrobinson.com/projects/redoable/">Redoable</a> theme with my own tweaks to colours, typography, images and background until it was almost my own.</p>
<p>Almost, but not quite.</p>
<p>As an engineer I prefer incremental improvement over a complete redesign but I was at the point where the code-base (HTML, CSS and PHP) was unworkable. Partly my fault, partly the sheer complexity of a general-purpose theme with wide-ranging plugin support I didn&#8217;t need.</p>
<p>These are the steps that helped me get to a  clean minimal code-base that did exactly what I wanted and would like to share the experience for friends about to go through a similar process.</p>
<h3>1. Decide on a layout</h3>
<p><a href="http://damieng.com/wp-content/uploads/2009/09/damienglayout1.png"><img src="http://damieng.com/wp-content/uploads/2009/09/damienglayout_thumb1.png" alt="Layout of DamienG.com" style="float:right" /></a>Getting layouts right across browsers can be tricky.</p>
<p>Thankfully a number of individuals have put together a number of <a href="http://net.tutsplus.com/html-css-techniques/which-css-grid-framework-should-you-use-for-web-design/">reusable CSS frameworks</a> that provide grid-based approaches to layout, compensating for differences in browser defaults and including some minimalistic styling.</p>
<p>These let you hit the ground running but they are not complete themes unless you&#8217;re into minimalistic design.</p>
<p>I&#8217;m not a fan of fixed-width sites that contribute to the years of wear on my scrolling mouse finger so settled on the <a href="http://www.designinfluences.com/fluid960gs/">Fluid 960 Grid System</a> which scales a 12 or 16 column grid system out to the full browser width while being incredibly easy to use and tweak.</p>
<p>At this point you&#8217;ll want to copy the CSS they provide into your own development folder and take the existing HTML sample page and cut it down to the bare minimum of &lt;head&gt; and its necessary &lt;link…&gt; elements to setup the CSS plus the &lt;body&gt; and any intermediate child elements required to get the basic structure in place.</p>
<p>Now think about how many columns each section needs to cover and whether it should continue taking columns to the right or whether it should start on a new row after the existing section has finished.</p>
<p>Given I wanted the layout shown above I needed just three containers – the primary left area (red) would span 12 columns and would contain the branding, navigation and actual content. The right area (blue) would span 4 columns and contain the sidebar. As I didn&#8217;t want my footer too high on pages with small amounts of content I created another section (not pictured) that also spanned 12 columns but would appear after the content in both sections. Simply:</p>
<pre><code class="html">&lt;body&gt;
&lt;div class="container_16"&gt;
   &lt;div class="grid_12"&gt;
       &lt;a href="http://damieng.com/" /&gt;
       &lt;ul class="nav" /&gt;
       &lt;div id="maincontent" /&gt;
   &lt;/div&gt;
   &lt;div class="grid_4" id="sidebar" /&gt;
   &lt;div class="clear" /&gt;
   &lt;div class="grid_12" id="footer" /&gt;
&lt;/div&gt;
&lt;/body&gt;</code></pre>
<h3>2. Add your content</h3>
<p>Unless you&#8217;re planning on throwing away any of your content (not recommended if you have it), now is the time to drop in actual content, navigation and any chrome. At this stage real static HTML content is best – the combination of PHP, remotely uploading files and hooking in to dynamic content can really slow you down while you are trying to get the basics sorted.</p>
<p>The easiest thing to do here is to just view source a page on your blog and copy out the required blocks. For me this was:</p>
<ul>
<li>Two blog posts from the main page, they sit in the <em>maincontent</em> div above, each contained within a new <em>&lt;div class=&#8221;article&#8221;&gt;</em> so I can provide article-specific styling</li>
<li>A brand new set of nested navigation elements created by hand based on the page structure – initially two levels deep to support the drop-down CSS menus</li>
<li>My five sidebar elements – <em>Search, Stay in touch, Topics, My most popular</em> and <em>Interesting finds</em></li>
</ul>
<p>Bear in mind that you are going to need to keep the structure and content of your existing pages and articles unless you have the time to either go-back and edit each one or apply some bulk-changes via SQL UPDATE statements. For me, this meant keeping my post sub-headings as <em>&lt;h3&gt;</em> and sticking with my <em>class=&#8221;alert&#8221;, class=&#8221;code&#8221;</em> and  <em>class=&#8221;download&#8221;</em> blocks I use for notifications, code snippets and downloads which required bringing some CSS elements in from the old theme.</p>
<h3>3. Style the page</h3>
<p>Design inspiration can come from many places &#8211; here are some best-of designs, portfolios and showcases to draw from:</p>
<ul>
<li><a href="http://cssbased.com/showcase/">CSS Showcase</a></li>
<li><a href="http://cssbased.com/showcase/"></a><a href="http://www.smashingmagazine.com/2009/07/22/50-new-beautiful-blog-designs/">50 New Beautiful Blog Designs</a></li>
<li><a href="http://www.instantshift.com/2009/09/13/70-fresh-and-inspirational-blog-designs/">70 Fresh and Inspirational Blog Designs</a></li>
<li><a href="http://www.instantshift.com/2009/09/17/70-ultimate-round-up-of-free-psd-website-templates/">70+ Ultimate Round-Up of Free PSD Website Templates</a></li>
</ul>
<p>Now you have some basic HTML and CSS displaying real content it&#8217;s easy to see what works and what doesn&#8217;t with minimal resistance to experimenting.</p>
<p>I was happy with the existing look and I plan on further tweaks now my code-base is easy to understand so for now took the basic colours, background and icons then adjusted the layout, spacing, positioning, wording and elements like the content metadata. This was also an opportunity to experiment with some <a href="http://www.smashingmagazine.com/2009/07/20/50-new-css-techniques-for-your-next-web-design/">CSS techniques available</a> but considering CSS3 browser support is limited right now I kept this to:</p>
<ul>
<li><em>@font-face</em> for headings – <a href="http://www.fontsquirrel.com/fontface">Font Squirrel have a great set of @font-face kits</a> including fonts with the CSS snippets</li>
<li><em>text-shadow</em> for headings and hyperlink hover-overs to achieve a glow effect</li>
<li><em>border-radius</em> for curved blocks and navigation bar (also used prior to the redesign)</li>
<li>JavaScript to upgrade the search-box from <em>type=&#8221;text&#8221; </em>to <em>type=&#8221;search&#8221;</em> in Safari</li>
</ul>
<p>The result is something that looks quite unique on Safari and Chrome yet still looks good on Internet Explorer 7.</p>
<h3>4. Convert to a theme</h3>
<p>Now our CSS and HTML looks great as a single page we need to create a theme for the blog engine. This consists of several specially-named files to dynamically construct the page as required.</p>
<p>You can build this from scratch but a basic theme like <a href="http://elliotjaystocks.com/blog/free-starkers-wordpress-theme/">Starkers &#8216;naked&#8217; WordPress theme</a> is recommended. Merge the layout and style of your theme with the dynamic tags that drop in content, navigation and titles in from the basic theme. A quick start would be to modify:</p>
<ul>
<li><strong>header.php</strong> with your HTML up to opening your main content div but:
<ul>
<li>remove <em>&lt;link type=&#8221;text/css&#8221;&gt;</em> elements to the CSS and replace with the one line <em>&lt;link&gt;</em> from the theme</li>
<li>replace the static navigation elements with a call to a function to dynamically build it such as <em>&lt;?php wp_list_pages(&#8216;depth=3&amp;title_li=&#8217;); ?&gt;</em></li>
<li>links for shortcut icons and ensure they point to files that exist, you don&#8217;t want to be serving up 404 error pages every time</li>
<li>meta tags – take the dynamic ones with <em>&lt;?php?&gt;</em> elements (content-type, description etc). from the theme and merge them with your sites existing ones if you have any</li>
</ul>
</li>
<li><strong>sidebar.php</strong> with your HTML from closing the main content div through to closing the sidebar div</li>
<li><strong>footer.php</strong> with your HTML footer div (and in my case the preceding clear div) through to the end of the file</li>
<li><strong>single.php</strong> with your HTML that appears around each article with the necessary tags (like <em>&lt;?php the_content(); ?&gt;</em> taken from the naked theme)</li>
<li><strong>style.css</strong> with relative references to your CSS files and your new metadata, e.g.</li>
</ul>
<pre><code class="css">/*
Theme Name: DamienGNew
Theme URI: http://damieng.com
Description: Minimalistic theme based on Fluid 960 Grid.
Version: 1
Author: Damien Guard
Author URI: http://damieng.com
*/
@import "css/reset.css";
@import "css/grid.css";
@import "css/damieng.css";
@import "css/navigation.css";</code></pre>
<p>Rename the theme folder and upload it to your blog in the right location – for WordPress this is <em>wp-content/themes</em>.</p>
<h3>5. Test drive, tweak, rinse and repeat</h3>
<p>Now you want to test the theme without interrupting the existing one so don&#8217;t go and set it to be the default just yet.</p>
<p>If you are using WordPress a few tips:</p>
<ol>
<li><a href="http://ocaoimh.ie/wp-super-cache/">WP Super Cache</a> enabled sites &#8211; check <em>Don&#8217;t cache pages for logged in users</em> so you don&#8217;t see cached pages in the original theme pages or serve up pre-cached new themed pages for other visitors</li>
<li><a href="http://www.prelovac.com/vladimir/wordpress-plugins/theme-test-drive">Theme Test Drive</a> – lets you specify a new theme and what access level it applies to (e.g. 10 for admin) so you will see it while you are logged in for testing</li>
<li>Page templates &#8211;  leave them to last as WordPress will try to use them in the default theme too</li>
<li>Keep an eye out for<em> error_log</em> files &#8211; they contain details of when pages failed</li>
</ol>
<p>It&#8217;s worth testing your site in popular browser and operating system combinations from your own analytics or you don&#8217;t have any of your own stats check out <a href="http://en.wikipedia.org/wiki/Usage_share_of_web_browsers">usage share of web browsers at Wikipedia</a>. The major engines are:</p>
<ul>
<li><strong>Internet Explorer </strong>(Windows)</li>
<li><strong>WebKit</strong> (Safari on OS X, Chrome on Windows &amp; Konqueror on Linux)</li>
<li><strong>Gecko</strong> (Firefox cross-platform &amp; Camino on Mac)</li>
<li><strong>Opera</strong> (cross-platform)</li>
</ul>
<p>Bear in mind that each browser can behave quite differently between versions &#8211; <a title="Virtual machine images for Internet Explorer" href="http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&amp;displaylang=en">Internet Explorer 6</a> will likely render quite differently to 7 or 8.</p>
<p>Sites like <a href="http://browsershots.org/">BrowserShots</a> can help by rendering your page on a multitude of browsers for you and present screen-shots (once the theme is live) to compare. Validating your <a href="http://validator.w3.org/">HTML</a> and <a href="http://jigsaw.w3.org/css-validator/">CSS</a> is a good idea because the errors and warnings it spots are the likely cause for odd rendering problems.</p>
<p>Now you see a single blog post rendered it&#8217;s time to go through the rest of the files and apply the same merging process before you sit back, smile and make your new theme the default.</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=SOo-fAuKrtc:SYw7t7PylZU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=SOo-fAuKrtc:SYw7t7PylZU:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/SOo-fAuKrtc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/09/11/5-steps-to-blog-redesign/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>First impressions of Snow Leopard</title>
		<link>http://damieng.com/blog/2009/08/29/first-impressions-of-snow-leopard</link>
		<comments>http://damieng.com/blog/2009/08/29/first-impressions-of-snow-leopard#comments</comments>
		<pubDate>Sat, 29 Aug 2009 08:14:19 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Apple]]></category>
		<category><![CDATA[Fonts]]></category>
		<category><![CDATA[Mac-OS-X]]></category>
		<category><![CDATA[snow leopard]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1273</guid>
		<description>I came home from work today to find my family pack upgrade version of Snow Leopard. It&amp;#8217;s been a few hours, so here are impressions so far.
Packaging &amp;#38; installation
The packaging was very small and lightweight and eco-friendly compared to the big-plastic-box-monsters that come out of Redmond.
Installation went mostly smoothly apart from an abort-and-restart that seems [...]</description>
			<content:encoded><![CDATA[<p>I came home from work today to find my family pack upgrade version of Snow Leopard. It&#8217;s been a few hours, so here are impressions so far.</p>
<h3>Packaging &amp; installation</h3>
<p>The packaging was very small and lightweight and eco-friendly compared to the big-plastic-box-monsters that come out of Redmond.</p>
<p>Installation went mostly smoothly apart from an abort-and-restart that seems to have been caused by my DVD drive flaking out on me. It&#8217;s been trouble since it came back from the Apple Store.</p>
<p>I had to run the separate Xcode installer to update that &#8211; it wasn&#8217;t automatically detected &#8211; which left me wondering if I need to manually install anything from the optional installs or not. Running Xcode before updating it not only failed to launch but left a background process I had to force quit with Actitity Monitor to let the installer upgrade it.</p>
<p>The less-is-more-approach followed through to disk space which freed up another 10.5 GB &#8211; impressive given that I had purged all the non-English language resources already using Monolingual and I elected to re-install the Rossetta PowerPC binary support.</p>
<h3>Noticeable changes</h3>
<p>Despite being an optimization release Apple squeezed a few features in to sweeten the deal the majority of which are documented at their site and in proper reviews. The ones I&#8217;ve encountered so far are:</p>
<h4>Location services, detect time-zone</h4>
<p><img src="http://images.damieng.com/blog/snow-timezone.png" alt="Screenshot of location aware time-zone in Snow Leopard" style="float:right" />Great for travelling users like myself, it found my nearest city instantly.</p>
<h4>AirPort status in menu bar</h4>
<p>Pop-up menu now shows signal strength of all other networks. (Hold down alt when popping up this menu to see detailed connection stats)</p>
<h4>Smoothing options</h4>
<p>Gone are the Automatic, light, medium and strong options replaced with a single &#8220;Use LCD font smoothing when available&#8221; option that <a href="http://blog.jjgod.org/2009/08/18/snow-leopard-vs-dell-lcd-displays/">isn&#8217;t too good at detecting third-party displays but you can activate the old hidden options</a>.</p>
<h4>Subpixel quality</h4>
<p>The rendering just looks plain wrong when booting. It has that awful colour-fringe that you see from time to time, the cause of which seems to be related to the default gamma (the curve on which digital colours become analogue levels) on <a href="http://support.apple.com/kb/HT3712?viewlocale=en_US">Mac OS X changing from 1.8 to the PC compatible 2.2</a>.</p>
<p>It seems however that the sub-pixel rendering algorithms haven&#8217;t been updated to correct this. There is absolutely no point in posting a screenshot as either your browser, screen or OS would make it appear different to how it did here.</p>
<p>Help is at hand though, you can head into the ColorSync Utility in your Applications folder and calibrate your display &#8211; just follow the instructions and set the gamma back to 1.8. It&#8217;s worth turning on &#8220;Expert&#8221; mode and spending a few minutes setting it up properly though.</p>
<h4>Unable to open NIBs</h4>
<p><img src="http://images.damieng.com/blog/no-compiled-nibs.png" alt="No compiled nibs error in Snow Leopard"  style="float:right" />I used to love opening up other people&#8217;s NIB files. You could in theory create your own customised versions of an applications interface. Localise it for yourself. Maybe even create a UK English version where Colour is spelt correctly.</p>
<p>No more.</p>
<p>Whether this was to save space or to prevent such hacking is anyone&#8217;s guess.</p>
<h3>Compatibility woes</h3>
<p>So far I&#8217;ve had a couple of things break:</p>
<ul>
<li><a href="http://cyberduck.ch/">Cyberduck</a> quits on launch &#8211; beta replacement is out</li>
<li>Xbox 360 controller extension (I don&#8217;t use it anymore anyway)</li>
<li><a href="http://www.islayer.com/apps/istatmenus/">iStat Menus</a> fails to launch &#8211; I need this to replace menu time with timezones and a drop-down calendar</li>
</ul>
<h3>Features I was expecting</h3>
<p>Given the lean-and-mean plus sensible small refinements I was expecting&#8230;</p>
<ol>
<li>Login Window keyboard shortcut &#8211; come on, seriously, with the secrecy at Apple surely you need this too?</li>
<li>Uninstaller &#8211; AWOL since the transition from OpenStep to NextStep and sorely needed</li>
<li>Language purging &#8211; I still don&#8217;t want French etc. on my laptop, odd omission given the reduction goals</li>
<li>System update framework &#8211; Other apps could use this too you know guys &#8211; and put clever delta&#8217;ing support in</li>
<li>Grab &#8211; STILL only saves in TIFF format. So I save it there, load into preview then into PNG. WTF??</li>
<li>Safari &#8211; should have an option to force new windows to open in a new tab</li>
</ol>
<p>I&#8217;d also love to see being able to pin documents to their dock icon and being able to push a window to an edge to tile like as these were two features I found useful in Windows 7. Talking of which when you hold the mouse button down on a dock icon it greys everything else out for a truly UAC-like moment every time you want to quit an app from the dock&#8230;</p>
<h3>The Menlo font</h3>
<p><a href="http://typophile.com/node/58625"><img src="http://images.damieng.com/blog/menlo-vs-vera.png" alt="Menlo and Vera Sans Mono overlaid for comparison" style="float:right" /></a>Apple needed to replace the ageing Monaco as it has poor international unicode support, has just a single style and poor hinting (it uses embedded bitmaps to look good without anti-aliasing in Terminal).</p>
<p>Given <a href="http://news.stanford.edu/news/2005/june15/jobs-061505.html">Steve Job&#8217;s apparently love of typography</a> would they commission a gorgeous new monospaced font as Microsoft did with <a href="http://www.ascendercorp.com/font/consolas/">Consolas</a>? No.</p>
<p>In 2003 Bitstream released the family <a href="http://www.gnome.org/fonts/">Bitstream Vera</a> under a free licence which included a great Sans Mono with bolt, italic and bold-italic variants. It even has some capable hinting so looks pretty good without anti-aliasing although could do with a few delta&#8217;s to clean that up. While it was short on the unicode support several forks filled in the gaps such as Deja Vu and Apple took Vera Sans Mono, grabbed some of these additions (adding 2900 glyphs) and tweaked some of the existing ones. Specifically they moved the vertical bar up on EBH, widened MN, shifted il, changed 0 from dotted to crossed and move/resized punctation then packed it up in a True Type Collection file that stores multiple TTF&#8217;s in a single file.</p>
<p>While these changes themselves look quite good &#8211; it seems they were optimizing for 14 point &#8211; in the process they destroyed the hinting for these glyphs despite the tiny amount of change made.<br />
<img src="http://images.damieng.com/blog/menlo-notepad.png" alt="Menlo on Windows in Notepad" /><img src="http://images.damieng.com/blog/menlo-aliased.png" alt="Menlo on Mac OS X in TextMate" /><br />
Spot which ones Apple modified on these screenshots (curiously Windows refuses to use the TTC file as it believes it is corrupt).</p>
<p><img src="http://images.damieng.com/blog/no-aliased-menlo.png" alt="Screenshot of Terminal preferences showing anti-aliasing forced for Menlo" style="float:left" />Apple is obviously aware it&#8217;s not a good job as the option to turn off anti-aliasing in Terminal when using Menlo is curiously disabled &#8211; this seems to be something hard-coded into Terminal.app as it doesn&#8217;t affect TextMate.</p>
<h3>Boot Camp</h3>
<p>Installation here was a little tricky as initially the installer told me that Boot Camp 64-bit was not supported on my computer model.</p>
<p>Whether they don&#8217;t support 64-bit Windows on a late 2007 MacBook Pro 17&#8243; (MacBookPro3,1) or whether it was complaining about Windows 7 isn&#8217;t clear as there are no Windows 7 specific drivers on the disk. </p>
<p>All is not lost however as if you navigate into Boot Camp\Drivers\Apple folder you can run the BootCamp.msi or BootCamp64.msi from there and it does not seem to perform the check. All the drivers installed without complaint and the trackpad, mouse, audio etc. is working just fine.</p>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=qAnwZnCqSVk:yYUBRUgWS48:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=qAnwZnCqSVk:yYUBRUgWS48:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/qAnwZnCqSVk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/08/29/first-impressions-of-snow-leopard/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL cheat sheet</title>
		<link>http://damieng.com/blog/2009/08/12/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>A few short words to say I&amp;#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) (76 KB)
[)amien</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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=kpN8Hau-WDA:ug7UQwy5YKk:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=kpN8Hau-WDA:ug7UQwy5YKk:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/kpN8Hau-WDA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet/feed</wfw:commentRss>
		<slash:comments>19</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</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>The design of a Dictionary&amp;#60;T&amp;#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&amp;#60;string,Employee&amp;#62; employees;
…
public static Employee GetByName(string name) {
    Employee employee;
    if (!employees.TryGetValue(name, out employee)) {
        employee [...]</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> TActualValue GetOrAdd&lt;TKey, TDictionaryValue, TActualValue&gt;(<strong>this</strong> IDictionary&lt;TKey, TDictionaryValue&gt; dictionary, TKey key, Func&lt;TActualValue&gt; newValue) <strong>where</strong> TActualValue : TDictionaryValue
{
    TDictionaryValue value;
    <strong>if</strong> (!dictionary.TryGetValue(key, <strong>out</strong> value)) {
        value = newValue.Invoke();
        dictionary.Add(key, value);
    }
    <strong>return</strong> (TActualValue)value;
}</code></pre>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=nWT9DdP8JbE:D_EA2tobF_s:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=nWT9DdP8JbE:D_EA2tobF_s:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/nWT9DdP8JbE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler/feed</wfw:commentRss>
		<slash:comments>8</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</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>David Fowler on the ASP.NET team and I have been bouncing ideas about on how to solve an annoyance using LINQ:
If you write properties on the client you can’t use them in remote LINQ operations.
The problem occurs because these properties can’t be translated and sent to the server as they have been compiled into intermediate [...]</description>
			<content:encoded><![CDATA[<p><a href="http://weblogs.asp.net/davidfowler/">David Fowler</a> on the ASP.NET team and I have been bouncing ideas about on how to solve an annoyance using LINQ:</p>
<blockquote><p>If you write properties on the client you can’t use them in remote LINQ operations.</p></blockquote>
<p>The problem occurs because these properties can’t be translated and sent to the server as they have been compiled into intermediate language (IL) and not LINQ expression trees that are required for translation by IQueryable implementations. There is nothing available in .NET to let us reverse-engineer the IL back into the methods and syntax that would allow us to translate the intended operation into a remote query.</p>
<p>This means you end up having to write your query in two parts; firstly the part the server can do, a ToList or AsEnumerable call to force that to happen and bring the intermediate results down to the client, and then the operations that can only be evaluated locally. This can hurt performance if you want to reduce or transform the result set significantly.</p>
<p>What we came up (David, <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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=hSu88MxihGM:Rs8sjBjw6TU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=hSu88MxihGM:Rs8sjBjw6TU:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/hSu88MxihGM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/24/client-side-properties-and-any-remote-linq-provider/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL resources</title>
		<link>http://damieng.com/blog/2009/06/04/linq-to-sql-resources</link>
		<comments>http://damieng.com/blog/2009/06/04/linq-to-sql-resources#comments</comments>
		<pubDate>Fri, 05 Jun 2009 05:33:51 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1224</guid>
		<description>A quick round-up of some useful LINQ to SQL related resources that are available for developers. I&amp;#8217;ve not used everything on this list myself so don&amp;#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 tool has a set of [...]</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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=B5lHIDKfsF4:vCc-FVct4ss:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=B5lHIDKfsF4:vCc-FVct4ss:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/B5lHIDKfsF4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/04/linq-to-sql-resources/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL changes in .NET 4.0</title>
		<link>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40</link>
		<comments>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40#comments</comments>
		<pubDate>Mon, 01 Jun 2009 22:15:29 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40</guid>
		<description>People have been asking via Twitter and the LINQ to SQL forums so here’s a list I put together on a number of the changes made for 4.0.
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 defining text parameter [...]</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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=IJdrMERKFc0:1P1GZ11b5pg:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=IJdrMERKFc0:1P1GZ11b5pg:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/IJdrMERKFc0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40/feed</wfw:commentRss>
		<slash:comments>70</slash:comments>
		</item>
		<item>
		<title>Font hinting and instructing – a primer</title>
		<link>http://damieng.com/blog/2009/05/07/font-hinting-and-instructing-a-primer</link>
		<comments>http://damieng.com/blog/2009/05/07/font-hinting-and-instructing-a-primer#comments</comments>
		<pubDate>Fri, 08 May 2009 04:11:00 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[Fonts]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[fontforge]]></category>
		<category><![CDATA[fontlab]]></category>
		<category><![CDATA[hinting]]></category>
		<category><![CDATA[truetype]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1164</guid>
		<description>Taking my bitmap font Envy Code B into the vector TrueType Envy Code R was a long process, the most difficult being hinting.
Bitmap v scalable fonts
Bitmap fonts are incredibly easy to make. Using a program like Softy or BitFonter you decide the size of your letters and start plotting pixels. You can see exactly how [...]</description>
			<content:encoded><![CDATA[<p>Taking my bitmap font <a href="http://damieng.com/creative/typography/envy-code-b">Envy Code B</a> into the vector TrueType <a href="http://damieng.com/fonts/envy-code-r">Envy Code R</a> was a long process, the most difficult being hinting.</p>
<h3>Bitmap v scalable fonts</h3>
<p>Bitmap fonts are incredibly easy to make. Using a program like <a href="http://users.breathe.com/l-emmett/">Softy</a> or <a href="http://www.fontlab.com/photofont/bitfonter/">BitFonter</a> you decide the size of your letters and start plotting pixels. You can see exactly how it will look because you draw every glyph (letter/symbol/number) in every size you want to support. This can obviously be very time consuming and doesn’t let you take full advantage of the resolution of the device and the capabilities it offers. A printer can handle in excess of 300 dpi while a display is typically 72 dpi (Mac) or 96 dpi (Windows) with LCD’s supporting sub-pixels due to the individual layout of the red-green and blue elements you can’t feasibly pre-plot every single combination and even if you could the file size would be rather large.</p>
<p>Rather than having specific set of pixels to turn on or off TrueType, OpenType and PostScript fonts contain a series of instructions that tell the computer the shape using a series of points, lines and curves. This means the computer can scale the glyph to the size that is required and then take full advantage of the device being rendered honoring the users preferences for anti-aliasing (smoothing using shades of grey), sub-pixel precision (smoothing using hints of red, green and blue to take advantage of the layout of colour elements in an LCD display), desired contrast and gamma settings etc.</p>
<h3>Grid fitting</h3>
<p>Such a scaled glyph won’t fit perfectly within a pixel grid and a small sizes and low resolution it can look awful. It is also necessary to ensure that the vertical part of the letter I (known as a stem) looks very similar to the stem of other letters at the same size – we don’t want some letters looking bold – and that the top of the letter o aligns nicely with the top of the i etc. (in most fonts). The glyphs themselves don’t know what is a stem, what should align with other glyphs etc.</p>
<p>Many renders include logic to try and improve un-hinted fonts such as the drop-out control in Windows through to the full auto-hinter in <a href="http://freetype.sourceforge.net/index2.html">FreeType</a>. If you’ve ever used free fonts from any of the numerous web sites around you’ve probably seen that it doesn’t get it right and it looks like this:<font size="2">&#160;<img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="Envy Code R unhinted" border="0" alt="Envy Code R unhinted" src="http://damieng.com/wp-content/uploads/2009/05/envycoderunhinted-thumb.png" width="376" height="21" /></font></p>
<p>The first few versions of Envy Code R looked like that because to address this problem you need to learn a process called hinting, which let’s the designer give the renderer “hints” on how to choose the pixels.</p>
<h3>Hinting</h3>
<p>Font hinting started off as stem and edge identification so that glyphs would maintain the right proportions when sized and rendered on these low-DPI devices. It became apparent that a much more fine-grained level of control was required and so a stack-based byte-code language was developed as part of the TrueType specification to allow designers finer control in how points are adjusted to better take advantage of the display characteristics.</p>
<p>A TrueType font can contain extra blocks which describes, using a sequence of bytes that represent instructions and their arguments, the process by which to align the points and therefore make decisions about how best to fit the letter into the grid by retaining and adjusting various elements.</p>
<p>The important blocks are:</p>
<table border="0" cellspacing="0" cellpadding="2" width="410">
<tbody>
<tr>
<th valign="top" width="10">Block</th>
<th valign="top" width="70">Name</th>
<th valign="top" width="328">Description</th>
</tr>
<tr>
<td valign="top" width="10">fpgm</td>
<td valign="top" width="70">Font program</td>
<td valign="top" width="328">Run once when font first used to setup the tables.</td>
</tr>
<tr>
<td valign="top" width="10">gasp</td>
<td valign="top" width="70">Grid-fitting and scan conversion</td>
<td valign="top" width="328">Table specifying when to apply smoothing and grid-fitting based on size ranges.</td>
</tr>
<tr>
<td valign="top" width="10">prep</td>
<td valign="top" width="70">Control value program</td>
<td valign="top" width="328">Run every time the font needs to be drawn differently (e.g. change of size, changing anti-aliasing etc)</td>
</tr>
<tr>
<td valign="top" width="10">cvt</td>
<td valign="top" width="70">Control value table</td>
<td valign="top" width="328">Set of tables that can be used to specify various heights, widths, spacing, positions etc. that glyphs can relate to.</td>
</tr>
</tbody>
</table>
<p>Each instruction (<a href="http://en.wikipedia.org/wiki/Opcode">opcode</a>) has a <a href="http://en.wikipedia.org/wiki/Mnemonic">mnemonic</a> that is representative of what it does and these are documented in Chapters 5 through 6 of the <a href="http://www.microsoft.com/typography/SpecificationsOverview.mspx">TrueType specification</a> (along with much other useful relevant information). Actual per-glyph instructions are stored with each glyph outline in the glyp block.</p>
<h3>Rasterizing &amp; rendering</h3>
<p>There are many <a href="http://fortes.com/2007/05/font-rendering-in-across-rich-platforms/">different ways a TrueType font can end up on your screen</a> with a lot of variants between how vendors chose to render the font and what options they expose to developers and users to fine-tune the experience.</p>
<ul>
<li>Windows – User choice of 1-bit, 4-bit grey-scale anti-aliasing, ClearType, ClearType tuning and display DPI plus WPF and DirectWrite per-app options </li>
<li>Mac OS X – User choice of sub-pixel anti-aliasing strength and 1-bit cut-off plus per-app 1-bit option (e.g. Terminal) </li>
<li>Java – Per-application choice of 1-bit, grey-scale or sub-pixel rendering </li>
<li>Flash – Per-application choice of 1-bit or grey-scale </li>
<li>FreeType – Rendering library that exposes a number of runtime and compile-time settings </li>
</ul>
<p>This is of course ignoring the other rendering engines out there such as the Adobe’s Photoshop, RiscOS, <a href="http://www.d-type.com/about/comparison.htm">D-Type rendering engine</a>, <a href="http://www.bitstream.com/font_rendering/products/font_fusion/">Font Fusion</a> (used on BeOS) etc. and prior versions of those renderers listed above (Flash and Mac OS changed significantly). Getting it pixel-perfect on every combination is impossible but we can try :)</p>
<h3>Tools</h3>
<p>Instructing fonts is a painstaking process at the best of times and few people deal directly with the low-level instructions instead relying on tools, stem identification and higher-level languages to achieve the same result. Some tools that have support for hinting instructions are:</p>
<ul>
<li><a href="http://www.fontlab.com/font-editor/fontlab-studio/">FontLab Studio 5</a>       <br />Comprehensive font-production package for Windows and Mac that includes auto-hinting and it’s own higher-level link language that it can generate TrueType instructions from but it does not support viewing or modifying existing TrueType instructions and does not handle diagonals well. Rendering preview includes mono, grey-scale and ClearType. <em>(Commercial $649)</em> </li>
<li><a href="http://www.fontlab.com/font-editor/fontographer/">Fontographer 4.1</a>       <br />Rather dated font-production package for Windows and Mac. <em>(Commercial $349)</em> </li>
<li><a href="http://fontforge.sourceforge.net">FontForge</a>       <br />Comprehensive font-production package that runs on X11 that includes auto-hinting and the ability to disassemble and edit existing TrueType instructions as well as debug them with stepping. Includes basic mono/grey-scale rendering options. <em>(Open source)</em> </li>
<li><a href="http://www.microsoft.com/typography/tools/vtt.aspx">Microsoft Visual TrueType</a>       <br />Hinting instruction tool from Microsoft that uses it’s own higher-level VTT Talk language that compiles down to TrueType instructions that you can further edit. Includes a comprehensive set of preview rendering options but is not capable of disassembling existing instructions.<em> (Commercial, free with signed licence agreement)</em> </li>
<li><a href="http://www.letterror.com/code/ttx/">TTX</a>       <br />Python scripts that can convert a font into an editable XML representation and back including disassembly and assembly of TrueType hinting instructions. <em>(BSD)</em> </li>
<li><a href="http://home.kabelfoon.nl/~slam/fonts/tticomp.html">TTIComp</a>       <br />Command-line tool that provides an alternative C-like hinting language. (<em>GPL)</em> </li>
<li><a href="http://xgridfit.sourceforge.net/">Xgridfit</a>       <br />FontForge scripts to provide an alternative XML-based hinting language. <em>(GPL)</em></li>
<li><a href="http://home.kabelfoon.nl/~slam/fonts/truetypeviewer.html">TrueTypeViewer</a>      <br />Windows tool for displaying TrueType fonts and glyphs including debugging and descriptive disassembly of instructions. <em>(GPL)</em></li>
<li><a href="http://www.cr8.netfirms.com/tthmachine.html">TTHMachine</a>       <br />Real-time editing of hinting instruction mnemonics and observing their effects which is useful for learning. <em>(Free, no longer supported)</em> </li>
</ul>
<p><em>[)amien</em></p>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=eVgIJBxh930:zWNsNsrCGrU:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=eVgIJBxh930:zWNsNsrCGrU:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/eVgIJBxh930" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/05/07/font-hinting-and-instructing-a-primer/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL tips and tricks #2</title>
		<link>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2</link>
		<comments>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2#comments</comments>
		<pubDate>Mon, 13 Apr 2009 07:21:05 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2</guid>
		<description>A few more useful and lesser-known techniques for using LINQ to SQL.
Take full control of  the TSQL
There are times when LINQ to SQL refuses to cook up the TSQL you wanted either because it doesn’t support the feature or because it has a different idea what makes an optimal query.
In either case the Translate method [...]</description>
			<content:encoded><![CDATA[<p>A few more useful and lesser-known techniques for using LINQ to SQL.</p>
<h3>Take full control of  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>
<div class="feedflare">
<a href="http://feed.damieng.com/~ff/DamienG?a=xZkyeHyeZPk:vZZaOw94jhE:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/DamienG?i=xZkyeHyeZPk:vZZaOw94jhE:D7DqB2pKExk" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/DamienG/~4/xZkyeHyeZPk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic page generated in 3.743 seconds. --><!-- Cached page generated by WP-Super-Cache on 2010-02-04 15:35:26 --><!-- Compression = gzip -->
