<?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>The Grubbsian &#187; .NET</title>
	<atom:link href="http://www.thegrubbsian.com/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.thegrubbsian.com</link>
	<description>Writings on .NET, Ruby, JavaScript, HTML/CSS, Design, and all things Web.</description>
	<lastBuildDate>Sun, 01 Aug 2010 20:57:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>LINQ-to-SQL Sugar</title>
		<link>http://www.thegrubbsian.com/2009/12/21/linq-to-sql-sugar/</link>
		<comments>http://www.thegrubbsian.com/2009/12/21/linq-to-sql-sugar/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 04:33:15 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=262</guid>
		<description><![CDATA[Yes, yes, LINQ-to-SQL is probably, one day, going to be consumed or deprecated by it&#8217;s big brother the Entity Framework. However, for the current .NET platform (3.5) and likely for the next (4.0) it is still a viable ORM option in the Visual Studio box. There are lots of reasons to use LINQ-to-SQL and lots [...]]]></description>
			<content:encoded><![CDATA[<p>Yes, yes, LINQ-to-SQL is probably, one day, going to be consumed or deprecated by it&#8217;s big brother the Entity Framework.  However, for the current .NET platform (3.5) and likely for the next (4.0) it is still a viable ORM option in the Visual Studio box.  There are lots of reasons to use LINQ-to-SQL and lots of reasons <em>not</em> to use it&#8230;that is for another post.  </p>
<p>What I do want to share is a set of extension methods that (for me) made using LINQ-to-SQL just a little bit nicer.  The title is indeed descriptive&#8230;these are &#8220;sugar&#8221; added to LINQ-to-SQL and don&#8217;t fundamentally improve how it works, just how the programmer works with the library.  I&#8217;m sure developers using LINQ-to-SQL have created scads of other such saccarine extensions to the framework&#8230;if you have some I&#8217;d be interested in hearing about them.</p>
<p>So here&#8217;s my LinqToSqlExtensions class:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> LinqToSqlExtensions <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TEntity GetById<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> Table<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> @<span style="color: #0600FF;">this</span>, <span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span>
        where TEntity <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">SingleOrDefault</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>IIdentified<span style="color: #000000;">&#41;</span>x<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ID</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TEntity Upsert<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> Table<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> @<span style="color: #0600FF;">this</span>, <span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span>
        where TEntity <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        var entity <span style="color: #008000;">=</span> @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">SingleOrDefault</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>IIdentified<span style="color: #000000;">&#41;</span>x<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ID</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>entity <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            entity <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TEntity<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>entity<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>entity <span style="color: #008000;">is</span> IAuditable<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>IAuditable<span style="color: #000000;">&#41;</span> entity<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ModifiedDate</span> <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">return</span> entity<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TEntity Upsert<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> Table<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> @<span style="color: #0600FF;">this</span>, Func<span style="color: #008000;">&lt;</span>TEntity, <span style="color: #FF0000;">bool</span><span style="color: #008000;">&gt;</span> predicate<span style="color: #000000;">&#41;</span>
        where TEntity <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        var entity <span style="color: #008000;">=</span> @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">SingleOrDefault</span><span style="color: #000000;">&#40;</span>predicate<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>entity <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            entity <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TEntity<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>entity<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>entity <span style="color: #008000;">is</span> IAuditable<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>IAuditable<span style="color: #000000;">&#41;</span> entity<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ModifiedDate</span> <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">return</span> entity<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Delete<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> Table<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> @<span style="color: #0600FF;">this</span>, TEntity entity<span style="color: #000000;">&#41;</span>
        where TEntity <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span> <span style="color: #000000;">&#123;</span>
        @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">DeleteOnSubmit</span><span style="color: #000000;">&#40;</span>entity<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> DeleteById<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> Table<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> @<span style="color: #0600FF;">this</span>, <span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span>
        where TEntity <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span> <span style="color: #000000;">&#123;</span>
        var entity <span style="color: #008000;">=</span> @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">GetById</span><span style="color: #000000;">&#40;</span>id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Delete</span><span style="color: #000000;">&#40;</span>entity<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> DeleteAll<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> Table<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> @<span style="color: #0600FF;">this</span>, 
        IEnumerable<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span> entities<span style="color: #000000;">&#41;</span> where TEntity <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span> <span style="color: #000000;">&#123;</span>
        entities.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0600FF;">ForEach</span><span style="color: #000000;">&#40;</span>e <span style="color: #008000;">=&gt;</span> @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Delete</span><span style="color: #000000;">&#40;</span>e<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> CommitChanges<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> DataContext @<span style="color: #0600FF;">this</span>, RepositoryContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        var changeSet <span style="color: #008000;">=</span> @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">GetChangeSet</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>var i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> changeSet.<span style="color: #0000FF;">Inserts</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>changeSet.<span style="color: #0000FF;">Inserts</span><span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span> <span style="color: #008000;">is</span> IAuditable<span style="color: #000000;">&#41;</span> UpdateAuditProperties<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>IAuditable<span style="color: #000000;">&#41;</span> changeSet.<span style="color: #0000FF;">Inserts</span><span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>, context, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span>var i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&lt;</span> changeSet.<span style="color: #0000FF;">Updates</span>.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>changeSet.<span style="color: #0000FF;">Updates</span><span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span> <span style="color: #008000;">is</span> IAuditable<span style="color: #000000;">&#41;</span> UpdateAuditProperties<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>IAuditable<span style="color: #000000;">&#41;</span> changeSet.<span style="color: #0000FF;">Updates</span><span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span>, context, <span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        @<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">SubmitChanges</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> UpdateAuditProperties<span style="color: #008000;">&lt;</span>TEntity<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>TEntity entity, RepositoryContext context, 
        <span style="color: #FF0000;">bool</span> isInsert<span style="color: #000000;">&#41;</span> where TEntity <span style="color: #008000;">:</span> IAuditable <span style="color: #000000;">&#123;</span>
&nbsp;
        entity.<span style="color: #0000FF;">ModifiedDate</span> <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span><span style="color: #008000;">;</span>
        entity.<span style="color: #0000FF;">ModifiedBy</span> <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">UserID</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>isInsert<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            entity.<span style="color: #0000FF;">CreatedDate</span> <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span><span style="color: #008000;">;</span>
            entity.<span style="color: #0000FF;">CreatedBy</span> <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">UserID</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Here&#8217;s a rundown of the methods it creates and how to use them:</p>
<p><strong>GetById</strong><br />
Simple enough, allows you to avoid using the LINQ syntax to find an element by it&#8217;s identifier.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var thing <span style="color: #008000;">=</span> DataContext.<span style="color: #0000FF;">Things</span>.<span style="color: #0000FF;">GetById</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p><strong>Upsert</strong><br />
This is probably the most convenient addition.  It simply checks to see whether the object exists (by it&#8217;s ID) if so it returns it if not it creates a new one and returns that.  It just avoids a lot of query-for-an-object-and-if-its-null-create-a-new-one-and-insert-it code.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var thing <span style="color: #008000;">=</span> DataContext.<span style="color: #0000FF;">Things</span>.<span style="color: #0000FF;">Upsert</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var anotherThing <span style="color: #008000;">=</span> DataContext.<span style="color: #0000FF;">Things</span>.<span style="color: #0000FF;">Upsert</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;That Thing&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p><strong>Delete and DeleteById</strong><br />
Pretty obvious&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">DataContext.<span style="color: #0000FF;">Things</span>.<span style="color: #0000FF;">Delete</span><span style="color: #000000;">&#40;</span>thing<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
DataContext.<span style="color: #0000FF;">Things</span>.<span style="color: #0000FF;">DeleteById</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">3</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p><strong>CommitChanges</strong><br />
This is just a replacement for SubmitChanges that allows us to update some audit columns automagically.</p>
<p>Some of this magic is provided via a set of partial classes on those that LINQ-to-SQL generates that applies some additional interfaces to those classes.  So, I have a Partials.cs file that contains the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IAuditable <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> DateTime CreatedDate <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> DateTime UpdatedDate <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> CreatedBy <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> UpdatedBy <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IIdentified <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> ID <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">partial</span> <span style="color: #FF0000;">class</span> Thing <span style="color: #008000;">:</span> IIdentified, IAuditable <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> OtherThing <span style="color: #008000;">:</span> IIdentified <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LastThing <span style="color: #008000;">:</span> IAuditable <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span></pre></div></div>

<p>As long as your generated class (and it&#8217;s related table) have properties of the same names as the IAuditable and IIdentified interfaces the LINQ-to-SQL extension methods can update them appropriately and in the background.  I could have accomplished much of this by just inheriting a new DataContext and adding some additional functionality, but doing it this way you can add these methods to even a closed assembly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2009/12/21/linq-to-sql-sugar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scriptability via the DLR and PostSharp</title>
		<link>http://www.thegrubbsian.com/2009/12/15/scriptability-via-the-dlr-and-postsharp/</link>
		<comments>http://www.thegrubbsian.com/2009/12/15/scriptability-via-the-dlr-and-postsharp/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 21:28:13 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[IronPython]]></category>
		<category><![CDATA[DLR]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=265</guid>
		<description><![CDATA[Making an application scriptable (particularly in a static language) has historically been difficult. With the advent of the DLR (Dynamic Language Runtime) on the .NET platform it becomes almost trivial to add scripting support to any application. For a recent project I needed the ability to add scripting hooks throughout the application and coupling the [...]]]></description>
			<content:encoded><![CDATA[<p>Making an application scriptable (particularly in a static language) has historically been difficult.  With the advent of the DLR (Dynamic Language Runtime) on the .NET platform it becomes almost trivial to add scripting support to any application.  For a recent project I needed the ability to add scripting hooks throughout the application and coupling the DLR with PostSharp AOP attributes made this effort pretty straightforward.  Here&#8217;s how it was done:</p>
<p><strong>Bring in the DLR</strong><br />
The DLR is implemented as a set of plain old DLL&#8217;s on top of the .NET Framework version 3.5&#8230;contrary to popular belief, you do not have to be running VS2010 or .NET 4 to use it.  Simply go to the CodePlex page for the DLR (<a href="http://dlr.codeplex.com">http://dlr.codeplex.com</a>), grab the source, and compile it.  There are solution files for VS2008 and VS2010.</p>
<p>For my purposes I used IronPython as the scripting language but IronRuby is available in the download as well.  To use the DLR your project will need to reference the following assemblies:</p>
<ul>
<li>Microsoft.Dynamic.dll</li>
<li>Microsoft.Scripting.Core.dll</li>
<li>Microsoft.Scripting.dll</li>
</ul>
<p>In order to use IronPython, you will also need to reference these:</p>
<ul>
<li>IronPython.dll</li>
<li>IronPython.Modules.dll</li>
<li>Microsoft.Scripting.ExtensionAttribute.dll</li>
</ul>
<p><strong>Register the Languages</strong><br />
Now that your project contains all the references it needs it&#8217;s time to set up the little bit of code needed to host the DLR.  First you&#8217;ll need to add a few things to your configuration file (App.config or Web.config depending on your project type&#8230;this works equally well with either).  Just add the following to the <configSections> node of your config file:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;section</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;microsoft.scripting&quot;</span> </span>
<span style="color: #009900;">	<span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting, </span>
<span style="color: #009900;">		Version=0.9.6.20, Culture=neutral, PublicKeyToken=null&quot;</span> </span>
<span style="color: #009900;">	<span style="color: #000066;">requirePermission</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>And add the following somewhere in the root <configuration> node:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;microsoft.scripting<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;languages<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;language</span> <span style="color: #000066;">names</span>=<span style="color: #ff0000;">&quot;IronPython;Python;py&quot;</span> </span>
<span style="color: #009900;">			<span style="color: #000066;">extensions</span>=<span style="color: #ff0000;">&quot;.py&quot;</span> <span style="color: #000066;">displayName</span>=<span style="color: #ff0000;">&quot;IronPython 2.6&quot;</span> </span>
<span style="color: #009900;">			<span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;IronPython.Runtime.PythonContext, IronPython, </span>
<span style="color: #009900;">				Version=2.6.10920.0, Culture=neutral, PublicKeyToken=null&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/languages<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/microsoft.scripting<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>This basically just tells the runtime what languages to register, what versions of those languages, and some info about file extensions, etc.</p>
<p><strong>Bring in PostSharp</strong><br />
Now I&#8217;m going to skip over to PostSharp for a minute.  If you&#8217;re not familiar with PostSharp you should run over to the website (<a href="http://www.postsharp.org">http://www.postsharp.org</a>) and check it out before continuing.  In short, it&#8217;s an AOP (Aspect Oriented Programming) library for .NET that allows easy injection of cross-cutting concerns through an application primarily via attributes.  The 10sec. version of how it works is this&#8230;it injects code in a post-compilation step.  This sounds scary, but it&#8217;s not.  In fact, this allows it to be extremely fast at runtime even if a small penalty is paid at compile-time.</p>
<p>In order to get PostSharp setup, it&#8217;s a simple download and install.  If you don&#8217;t want to install it on your machine, you can simply bin deploy it but it does require a tweak to your .proj file to get the post-compilation to work.  If you want to go that route, you can <a href="http://doc.postsharp.org/1.5/##PostSharp.HxS/UserGuide/Platform/EnablingPostSharp.html">find instructions here</a>.  At this point you will either follow those instructions or if you&#8217;ve installed directly, just include the following assemblies in your project:</p>
<ul>
<li>PostSharp.Laos.dll</li>
<li>PostSharp.Public.dll</li>
</ul>
<p><strong>The ScriptHook Attribute</strong><br />
PostSharp&#8217;s primary way of injecting an aspect is through attributes.  In our case we&#8217;re going to inherit from the OnMethodBoundaryAspect attribute in the PostSharp.Laos namespace.  This attribute exposes four virtual methods that allow injection of code at different points in the execution of a method:</p>
<ul>
<li>OnEntry</li>
<li>OnExit</li>
<li>OnException</li>
<li>OnSuccess</li>
</ul>
<p>Each of these methods accept a MethodExecutionEventArgs as an argument that provides access (including arguments) to the method on which the attribute is applied.  Here&#8217;s the ScriptHook attribute:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Serializable<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ScriptHookAttribute <span style="color: #008000;">:</span> OnMethodBoundaryAspect <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> ScriptEventTypes _scriptEventType<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> ScriptEventAttribute<span style="color: #000000;">&#40;</span>ScriptEventTypes scriptEventType<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        _scriptEventType <span style="color: #008000;">=</span> scriptEventType<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnSuccess<span style="color: #000000;">&#40;</span>MethodExecutionEventArgs eventArgs<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        var args <span style="color: #008000;">=</span> eventArgs.<span style="color: #0000FF;">GetReadOnlyArgumentArray</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        ScriptRunner.<span style="color: #0000FF;">ExecuteEvent</span><span style="color: #000000;">&#40;</span>_scriptEventType, args<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>For now, ignore the ScriptRunner reference, but notice that I&#8217;ve created an enum (ScriptEventTypes) that distinguishes different &#8220;types&#8221; of scripts to be run, by types, I mean different usages.  At some point you can switch on the type of event that&#8217;s occurring and change which scripts are loaded or how they are handled, etc.  You would use the attribute like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ScriptHook<span style="color: #000000;">&#40;</span>ScriptEventTypes.<span style="color: #0000FF;">ThingSaved</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> SaveThing<span style="color: #000000;">&#40;</span>Thing t<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>ScriptHook<span style="color: #000000;">&#40;</span>ScriptEventTypes.<span style="color: #0000FF;">ThingDeleted</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DeleteThing<span style="color: #000000;">&#40;</span>Thing t<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span></pre></div></div>

<p><strong>The ScriptRunner</strong><br />
At this point we&#8217;ve got the DLR available and we have the PostSharp attribute that&#8217;s injecting our hooks.  Now we need something to execute our scripts.  Enter the ScriptRunner:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> ScriptRunner <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> ExecuteEvent<span style="color: #000000;">&#40;</span>ScriptEventTypes scriptEventType, <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> eventContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
    IScriptEvent scriptEvent <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>scriptEventType<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">case</span> ScriptEventTypes.<span style="color: #0000FF;">ThingSaved</span><span style="color: #008000;">:</span>
	    scriptEvent <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThingSavedScriptEvent<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	    break<span style="color: #008000;">;</span>
	<span style="color: #0600FF;">case</span> ScriptEventTypes.<span style="color: #0000FF;">ThingDeleted</span><span style="color: #008000;">:</span>
	    scriptEvent <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThingDeletedScriptEvent<span style="color: #008000;">;</span>
	    break<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>scriptEvent <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">try</span> <span style="color: #000000;">&#123;</span>
                scriptEvent.<span style="color: #0000FF;">ExecuteScripts</span><span style="color: #000000;">&#40;</span>eventContext<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span> <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> ScriptExecutionExecption<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The runner is just a simple static class with a single ExecuteEvent method&#8230;it&#8217;s so simple in fact that it speaks for itself.  The one thing to note is the eventContext argument to the ExecuteEvent method.  If you look back at the ScriptHook attribute you can see that is&#8217; passing an object array from the MethodExecutionEventArgs instance.  This object array contains all the arguments to the executing method.  So for SaveThing() or DeleteThing() for example the eventContext array contains the instance of Thing that was passed.</p>
<p><strong>The IScriptEvent Classes</strong><br />
Lastly, we need something to actually grab the scripts and execute them in something like the context of the executing method.  So that&#8217;s where our example ThingSavedScriptEvent and ThingDeletedScriptEvent come in to play.  Here&#8217;s an example:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ThingSavedScriptEvent <span style="color: #008000;">:</span> IScriptEvent <span style="color: #000000;">&#123;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> ScriptRuntime _scriptRuntime<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> IThingRepository _thingRepo<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> ProjectCreatedScriptEvent<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        _thingRepo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ThingRepository<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        _scriptRuntime <span style="color: #008000;">=</span> ScriptRuntime.<span style="color: #0000FF;">CreateFromConfiguration</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> ExecuteScripts<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> contextValues<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        var thing <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>Thing<span style="color: #000000;">&#41;</span>contextValues.<span style="color: #0000FF;">SingleOrDefault</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x <span style="color: #008000;">is</span> Thing<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		var scriptScope <span style="color: #008000;">=</span> _scriptRuntime.<span style="color: #0000FF;">CreateScope</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        scriptScope.<span style="color: #0000FF;">SetVariable</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;thingRepo&quot;</span>, _thingRepo<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        scriptScope.<span style="color: #0000FF;">SetVariable</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;thing&quot;</span>, thing<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        var script <span style="color: #008000;">=</span> GetScript<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        var scriptEngine <span style="color: #008000;">=</span> _scriptRuntime.<span style="color: #0000FF;">GetEngine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;IronPython&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        scriptEngine.<span style="color: #0000FF;">Execute</span><span style="color: #000000;">&#40;</span>script, scriptScope<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> GetScript<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
        var script <span style="color: #008000;">=</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Empty</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">try</span> <span style="color: #000000;">&#123;</span>
            code <span style="color: #008000;">=</span> File.<span style="color: #0000FF;">ReadAllText</span><span style="color: #000000;">&#40;</span>HttpContext.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">Server</span>.<span style="color: #0000FF;">MapPath</span><span style="color: #000000;">&#40;</span>
                ConfigSettings.<span style="color: #0000FF;">ProjectTemplateStorePath</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;ThingSaved.py&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span> <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>FileNotFoundException<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">return</span> script<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The ScriptRuntime class is where the DLR magic happens.  We create an instance of it and then ask it for an engine that can execute IronPython scripts.  ScriptScope is a class used for constructing the scope that the script will have available to it.  Here for example we&#8217;re &#8220;passing&#8221; the &#8216;thingRepo&#8217; and &#8216;thing&#8217; variables into the script via the ScriptScope.  Lastly, we get the engine from the ScriptRuntime, pass it both the ScriptScope and the literal text of the script.  And that&#8217;s that&#8230;pretty easy eh?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2009/12/15/scriptability-via-the-dlr-and-postsharp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Reusable Test Scope Pattern</title>
		<link>http://www.thegrubbsian.com/2009/08/22/the-reusable-test-scope-pattern/</link>
		<comments>http://www.thegrubbsian.com/2009/08/22/the-reusable-test-scope-pattern/#comments</comments>
		<pubDate>Sun, 23 Aug 2009 00:31:27 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General Programming]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=251</guid>
		<description><![CDATA[I’m almost positive someone has come up with this pattern before, but it was a big help on a recent project so I thought I’d share it. The basic goal of the pattern is to make the setup and teardown work of test classes reusable. We found this to cause particular pain for integration tests [...]]]></description>
			<content:encoded><![CDATA[<p>I’m almost positive someone has come up with this pattern before, but it was a big help on a recent project so I thought I’d share it.  The basic goal of the pattern is to make the setup and teardown work of test classes reusable.  We found this to cause particular pain for integration tests written against a database where multiple dependent records needed to be created before the actual test could be performed.  The second goal was that these externalized bits of code would be composable so that tests requiring multiple setup resources could create just the right ones.</p>
<p>Before really describing the workflow of the pattern, here are the basic components of our implementation:</p>
<p><b>The ITestScope Interface</b></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> ITestScope <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">void</span> SetupScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">void</span> TeardownScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>These two methods (SetupScope and TeardownScope) are where we move all of the test setup and cleanup logic.  Any state that needs to be maintained between setup and teardown (i.e. needs to be available to the test itself) can be stored in public properties or fields on the class implementing ITestScope.</p>
<p><b>The TestBase Class</b></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> abstract <span style="color: #FF0000;">class</span> TestBase <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> abstract <span style="color: #0600FF;">void</span> ScopeSetup<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">public</span> abstract <span style="color: #0600FF;">void</span> ScopeTeardown<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Requiring that all test classes inherit from TestBase insures that at least developers will be considering the setup and cleanup of their tests.  The TestBase.ScopeSetup method would include instantiating and calling the TestScope.SetupScope methods for any scopes that are needed in the test class&#8230;likewise for teardown.</p>
<p><b>The TestFactory Class</b></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> TestFactory <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TRepository GetRepository<span style="color: #008000;">&lt;</span>TRepository<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> where TRepository <span style="color: #008000;">:</span> <span style="color: #FF0000;">class</span> <span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> TController GetController<span style="color: #008000;">&lt;</span>TController<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> where TController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span><span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This isn&#8217;t directly related to the scope pattern, but it&#8217;s invaluable as a point where you can use a DI container in the test project.  All repository or controllers (or other resources) can be obtained from here.</p>
<p><b>An Example</b></p>
<p>So here&#8217;s an example test class that might use this pattern.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerTestScope <span style="color: #008000;">:</span> ITestScope <span style="color: #000000;">&#123;</span>
&nbsp;
	<span style="color: #0600FF;">private</span> ICustomerRepository _customerRepo<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> Customer TestCustomer <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> <span style="color: #0600FF;">private</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> CustomerTestScope<span style="color: #000000;">&#40;</span>ICustomerRepository customerRepo<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		_customerRepo <span style="color: #008000;">=</span> customerRepo<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> SetupScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		TestCustomer <span style="color: #008000;">=</span> _customerRepo.<span style="color: #0000FF;">Create</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #008080; font-style: italic;">// Other complex test setup logic</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> TeardownScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		_customerRepo.<span style="color: #0000FF;">Delete</span><span style="color: #000000;">&#40;</span>TestCustomer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                <span style="color: #008080; font-style: italic;">// The reverse of the complex setup logic</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>TestClass<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerRepositoryTests <span style="color: #008000;">:</span> TestBase <span style="color: #000000;">&#123;</span>
&nbsp;
	<span style="color: #0600FF;">private</span> CustomerTestScope _customerScope<span style="color: #008000;">;</span>
	<span style="color: #0600FF;">private</span> ICustomerRepository _customerRepo<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>TestInitialize<span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> ScopeSetup<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
		_customerRepo <span style="color: #008000;">=</span> TestFactory.<span style="color: #0000FF;">GetRepository</span><span style="color: #008000;">&lt;</span>ICustomerRepository<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		_customerScope <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CustomerTestScope<span style="color: #000000;">&#40;</span>_customerRepo<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		_customerScope.<span style="color: #0000FF;">SetupScope</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>TestMethod<span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> SaveCustomer_ShouldRenameCustomer_WhenNewNameGiven<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
		_customerScope.<span style="color: #0000FF;">TestCustomer</span>.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;New Name&quot;</span><span style="color: #008000;">;</span>
		_customerRepo.<span style="color: #0000FF;">Save</span><span style="color: #000000;">&#40;</span>_customerScope.<span style="color: #0000FF;">TestCustomer</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		var customer <span style="color: #008000;">=</span> _customerRepo.<span style="color: #0000FF;">GetById</span><span style="color: #000000;">&#40;</span>_customerScope.<span style="color: #0000FF;">TestCustomer</span>.<span style="color: #0000FF;">ID</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		Assert.<span style="color: #0000FF;">IsTrue</span><span style="color: #000000;">&#40;</span>customer.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;New Name&quot;</span>, 
			<span style="color: #666666;">&quot;SaveCustomer failed to update customer name.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>TestCleanup<span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> ScopeTeardown<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		_customerScope.<span style="color: #0000FF;">TeardownScope</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>If additional scopes were needed then they could simple be added to the test class.  For example, if a ProductTestScope was also needed then it would be initialized just like the CustomerTestScope and torn down appropriately.  </p>
<p>Dependencies between scopes would be supplied via constructor parameters.  This does imply that the SetupScope methods be called in sequence and TeardownScope be called in reverse order.</p>
<p>That&#8217;s the pattern, pretty simple but now the logic for creating these setup conditions can be offloaded and reused in a simple way and we&#8217;ve made it easy to clean up that test data after the tests complete.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2009/08/22/the-reusable-test-scope-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Martin: A Lightweight REST Framework Inspired by Sinatra and MVC</title>
		<link>http://www.thegrubbsian.com/2009/07/02/martin-a-framework-inspired-by-sinatra/</link>
		<comments>http://www.thegrubbsian.com/2009/07/02/martin-a-framework-inspired-by-sinatra/#comments</comments>
		<pubDate>Thu, 02 Jul 2009 21:29:59 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Martin]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=228</guid>
		<description><![CDATA[Those of you who work in the Rails community will know something about Sinatra. It&#8217;s a lightweight web framework for building REST services in Ruby. I&#8217;m not a Ruby programmer (I know enough to be dangerous) but I really like the idea of Sinatra. The basic premise of Sinatra is that every method defines a [...]]]></description>
			<content:encoded><![CDATA[<p>Those of you who work in the Rails community will know something about Sinatra.  It&#8217;s a lightweight web framework for building REST services in Ruby.  I&#8217;m not a Ruby programmer (I know enough to be dangerous) but I really like the idea of Sinatra.  </p>
<p>The basic premise of Sinatra is that every method defines a route, and a route (URL + Verb) invokes a single method.  Ruby, being a dynamic language, makes this extremely easy.  Like I said I&#8217;m no Ruby guru but the built-in introspection of the language makes it easier to build a DSL that can describe these route methods.</p>
<p>Martin, isn&#8217;t at all a port of Sinatra.  Rather it&#8217;s inspired by the lightweight nature of Sinatra and it&#8217;s general pattern.  Martin relies on the new System.Web.Routing namespace in .NET 3.5 SP1 and will eventually ship with a DSL that will encapsulate defining your RouteTable.  Because it doesn&#8217;t have any external dependencies and really doesn&#8217;t need any templates it can plug into any ASP.NET or ASP.NET MVC project and live along side just fine*.</p>
<p>In Martin, the first step to creating a new action is defining it with the Config API.  At this point it&#8217;s excruciatingly simple.</p>
<p>In Global.asax:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    Config.<span style="color: #0000FF;">AddAction</span><span style="color: #008000;">&lt;</span>DateAction<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show/CurrentDate&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>What this does is maps the URL: http://domain.com/Show/CurrentDate to the DateAction.Get() method.  Behind the scenes there is a factory class that&#8217;s constructing instances of DateAction, calling the Get() method, and then responding with the result to the request pipeline.</p>
<p>The DateAction class looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DateAction <span style="color: #008000;">:</span> ActionBase <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> IResponse Get<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> Text<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;The current date is {0}.&quot;</span>, DateTime.<span style="color: #0000FF;">Now</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>There are four methods on ActionBase that can be overridden: Get(), Post(), Put(), and Delete().  Each method (obviously) corresponds to an HTTP Verb and only requests using that verb will invoke the appropriate method.  So, the same URL pattern can be mapped to two different methods provided that the request uses different verbs.</p>
<p>The ActionBase class provides a way to get access to any RouteData or Request items that might be part of the request.  Using the ValueOf<T>(String key) method you can find for example an ID that&#8217;s tacked on to the URL or a piece of data from the querystring or form collection.</p>
<p>~~</p>
<p>For now the project is in a very early stage, no real sample, no real documentation.  However, it&#8217;s so simple that reading through the handful of classes that make up the project is almost all the documentation you&#8217;ll need.  If you get a chance, poke around and let me know what you think&#8230;if you want to help make it better just let me know and I&#8217;ll get you commit rights to the Google Code repo.</p>
<p>Source at: <a href="http://code.google.com/p/martin-framework/">http://code.google.com/p/martin-framework/</a></p>
<p>* In the case of integration with ASP.NET MVC the routes defined by Martin and those your application might need could conflict so care must be taken to insure there are no collisions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2009/07/02/martin-a-framework-inspired-by-sinatra/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Server Block Formatting in Visual Studio</title>
		<link>http://www.thegrubbsian.com/2009/04/22/server-block-formatting-in-visual-studio/</link>
		<comments>http://www.thegrubbsian.com/2009/04/22/server-block-formatting-in-visual-studio/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 21:04:54 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[General Programming]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=183</guid>
		<description><![CDATA[This is one of those more-for-me-than-you posts. If you&#8217;re working with ASP.NET MVC (or god help you ASP Classic) you&#8217;ll likely be annoyed by the way server blocks are formatted in Visual Studio. In particular closing curly braces seem to throw the formatting engine a real curve-ball. For example, you type something like this: &#60;% [...]]]></description>
			<content:encoded><![CDATA[<p>This is one of those more-for-me-than-you posts.</p>
<p>If you&#8217;re working with ASP.NET MVC (or god help you ASP Classic) you&#8217;ll likely be annoyed by the way server blocks are formatted in Visual Studio.  In particular closing curly braces seem to throw the formatting engine a real curve-ball.  For example, you type something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;%</span> <span style="color: #000000;">&#125;</span> <span style="color: #008000;">%&gt;</span></pre></div></div>

<p>But after slapping return, you ultimately get this lovely thing:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;%</span>
       <span style="color: #000000;">&#125;</span>
     <span style="color: #008000;">%&gt;</span></pre></div></div>

<p>Thanks Visual Studio!</p>
<p>So how do we fix this.  Well, you&#8217;d like it if hitting Ctrl+K+D took care of this for you, but apparently that ignores server blocks.  Next you&#8217;ll hunt and peck your way through the mounds of Visual Studio options in Tools > Options&#8230;but that search will ultimately prove fruitless.  Finally, you&#8217;ll turn to the humble macro&#8230;I know macro can be a dirty word but in this case it&#8217;s really your only option.</p>
<p>Here&#8217;s how this goes:</p>
<p>1. Mouse over to Tools > Macros > Macro IDE<br />
2. Notice that Visual Studio macros are in Visual Basic&#8230;really? I know&#8230;but go with it.<br />
3. Right-click &#8216;My Macros&#8217;<br />
4. Choose &#8216;Add New Item&#8217;<br />
5. Choose &#8216;Module&#8217; in the dialog<br />
6. Enter the following method in the newly created Module:</p>

<div class="wp_syntax"><div class="code"><pre class="vb" style="font-family:monospace;"><span style="color: #000080;">Public</span> Module FormatCurrentFile
&nbsp;
    <span style="color: #000080;">Sub</span> FixServerBlocks()
        <span style="color: #000080;">Dim</span> selection <span style="color: #000080;">As</span> TextSelection = DTE.ActiveDocument.Selection
        <span style="color: #000080;">Dim</span> fixed <span style="color: #000080;">As</span> <span style="color: #000080;">String</span> = <span style="color: #800000;">&quot;&lt;% } %&gt;&quot;</span>
        <span style="color: #000080;">Dim</span> regex <span style="color: #000080;">As</span> <span style="color: #000080;">String</span> = <span style="color: #800000;">&quot;\&lt;\%:Wh*\}:Wh*\%\&gt;&quot;</span>
        <span style="color: #000080;">While</span> selection.FindPattern(regex, vsFindOptions.vsFindOptionsRegularExpression)
            selection.ReplacePattern(regex, fixed, vsFindOptions.vsFindOptionsRegularExpression)
        <span style="color: #000080;">End</span> <span style="color: #000080;">While</span>
    <span style="color: #000080;">End</span> <span style="color: #000080;">Sub</span>
&nbsp;
<span style="color: #000080;">End</span> Module</pre></div></div>

<p>Now you can go through Tools > Options > Keyboard and map a key command to this macro&#8230;I chose Ctrl+K+C for example since it&#8217;s close to the other magic formatting keys that you&#8217;ll want to run right before the macro.  There you have it.</p>
<p><i>Thanks to some help from StackOverflow.com for this solution: <a href="http://stackoverflow.com/questions/720042">http://stackoverflow.com/questions/720042</a></i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2009/04/22/server-block-formatting-in-visual-studio/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easy &#8220;LIKE&#8221; Operations in LINQ to SQL</title>
		<link>http://www.thegrubbsian.com/2009/03/06/easy-like-operations-in-linq-to-sql/</link>
		<comments>http://www.thegrubbsian.com/2009/03/06/easy-like-operations-in-linq-to-sql/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 19:18:32 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=166</guid>
		<description><![CDATA[There are two basic ways to do LIKE operations in LINQ to SQL queries&#8230;the easy way and the hard way.  The hard way consists of copious usage of String.StartsWith, String.Contains, and String.EndsWith.  The easy way takes advantage of a handy class called SqlMethods found in the System.Data.Linq.SqlClient namespace. Using the SqlMethods.Like() method, you can do the following: [...]]]></description>
			<content:encoded><![CDATA[<p>There are two basic ways to do LIKE operations in LINQ to SQL queries&#8230;the easy way and the hard way.  The hard way consists of copious usage of String.StartsWith, String.Contains, and String.EndsWith.  The easy way takes advantage of a handy class called <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.sqlclient.sqlmethods_methods.aspx">SqlMethods</a> found in the System.Data.Linq.SqlClient namespace.</p>
<p>Using the SqlMethods.Like() method, you can do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var keyword <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Marshmal&quot;</span><span style="color: #008000;">;</span>
var things <span style="color: #008000;">=</span> from thing <span style="color: #0600FF;">in</span> db.<span style="color: #0000FF;">Things</span>
                     where SqlMethods.<span style="color: #0000FF;">Like</span><span style="color: #000000;">&#40;</span>thing.<span style="color: #0000FF;">Name</span>, keyword<span style="color: #000000;">&#41;</span>
                     select thing<span style="color: #008000;">;</span></pre></div></div>

<p>And if you want to search the start, middle, or end of your string, just tack on the &#8216;%&#8217; as you would in any normal SQL statement:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var keyword <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;mallow&quot;</span><span style="color: #008000;">;</span>
var things <span style="color: #008000;">=</span> from thing <span style="color: #0600FF;">in</span> db.<span style="color: #0000FF;">Things</span>
                     where SqlMethods.<span style="color: #0000FF;">Like</span><span style="color: #000000;">&#40;</span>thing.<span style="color: #0000FF;">Name</span>, <span style="color: #666666;">&quot;%&quot;</span> <span style="color: #008000;">+</span> keyword<span style="color: #000000;">&#41;</span>
                     select thing<span style="color: #008000;">;</span></pre></div></div>

<p>And there you have it&#8230;an easy way to find your marshmallows.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2009/03/06/easy-like-operations-in-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic Expressions with LINQ to Entities</title>
		<link>http://www.thegrubbsian.com/2008/12/01/dynamic-expressions-with-linq-to-entities/</link>
		<comments>http://www.thegrubbsian.com/2008/12/01/dynamic-expressions-with-linq-to-entities/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 09:47:09 +0000</pubDate>
		<dc:creator>JC Grubbs</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://www.thegrubbsian.com/?p=108</guid>
		<description><![CDATA[There&#39;s been a lot of buzz lately around LINQ to Entities (aka Entity Framework).&#0160; Some of the buzz has been positive, a lot has been negative, but it does appear that Microsoft will invest a lot in LINQ to Entities moving forward.&#0160; On a recent side project I had occasion to use EF to connect [...]]]></description>
			<content:encoded><![CDATA[<p>There&#39;s been a lot of buzz lately around LINQ to Entities (aka Entity Framework).&#0160; Some of the buzz has been positive, a lot has been negative, but it does appear that Microsoft will invest a lot in LINQ to Entities moving forward.&#0160; On a recent side project I had occasion to use EF to connect to a SQLite database running locally within a web application.&#0160; It&#39;s an interesting little architecture and despite it&#39;s obvious scaling issues, it&#39;s working really well for the problem space.</p>
<p>Anyway, one of the features I needed was search&#8230;and not just any search, a very dynamic search.&#0160; The application is an inventory tracking system and it allows a user to set up different kinds of items and create a unique list of properties that each of those items can have.&#0160; For example you might create an item of type &#39;Widget&#39; with two properties &#39;Size&#39; and &#39;Color&#39;.&#0160; Another type might be &#39;Bobble&#39; and it has properties &#39;Width&#39;, &#39;Volume&#39;, and &#39;Friction Coefficient&#39;.&#0160; So in order to search for these types I&#39;m forced to dynamically construct a search screen.</p>
<p>This dynamic search screen is where the issue comes in.&#0160; Because I&#39;m searching an indiscriminate number of properties and I don&#39;t know at compile time what those properties are, I need to execute some type of dynamic query.&#0160; Those of you who are familiar with LINQ will know that this is easier said than done.&#0160; It&#39;s not like I can just construct a SQL statement at runtime and then pass it to the database for execution.&#0160; Enter the System.Linq.Dynamic namespace.</p>
<p>I found <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx">this blog post</a> by ScottGu on the exact subject.&#0160; (The post is labeled Part 1 but I haven&#39;t been able to find a Part 2 anywhere&#8230;if you find it let me know.)&#0160; His post will point you to where you can download the source for the System.Linq.Dynamic assembly which you&#39;ll need to build and include in your project.&#0160; I did see mentioned that this is part of .NET 3.5 SP1, however I was unable to find it on my system.</p>
<p>Once you have the library referenced it becomes quite a bit simpler to generate a query at runtime.&#0160; The library parses an expression syntax that&#39;s pretty simple.&#0160; The primary use for generating queries at runtime is going to be setting up WHERE conditions; you can however create an entire query dynamically if you need to.&#0160; Here&#39;s an example of a LINQ query as it would be written at design time:</p>
<p style="font-size: 12px; font-family: Courier;">var items = (from InventoryItem item in db.InventoryItem<br />&#0160;&#0160;&#0160; &#0160;&#0160;&#0160; &#0160;&#0160;&#0160;&#0160; where item.Category.ID = 7<br />&#0160;&#0160;&#0160;&#0160;&#0160;&#0160;&#0160;&#0160;&#0160;&#0160;&#0160;&#0160; select item).ToList&lt;InventoryItem&gt;();</p>
<p>This is a pretty innocuous query and doesn&#39;t really warrent being turned into a dynamic query but for example&#39;s sake, here&#39;s how you&#39;d write it:</p>
<p style="font-family: Courier;">var items = db.InventoryItem.Where(&quot;Category.ID = @0&quot;, 7).ToList&lt;InventoryItem&gt;();</p>
<p>It&#39;s really that simple.&#0160; After you include System.Linq.Dynamic in your using statements a new overload of the Where method is available.&#0160; This new version of Where takes a string predicate (the where statement) and an array of objects that are parameters for the query string.</p>
<p>Because you don&#39;t have the benefit of type safety within the query string, you&#39;ll have to be careful with your syntax.&#0160; For example, when using a property of a property (item.Category.ID in the above example) you have to remember to use the names you&#39;ve assigned to entities in your model not the names in the underlying data source.</p>
<p>There are other ways to create a query dynamically including using <a href="http://msdn.microsoft.com/en-us/library/bb345303.aspx">ObjectQuery&lt;T&gt;</a>, or building up predicates in a pseudo-recursive way as in <a href="http://www.albahari.com/nutshell/predicatebuilder.aspx">this post</a> from the <em>C# 3.0 in a Nutshell</em> guys.&#0160; However, I find the dynamic query method here to be easy to understand and very powerful.</p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.thegrubbsian.com/2008/12/01/dynamic-expressions-with-linq-to-entities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
