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

<channel>
	<title>DamienG &#187; Development</title>
	<atom:link href="http://damieng.com/blog/category/development/feed" rel="self" type="application/rss+xml" />
	<link>http://damieng.com</link>
	<description>A .NET developer in Redmond</description>
	<lastBuildDate>Sat, 27 Feb 2010 17:18:17 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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><![CDATA[A few more interesting and lesser-known LINQ to SQL techniques.
Lazy loading with stored procedures
LINQ to SQL supports stored procedures for retrieving entities, insert, update and delete operations but you can also use them to perform lazy-loading of navigation properties.
Lets show an example of a bi-directional relationship between a Post and a Comment. We 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>
]]></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>SQL Server query plan cache &#8211; what is it and why should you care?</title>
		<link>http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache</link>
		<comments>http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache#comments</comments>
		<pubDate>Mon, 14 Dec 2009 00:55:42 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[sql-server]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1487</guid>
		<description><![CDATA[What is a query plan?
SQL Server like all databases goes through a number of steps when it receives a command. Besides parsing and validating the command text and parameters it looks at the database schema, statistics and indexes to come up with a plan to efficiently query or change your data.
You can view 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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/12/13/sql-server-query-plan-cache/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Multiple outputs from T4 made easy &#8211; revisited</title>
		<link>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited</link>
		<comments>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited#comments</comments>
		<pubDate>Fri, 06 Nov 2009 08:20:37 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[entity framework]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1457</guid>
		<description><![CDATA[My multiple outputs from t4 made easy post contained a class making it easy to produce multiple files from Visual Studio’s text templating engine (T4).
While useful it had a few issues:

Getting start/end blocks mixed up resulted in unpredictable behaviour
Files were rewritten even when content did not change
Did not play well with 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>));
        }
    }
} #&gt;</code></pre>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited/feed</wfw:commentRss>
		<slash:comments>6</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><![CDATA[I fired up Visual Studio this evening to write a proof-of-concept app and found myself wanting strongly typed domain objects from a database but without the overhead of an object-relational mapper  (the application is read-only).
One solution is to write methods by hand, another is to code generate them but it would be nice to 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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/09/22/when-an-object-relational-mapper-is-too-much-datareader-too-little/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL cheat sheet</title>
		<link>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet</link>
		<comments>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet#comments</comments>
		<pubDate>Thu, 13 Aug 2009 07:55:33 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[cheat sheet]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1248</guid>
		<description><![CDATA[A few short words to say I&#8217;ve put together a cheat sheet for LINQ to SQL with one page for C# and another for VB.NET.

It shows the syntax for a number of common query operations, manipulations and attributes and can be a very useful quick reference :)
Download LINQ to SQL cheat sheet (PDF) (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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/08/12/linq-to-sql-cheat-sheet/feed</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>Dictionary look-up or create made simpler</title>
		<link>http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler</link>
		<comments>http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler#comments</comments>
		<pubDate>Wed, 05 Aug 2009 00:24:04 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/08/04/dictionaryt-look-up-or-create-made-simpler</guid>
		<description><![CDATA[The design of a Dictionary&#60;T&#62; lends itself well to a caching or identification mechanism and as a result you often see code that looks like this:
private static Dictionary&#60;string,Employee&#62; employees;
…
public static Employee GetByName(string name) {
    Employee employee;
    if (!employees.TryGetValue(name, out employee)) {
        employee [...]]]></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>
]]></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><![CDATA[David Fowler on the ASP.NET team and I have been bouncing ideas about on how to solve an annoyance using LINQ:
If you write properties on the client you can’t use them in remote LINQ operations.
The problem occurs because these properties can’t be translated and sent to the server as they have been compiled 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>
]]></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><![CDATA[A quick round-up of some useful LINQ to SQL related resources that are available for developers. I&#8217;ve not used everything on this list myself so don&#8217;t take this as personal endorsement.
Templates

Entity Developer
Add-in for Visual Studio that provides a replacement designer with code templates. Commercial ($99.95)
LLBLGen Pro
This ORM templating and design 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>
]]></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><![CDATA[People have been asking via Twitter and the LINQ to SQL forums so here’s a list I put together on a number of the changes made for 4.0.
25 Aug 2009 – Updated with additional changes, some of which are new in beta 2. 
Change list
Performance

Query plans are reused more often by specifically 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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40/feed</wfw:commentRss>
		<slash:comments>73</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><![CDATA[A few more useful and lesser-known techniques for using LINQ to SQL.
Take full control of  the TSQL
There are times when LINQ to SQL refuses to cook up the TSQL you wanted either because it doesn’t support the feature or because it has a different idea what makes an optimal query.
In either case 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>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL tips and tricks #1</title>
		<link>http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1</link>
		<comments>http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1#comments</comments>
		<pubDate>Mon, 16 Mar 2009 22:01:51 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1</guid>
		<description><![CDATA[Being on the inside of a product team often leads to uncovering or stumbling upon lesser known techniques and here are a few little nuggets I found interesting – I have more if there is interest.
Loading a delay-loaded property
LINQ to SQL lets you specify that a property is delay-loaded meaning that it is not normally [...]]]></description>
			<content:encoded><![CDATA[<p>Being on the inside of a product team often leads to uncovering or stumbling upon lesser known techniques and here are a few little nuggets I found interesting – I have more if there is interest.</p>
<h3>Loading a delay-loaded property</h3>
<p>LINQ to SQL lets you specify that a property is delay-loaded meaning that it is not normally retrieved as part of normal query operations against that entity. This is particularly useful for binary and large text fields such as a photo property on an employee object that is rarely used and would cause a large amount of memory to be consumed on the client not to mention traffic between the SQL and application.</p>
<p>There are times however when you want all these binaries returned in a single query, say for example returning all the photos for the company photo intranet page:</p>
<pre><code><strong>var</strong> db = <strong>new</strong> NorthwindContext();
<strong>var</strong> loadOptions = <strong>new</strong> DataLoadOptions();
loadOptions.LoadWith&lt;Employee&gt;(e =&gt; e.Photo);
db.LoadOptions = loadOptions;</code></pre>
<h3>Multiple entity types from a single stored procedure</h3>
<p>It is actually possible to return multiple entity types from a single stored procedure in LINQ to SQL although this is not well known as the LINQ to SQL designer doesn’t actually support it. Indeed to generate the code it is necessary to hand-edit the DBML and then use SQL Metal (or my T4 template) to generate the required method signature.</p>
<p>In fact it is just much easier to write the code yourself and add it to the non-generated portion of your data context. If you imagine a stored procedure GetStaticData that looks like this:</p>
<pre><code><strong>CREATE PROCEDURE</strong> GetStaticData <strong>AS
  SELECT</strong> * <strong>FROM</strong> Region
<strong>  SELECT</strong> * <strong>FROM</strong> Categories
<strong>  SELECT</strong> * <strong>FROM</strong> Territories</code></pre>
<p>Then all you need to do is write a method signature that looks like this (the sequence of result type attributes must match the order in the stored procedure):</p>
<pre><code>[Function(Name=@"dbo.DynamicContractsActiveBetween")]
[ResultType(<strong>typeof</strong>(Region))]
[ResultType(<strong>typeof</strong>(Category))]
[ResultType(<strong>typeof</strong>(Territory))]
<strong>public</strong> IMultipleResults GetStaticData() {
   <strong>return</strong> (IMultipleResults) ExecuteMethodCall(<strong>this</strong>, (MethodInfo) MethodInfo.GetCurrentMethod()).ReturnValue;
}</code></pre>
<h3>Intercepting create, update and delete operations</h3>
<p>There are times it is useful to be able to listen in to when these events happen and perform your own logic, perhaps auditing or logging for some scenarios. The easiest way to do this is to implement some specially-named methods on your data context, perform your action and then to dispatch the call back to LINQ to SQL.</p>
<p>The format of these specially-named methods is [Action][Entity] and then you should pass back control to LINQ to SQL using ExecuteDynamic[Action] where [Action] is either Insert, Update or Delete. One example of such usage might be:</p>
<pre><code><strong>partial class</strong> NorthwindContext {
   <strong>partial void</strong> InsertEmployee(Employee instance) {
      instance.CreatedBy = CurrentUser;
      instance.CreatedAt = DateTime.Now;
      ExecuteDynamicInsert(instance);
   }

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

   <strong>partial void</strong> DeleteEmployee(Employee instance) {
      AuditDelete(instance, CurrentUser);
      ExecuteDynamicDelete(instance);
   }
}</code></pre>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/03/16/linq-to-sql-tips-and-tricks-1/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Multiple outputs from T4 made easy</title>
		<link>http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy</link>
		<comments>http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy#comments</comments>
		<pubDate>Thu, 22 Jan 2009 19:53:13 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy</guid>
		<description><![CDATA[An improved version is now available.
One of the things I wanted my LINQ to SQL T4 templates to do was be able to split the output into a file-per-entity. Existing solutions used either a separate set of templates with duplicate code or intrusive handling code throughout the template. Here’s my helper class to abstract the [...]]]></description>
			<content:encoded><![CDATA[<p class="new">An <a href="http://damieng.com/blog/2009/11/06/multiple-outputs-from-t4-made-easy-revisited">improved version is now available.</a></p>
<p>One of the things I wanted my <a href="http://l2st4.codeplex.com/">LINQ to SQL T4 templates</a> to do was be able to split the output into a file-per-entity. Existing solutions used either a separate set of templates with duplicate code or intrusive handling code throughout the template. Here’s my helper class to abstract the problem away from what is already complicated enough template code.</p>
<h3>Using the Manager class</h3>
<h4>Setup</h4>
<p>You’ll need to get the code into your template – either copy the code in or reference it with an include directive. Then declare an instance of the Manager class passing in some environmental options such as the desired default output path.</p>
<pre><code>&lt;#@ template language="C#v3.5" hostspecific="True"
#&gt;&lt;#@ include file="Manager.ttinclude"
#&gt;&lt;# <strong>var</strong> manager = <strong>new</strong> Manager(Host, GenerationEnvironment, <strong>true</strong>) { OutputPath = Path.GetDirectoryName(Host.TemplateFile) }; #&gt;</code></pre>
<h4>Define a block</h4>
<p>Then add one line before and one line after each block which could be split out into it’s own file passing in what the filename would be if split.</p>
<pre><code>&lt;# manager.StartBlock("Employee.generated.cs"); #&gt;
public class Employee { … }
&lt;# manager.EndBlock(); #&gt;</code></pre>
<h4>Headers and footers</h4>
<p>Many templates need to share a common header/footer for such things as comments or using/import statements or turning on/off warnings. Simply use StartHeader/EndHeader and StartFooter/EndFooter. The resulting blocks will be emitted into all split files and left in the original output too.</p>
<pre><code>&lt;# manager.StartHeader(); #&gt;
// Code generated template
using System;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		EnvDTE.DTE 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);
	}

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

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

	<strong>private void</strong> FindAndDeleteFile(String fileName) {
		<strong>foreach</strong>(EnvDTE.ProjectItem projectItem <strong>in</strong> templateProjectItem.ProjectItems) {
			<strong>if</strong> (projectItem.get_FileNames(0) == fileName) {
				projectItem.Delete();
				<strong>return</strong>;
			}
		}
	}
}#&gt;</code></pre>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/22/multiple-outputs-from-t4-made-easy/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL templates updated, now on CodePlex</title>
		<link>http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex</link>
		<comments>http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex#comments</comments>
		<pubDate>Tue, 20 Jan 2009 01:48:27 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[t4]]></category>

		<guid isPermaLink="false">http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex</guid>
		<description><![CDATA[My templates that allow you to customize the LINQ to SQL code-generation process (normally performed by SQLMetal/LINQ to SQL classes designer) have been updated once again.
Updates

Now licensed under the Microsoft Public License and hosted at CodePlex
User options specified with a var options block at the start of the template
Option for each class to be a [...]]]></description>
			<content:encoded><![CDATA[<p>My templates that allow you to customize the LINQ to SQL code-generation process (normally performed by SQLMetal/LINQ to SQL classes designer) have been updated once again.</p>
<h3>Updates</h3>
<ul>
<li>Now licensed under the <a href="http://www.codeplex.com/l2st4/license">Microsoft Public License</a> and <a href="http://l2st4.codeplex.com/">hosted at CodePlex</a></li>
<li>User options specified with a <em>var options</em> block at the start of the template</li>
<li>Option for each class to be a separate file that is reflected in the VS project (EntityPerFile=true)</li>
<li>Detection and support of IsComposable functions</li>
<li>General code clean-up and better error handling such as missing DBML file</li>
</ul>
<h3>In action!</h3>
<p class="warning">Screen cast is no longer available, sorry.</p>
<h3>CodePlex</h3>
<p>CodePlex makes it easier for people to be able to see and merge updates in with their own modified versions as well as report issues via the issue tracker etc. There is also an RSS feed that lets you keep track of releases, source updates or whatever else you are interested in.</p>
<p>For now it is a grab-the-source style release but I hope to publish downloadable tested releases wrapped up in a Visual Studio Installer (VSI) package to make getting started easier soon.  Feel free to grab the sources directly via TFS/Subversion to be able to diff them with your own modified versions.</p>
<p>Enjoy!</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/19/linq-to-sql-templates-updated-now-on-codeplex/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
<enclosure url="http://silverlight.services.live.com/89084/LINQ%20to%20SQL%20templates%20introduction/video.wmv" length="5418479" type="audio/x-ms-wmv" />
		</item>
		<item>
		<title>Changing type, the state pattern and LINQ to SQL</title>
		<link>http://damieng.com/blog/2009/01/05/changing-type-the-state-pattern-and-linq-to-sql</link>
		<comments>http://damieng.com/blog/2009/01/05/changing-type-the-state-pattern-and-linq-to-sql#comments</comments>
		<pubDate>Tue, 06 Jan 2009 03:24:18 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design-Patterns]]></category>
		<category><![CDATA[linq-to-sql]]></category>
		<category><![CDATA[state pattern]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1126</guid>
		<description><![CDATA[A question I see from time-to-time on LINQ to SQL relates to changing an entity’s class.
C# and VB.NET don’t allow a class to change its type at runtime and LINQ to SQL specifically doesn’t provide a mechanism for changing the underlying discriminator for this reason.
Discarding the current object and creating a new one is fraught [...]]]></description>
			<content:encoded><![CDATA[<p>A question I see from time-to-time on LINQ to SQL relates to changing an entity’s class.</p>
<p>C# and VB.NET don’t allow a class to change its type at runtime and LINQ to SQL specifically doesn’t provide a mechanism for changing the underlying discriminator for this reason.</p>
<p>Discarding the current object and creating a new one is fraught with issues. What do we do about existing references, unsaved data, established associations and caches?</p>
<h3>Start with an example</h3>
<p>Consider an abstract Account class with SavingsAccount and CurrentAccount sub-classes. Bank accounts don’t change type once created (in my experience) so that’s good so far.</p>
<p>When we get into processing and validation logic its tempting to create ClosedAccount and OpenAccount classes but what happens during execution when closing an account?</p>
<p>A further consideration is how exactly ClosedAccount and OpenAccount fit into the hierarchy given the single-inheritance limitation of C# and VB.NET.</p>
<h3>Enter the State Pattern</h3>
<p>The ever-resourceful <a href="http://en.wikipedia.org/wiki/Gang_of_Four_(software)">Gang of Four</a> describe the <a href="http://en.wikipedia.org/wiki/State_pattern">State Pattern</a> as:</p>
<blockquote><p>Allow an object to alter its behavior when its internal state changes.<br />
The object will appear to change its class.</p></blockquote>
<p>Taking the bank accounts example and applying the state pattern gives:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="StatePattern" src="http://damieng.com/wp-content/uploads/2009/01/statepattern1.png" border="0" alt="StatePattern" width="739" height="372" /></p>
<p>Account no longer needs to change type at run-time yet is still able to have clients call Validate and process Methods that end up in discrete methods as if inheritance had been used.</p>
<p>To achieve this we have:</p>
<ol>
<li>Created a State hierarchy that contains the logic we need to change at run-time</li>
<li>Introduced a private member in Account that points to the current state instance</li>
<li>Ensured the Account methods call the current state class via the private member</li>
</ol>
<p>Because the state member is private and only accessed by Account itself we can happily create and dispose it as the conditions that affect the state change as much as we like without worrying about references to it.</p>
<p>This is best illustrated with code. Here rather than just calling the state’s validation logic there is a combination of core Account validation (balance), state validation (closed) and CheckingAccount validation (transaction limits):</p>
<pre><code><strong>public abstract class</strong> Account {
    <strong>private</strong> AccountState state;

    <strong>public virtual</strong> Status Validate(ITransaction tx) {
        Status result = state.Validate(tx);
        <strong>if</strong> (tx.Amount &gt; Balance)
            result.Add(TransactionFailures.InsufficientFunds);
        <strong>return</strong> result;
    }
}
<strong>public class </strong>SavingsAccount : Account {
    <strong>public override</strong> Status Validate(ITransaction tx) {
        Status result = <strong>base</strong>.Validate(tx);
        <strong>if</strong> (Transactions.Count &gt; TransactionLimit)
            result.Add(TransactionFailures.TransactionLimitReached);
        <strong>return</strong> result;
    }
}<strong>
public class</strong> ClosedAccountState : AccountState {
<strong>    public override</strong> Status Validate(ITransaction tx) {
        <strong>return new </strong>Status(TransactionFailures.InvalidSourceAccount);
    }
}</code></pre>
<p>This is less complex than selectively replacing objects within our application at run-time and can bring additional benefits:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single responsibility principle</a> – logic relating to a specific state has its own class to live in</li>
<li><a href="http://www.artima.com/lejava/articles/designprinciples4.html">Favor composition over inheritance</a> – inheritance for OpenSavingsAccount, ClosedCheckingAccount etc. is complex</li>
</ul>
<p>Like all guidance, patterns and principles do not blindly follow these guidelines or patterns but consider how it affects and fits with your application. For this particular example it not only solves the problem but helps maintainability – at least at this simple stage. Once Validation becomes sufficiently complex it would likely move out entirely into a new set of orchestrated classes just for that.</p>
<h3>With LINQ to SQL (and other mappers)</h3>
<p>Moving this example into an object-relational mapper requires two &#8211; not unexpected &#8211; database-mapped properties.</p>
<ol>
<li>The inheritance discriminator (Type)</li>
<li>A state indicator (Active)</li>
</ol>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Dbml" src="http://damieng.com/wp-content/uploads/2009/01/dbml1.png" border="0" alt="Dbml" width="599" height="337" /></p>
<p>The only thing we need to ensure is the Account’s state member always refers to either a ClosedAccountState or OpenedAccountState depending upon the Active flag.</p>
<p>Given that LINQ to SQL code-generates the property for Active we could:</p>
<ol>
<li>Make Active private, wrap it in another property and set the state member when it changes and at initialization</li>
<li>Make the state member a read-only property instead of an instance variable</li>
</ol>
<p>The second works well here and given that AccountState is itself stateless (perhaps not the best choice of name) we can use a singleton to avoid multiple instances. The state instance variable in the Account class is replaced with:</p>
<pre><code><strong>private</strong> AccountState State {
    <strong>get</strong> {
        <strong>if</strong> (Active)
            <strong>return</strong> OpenAccountState.Instance;
        <strong>else</strong>
            <strong>return</strong> ClosedAccountState.Instance;
    }
}</code></pre>
<p>The code continues to work and now changing the Active flag results in different behavior.</p>
<p>Best of all we still have the code in separate classes, no switch/case/if statements relating to validation or account types, a clean inheritance hierarchy and no running around trying to invalidate existing references.</p>
<h3>Hitting the discriminator directly</h3>
<p>There may be times when claims are made that a type has to change &#8211; perhaps data was entered incorrectly.</p>
<p>Before delving into the database or providing a tool to flip the underlying discriminator value consider:</p>
<ol>
<li>Does the new class interpret the same data in a different manner?<em><br />
Has a $1,000 credit limit just become a 1,000 transactions per-month limit?</em></li>
<li>Would the object be valid in the new class?<em><br />
Did a ProposedCustomer just become ApprovedCustomer without a policy-enforced credit check?</em></li>
<li>Are associations still honored?<em><br />
Are 300 unshipped orders for a GameProduct still honored for a BookProduct?</em></li>
</ol>
<p>If in doubt don’t do it.</p>
<p>An inconsistent database bleeding through your application isn’t good for anyone and will take a lot longer to sort out than setting up a new entity.</p>
<p><em>[)amien</em></p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/05/changing-type-the-state-pattern-and-linq-to-sql/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>ALT.NET Seattle</title>
		<link>http://damieng.com/blog/2009/01/03/altnet-seattle</link>
		<comments>http://damieng.com/blog/2009/01/03/altnet-seattle#comments</comments>
		<pubDate>Sun, 04 Jan 2009 03:32:25 +0000</pubDate>
		<dc:creator>Damien Guard</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[alt.net]]></category>
		<category><![CDATA[seattle]]></category>

		<guid isPermaLink="false">http://damieng.com/?p=1108</guid>
		<description><![CDATA[One of the cool things about living in Seattle is the sheer number of passionate developers around. Whether you&#8217;re dropping into offices, heading across campus for lunch, meeting downtown for music and beer or in my case last month taking a Saturday out to participate in ALT.NET Seattle, there are ideas, enthusiasm and discussions with [...]]]></description>
			<content:encoded><![CDATA[<p>One of the cool things about living in Seattle is the sheer number of passionate developers around. Whether you&#8217;re dropping into offices, heading across campus for lunch, meeting downtown for music and beer or in my case last month taking a Saturday out to participate in ALT.NET Seattle, there are ideas, enthusiasm and discussions with great developers to be had everywhere.</p>
<p>The <a href="http://laribee.com/blog/2007/04/10/altnet/">ALT.NET</a> event was particularly interesting. If you didn&#8217;t already know the name encapsulates:</p>
<ul>
<li>the desire to improve the art, process, individual and product</li>
<li>the understanding that the right tool for the job doesn&#8217;t always ship with the .NET</li>
</ul>
<p>The event follows the same minimal up-front planning modern development practices enjoy relying on talented people and simple structure to achieving something great in a short space of time.<sup>1</sup></p>
<p>This open-spaces format involves a small deck of cards to write topics you&#8217;d like to talk about on and a board with rooms and times to drop them into. I was surprised at how well the event unfolded (bar one session that veered off-course) given our unplanned attempts at the <a href="http://developers.org.gg">Guernsey developer group</a> always resulted in five people having dinner in a bar :)</p>
<p>I had an enjoyable day and my thanks go to <a href="http://bradwilson.typepad.com/">Brad Wilson</a> (ASP.NET) for driving and listening to my nostalgic 8-bit discussion with fellow brit <a href="http://www.ademiller.com/blogs/tech/">Ade Miller</a> (p&amp;p) who previously worked at Future Publishing (<a href="http://en.wikipedia.org/wiki/Your_Sinclair">Your Sinclair</a> magazine). I&#8217;m now messing around with a .NET based Spectrum emulator I started years ago and I&#8217;m going to blame him for that.</p>
<p>The best news is that there are more events planned for the coming months:</p>
<ul>
<li>January 17th normal format, location TBA</li>
<li>February &#8211;  provisionally the 7th, regular format, location TBA</li>
</ul>
<h3>ALT.NET Seattle 2009 Conference</h3>
<p>This is the big one immediately preceding the MVP Summit by running February 27th to March 1st at <a href="https://www.digipen.edu/">Digipen</a> in Redmond. <a href="http://codebetter.com/blogs/glenn.block/archive/2009/01/02/alt-net-seattle-2009-is-happening.aspx">Glenn Block has more details</a>.</p>
<p>Registration will open on Tuesday, 6pm (GMT-8), attendance is free and spaces are limited so get in quick!</p>
<p>Consider joining the <a href="http://groups.google.com/group/altnetseattle?hl=en&#038;pli=1">Seattle area ALT.NET group</a> or <a href="http://www.facebook.com/group.php?gid=111345965570">ALT.NET Facebook group</a> for more details or to get involved.</p>
<p><em>[)amien</em><br />
<sup>1</sup>And as either Glen or Brad said with a nod to the end-of-credits bit in Ferris Bueller &#8211; &#8220;When it&#8217;s over it&#8217;s over. Go home already.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://damieng.com/blog/2009/01/03/altnet-seattle/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
