<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Chris Cavanagh&#039;s Blog</title>
	<atom:link href="http://chriscavanagh.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://chriscavanagh.wordpress.com</link>
	<description>Happy coding</description>
	<lastBuildDate>Mon, 20 May 2013 21:25:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='chriscavanagh.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Chris Cavanagh&#039;s Blog</title>
		<link>http://chriscavanagh.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://chriscavanagh.wordpress.com/osd.xml" title="Chris Cavanagh&#039;s Blog" />
	<atom:link rel='hub' href='http://chriscavanagh.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Twin Cities Code Camp 2013</title>
		<link>http://chriscavanagh.wordpress.com/2013/03/09/twin-cities-code-camp-2013/</link>
		<comments>http://chriscavanagh.wordpress.com/2013/03/09/twin-cities-code-camp-2013/#comments</comments>
		<pubDate>Sat, 09 Mar 2013 16:04:22 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=788</guid>
		<description><![CDATA[TCCC14 (off-by-one error?) takes place on April 27th.&#160; Go register!&#160; Even if you just want the free breakfast (donuts, coffee… what more does a geek need?), campus atmosphere and chance to win prizes, do it! &#160; It doesn’t even matter if some of the presentations aren’t in your usual fields; if you can’t decide, go [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=788&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>TCCC14 (off-by-one error?) takes place on April 27th.&#160; Go register!&#160; Even if you just want the free breakfast (donuts, coffee… what more does a geek need?), campus atmosphere and chance to win prizes, do it! <img class="wlEmoticon wlEmoticon-smile" style="border-style:none;" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2013/03/wlemoticon-smile.png?w=490" />&#160; It doesn’t even matter if some of the presentations aren’t in your usual fields; if you can’t decide, go to a random or fun-looking one!</p>
<p><a title="http://www.twincitiescodecamp.com/TCCC/Default.aspx" href="http://www.twincitiescodecamp.com/TCCC/Default.aspx">http://www.twincitiescodecamp.com/TCCC/Default.aspx</a></p>
<p>I’ve been to the last two, and they’re great!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/788/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/788/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=788&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2013/03/09/twin-cities-code-camp-2013/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2013/03/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>
	</item>
		<item>
		<title>Multiplayer Physics with Raspberry Pi</title>
		<link>http://chriscavanagh.wordpress.com/2013/01/22/multiplayer-physics-with-raspberry-pi/</link>
		<comments>http://chriscavanagh.wordpress.com/2013/01/22/multiplayer-physics-with-raspberry-pi/#comments</comments>
		<pubDate>Tue, 22 Jan 2013 15:11:12 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[RPi]]></category>
		<category><![CDATA[socket.io]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=774</guid>
		<description><![CDATA[Update: Source code now available on github, and also as an npm package! What happens when you put node.js and socket.io on a Raspberry Pi, then use them as goop between Box2D (physics engine) demos? All kinds of awesome &#8211; Try it here (not sure how long I’ll keep this running, so get it while [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=774&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><strong>Update:</strong> Source code now available on <a title="Box2DWeb Multiplayer demo" href="https://github.com/BobStrogg/box2dweb-multiplayer-demo" target="_blank">github</a>, and also as an <a title="Box2DWeb Multiplayer demo in npm repository" href="https://npmjs.org/package/box2dweb-multiplayer-demo" target="_blank">npm package</a>!</p>
<p>What happens when you put <a title="node.js" href="http://nodejs.org" target="_blank">node.js</a> and <a title="socket.io" href="http://socket.io" target="_blank">socket.io</a> on a <a title="http://www.raspberrypi.org" href="http://www.raspberrypi.org" target="_blank">Raspberry Pi</a>, then use them as goop between <a title="Box2DWeb" href="http://code.google.com/p/box2dweb/" target="_blank">Box2D</a> (physics engine) demos?</p>
<p>All kinds of awesome <img class="wlEmoticon wlEmoticon-smile" style="border-style:none;" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2013/01/wlemoticon-smile.png?w=490" /> &#8211; Try it <a title="Box2DWeb physics with node.js +socket.io on Raspberry Pi" href="http://bobstrogg.no-ip.org:8080/demo.html" target="_blank">here</a> (not sure how long I’ll keep this running, so get it while it’s hot).</p>
<p>Open it in two browsers, and see how long you can keep them in sync.</p>
<p><a title="Multiplayer Box2DWeb (node.js + socket.io on Raspberry Pi)" href="http://bobstrogg.no-ip.org:8080/demo.html" target="_blank"><img title="image" style="background-image:none;padding-top:0;padding-left:0;display:inline;padding-right:0;border-width:0;" border="0" alt="image" src="http://chriscavanagh.files.wordpress.com/2013/01/image1.png?w=450&#038;h=459" width="450" height="459" /></a></p>
<p>You can find the source on <a title="Box2DWeb Multiplayer demo" href="https://github.com/BobStrogg/box2dweb-multiplayer-demo" target="_blank">github</a>, and also as an <a title="Box2DWeb Multiplayer demo in npm repository" href="https://npmjs.org/package/box2dweb-multiplayer-demo" target="_blank">npm package</a>.</p>
<p><img class="wlEmoticon wlEmoticon-smile" style="border-style:none;" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2013/01/wlemoticon-smile.png?w=490" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/774/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/774/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=774&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2013/01/22/multiplayer-physics-with-raspberry-pi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2013/01/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2013/01/image1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2013/01/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>
	</item>
		<item>
		<title>Modifying LINQ to SQL command text without Reflection</title>
		<link>http://chriscavanagh.wordpress.com/2012/07/06/modifying-linq-to-sql-command-text-without-reflection/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/07/06/modifying-linq-to-sql-command-text-without-reflection/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 16:05:02 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=757</guid>
		<description><![CDATA[Following my post last year about modifying LINQ to SQL command text (evil, as it calls private methods through reflection) here’s an equally evil, but faster version that pre-compiles most of its work through an expression tree: public delegate string ModifyCommandDelegate( string commandText, IDictionary&#60;string, object&#62; parameters ); public class DataContextInterceptor { private DataContext dc; private [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=757&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Following my post last year about <a title="Modifying LINQ to SQL command text" href="http://chriscavanagh.wordpress.com/2011/03/12/manipulating-linq-to-sql-command-text/" target="_blank">modifying LINQ to SQL command text</a> (evil, as it calls private methods through reflection) here’s an equally evil, but faster version that pre-compiles most of its work through an expression tree:</p>
<pre class="code"><span style="color:blue;">public delegate string </span><span style="color:#2b91af;">ModifyCommandDelegate</span>( <span style="color:blue;">string </span>commandText, <span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; parameters );

<span style="color:blue;">public class </span><span style="color:#2b91af;">DataContextInterceptor
</span>{
    <span style="color:blue;">private </span><span style="color:#2b91af;">DataContext </span>dc;
    <span style="color:blue;">private object </span>oldProvider;
    <span style="color:blue;">private </span><span style="color:#2b91af;">Type </span>providerType;
    <span style="color:blue;">private </span><span style="color:#2b91af;">ModifyCommandDelegate </span>modifyCommand;

    <span style="color:blue;">private static </span><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">ModifyCommandDelegate</span>, <span style="color:#2b91af;">DataContext</span>, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:blue;">object</span>&gt;&gt; CompileFactory = CreateCompileFactory().Compile();
    <span style="color:blue;">private static </span><span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">ModifyCommandDelegate</span>, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:#2b91af;">IExecuteResult</span>&gt;&gt; ExecuteFactory = CreateExecuteFactory().Compile();

    <span style="color:blue;">public static </span>TDataContext Intercept&lt;TDataContext&gt;( TDataContext dc, <span style="color:#2b91af;">ModifyCommandDelegate </span>modifyCommand )
        <span style="color:blue;">where </span>TDataContext : <span style="color:#2b91af;">DataContext
    </span>{
        <span style="color:blue;">new </span><span style="color:#2b91af;">DataContextInterceptor</span>( dc, modifyCommand );

        <span style="color:green;">//            typeof( Expression ).GetProperty( &quot;DebugView&quot;, BindingFlags.Instance | BindingFlags.NonPublic ).GetValue( executeFactoryExp, null ).Dump();

        </span><span style="color:blue;">return </span>dc;
    }

    <span style="color:blue;">public </span>DataContextInterceptor( <span style="color:#2b91af;">DataContext </span>dc, <span style="color:#2b91af;">ModifyCommandDelegate </span>modifyCommand )
    {
        <span style="color:blue;">this</span>.dc = dc;
        <span style="color:blue;">this</span>.modifyCommand = modifyCommand;

        <span style="color:#2b91af;">FieldInfo </span>providerField = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">DataContext </span>).GetField( <span style="color:#a31515;">&quot;provider&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>existingProvider = providerField.GetValue( dc );

        <span style="color:blue;">if </span>( existingProvider <span style="color:blue;">is </span><span style="color:#2b91af;">IProviderProxy </span>)
        {
            <span style="color:green;">// System.Diagnostics.Trace.WriteLine( string.Format( &quot;DataContext {0} already intercepted&quot;, dc.GetHashCode() ) );
        </span>}
        <span style="color:blue;">else
        </span>{
            oldProvider = existingProvider;

            <span style="color:blue;">var </span>proxy = <span style="color:blue;">new </span><span style="color:#2b91af;">ProviderProxy</span>( <span style="color:blue;">this</span>, oldProvider ).GetTransparentProxy();

            providerField.SetValue( dc, proxy );

            <span style="color:green;">// System.Diagnostics.Trace.WriteLine( string.Format( &quot;DataContext {0} intercepted&quot;, dc.GetHashCode() ) );
        </span>}
    }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">MethodCallExpression </span>MakeMethodCall( <span style="color:#2b91af;">Type </span>type, <span style="color:blue;">string </span>methodName, <span style="color:blue;">params </span><span style="color:#2b91af;">Expression</span>[] arguments )
    {
        <span style="color:green;">// ( &quot;Making MethodCallExpression for &quot; + methodName ).Dump();

        </span><span style="color:blue;">var </span>methodInfo = type.GetMethod(
            methodName,
            <span style="color:#2b91af;">BindingFlags</span>.Static | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic,
            <span style="color:blue;">null</span>,
            arguments.Select( a =&gt; a.Type ).ToArray(),
            <span style="color:blue;">null </span>);

        <span style="color:blue;">if </span>( methodInfo == <span style="color:blue;">null </span>) <span style="color:blue;">throw new </span><span style="color:#2b91af;">ArgumentException</span>( <span style="color:blue;">string</span>.Format( <span style="color:#a31515;">&quot;Unable to find method {0}.{1}&quot;</span>, type.Name, methodName ), <span style="color:#a31515;">&quot;methodName&quot; </span>);

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Call( methodInfo, arguments );
    }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">MethodCallExpression </span>MakeMethodCall( <span style="color:#2b91af;">Expression </span>instance, <span style="color:blue;">string </span>methodName, <span style="color:blue;">params </span><span style="color:#2b91af;">Expression</span>[] arguments )
    {
        <span style="color:green;">// ( &quot;Making MethodCallExpression for &quot; + instance.ToString() + &quot;.&quot; + methodName ).Dump();

        </span><span style="color:blue;">var </span>methodInfo = instance.Type.GetMethod(
            methodName,
            <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic,
            <span style="color:blue;">null</span>,
            arguments.Select( a =&gt; a.Type ).ToArray(),
            <span style="color:blue;">null </span>);

        <span style="color:blue;">if </span>( methodInfo == <span style="color:blue;">null </span>) <span style="color:blue;">throw new </span><span style="color:#2b91af;">ArgumentException</span>( <span style="color:blue;">string</span>.Format( <span style="color:#a31515;">&quot;Unable to find method {0}.{1}&quot;</span>, instance.Type.Name, methodName ), <span style="color:#a31515;">&quot;methodName&quot; </span>);

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Call( instance, methodInfo, arguments );
    }

    <span style="color:blue;">protected internal object </span>Compile( <span style="color:#2b91af;">Expression </span>query )
    {
        <span style="color:blue;">return </span><span style="color:#2b91af;">DataContextInterceptor</span>.CompileFactory( oldProvider, modifyCommand, dc )( query );
    }

    <span style="color:blue;">protected internal virtual </span><span style="color:#2b91af;">IExecuteResult </span>Execute( <span style="color:#2b91af;">Expression </span>query )
    {
        <span style="color:blue;">return </span><span style="color:#2b91af;">DataContextInterceptor</span>.ExecuteFactory( oldProvider, modifyCommand )( query );
    }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">ModifyCommandDelegate</span>, <span style="color:#2b91af;">DataContext</span>, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:blue;">object</span>&gt;&gt;&gt; CreateCompileFactory()
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>providerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>);
        <span style="color:blue;">var </span>providerParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:blue;">object </span>), <span style="color:#a31515;">&quot;provider&quot; </span>);
        <span style="color:blue;">var </span>modifyCommandParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ModifyCommandDelegate </span>), <span style="color:#a31515;">&quot;modifyCommand&quot; </span>);
        <span style="color:blue;">var </span>dataContextParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">DataContext </span>), <span style="color:#a31515;">&quot;dataContext&quot; </span>);

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">ModifyCommandDelegate</span>, <span style="color:#2b91af;">DataContext</span>, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:blue;">object</span>&gt;&gt;&gt;(
            CreateCompileMethod( <span style="color:#2b91af;">Expression</span>.Convert( providerParam, providerType ), modifyCommandParam, dataContextParam ),
            providerParam,
            modifyCommandParam,
            dataContextParam );
    }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:blue;">object</span>&gt;&gt; CreateCompileMethod( <span style="color:#2b91af;">Expression </span>oldProvider, <span style="color:#2b91af;">Expression </span>modifyCommand, <span style="color:#2b91af;">Expression </span>dataContextParam )
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>providerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.Provider.IProvider&quot; </span>);
        <span style="color:blue;">var </span>funcletizerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.Funcletizer&quot; </span>);
        <span style="color:blue;">var </span>annotationsType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlNodeAnnotations&quot; </span>);
        <span style="color:blue;">var </span>queryInfoType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;QueryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>readerFactoryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.IObjectReaderFactory&quot; </span>);
        <span style="color:blue;">var </span>resultShapeType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;ResultShape&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>compiledSubQueryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.ICompiledSubQuery&quot; </span>);
        <span style="color:blue;">var </span>typeSystemType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.TypeSystem&quot; </span>);
        <span style="color:blue;">var </span>compiledQueryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider+CompiledQuery&quot; </span>);

        <span style="color:blue;">var </span>queryParam = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">Expression </span>), <span style="color:#a31515;">&quot;query&quot; </span>);

        <span style="color:blue;">var </span>providerField = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">DataContext </span>).GetField( <span style="color:#a31515;">&quot;provider&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );

        <span style="color:blue;">var </span>annotationsVar = <span style="color:#2b91af;">Expression</span>.Variable( annotationsType, <span style="color:#a31515;">&quot;annotations&quot; </span>);
        <span style="color:blue;">var </span>queriesVar = <span style="color:#2b91af;">Expression</span>.Variable( queryInfoType.MakeArrayType(), <span style="color:#a31515;">&quot;queries&quot; </span>);
        <span style="color:blue;">var </span>infoVar = <span style="color:#2b91af;">Expression</span>.Variable( queryInfoType, <span style="color:#a31515;">&quot;info&quot; </span>);
        <span style="color:blue;">var </span>lambdaVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">LambdaExpression </span>), <span style="color:#a31515;">&quot;lambda&quot; </span>);
        <span style="color:blue;">var </span>readerFactoryVar = <span style="color:#2b91af;">Expression</span>.Variable( readerFactoryType, <span style="color:#a31515;">&quot;readerFactory&quot; </span>);
        <span style="color:blue;">var </span>subQueriesVar = <span style="color:#2b91af;">Expression</span>.Variable( compiledSubQueryType.MakeArrayType(), <span style="color:#a31515;">&quot;subQueries&quot; </span>);
        <span style="color:blue;">var </span>resultShapeVar = <span style="color:#2b91af;">Expression</span>.Variable( resultShapeType, <span style="color:#a31515;">&quot;resultShape&quot; </span>);
        <span style="color:blue;">var </span>returnTarget = <span style="color:#2b91af;">Expression</span>.Label( compiledQueryType );

        <span style="color:blue;">var </span>getQuery = MakeMethodCall( infoVar, <span style="color:#a31515;">&quot;get_Query&quot; </span>);
        <span style="color:blue;">var </span>getResultType = MakeMethodCall( infoVar, <span style="color:#a31515;">&quot;get_ResultType&quot; </span>);
        <span style="color:blue;">var </span>getResultElementType = MakeMethodCall( typeSystemType, <span style="color:#a31515;">&quot;GetElementType&quot;</span>, getResultType );
        <span style="color:blue;">var </span>modifySubQueries = CreateModifySubQueriesMethod();
        <span style="color:blue;">var </span>compiledQueryConstructor = compiledQueryType.GetConstructors( <span style="color:#2b91af;">BindingFlags</span>.NonPublic | <span style="color:#2b91af;">BindingFlags</span>.Instance ).First();

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:blue;">object</span>&gt;&gt;(
            <span style="color:#2b91af;">Expression</span>.Block(
                <span style="color:blue;">new</span>[] { annotationsVar, queriesVar, infoVar, lambdaVar, readerFactoryVar, subQueriesVar, resultShapeVar },

                <span style="color:green;">// this.InitializeProviderMode();
                </span>MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;InitializeProviderMode&quot; </span>),

                <span style="color:green;">// SqlNodeAnnotations annotations = new SqlNodeAnnotations();
                </span><span style="color:#2b91af;">Expression</span>.Assign( annotationsVar, <span style="color:#2b91af;">Expression</span>.New( annotationsType ) ),

                <span style="color:green;">// QueryInfo[] queries = this.BuildQuery( query, annotations );
                </span><span style="color:#2b91af;">Expression</span>.Assign( queriesVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;BuildQuery&quot;</span>, queryParam, annotationsVar ) ),

                <span style="color:green;">// var info = ModifyQueries( (IEnumerable)queries );
                </span><span style="color:#2b91af;">Expression</span>.Assign( infoVar, <span style="color:#2b91af;">Expression</span>.Invoke( CreateModifyQueriesMethod(), queriesVar, modifyCommand ) ),

                <span style="color:green;">// this.CheckSqlCompatibility(queries, annotations);
                </span>MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;CheckSqlCompatibility&quot;</span>, queriesVar, annotationsVar ),

                <span style="color:green;">// var lambda = query as LambdaExpression;
                </span><span style="color:#2b91af;">Expression</span>.Assign( lambdaVar, <span style="color:#2b91af;">Expression</span>.TypeAs( queryParam, lambdaVar.Type ) ),

                <span style="color:green;">// if ( lambda != null )
                </span><span style="color:#2b91af;">Expression</span>.IfThen(
                    <span style="color:#2b91af;">Expression</span>.NotEqual( lambdaVar, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null </span>) ),
                    <span style="color:green;">// query = lambda.Body;
                    </span><span style="color:#2b91af;">Expression</span>.Assign( queryParam, <span style="color:#2b91af;">Expression</span>.Property( lambdaVar, <span style="color:#a31515;">&quot;Body&quot; </span>) ) ),

                <span style="color:green;">// IObjectReaderFactory readerFactory = null;
                // ICompiledSubQuery[] subQueries = null;

                // QueryInfo info = queries[queries.Length - 1];
                // info defined above
                // var resultShape = (int)Invoke( info, &quot;get_ResultShape&quot; );
                </span><span style="color:#2b91af;">Expression</span>.Assign( resultShapeVar, MakeMethodCall( infoVar, <span style="color:#a31515;">&quot;get_ResultShape&quot; </span>) ),

                <span style="color:#2b91af;">Expression</span>.Switch(
                    <span style="color:#2b91af;">Expression</span>.Convert( resultShapeVar, <span style="color:blue;">typeof</span>( <span style="color:blue;">int </span>) ),
                    <span style="color:green;">// if ( resultShape == 1 /* ResultShape.Singleton */ )
                    </span><span style="color:#2b91af;">Expression</span>.SwitchCase(
                        <span style="color:#2b91af;">Expression</span>.Block(
                            <span style="color:green;">// subQueries = this.CompileSubQueries( info.Query );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( subQueriesVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, getQuery ) ),
                            <span style="color:green;">// ModifySubQueries( (IEnumerable)subQueries );
                            </span><span style="color:#2b91af;">Expression</span>.Invoke( modifySubQueries, subQueriesVar, modifyCommand ),
                            <span style="color:green;">// readerFactory = this.GetReaderFactory( info.Query, info.ResultType );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( readerFactoryVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, getQuery, getResultType ) ),
                            <span style="color:#2b91af;">Expression</span>.Empty() ),
                        <span style="color:#2b91af;">Expression</span>.Constant( 1 ) ),
                    <span style="color:green;">// else if ( resultShape == 2 /* ResultShape.Sequence */ )
                    </span><span style="color:#2b91af;">Expression</span>.SwitchCase(
                        <span style="color:#2b91af;">Expression</span>.Block(
                            <span style="color:green;">// subQueries = this.CompileSubQueries( info.Query );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( subQueriesVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, getQuery ) ),
                            <span style="color:green;">// ModifySubQueries( (IEnumerable)subQueries );
                            </span><span style="color:#2b91af;">Expression</span>.Invoke( modifySubQueries, subQueriesVar, modifyCommand ),
                            <span style="color:green;">// readerFactory = this.GetReaderFactory( info.Query, TypeSystem.GetElementType( info.ResultType ) );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( readerFactoryVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, getQuery, getResultElementType ) ),
                            <span style="color:#2b91af;">Expression</span>.Empty() ),
                        <span style="color:#2b91af;">Expression</span>.Constant( 2 ) ) ),

                <span style="color:green;">// dc.provider = oldProvider;    // (Unfortunately needed to ensure compilation runs)
                </span><span style="color:#2b91af;">Expression</span>.Assign( <span style="color:#2b91af;">Expression</span>.MakeMemberAccess( dataContextParam, providerField ), oldProvider ),

                <span style="color:green;">// return new CompiledQuery( oldProvider, query, queries, readerFactory, subQueries );
                </span><span style="color:#2b91af;">Expression</span>.Return( returnTarget, <span style="color:#2b91af;">Expression</span>.New( compiledQueryConstructor, oldProvider, queryParam, queriesVar, readerFactoryVar, subQueriesVar ) ),
                <span style="color:green;">// --- Expression.Throw( Expression.New( typeof( Exception ).GetConstructor( new[] { typeof( string ) } ), Expression.Constant( &quot;boo4&quot; ) ) ),
                </span><span style="color:#2b91af;">Expression</span>.Label( returnTarget, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null</span>, compiledQueryType ) ) ),
            queryParam );
    }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">ModifyCommandDelegate</span>, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:#2b91af;">IExecuteResult</span>&gt;&gt;&gt; CreateExecuteFactory()
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>providerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>);
        <span style="color:blue;">var </span>providerParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:blue;">object </span>), <span style="color:#a31515;">&quot;provider&quot; </span>);
        <span style="color:blue;">var </span>modifyCommandParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ModifyCommandDelegate </span>), <span style="color:#a31515;">&quot;modifyCommand&quot; </span>);

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:blue;">object</span>, <span style="color:#2b91af;">ModifyCommandDelegate</span>, <span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:#2b91af;">IExecuteResult</span>&gt;&gt;&gt;(
            CreateExecuteMethod( <span style="color:#2b91af;">Expression</span>.Convert( providerParam, providerType ), modifyCommandParam ),
            providerParam,
            modifyCommandParam );
    }

    <span style="color:blue;">public static </span><span style="color:#2b91af;">Expression</span>&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:#2b91af;">IExecuteResult</span>&gt;&gt; CreateExecuteMethod( <span style="color:#2b91af;">Expression </span>oldProvider, <span style="color:#2b91af;">Expression </span>modifyCommand )
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>providerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.Provider.IProvider&quot; </span>);
        <span style="color:blue;">var </span>funcletizerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.Funcletizer&quot; </span>);
        <span style="color:blue;">var </span>annotationsType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlNodeAnnotations&quot; </span>);
        <span style="color:blue;">var </span>queryInfoType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;QueryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>readerFactoryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.IObjectReaderFactory&quot; </span>);
        <span style="color:blue;">var </span>resultShapeType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;ResultShape&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>compiledSubQueryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.ICompiledSubQuery&quot; </span>);
        <span style="color:blue;">var </span>typeSystemType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.TypeSystem&quot; </span>);

        <span style="color:blue;">var </span>queryParam = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">Expression </span>), <span style="color:#a31515;">&quot;query&quot; </span>);

        <span style="color:blue;">var </span>cachedResultVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">IExecuteResult </span>), <span style="color:#a31515;">&quot;cachedResult&quot; </span>);
        <span style="color:blue;">var </span>annotationsVar = <span style="color:#2b91af;">Expression</span>.Variable( annotationsType, <span style="color:#a31515;">&quot;annotations&quot; </span>);
        <span style="color:blue;">var </span>queriesVar = <span style="color:#2b91af;">Expression</span>.Variable( queryInfoType.MakeArrayType(), <span style="color:#a31515;">&quot;queries&quot; </span>);
        <span style="color:blue;">var </span>infoVar = <span style="color:#2b91af;">Expression</span>.Variable( queryInfoType, <span style="color:#a31515;">&quot;info&quot; </span>);
        <span style="color:blue;">var </span>lambdaVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">LambdaExpression </span>), <span style="color:#a31515;">&quot;lambda&quot; </span>);
        <span style="color:blue;">var </span>readerFactoryVar = <span style="color:#2b91af;">Expression</span>.Variable( readerFactoryType, <span style="color:#a31515;">&quot;readerFactory&quot; </span>);
        <span style="color:blue;">var </span>subQueriesVar = <span style="color:#2b91af;">Expression</span>.Variable( compiledSubQueryType.MakeArrayType(), <span style="color:#a31515;">&quot;subQueries&quot; </span>);
        <span style="color:blue;">var </span>resultShapeVar = <span style="color:#2b91af;">Expression</span>.Variable( resultShapeType, <span style="color:#a31515;">&quot;resultShape&quot; </span>);
        <span style="color:blue;">var </span>returnTarget = <span style="color:#2b91af;">Expression</span>.Label( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">IExecuteResult </span>) );

        <span style="color:blue;">var </span>getQuery = MakeMethodCall( infoVar, <span style="color:#a31515;">&quot;get_Query&quot; </span>);
        <span style="color:blue;">var </span>getResultType = MakeMethodCall( infoVar, <span style="color:#a31515;">&quot;get_ResultType&quot; </span>);
        <span style="color:blue;">var </span>getResultElementType = MakeMethodCall( typeSystemType, <span style="color:#a31515;">&quot;GetElementType&quot;</span>, getResultType );
        <span style="color:blue;">var </span>modifySubQueriesMethod = CreateModifySubQueriesMethod();

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda&lt;<span style="color:#2b91af;">Func</span>&lt;<span style="color:#2b91af;">Expression</span>, <span style="color:#2b91af;">IExecuteResult</span>&gt;&gt;(
            <span style="color:#2b91af;">Expression</span>.Block(
                <span style="color:blue;">new</span>[] { annotationsVar, queriesVar, infoVar, lambdaVar, readerFactoryVar, subQueriesVar, resultShapeVar },

                <span style="color:green;">// this.InitializeProviderMode();
                </span>MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;InitializeProviderMode&quot; </span>),

                <span style="color:green;">// query = Funcletizer.Funcletize(query);
                </span><span style="color:#2b91af;">Expression</span>.Assign( queryParam, MakeMethodCall( funcletizerType, <span style="color:#a31515;">&quot;Funcletize&quot;</span>, queryParam ) ),

                <span style="color:green;">// if ( this.EnableCacheLookup )
                </span><span style="color:#2b91af;">Expression</span>.IfThen(
                    MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;get_EnableCacheLookup&quot; </span>),
                    <span style="color:#2b91af;">Expression</span>.Block(
                        <span style="color:blue;">new</span>[] { cachedResultVar },
                        <span style="color:green;">// IExecuteResult cachedResult = this.GetCachedResult(query);
                        </span><span style="color:#2b91af;">Expression</span>.Assign( cachedResultVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;GetCachedResult&quot;</span>, queryParam ) ),
                        <span style="color:green;">// if ( cachedResult != null )
                        </span><span style="color:#2b91af;">Expression</span>.IfThen(
                            <span style="color:#2b91af;">Expression</span>.NotEqual( cachedResultVar, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null </span>) ),
                            <span style="color:green;">// return cachedResult;
                            </span><span style="color:#2b91af;">Expression</span>.Return( returnTarget, cachedResultVar ) ) ) ),

                <span style="color:green;">// SqlNodeAnnotations annotations = new SqlNodeAnnotations();
                </span><span style="color:#2b91af;">Expression</span>.Assign( annotationsVar, <span style="color:#2b91af;">Expression</span>.New( annotationsType ) ),

                <span style="color:green;">// QueryInfo[] queries = this.BuildQuery(query, annotations);
                </span><span style="color:#2b91af;">Expression</span>.Assign( queriesVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;BuildQuery&quot;</span>, queryParam, annotationsVar ) ),

                <span style="color:green;">// var info = ModifyQueries( (IEnumerable)queries );
                </span><span style="color:#2b91af;">Expression</span>.Assign( infoVar, <span style="color:#2b91af;">Expression</span>.Invoke( CreateModifyQueriesMethod(), queriesVar, modifyCommand ) ),

                <span style="color:green;">// this.CheckSqlCompatibility(queries, annotations);
                </span>MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;CheckSqlCompatibility&quot;</span>, queriesVar, annotationsVar ),

                <span style="color:green;">// var lambda = query as LambdaExpression;
                </span><span style="color:#2b91af;">Expression</span>.Assign( lambdaVar, <span style="color:#2b91af;">Expression</span>.TypeAs( queryParam, lambdaVar.Type ) ),

                <span style="color:green;">// if ( lambda != null )
                </span><span style="color:#2b91af;">Expression</span>.IfThen(
                    <span style="color:#2b91af;">Expression</span>.NotEqual( lambdaVar, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null </span>) ),
                    <span style="color:green;">// query = lambda.Body;
                    </span><span style="color:#2b91af;">Expression</span>.Assign( queryParam, <span style="color:#2b91af;">Expression</span>.Property( lambdaVar, <span style="color:#a31515;">&quot;Body&quot; </span>) ) ),

                <span style="color:green;">// IObjectReaderFactory readerFactory = null;
                // ICompiledSubQuery[] subQueries = null;

                // QueryInfo info = queries[queries.Length - 1];
                // info defined above
                // var resultShape = (int)Invoke( info, &quot;get_ResultShape&quot; );
                </span><span style="color:#2b91af;">Expression</span>.Assign( resultShapeVar, MakeMethodCall( infoVar, <span style="color:#a31515;">&quot;get_ResultShape&quot; </span>) ),

                <span style="color:#2b91af;">Expression</span>.Switch(
                    <span style="color:#2b91af;">Expression</span>.Convert( resultShapeVar, <span style="color:blue;">typeof</span>( <span style="color:blue;">int </span>) ),
                    <span style="color:green;">// if ( resultShape == 1 /* ResultShape.Singleton */ )
                    </span><span style="color:#2b91af;">Expression</span>.SwitchCase(
                        <span style="color:#2b91af;">Expression</span>.Block(
                            <span style="color:green;">// subQueries = this.CompileSubQueries( info.Query );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( subQueriesVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, getQuery ) ),
                            <span style="color:green;">// ModifySubQueries( (IEnumerable)subQueries );
                            </span><span style="color:#2b91af;">Expression</span>.Invoke( modifySubQueriesMethod, subQueriesVar, modifyCommand ),
                            <span style="color:green;">// readerFactory = this.GetReaderFactory( info.Query, info.ResultType );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( readerFactoryVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, getQuery, getResultType ) ),
                            <span style="color:#2b91af;">Expression</span>.Empty() ),
                        <span style="color:#2b91af;">Expression</span>.Constant( 1 ) ),
                    <span style="color:green;">// else if ( resultShape == 2 /* ResultShape.Sequence */ )
                    </span><span style="color:#2b91af;">Expression</span>.SwitchCase(
                        <span style="color:#2b91af;">Expression</span>.Block(
                            <span style="color:green;">// subQueries = this.CompileSubQueries( info.Query );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( subQueriesVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, getQuery ) ),
                            <span style="color:green;">// ModifySubQueries( (IEnumerable)subQueries );
                            </span><span style="color:#2b91af;">Expression</span>.Invoke( modifySubQueriesMethod, subQueriesVar, modifyCommand ),
                            <span style="color:green;">// readerFactory = this.GetReaderFactory( info.Query, TypeSystem.GetElementType( info.ResultType ) );
                            </span><span style="color:#2b91af;">Expression</span>.Assign( readerFactoryVar, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, getQuery, getResultElementType ) ),
                            <span style="color:#2b91af;">Expression</span>.Empty() ),
                        <span style="color:#2b91af;">Expression</span>.Constant( 2 ) ) ),

                <span style="color:green;">// return this.ExecuteAll(query, queries, readerFactory, null, subQueries);
                </span><span style="color:#2b91af;">Expression</span>.Return( returnTarget, MakeMethodCall( oldProvider, <span style="color:#a31515;">&quot;ExecuteAll&quot;</span>, queryParam, queriesVar, readerFactoryVar, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null</span>, <span style="color:blue;">typeof</span>( <span style="color:blue;">object</span>[] ) ), subQueriesVar ) ),
                <span style="color:green;">// --- Expression.Throw( Expression.New( typeof( Exception ).GetConstructor( new[] { typeof( string ) } ), Expression.Constant( &quot;boo4&quot; ) ) ),
                </span><span style="color:#2b91af;">Expression</span>.Label( returnTarget, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null</span>, <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">IExecuteResult </span>) ) ) ),
            queryParam );
    }

    <span style="color:blue;">private static </span><span style="color:#2b91af;">LambdaExpression </span>CreateModifyQueriesMethod()
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>queryInfoType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;QueryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>queriesParam = <span style="color:#2b91af;">Expression</span>.Parameter( queryInfoType.MakeArrayType(), <span style="color:#a31515;">&quot;queries&quot; </span>);
        <span style="color:blue;">var </span>modifyCommandParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ModifyCommandDelegate </span>), <span style="color:#a31515;">&quot;modifyCommand&quot; </span>);

        <span style="color:blue;">var </span>returnLabel = <span style="color:#2b91af;">Expression</span>.Label();
        <span style="color:blue;">var </span>indexVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:blue;">int </span>), <span style="color:#a31515;">&quot;index&quot; </span>);
        <span style="color:blue;">var </span>queryVar = <span style="color:#2b91af;">Expression</span>.Variable( queryInfoType, <span style="color:#a31515;">&quot;query&quot; </span>);

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda(
            <span style="color:#2b91af;">Expression</span>.Block(
                <span style="color:blue;">new</span>[] { indexVar, queryVar },
                <span style="color:green;">// var index = 0;
                </span><span style="color:#2b91af;">Expression</span>.Assign( indexVar, <span style="color:#2b91af;">Expression</span>.Constant( 0 ) ),
                <span style="color:#2b91af;">Expression</span>.Loop(
                    <span style="color:#2b91af;">Expression</span>.Block(
                        <span style="color:green;">// if ( index &gt;= queries.Length ) break;
                        </span><span style="color:#2b91af;">Expression</span>.IfThen(
                            <span style="color:#2b91af;">Expression</span>.GreaterThanOrEqual( indexVar, <span style="color:#2b91af;">Expression</span>.ArrayLength( queriesParam ) ),
                            <span style="color:#2b91af;">Expression</span>.Break( returnLabel ) ),
                        <span style="color:green;">// query = queries[ index ];
                        </span><span style="color:#2b91af;">Expression</span>.Assign( queryVar, <span style="color:#2b91af;">Expression</span>.ArrayIndex( queriesParam, indexVar ) ),
                        <span style="color:green;">// ModifyQuery( query );
                        </span><span style="color:#2b91af;">Expression</span>.Invoke( CreateModifyQueryMethod(), queryVar, modifyCommandParam ),
                        <span style="color:green;">// ++ index;
                        </span><span style="color:#2b91af;">Expression</span>.PreIncrementAssign( indexVar ) ),
                    returnLabel ),
                queryVar ),
            queriesParam,
            modifyCommandParam );
    }

    <span style="color:blue;">private static </span><span style="color:#2b91af;">LambdaExpression </span>CreateModifySubQueriesMethod()
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>iCompiledSubQueryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.ICompiledSubQuery&quot; </span>);
        <span style="color:blue;">var </span>compiledSubQueryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;CompiledSubQuery&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>queryInfoType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;QueryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>subQueriesType = iCompiledSubQueryType.MakeArrayType();

        <span style="color:blue;">var </span>queryInfoField = compiledSubQueryType.GetField( <span style="color:#a31515;">&quot;queryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>subQueriesField = compiledSubQueryType.GetField( <span style="color:#a31515;">&quot;subQueries&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );

        <span style="color:blue;">var </span>subQueriesParam = <span style="color:#2b91af;">Expression</span>.Parameter( subQueriesType, <span style="color:#a31515;">&quot;subQueries&quot; </span>);
        <span style="color:blue;">var </span>modifyCommandParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ModifyCommandDelegate </span>), <span style="color:#a31515;">&quot;modifyCommand&quot; </span>);

        <span style="color:blue;">var </span>indexVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:blue;">int </span>), <span style="color:#a31515;">&quot;index&quot; </span>);
        <span style="color:blue;">var </span>subQueryVar = <span style="color:#2b91af;">Expression</span>.Variable( compiledSubQueryType, <span style="color:#a31515;">&quot;subQuery&quot; </span>);
        <span style="color:blue;">var </span>queryInfoVar = <span style="color:#2b91af;">Expression</span>.Variable( queryInfoType, <span style="color:#a31515;">&quot;queryInfo&quot; </span>);
        <span style="color:blue;">var </span>nestedSubQueriesVar = <span style="color:#2b91af;">Expression</span>.Variable( iCompiledSubQueryType.MakeArrayType(), <span style="color:#a31515;">&quot;nestedSubQueries&quot; </span>);
        <span style="color:blue;">var </span>modifySubQueriesDelegateType = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">Action</span>&lt;&gt; ).MakeGenericType( iCompiledSubQueryType.MakeArrayType() );
        <span style="color:blue;">var </span>modifySubQueriesDelegateVar = <span style="color:#2b91af;">Expression</span>.Variable( modifySubQueriesDelegateType, <span style="color:#a31515;">&quot;modifySubQueries&quot; </span>);
        <span style="color:blue;">var </span>loopTarget = <span style="color:#2b91af;">Expression</span>.Label();

        <span style="color:blue;">var </span>innerLambda = <span style="color:#2b91af;">Expression</span>.Lambda(
            modifySubQueriesDelegateType,
            <span style="color:#2b91af;">Expression</span>.Block(
                <span style="color:blue;">new</span>[] { indexVar },
            <span style="color:green;">// var index = 0;
                </span><span style="color:#2b91af;">Expression</span>.Assign( indexVar, <span style="color:#2b91af;">Expression</span>.Constant( 0 ) ),
                <span style="color:#2b91af;">Expression</span>.Loop(
                    <span style="color:#2b91af;">Expression</span>.Block(
                        <span style="color:blue;">new</span>[] { subQueryVar },
                        <span style="color:green;">// if ( index &gt;= subQueries.Length ) break;
                        </span><span style="color:#2b91af;">Expression</span>.IfThen(
                            <span style="color:#2b91af;">Expression</span>.GreaterThanOrEqual( indexVar, <span style="color:#2b91af;">Expression</span>.ArrayLength( subQueriesParam ) ),
                            <span style="color:#2b91af;">Expression</span>.Break( loopTarget ) ),
                        <span style="color:green;">// var subQuery = subQueries[ index ];
                        </span><span style="color:#2b91af;">Expression</span>.Assign( subQueryVar, <span style="color:#2b91af;">Expression</span>.TypeAs( <span style="color:#2b91af;">Expression</span>.ArrayIndex( subQueriesParam, indexVar ), compiledSubQueryType ) ),
                        <span style="color:green;">// if ( subQuery != null )
                        </span><span style="color:#2b91af;">Expression</span>.IfThen(
                            <span style="color:#2b91af;">Expression</span>.NotEqual( subQueryVar, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null </span>) ),
                            <span style="color:#2b91af;">Expression</span>.Block(
                                <span style="color:blue;">new</span>[] { queryInfoVar, nestedSubQueriesVar },
                                <span style="color:green;">// var queryInfo = subQuery.queryInfo;
                                </span><span style="color:#2b91af;">Expression</span>.Assign( queryInfoVar, <span style="color:#2b91af;">Expression</span>.MakeMemberAccess( subQueryVar, queryInfoField ) ),
                                <span style="color:green;">// ModifyQuery( queryInfo, modifyCommand );
                                </span><span style="color:#2b91af;">Expression</span>.Invoke( CreateModifyQueryMethod(), queryInfoVar, modifyCommandParam ),
                                <span style="color:green;">// var nestedSubQueries = subQuery.subQueries;
                                </span><span style="color:#2b91af;">Expression</span>.Assign( nestedSubQueriesVar, <span style="color:#2b91af;">Expression</span>.MakeMemberAccess( subQueryVar, subQueriesField ) ),
                                <span style="color:green;">// if ( nestedSubQueries != null )
                                </span><span style="color:#2b91af;">Expression</span>.IfThen(
                                    <span style="color:#2b91af;">Expression</span>.NotEqual( nestedSubQueriesVar, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null </span>) ),
                                    <span style="color:green;">// ModifySubQueries( nestedSubQueries, modifyCommand );
                                    </span><span style="color:#2b91af;">Expression</span>.Invoke( modifySubQueriesDelegateVar, nestedSubQueriesVar ) ) ) ),
                        <span style="color:green;">// ++ index;
                        </span><span style="color:#2b91af;">Expression</span>.PreIncrementAssign( indexVar ) ),
                    loopTarget ) ),
                subQueriesParam );

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda(
            <span style="color:#2b91af;">Expression</span>.Block(
                <span style="color:blue;">new</span>[] { modifySubQueriesDelegateVar },
                <span style="color:#2b91af;">Expression</span>.Assign( modifySubQueriesDelegateVar, innerLambda ),
                <span style="color:#2b91af;">Expression</span>.Invoke( modifySubQueriesDelegateVar, subQueriesParam ) ),
            subQueriesParam,
            modifyCommandParam );
    }

    <span style="color:blue;">private static </span><span style="color:#2b91af;">LambdaExpression </span>CreateModifyQueryMethod()
    {
        <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

        <span style="color:blue;">var </span>queryInfoType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider&quot; </span>).GetNestedType( <span style="color:#a31515;">&quot;QueryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>sqlParameterInfoType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlParameterInfo&quot; </span>);
        <span style="color:blue;">var </span>sqlParameterType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlParameter&quot; </span>);

        <span style="color:blue;">var </span>queryInfoParam = <span style="color:#2b91af;">Expression</span>.Parameter( queryInfoType, <span style="color:#a31515;">&quot;query&quot; </span>);
        <span style="color:blue;">var </span>modifyCommandParam = <span style="color:#2b91af;">Expression</span>.Parameter( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ModifyCommandDelegate </span>), <span style="color:#a31515;">&quot;modifyCommand&quot; </span>);

        <span style="color:blue;">var </span>commandTextField = queryInfoType.GetField( <span style="color:#a31515;">&quot;commandText&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
        <span style="color:blue;">var </span>parametersField = queryInfoType.GetField( <span style="color:#a31515;">&quot;parameters&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );

        <span style="color:blue;">var </span>commandTextVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:blue;">string </span>), <span style="color:#a31515;">&quot;commandText&quot; </span>);
        <span style="color:blue;">var </span>parameterInfosVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ReadOnlyCollection</span>&lt;&gt; ).MakeGenericType( sqlParameterInfoType ), <span style="color:#a31515;">&quot;parameterInfos&quot; </span>);
        <span style="color:blue;">var </span>parametersVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; ), <span style="color:#a31515;">&quot;parameters&quot; </span>);
        <span style="color:blue;">var </span>indexVar = <span style="color:#2b91af;">Expression</span>.Variable( <span style="color:blue;">typeof</span>( <span style="color:blue;">int </span>), <span style="color:#a31515;">&quot;index&quot; </span>);
        <span style="color:blue;">var </span>paramInfoVar = <span style="color:#2b91af;">Expression</span>.Variable( sqlParameterInfoType, <span style="color:#a31515;">&quot;paramInfo&quot; </span>);
        <span style="color:blue;">var </span>paramVar = <span style="color:#2b91af;">Expression</span>.Variable( sqlParameterType, <span style="color:#a31515;">&quot;param&quot; </span>);
        <span style="color:blue;">var </span>loopTarget = <span style="color:#2b91af;">Expression</span>.Label();

        <span style="color:blue;">return </span><span style="color:#2b91af;">Expression</span>.Lambda(
            <span style="color:#2b91af;">Expression</span>.IfThen(
                <span style="color:#2b91af;">Expression</span>.NotEqual( modifyCommandParam, <span style="color:#2b91af;">Expression</span>.Constant( <span style="color:blue;">null </span>) ),
                <span style="color:#2b91af;">Expression</span>.Block(
                    <span style="color:blue;">new</span>[] { commandTextVar, parameterInfosVar, parametersVar, indexVar },
                    <span style="color:green;">// var commandText = queryInfo.CommandText;
                    </span><span style="color:#2b91af;">Expression</span>.Assign( commandTextVar, <span style="color:#2b91af;">Expression</span>.MakeMemberAccess( queryInfoParam, commandTextField ) ),
                    <span style="color:green;">// var parameterInfos = queryInfo.Parameters;
                    </span><span style="color:#2b91af;">Expression</span>.Assign( parameterInfosVar, <span style="color:#2b91af;">Expression</span>.MakeMemberAccess( queryInfoParam, parametersField ) ),
                    <span style="color:green;">// var parameters = new Dictionary&lt;string, object&gt;();
                    </span><span style="color:#2b91af;">Expression</span>.Assign( parametersVar, <span style="color:#2b91af;">Expression</span>.New( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; ) ) ),
                    <span style="color:green;">// var index = 0;
                    </span><span style="color:#2b91af;">Expression</span>.Assign( indexVar, <span style="color:#2b91af;">Expression</span>.Constant( 0 ) ),
                    <span style="color:#2b91af;">Expression</span>.Loop(
                        <span style="color:#2b91af;">Expression</span>.Block(
                            <span style="color:blue;">new</span>[] { paramInfoVar, paramVar },
                            <span style="color:green;">// if ( index &gt;= parameterInfos.Count ) break;
                            </span><span style="color:#2b91af;">Expression</span>.IfThen(
                                <span style="color:#2b91af;">Expression</span>.GreaterThanOrEqual( indexVar, <span style="color:#2b91af;">Expression</span>.Property( parameterInfosVar, <span style="color:#a31515;">&quot;Count&quot; </span>) ),
                                <span style="color:#2b91af;">Expression</span>.Break( loopTarget ) ),
                            <span style="color:green;">// var paramInfo = parameterInfos[ index ];
                            </span><span style="color:#2b91af;">Expression</span>.Assign( paramInfoVar, MakeMethodCall( parameterInfosVar, <span style="color:#a31515;">&quot;get_Item&quot;</span>, indexVar ) ),
                            <span style="color:green;">// var param = paramInfo.Parameter;
                            </span><span style="color:#2b91af;">Expression</span>.Assign( paramVar, MakeMethodCall( paramInfoVar, <span style="color:#a31515;">&quot;get_Parameter&quot; </span>) ),
                            <span style="color:green;">// parameters[ param.Name ] = paramInfo.Value;
                            </span>MakeMethodCall( parametersVar, <span style="color:#a31515;">&quot;set_Item&quot;</span>, MakeMethodCall( paramVar, <span style="color:#a31515;">&quot;get_Name&quot; </span>), MakeMethodCall( paramInfoVar, <span style="color:#a31515;">&quot;get_Value&quot; </span>) ),
                            <span style="color:green;">// ++ index;
                            </span><span style="color:#2b91af;">Expression</span>.PreIncrementAssign( indexVar ) ),
                        loopTarget ),
                    <span style="color:green;">// queryInfo.CommandText = modifyCommand( commandText, parameters );
                    </span><span style="color:#2b91af;">Expression</span>.Assign( <span style="color:#2b91af;">Expression</span>.MakeMemberAccess( queryInfoParam, commandTextField ), <span style="color:#2b91af;">Expression</span>.Invoke( modifyCommandParam, commandTextVar, parametersVar ) ) ) ),
            queryInfoParam,
            modifyCommandParam );
    }

    <span style="color:blue;">internal interface </span><span style="color:#2b91af;">IProviderProxy
    </span>{
        <span style="color:#2b91af;">DataContextInterceptor </span>Interceptor { <span style="color:blue;">get</span>; }
        <span style="color:blue;">object </span>OldProvider { <span style="color:blue;">get</span>; }
    }

    <span style="color:blue;">public class </span><span style="color:#2b91af;">ProviderProxy </span>: <span style="color:#2b91af;">RealProxy</span>, <span style="color:#2b91af;">IRemotingTypeInfo</span>, <span style="color:#2b91af;">IProviderProxy
    </span>{
        <span style="color:blue;">public </span><span style="color:#2b91af;">DataContextInterceptor </span>Interceptor { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
        <span style="color:blue;">public object </span>OldProvider { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }

        <span style="color:blue;">internal </span>ProviderProxy( <span style="color:#2b91af;">DataContextInterceptor </span>extender, <span style="color:blue;">object </span>oldProvider )
            : <span style="color:blue;">base</span>( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ContextBoundObject </span>) )
        {
            <span style="color:blue;">this</span>.Interceptor = extender;
            <span style="color:blue;">this</span>.OldProvider = oldProvider;
        }

        <span style="color:blue;">public override </span><span style="color:#2b91af;">IMessage </span>Invoke( <span style="color:#2b91af;">IMessage </span>msg )
        {
            <span style="color:blue;">var </span>call = msg <span style="color:blue;">as </span><span style="color:#2b91af;">IMethodCallMessage</span>;

            <span style="color:blue;">if </span>( call != <span style="color:blue;">null </span>&amp;&amp; OldProvider != <span style="color:blue;">null </span>)
            {
                <span style="color:blue;">try
                </span>{
                    <span style="color:blue;">if </span>( call.MethodBase.DeclaringType.Name == <span style="color:#a31515;">&quot;IProvider&quot; </span>&amp;&amp; call.MethodBase.DeclaringType.IsInterface )
                    {
                        Interceptor.providerType = call.MethodBase.DeclaringType;

                        <span style="color:blue;">switch </span>( call.MethodName )
                        {
                            <span style="color:blue;">case </span><span style="color:#a31515;">&quot;Compile&quot;</span>: <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( Interceptor.Compile( call.Args.Cast&lt;<span style="color:#2b91af;">Expression</span>&gt;().First() ), <span style="color:blue;">null</span>, 0, <span style="color:blue;">null</span>, call );
                            <span style="color:blue;">case </span><span style="color:#a31515;">&quot;Execute&quot;</span>: <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( Interceptor.Execute( call.Args.Cast&lt;<span style="color:#2b91af;">Expression</span>&gt;().First() ), <span style="color:blue;">null</span>, 0, <span style="color:blue;">null</span>, call );
                        }
                    }

                    <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( call.MethodBase.Invoke( OldProvider, call.Args ), <span style="color:blue;">null</span>, 0, <span style="color:blue;">null</span>, call );
                }
                <span style="color:blue;">catch </span>( <span style="color:#2b91af;">TargetInvocationException </span>e )
                {
                    <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( e.InnerException, call );
                }
            }

            <span style="color:blue;">throw new </span><span style="color:#2b91af;">NotImplementedException</span>();
        }

        <span style="color:blue;">public bool </span>CanCastTo( <span style="color:#2b91af;">Type </span>fromType, <span style="color:blue;">object </span>o )
        {
            <span style="color:blue;">return true</span>;
        }

        <span style="color:blue;">public string </span>TypeName
        {
            <span style="color:blue;">get </span>{ <span style="color:blue;">return this</span>.GetType().Name; }
            <span style="color:blue;">set </span>{ }
        }
    }
}</pre>
<p>To use it, simply call DataContextInterceptor.Intercept on your DataContext before use (passing in a delegate to modify command text as needed):</p>
<pre class="code"><span style="color:black;">DataContextInterceptor.Intercept( </span><span style="color:blue;">this</span><span style="color:black;">, ( c, p ) =&gt; c.Replace( </span><span style="color:#dc1414;">&quot;[t0].[cName]&quot;</span><span style="color:black;">, </span><span style="color:#dc1414;">&quot;NULL&quot; </span><span style="color:black;">).Dump( </span><span style="color:#dc1414;">&quot;test&quot;</span><span style="color:black;">) );
</span></pre>
<p>&#160;</p>
<p>As it’s still calling private methods, you’ll need to be running in a full-trust environment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/757/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=757&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/07/06/modifying-linq-to-sql-command-text-without-reflection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>
	</item>
		<item>
		<title>Modifying LINQ to SQL command text again</title>
		<link>http://chriscavanagh.wordpress.com/2012/07/06/modifying-linq-to-sql-command-text-again/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/07/06/modifying-linq-to-sql-command-text-again/#comments</comments>
		<pubDate>Fri, 06 Jul 2012 14:37:38 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=753</guid>
		<description><![CDATA[Last year I posted this article about modifying LINQ to SQL (L2S) command text.&#160; It was slightly evil in that it called private methods inside L2S, and it did it through reflection. I have an alternative version that does the same thing through a pre-compiled expression tree, which I’ll post soon.&#160; Until then, here’s an [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=753&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Last year I posted <a title="Modifying LINQ to SQL command text" href="http://chriscavanagh.wordpress.com/2011/03/12/manipulating-linq-to-sql-command-text/" target="_blank">this article about modifying LINQ to SQL (L2S) command text</a>.&#160; It was slightly evil in that it called private methods inside L2S, and it did it through reflection.</p>
<p>I have an alternative version that does the same thing through a pre-compiled expression tree, which I’ll post soon.&#160; Until then, here’s an update to the original reflection-based interceptor that properly handles sub-queries:</p>
<pre class="code">    <span style="color:blue;">public delegate string </span><span style="color:#2b91af;">ModifyCommandDelegate</span>( <span style="color:blue;">string </span>commandText, <span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; parameters );

    <span style="color:blue;">public class </span><span style="color:#2b91af;">ReflectionDataContextInterceptor
    </span>{
        <span style="color:blue;">private </span><span style="color:#2b91af;">DataContext </span>dc;
        <span style="color:blue;">private object </span>oldProvider;
        <span style="color:blue;">private </span><span style="color:#2b91af;">Type </span>providerType;
        <span style="color:blue;">private </span><span style="color:#2b91af;">ModifyCommandDelegate </span>modifyCommand;

        <span style="color:blue;">public static </span>TDataContext Intercept&lt;TDataContext&gt;( TDataContext dc, <span style="color:#2b91af;">ModifyCommandDelegate </span>modifyCommand )
            <span style="color:blue;">where </span>TDataContext : <span style="color:#2b91af;">DataContext
        </span>{
            <span style="color:blue;">new </span><span style="color:#2b91af;">ReflectionDataContextInterceptor</span>( dc, modifyCommand );

            <span style="color:blue;">return </span>dc;
        }

        <span style="color:blue;">public </span>ReflectionDataContextInterceptor( <span style="color:#2b91af;">DataContext </span>dc, <span style="color:#2b91af;">ModifyCommandDelegate </span>modifyCommand )
        {
            <span style="color:blue;">this</span>.dc = dc;
            <span style="color:blue;">this</span>.modifyCommand = modifyCommand;

            <span style="color:#2b91af;">FieldInfo </span>providerField = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">DataContext </span>).GetField( <span style="color:#a31515;">&quot;provider&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
            <span style="color:blue;">var </span>existingProvider = providerField.GetValue( dc );

            <span style="color:blue;">if </span>( existingProvider <span style="color:blue;">is </span><span style="color:#2b91af;">IProviderProxy </span>)
            {
<span style="color:green;">//                System.Diagnostics.Trace.WriteLine( string.Format( &quot;DataContext {0} already intercepted&quot;, dc.GetHashCode() ) );
            </span>}
            <span style="color:blue;">else
            </span>{
                oldProvider = existingProvider;

                <span style="color:blue;">var </span>proxy = <span style="color:blue;">new </span><span style="color:#2b91af;">ProviderProxy</span>( <span style="color:blue;">this</span>, oldProvider ).GetTransparentProxy();

                providerField.SetValue( dc, proxy );

<span style="color:green;">//                System.Diagnostics.Trace.WriteLine( string.Format( &quot;DataContext {0} intercepted&quot;, dc.GetHashCode() ) );
            </span>}
        }

        <span style="color:blue;">public static </span><span style="color:#2b91af;">MethodInfo </span>GetMethod( <span style="color:#2b91af;">Type </span>type, <span style="color:blue;">string </span>methodName, <span style="color:blue;">params object</span>[] args )
        {
            <span style="color:blue;">var </span>hasNullArgs = args.Any( a =&gt; a == <span style="color:blue;">null </span>);

            <span style="color:blue;">var </span>method = hasNullArgs
                ? type.GetMethods( <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic )
                    .FirstOrDefault( m =&gt; m.Name == methodName )
                : <span style="color:blue;">null</span>;

            <span style="color:blue;">if </span>( method == <span style="color:blue;">null </span>&amp;&amp; !hasNullArgs )
            {
                method = type.GetMethod(
                    methodName,
                    <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic,
                    <span style="color:blue;">null</span>,
                    args.Select( a =&gt; a.GetType() ).ToArray(),
                    <span style="color:blue;">null </span>);
            }

            <span style="color:blue;">return </span>method;
        }

        <span style="color:blue;">private object </span>Invoke( <span style="color:blue;">object </span>instance, <span style="color:blue;">string </span>methodName, <span style="color:blue;">params object</span>[] args )
        {
            <span style="color:blue;">var </span>type = instance.GetType();
            <span style="color:blue;">var </span>method = GetMethod( type, methodName, args );

            <span style="color:blue;">return </span>( method != <span style="color:blue;">null </span>)
                ? method.Invoke( instance, args )
                : <span style="color:blue;">null</span>;
        }

        <span style="color:blue;">private object </span>Invoke( <span style="color:#2b91af;">Type </span>type, <span style="color:blue;">string </span>methodName, <span style="color:blue;">params object</span>[] args )
        {
            <span style="color:blue;">var </span>method = type.GetMethod( methodName, <span style="color:#2b91af;">BindingFlags</span>.Static | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );

            <span style="color:blue;">return </span>method.Invoke( <span style="color:blue;">null</span>, args );
        }

        <span style="color:blue;">protected object </span>CompileImpl( <span style="color:#2b91af;">Expression </span>query )
        {
            <span style="color:blue;">try
            </span>{
                <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

                <span style="color:green;">/*
                this.CheckDispose();
                this.CheckInitialized();
                if ( query == null )
                {
                    throw Error.ArgumentNull( &quot;query&quot; );
                }
                */

                // this.InitializeProviderMode();
                </span>Invoke( oldProvider, <span style="color:#a31515;">&quot;InitializeProviderMode&quot; </span>);

                <span style="color:green;">// SqlNodeAnnotations annotations = new SqlNodeAnnotations();
                </span><span style="color:blue;">var </span>annotations = <span style="color:#2b91af;">Activator</span>.CreateInstance( assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlNodeAnnotations&quot; </span>) );

                <span style="color:green;">// QueryInfo[] queries = this.BuildQuery( query, annotations );
                </span><span style="color:blue;">var </span>queries = Invoke( oldProvider, <span style="color:#a31515;">&quot;BuildQuery&quot;</span>, query, annotations );

                <span style="color:blue;">var </span>info = ModifyQueries( (<span style="color:#2b91af;">IEnumerable</span>)queries );

                <span style="color:green;">// this.CheckSqlCompatibility( queries, annotations );
                </span>Invoke( oldProvider, <span style="color:#a31515;">&quot;CheckSqlCompatibility&quot;</span>, queries, annotations );

                <span style="color:#2b91af;">LambdaExpression </span>expression = query <span style="color:blue;">as </span><span style="color:#2b91af;">LambdaExpression</span>;

                <span style="color:blue;">if </span>( expression != <span style="color:blue;">null </span>)
                {
                    query = expression.Body;
                }

                <span style="color:green;">// IObjectReaderFactory readerFactory = null;
                </span><span style="color:blue;">object </span>readerFactory = <span style="color:blue;">null</span>;

                <span style="color:green;">// ICompiledSubQuery[] subQueries = null;
                </span><span style="color:blue;">object </span>subQueries = <span style="color:blue;">null</span>;

                <span style="color:green;">// QueryInfo info = queries[ queries.Length - 1 ];
                // info defined above

                </span><span style="color:blue;">var </span>resultShape = (<span style="color:blue;">int</span>)Invoke( info, <span style="color:#a31515;">&quot;get_ResultShape&quot; </span>);

                <span style="color:green;">// if ( info.ResultShape == ResultShape.Singleton )
                </span><span style="color:blue;">if </span>( resultShape == 1 <span style="color:green;">/* Singleton */ </span>)
                {
                    <span style="color:green;">// subQueries = this.CompileSubQueries( info.Query );
                    </span>subQueries = Invoke( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>) );

                    ModifySubQueries( (<span style="color:#2b91af;">IEnumerable</span>)subQueries );

                    <span style="color:green;">// readerFactory = this.GetReaderFactory( info.Query, info.ResultType );
                    </span>readerFactory = Invoke( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>), Invoke( info, <span style="color:#a31515;">&quot;get_ResultType&quot; </span>) );
                }
                <span style="color:green;">// else if ( info.ResultShape == ResultShape.Sequence )
                </span><span style="color:blue;">else if </span>( resultShape == 2 <span style="color:green;">/* Sequence */ </span>)
                {
                    <span style="color:green;">// subQueries = this.CompileSubQueries( info.Query );
                    </span>subQueries = Invoke( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>) );

                    ModifySubQueries( (<span style="color:#2b91af;">IEnumerable</span>)subQueries );

                    <span style="color:green;">// readerFactory = this.GetReaderFactory( info.Query, TypeSystem.GetElementType( info.ResultType ) );
                    </span><span style="color:blue;">var </span>resultType = Invoke( info, <span style="color:#a31515;">&quot;get_ResultType&quot; </span>);
                    <span style="color:blue;">var </span>typeSystemType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.TypeSystem&quot; </span>);
                    <span style="color:blue;">var </span>elementType = Invoke( typeSystemType, <span style="color:#a31515;">&quot;GetElementType&quot;</span>, resultType );

                    readerFactory = Invoke( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>), elementType );
                }

                <span style="color:#2b91af;">FieldInfo </span>providerField = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">DataContext </span>).GetField( <span style="color:#a31515;">&quot;provider&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
                providerField.SetValue( dc, oldProvider );

                <span style="color:green;">//            System.Diagnostics.Trace.WriteLine( string.Format( &quot;DataContext {0} interceptor released (compiled query)&quot;, dc.GetHashCode() ) );

                // return new CompiledQuery( this, query, queries, readerFactory, subQueries );
                </span><span style="color:blue;">var </span>compiledQueryType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlProvider+CompiledQuery&quot; </span>);

                <span style="color:blue;">return </span><span style="color:#2b91af;">Activator</span>.CreateInstance(
                    compiledQueryType,
                    <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic,
                    <span style="color:blue;">null</span>,
                    <span style="color:blue;">new object</span>[] { oldProvider, query, queries, readerFactory, subQueries },
                    <span style="color:blue;">null </span>);
            }
            <span style="color:blue;">catch </span>( <span style="color:#2b91af;">TargetInvocationException </span>ex )
            {
                <span style="color:blue;">throw </span>ex.InnerException;
            }
        }

        <span style="color:blue;">protected internal virtual </span><span style="color:#2b91af;">IExecuteResult </span>ExecuteImpl( <span style="color:#2b91af;">Expression </span>query )
        {
            <span style="color:blue;">try
            </span>{
                <span style="color:blue;">var </span>assembly = <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">SqlProvider </span>).Assembly;

                <span style="color:green;">/*
                this.CheckDispose();
                this.CheckInitialized();
                this.CheckNotDeleted();
                if (query == null)
                {
                    throw Error.ArgumentNull(&quot;query&quot;);
                }
                */

                // this.InitializeProviderMode();
                </span>Invoke( oldProvider, <span style="color:#a31515;">&quot;InitializeProviderMode&quot; </span>);

                <span style="color:green;">// query = Funcletizer.Funcletize(query);
                </span><span style="color:blue;">var </span>funcletizerType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.Funcletizer&quot; </span>);
                query = (<span style="color:#2b91af;">Expression</span>)Invoke( funcletizerType, <span style="color:#a31515;">&quot;Funcletize&quot;</span>, query );

                <span style="color:green;">// if ( this.EnableCacheLookup )
                </span><span style="color:blue;">if </span>( (<span style="color:blue;">bool</span>)Invoke( oldProvider, <span style="color:#a31515;">&quot;get_EnableCacheLookup&quot; </span>) )
                {
                    <span style="color:green;">// IExecuteResult cachedResult = this.GetCachedResult(query);
                    </span><span style="color:blue;">object </span>cachedResult = Invoke( oldProvider, <span style="color:#a31515;">&quot;GetCachedResult&quot;</span>, query );

                    <span style="color:blue;">if </span>( cachedResult != <span style="color:blue;">null </span>)
                    {
                        <span style="color:green;">// return cachedResult;
                        </span><span style="color:blue;">return </span>(<span style="color:#2b91af;">IExecuteResult</span>)cachedResult;
                    }
                }

                <span style="color:green;">// SqlNodeAnnotations annotations = new SqlNodeAnnotations();
                </span><span style="color:blue;">var </span>annotations = <span style="color:#2b91af;">Activator</span>.CreateInstance( assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.SqlNodeAnnotations&quot; </span>) );

                <span style="color:green;">// QueryInfo[] queries = this.BuildQuery(query, annotations);
                </span><span style="color:blue;">var </span>queries = Invoke( oldProvider, <span style="color:#a31515;">&quot;BuildQuery&quot;</span>, query, annotations );

                <span style="color:blue;">var </span>info = ModifyQueries( (<span style="color:#2b91af;">IEnumerable</span>)queries );

                <span style="color:green;">// this.CheckSqlCompatibility(queries, annotations);
                </span>Invoke( oldProvider, <span style="color:#a31515;">&quot;CheckSqlCompatibility&quot;</span>, queries, annotations );

                <span style="color:#2b91af;">LambdaExpression </span>expression = query <span style="color:blue;">as </span><span style="color:#2b91af;">LambdaExpression</span>;

                <span style="color:blue;">if </span>( expression != <span style="color:blue;">null </span>)
                {
                    query = expression.Body;
                }

                <span style="color:green;">// IObjectReaderFactory readerFactory = null;
                </span><span style="color:blue;">object </span>readerFactory = <span style="color:blue;">null</span>;

                <span style="color:green;">// ICompiledSubQuery[] subQueries = null;
                </span><span style="color:blue;">object </span>subQueries = <span style="color:blue;">null</span>;

                <span style="color:green;">// QueryInfo info = queries[queries.Length - 1];
                // info defined above

                </span><span style="color:blue;">var </span>resultShape = (<span style="color:blue;">int</span>)Invoke( info, <span style="color:#a31515;">&quot;get_ResultShape&quot; </span>);

                <span style="color:green;">// if (info.ResultShape == ResultShape.Singleton)
                </span><span style="color:blue;">if </span>( resultShape == 1 <span style="color:green;">/* Singleton */ </span>)
                {
                    <span style="color:green;">// subQueries = this.CompileSubQueries(info.Query);
                    </span>subQueries = Invoke( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>) );

                    ModifySubQueries( (<span style="color:#2b91af;">IEnumerable</span>)subQueries );

                    <span style="color:green;">// readerFactory = this.GetReaderFactory(info.Query, info.ResultType);
                    </span>readerFactory = Invoke( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>), Invoke( info, <span style="color:#a31515;">&quot;get_ResultType&quot; </span>) );
                }
                <span style="color:green;">// else if (info.ResultShape == ResultShape.Sequence)
                </span><span style="color:blue;">else if </span>( resultShape == 2 <span style="color:green;">/* Sequence */ </span>)
                {
                    <span style="color:green;">// subQueries = this.CompileSubQueries(info.Query);
                    </span>subQueries = Invoke( oldProvider, <span style="color:#a31515;">&quot;CompileSubQueries&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>) );

                    ModifySubQueries( (<span style="color:#2b91af;">IEnumerable</span>)subQueries );

                    <span style="color:green;">// readerFactory = this.GetReaderFactory(info.Query, TypeSystem.GetElementType(info.ResultType));
                    </span><span style="color:blue;">var </span>resultType = Invoke( info, <span style="color:#a31515;">&quot;get_ResultType&quot; </span>);
                    <span style="color:blue;">var </span>typeSystemType = assembly.GetType( <span style="color:#a31515;">&quot;System.Data.Linq.SqlClient.TypeSystem&quot; </span>);
                    <span style="color:blue;">var </span>elementType = Invoke( typeSystemType, <span style="color:#a31515;">&quot;GetElementType&quot;</span>, resultType );

                    readerFactory = Invoke( oldProvider, <span style="color:#a31515;">&quot;GetReaderFactory&quot;</span>, Invoke( info, <span style="color:#a31515;">&quot;get_Query&quot; </span>), elementType );
                }

                <span style="color:green;">// return this.ExecuteAll(query, queries, readerFactory, null, subQueries);
                </span><span style="color:blue;">return </span>(<span style="color:#2b91af;">IExecuteResult</span>)Invoke( oldProvider, <span style="color:#a31515;">&quot;ExecuteAll&quot;</span>, query, queries, readerFactory, <span style="color:blue;">null</span>, subQueries );
            }
            <span style="color:blue;">catch </span>( <span style="color:#2b91af;">TargetInvocationException </span>ex )
            {
                <span style="color:blue;">throw </span>ex.InnerException;
            }
        }

        <span style="color:blue;">private object </span>ModifyQueries( <span style="color:#2b91af;">IEnumerable </span>queries )
        {
            <span style="color:blue;">object </span>lastQuery = <span style="color:blue;">null</span>;

            <span style="color:blue;">foreach </span>( <span style="color:blue;">var </span>q <span style="color:blue;">in </span>queries )
            {
                lastQuery = q;

                ModifyQuery( q );
            }

            <span style="color:blue;">return </span>lastQuery;
        }

        <span style="color:blue;">private void </span>ModifySubQueries( <span style="color:#2b91af;">IEnumerable </span>subQueries )
        {
            <span style="color:blue;">if </span>( subQueries == <span style="color:blue;">null </span>) <span style="color:blue;">return</span>;

            <span style="color:blue;">foreach </span>( <span style="color:blue;">var </span>sq <span style="color:blue;">in </span>subQueries )
            {
                <span style="color:blue;">var </span>queryInfoField = sq.GetType().GetField( <span style="color:#a31515;">&quot;queryInfo&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
                <span style="color:blue;">var </span>queryInfo = queryInfoField.GetValue( sq );
                ModifyQuery( queryInfo );

                <span style="color:blue;">var </span>subQueriesField = sq.GetType().GetField( <span style="color:#a31515;">&quot;subQueries&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
                <span style="color:blue;">var </span>nestedSubQueries = subQueriesField.GetValue( sq );

                <span style="color:blue;">if </span>( nestedSubQueries != <span style="color:blue;">null </span>) ModifySubQueries( (<span style="color:#2b91af;">IEnumerable</span>)nestedSubQueries );
            }
        }

        <span style="color:blue;">private void </span>ModifyQuery( <span style="color:blue;">object </span>q <span style="color:green;">/* QueryInfo */ </span>)
        {
            <span style="color:blue;">var </span>commandTextField = q.GetType().GetField( <span style="color:#a31515;">&quot;commandText&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );
            <span style="color:blue;">var </span>parametersField = q.GetType().GetField( <span style="color:#a31515;">&quot;parameters&quot;</span>, <span style="color:#2b91af;">BindingFlags</span>.Instance | <span style="color:#2b91af;">BindingFlags</span>.Public | <span style="color:#2b91af;">BindingFlags</span>.NonPublic );

            <span style="color:blue;">var </span>commandText = (<span style="color:blue;">string</span>)commandTextField.GetValue( q );
            <span style="color:blue;">var </span>parameterInfos = parametersField.GetValue( q );
            <span style="color:blue;">var </span>parameters = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt;();

            <span style="color:blue;">foreach </span>( <span style="color:blue;">var </span>p <span style="color:blue;">in </span>(<span style="color:#2b91af;">IEnumerable</span>)parameterInfos )
            {
                <span style="color:blue;">var </span>param = Invoke( p, <span style="color:#a31515;">&quot;get_Parameter&quot; </span>);
                <span style="color:blue;">var </span>name = (<span style="color:blue;">string</span>)Invoke( param, <span style="color:#a31515;">&quot;get_Name&quot; </span>);

                parameters[ name ] = Invoke( p, <span style="color:#a31515;">&quot;get_Value&quot; </span>);
            }

            <span style="color:blue;">var </span>modifiedCommandText = modifyCommand( commandText, parameters );

<span style="color:green;">//            System.Diagnostics.Trace.WriteLine( modifiedCommandText + &quot;\n---&quot; );

            </span>commandTextField.SetValue( q, modifiedCommandText );
        }
<span style="color:green;">/*
        protected internal DbCommand GetCommandImpl( Expression query )
        {
            return (DbCommand)Invoke( oldProvider, &quot;GetCommand&quot;, query );
        }

        protected internal string GetQueryTextImpl( Expression query )
        {
            return (string)Invoke( oldProvider, &quot;GetQueryText&quot;, query );
        }
*/
        </span><span style="color:blue;">internal interface </span><span style="color:#2b91af;">IProviderProxy
        </span>{
            <span style="color:#2b91af;">ReflectionDataContextInterceptor </span>Interceptor { <span style="color:blue;">get</span>; }
            <span style="color:blue;">object </span>OldProvider { <span style="color:blue;">get</span>; }
        }

        <span style="color:blue;">public class </span><span style="color:#2b91af;">ProviderProxy </span>: <span style="color:#2b91af;">RealProxy</span>, <span style="color:#2b91af;">IRemotingTypeInfo</span>, <span style="color:#2b91af;">IProviderProxy
        </span>{
            <span style="color:blue;">public </span><span style="color:#2b91af;">ReflectionDataContextInterceptor </span>Interceptor { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }
            <span style="color:blue;">public object </span>OldProvider { <span style="color:blue;">get</span>; <span style="color:blue;">private set</span>; }

            <span style="color:blue;">internal </span>ProviderProxy( <span style="color:#2b91af;">ReflectionDataContextInterceptor </span>extender, <span style="color:blue;">object </span>oldProvider )
                : <span style="color:blue;">base</span>( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ContextBoundObject </span>) )
            {
                <span style="color:blue;">this</span>.Interceptor = extender;
                <span style="color:blue;">this</span>.OldProvider = oldProvider;
            }

            <span style="color:blue;">public override </span><span style="color:#2b91af;">IMessage </span>Invoke( <span style="color:#2b91af;">IMessage </span>msg )
            {
                <span style="color:blue;">if </span>( msg <span style="color:blue;">is </span><span style="color:#2b91af;">IMethodCallMessage </span>)
                {
                    <span style="color:#2b91af;">IMethodCallMessage </span>call = (<span style="color:#2b91af;">IMethodCallMessage</span>)msg;
                    <span style="color:#2b91af;">MethodInfo </span>mi = <span style="color:blue;">null</span>;

                    <span style="color:blue;">if </span>( call.MethodBase.DeclaringType.Name == <span style="color:#a31515;">&quot;IProvider&quot; </span>&amp;&amp; call.MethodBase.DeclaringType.IsInterface )
                    {
                        Interceptor.providerType = call.MethodBase.DeclaringType;

                        mi = <span style="color:#2b91af;">ReflectionDataContextInterceptor</span>.GetMethod( <span style="color:blue;">typeof</span>( <span style="color:#2b91af;">ReflectionDataContextInterceptor </span>), call.MethodBase.Name + <span style="color:#a31515;">&quot;Impl&quot;</span>, call.Args );

                        <span style="color:blue;">if </span>( mi == <span style="color:blue;">null </span>&amp;&amp; OldProvider != <span style="color:blue;">null </span>)
                        {
                            mi = <span style="color:#2b91af;">ReflectionDataContextInterceptor</span>.GetMethod( call.MethodBase.DeclaringType, call.MethodBase.Name, call.Args );

                            <span style="color:blue;">try
                            </span>{
                                <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( mi.Invoke( OldProvider, call.Args ), <span style="color:blue;">null</span>, 0, <span style="color:blue;">null</span>, call );
                            }
                            <span style="color:blue;">catch </span>( <span style="color:#2b91af;">TargetInvocationException </span>e )
                            {
                                <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( e.InnerException, call );
                            }
                        }

                        <span style="color:blue;">if </span>( mi != <span style="color:blue;">null </span>)
                        {
                            <span style="color:blue;">try
                            </span>{
                                <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( mi.Invoke( <span style="color:blue;">this</span>.Interceptor, call.Args ), <span style="color:blue;">null</span>, 0, <span style="color:blue;">null</span>, call );
                            }
                            <span style="color:blue;">catch </span>( <span style="color:#2b91af;">TargetInvocationException </span>e )
                            {
                                <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( e.InnerException, call );
                            }
                        }
                    }
<span style="color:green;">//                    else mi = typeof( ReflectionDataContextInterceptor ).GetMethod( call.MethodBase.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
                    </span><span style="color:blue;">else
                    </span>{
                        mi = <span style="color:#2b91af;">ReflectionDataContextInterceptor</span>.GetMethod( OldProvider.GetType(), call.MethodBase.Name, call.Args );

                        <span style="color:blue;">if </span>( mi != <span style="color:blue;">null </span>)
                        {
                            <span style="color:blue;">try
                            </span>{
                                <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( mi.Invoke( OldProvider, call.Args ), <span style="color:blue;">null</span>, 0, <span style="color:blue;">null</span>, call );
                            }
                            <span style="color:blue;">catch </span>( <span style="color:#2b91af;">TargetInvocationException </span>e )
                            {
                                <span style="color:blue;">return new </span><span style="color:#2b91af;">ReturnMessage</span>( e.InnerException, call );
                            }
                        }
                    }

                    <span style="color:blue;">throw new </span><span style="color:#2b91af;">NotImplementedException</span>(
                        <span style="color:blue;">string</span>.Format( <span style="color:#a31515;">&quot;Method not found: {0}( {1} )&quot;</span>,
                            call.MethodBase.Name,
                            <span style="color:blue;">string</span>.Join( <span style="color:#a31515;">&quot;, &quot;</span>, call.Args.Select( a =&gt; <span style="color:#2b91af;">Convert</span>.ToString( a ) ) ) ) );
                }

                <span style="color:blue;">throw new </span><span style="color:#2b91af;">NotImplementedException</span>();
            }

            <span style="color:blue;">public bool </span>CanCastTo( <span style="color:#2b91af;">Type </span>fromType, <span style="color:blue;">object </span>o )
            {
                <span style="color:blue;">return true</span>;
            }

            <span style="color:blue;">public string </span>TypeName
            {
                <span style="color:blue;">get </span>{ <span style="color:blue;">return this</span>.GetType().Name; }
                <span style="color:blue;">set </span>{ }
            }
        }
    }</pre>
<p>It’s still evil, but works great <img style="border-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2012/07/wlemoticon-smile.png?w=490" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/753/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=753&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/07/06/modifying-linq-to-sql-command-text-again/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2012/07/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>
	</item>
		<item>
		<title>Recursive Methods in Expression Trees</title>
		<link>http://chriscavanagh.wordpress.com/2012/06/18/recursive-methods-in-expression-trees/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/06/18/recursive-methods-in-expression-trees/#comments</comments>
		<pubDate>Mon, 18 Jun 2012 20:09:41 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=745</guid>
		<description><![CDATA[Writing a recursive method in C# is easy, but it’s not immediately obvious how to do the same in a LINQ expression tree. Here’s the usual factorial example: public uint Factorial( uint n ) { return ( n &#60;= 1 ) ? 1 : n * Factorial( n - 1 ); } To represent this [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=745&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Writing a recursive method in C# is easy, but it’s not immediately obvious how to do the same in a LINQ expression tree.</p>
<p>Here’s the usual factorial example:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">uint</span> Factorial( <span class="kwrd">uint</span> n )
{
    <span class="kwrd">return</span> ( n &lt;= 1 ) ? 1 : n * Factorial( n - 1 );
}</pre>
<p>To represent this in an expression tree, just assign the method to a local variable and call it.&#160; Here’s the equivalent C#:</p>
<pre class="csharpcode">Func&lt;<span class="kwrd">uint</span>, <span class="kwrd">uint</span>&gt; factorial;
factorial = n =&gt; ( n &lt;= 1 ) ? 1 : n * factorial( n - 1 );</pre>
<p>Here’s how you might build it:</p>
<pre class="csharpcode"><span class="kwrd">public</span> Expression&lt;Func&lt;T, T&gt;&gt; MakeFactorialExpression&lt;T&gt;()
{
    var nParam = Expression.Parameter( <span class="kwrd">typeof</span>( T ), <span class="str">&quot;n&quot;</span> );
    var methodVar = Expression.Variable( <span class="kwrd">typeof</span>( Func&lt;T, T&gt; ), <span class="str">&quot;factorial&quot;</span> );
    var one = Expression.Convert( Expression.Constant( 1 ), <span class="kwrd">typeof</span>( T ) );

    <span class="kwrd">return</span> Expression.Lambda&lt;Func&lt;T, T&gt;&gt;(
        Expression.Block(
            <span class="rem">// Func&lt;uint, uint&gt; method;</span>
            <span class="kwrd">new</span>[] { methodVar },
            <span class="rem">// method = n =&gt; ( n &lt;= 1 ) ? 1 : n * method( n - 1 );</span>
            Expression.Assign(
                methodVar,
                Expression.Lambda&lt;Func&lt;T, T&gt;&gt;(
                    Expression.Condition(
                        <span class="rem">// ( n &lt;= 1 )</span>
                        Expression.LessThanOrEqual( nParam, one ),
                        <span class="rem">// 1</span>
                        one,
                        <span class="rem">// n * method( n - 1 )</span>
                        Expression.Multiply(
                            <span class="rem">// n</span>
                            nParam,
                            <span class="rem">// method( n - 1 )</span>
                            Expression.Invoke(
                                methodVar,
                                Expression.Subtract( nParam, one ) ) ) ),
                    nParam ) ),
            <span class="rem">// return method( n );</span>
            Expression.Invoke( methodVar, nParam ) ),
        nParam );            
}</pre>
<p>This just returns an Expression&lt;Func&lt;T, T&gt;&gt;, which you could compile and call like this:</p>
<pre class="csharpcode">var factorial = MakeFactorialExpression&lt;<span class="kwrd">uint</span>&gt;().Compile();
var result = factorial( 5 );</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/745/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/745/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=745&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/06/18/recursive-methods-in-expression-trees/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>
	</item>
		<item>
		<title>WPF 4 WebBrowser Update</title>
		<link>http://chriscavanagh.wordpress.com/2012/05/23/wpf-4-webbrowser-update/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/05/23/wpf-4-webbrowser-update/#comments</comments>
		<pubDate>Thu, 24 May 2012 03:32:57 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=732</guid>
		<description><![CDATA[Since posting the WPF 4 version of my Awesomium (Chromium-based) browser wrapper, Awesomium introduced its own wrapper.&#160; I assumed everyone would just use the new wrapper and everything would be fine. Turns out it wasn’t quite that simple, so I’ve updated my WPF 4.0 Chromium browser demo to use the new Awesomium wrapper.&#160; You can [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=732&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Since posting the WPF 4 version of my Awesomium (Chromium-based) <a title="A Real WPF 4.0 WebBrowser" href="http://chriscavanagh.wordpress.com/2010/10/04/a-real-net-4-0-webbrowser/" target="_blank">browser wrapper</a>, Awesomium introduced its own wrapper.&#160; I assumed everyone would just use the new wrapper and everything would be fine.</p>
<p>Turns out it wasn’t quite that simple, so I’ve updated my WPF 4.0 Chromium browser demo to use the new Awesomium wrapper.&#160; You can get the project <a title="Cjc.AwesomiumDotNetDemo" href="http://dl.dropbox.com/u/6684256/Blog/Cjc.AwesomiumDotNetDemo.zip" target="_blank">here</a> (requires VS2010).</p>
<p>It’s setup assuming you’ve installed the <a title="Awesomium SDK install" href="http://awesomium.com/download/" target="_blank">Awesomium SDK</a> to the default location.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/732/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/732/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=732&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/05/23/wpf-4-webbrowser-update/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>
	</item>
		<item>
		<title>MVC Strongly-Typed Action Helpers</title>
		<link>http://chriscavanagh.wordpress.com/2012/05/22/mvc-strongly-typed-action-helpers/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/05/22/mvc-strongly-typed-action-helpers/#comments</comments>
		<pubDate>Wed, 23 May 2012 04:10:59 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=728</guid>
		<description><![CDATA[Way back in 2009, the MVC Futures assembly introduced “strongly-typed action helpers”.&#160; They allowed you to render links using lambda expressions pointing directly to the actions on your controller, rather than using strings: &#60;%= Html.ActionLink&#60;HomeController&#62;( c =&#62; c.Index() ) %&#62; Other benefits included: Intellisense and refactoring in Visual Studio Compile-time validation Check if user is [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=728&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Way back in 2009, the MVC Futures assembly introduced “strongly-typed action helpers”.&#160; They allowed you to render links using lambda expressions pointing directly to the actions on your controller, rather than using strings:</p>
<pre>&lt;%= Html.ActionLink&lt;HomeController&gt;( c =&gt; c.Index() ) %&gt;</pre>
<p>Other benefits included:</p>
<ul>
<li>Intellisense and refactoring in Visual Studio </li>
<li>Compile-time validation </li>
<li>Check if user is <a title="MVC IsAuthorized and AuthorizedActionLink" href="http://chriscavanagh.wordpress.com/2010/07/16/mvc-isauthorized-and-authorizedactionlink-revisited/" target="_blank">authorized for an action</a> (automatically hide or disable links) </li>
</ul>
<p>Unfortunately there was a performance overhead associated with all this <a title="http://haacked.com/archive/2009/06/02/alternative-to-expressions.aspx" href="http://haacked.com/archive/2009/06/02/alternative-to-expressions.aspx">(http://haacked.com/archive/2009/06/02/alternative-to-expressions.aspx</a>) that led to some interesting alternatives, including the <a title="T4MVC" href="http://mvccontrib.codeplex.com/wikipage?title=T4MVC" target="_blank">T4MVC</a> project.</p>
<p>However, there’s still hope for strongly-typed helpers.&#160; You can find an alternative implementation <a title="Strongly Typed Action Helpers demo source" href="http://dl.dropbox.com/u/6684256/Strongly-typed%20action%20helpers.zip" target="_blank">here</a> that aims to resolve most of the performance concerns.</p>
<p>The main classes of interest are:</p>
<ul>
<li>ActionTemplate – Captures controller and action name from action expression.&#160; Defers getting “baked in” parameter values until (and if) needed. </li>
<li>ActionBuilder – Created from ActionTemplate, captures optional parameter values.&#160; Renders links and forms (calls HtmlHelper.ActionLink or BeginForm). </li>
</ul>
<p>Previously, most of the performance hit was from compiling the argument expressions. This version tries a few alternative approaches first, like extracting the argument value directly if it&#8217;s a ConstantExpression, and allowing named parameters in the ActionBuilder instance (if it finds a value in the parameters collection, it doesn&#8217;t bother looking at the argument part of the action expression).</p>
<p>Some of the features demonstrated (in HomeController.cs) include:</p>
<ul>
<li>Using ActionBuilders as properties of the view model.&#160; The controller defines the target actions, and the view just renders them as links. </li>
<li>Using a static ActionTemplate instance to minimize the work needed to generate a list of parameterized ActionBuilders.&#160; Note the template expression simply passes ‘null’ as the argument; in this case it’ll never get used as the ActionBuilders are given their own parameter values.</li>
<li>A dummy authentication mechanism to demonstrate automatically disabled links (log in with password “password” to enable the actions marked with the Authorize attribute). </li>
</ul>
<p>You can get all the source code <a title="Strongly Typed Action Helpers demo source" href="http://dl.dropbox.com/u/6684256/Strongly-typed%20action%20helpers.zip" target="_blank">here</a>&#160;<img style="border-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2012/05/wlemoticon-smile.png?w=490" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/728/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/728/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=728&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/05/22/mvc-strongly-typed-action-helpers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2012/05/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>
	</item>
		<item>
		<title>Expression Trees + Generic Static Constructors</title>
		<link>http://chriscavanagh.wordpress.com/2012/04/26/expression-trees-generic-static-constructors/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/04/26/expression-trees-generic-static-constructors/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 04:09:41 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=718</guid>
		<description><![CDATA[A great thing about .NET Expression Trees is you can compile them at runtime, and they’ll execute as fast as any .NET code.&#160; However, while building and compiling a tree is pretty quick, it’s best if you only need to do it once. The way you’d usually do that is cache the compiled delegate somewhere.&#160; [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=718&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>A great thing about .NET Expression Trees is you can compile them at runtime, and they’ll execute as fast as any .NET code.&#160; However, while building and compiling a tree is pretty quick, it’s best if you only need to do it once.</p>
<p>The way you’d usually do that is cache the compiled delegate somewhere.&#160; If you just want to create it and use it repeatedly in the same code block, just hold the delegate in a local variable:</p>
<pre class="csharpcode"><span class="kwrd">void</span> Main()
{
    var dump = MakeDumpDelegate&lt;DateTime&gt;();

    <span class="kwrd">for</span> ( var yearOffset = 0; yearOffset &lt; 5; ++ yearOffset )
    {
        Console.WriteLine( <span class="kwrd">string</span>.Join( <span class="str">&quot; | &quot;</span>, dump( DateTime.Now.AddYears( yearOffset ) ) ) );
    }
}

Func&lt;TModel, <span class="kwrd">object</span>[]&gt; MakeDumpDelegate&lt;TModel&gt;()
{
    var modelParam = Expression.Parameter( <span class="kwrd">typeof</span>( TModel ), <span class="str">&quot;model&quot;</span> );
    var properties = <span class="kwrd">typeof</span>( TModel ).GetProperties( BindingFlags.Public | BindingFlags.Instance ).OrderBy( p =&gt; p.Name );

    var lambda = Expression.Lambda&lt;Func&lt;TModel, <span class="kwrd">object</span>[]&gt;&gt;(
        Expression.NewArrayInit(
            <span class="kwrd">typeof</span>( <span class="kwrd">object</span> ),
            from p <span class="kwrd">in</span> properties
            select Expression.Convert( Expression.MakeMemberAccess( modelParam, p ), <span class="kwrd">typeof</span>( <span class="kwrd">object</span> ) ) ),
        modelParam );

    <span class="kwrd">return</span> lambda.Compile();
}</pre>
<p>Here MakeDumpDelegate creates a delegate that takes an object of type TModel, and returns an object array of its alphabetically sorted property values.&#160; In the Main method we’re creating a delegate based on the DateTime type, running it 5 times and spitting out the values.</p>
<p>What if there are a bunch of classes we want to run delegates for?&#160; We could move the code out of Main and call it wherever we need it:</p>
<pre class="csharpcode"><span class="kwrd">void</span> Main()
{
    var dates = Enumerable.Range( 0, 5 ).Select( yo =&gt; DateTime.Now.AddYears( yo ) );

    <span class="kwrd">foreach</span> ( var d <span class="kwrd">in</span> DumpProperties( dates ) )
    {
        Console.WriteLine( d );
    }
}

IEnumerable&lt;<span class="kwrd">string</span>&gt; DumpProperties&lt;TModel&gt;( IEnumerable&lt;TModel&gt; models )
{
    var dump = MakeDumpDelegate&lt;TModel&gt;();

    <span class="kwrd">return</span> from m <span class="kwrd">in</span> models select <span class="kwrd">string</span>.Join( <span class="str">&quot; | &quot;</span>, dump( m ) );
}</pre>
<p>This works great, and we can call DumpProperties with any collection we like.&#160; The problem is, we’re building and compiling the expression tree every time we use it.&#160; This is pretty inefficient, so let’s add a cache of delegates for each type.</p>
<p>But wait…&#160; Let’s say we want to hit these things from multiple threads.&#160; We’re probably going to need a static Dictionary&lt;Type, delegate&gt; to hold onto them, and we’ll need to provide some locking to stop the threads messing us up.&#160; This is too complicated to be good.</p>
<p>Instead, we’ll use a generic class and let .NET help us out.&#160; When you declare a generic class, each specialization of that class gets its own copy of its static members:</p>
<pre class="csharpcode"><span class="kwrd">class</span> MyClass&lt;T&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> T MyStaticValue { get; set; }
}</pre>
<p>So if you access <font face="Courier New">MyClass&lt;int&gt;.MyStaticValue</font> or <font face="Courier New">MyClass&lt;double&gt;.MyStaticValue</font>, they’re obviously different instances (one is <font face="Courier New">int</font> and the other <font face="Courier New">double</font>).&#160; We can use this to hold onto our delegate:</p>
<pre class="csharpcode"><span class="kwrd">void</span> Main()
{
    var dates = Enumerable.Range( 0, 5 ).Select( yo =&gt; DateTime.Now.AddYears( yo ) );

    <span class="kwrd">foreach</span> ( var d <span class="kwrd">in</span> DumpProperties( dates ) )
    {
        Console.WriteLine( d );
    }
}

IEnumerable&lt;<span class="kwrd">string</span>&gt; DumpProperties&lt;TModel&gt;( IEnumerable&lt;TModel&gt; models )
{
    var dump = DumpDelegate&lt;TModel&gt;.Dump;

    <span class="kwrd">return</span> from m <span class="kwrd">in</span> models select <span class="kwrd">string</span>.Join( <span class="str">&quot; | &quot;</span>, dump( m ) );
}

<span class="kwrd">class</span> DumpDelegate&lt;TModel&gt;
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> Func&lt;TModel, <span class="kwrd">object</span>[]&gt; Dump { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">static</span> DumpDelegate()
    {
        var modelParam = Expression.Parameter( <span class="kwrd">typeof</span>( TModel ), <span class="str">&quot;model&quot;</span> );
        var properties = <span class="kwrd">typeof</span>( TModel ).GetProperties( BindingFlags.Public | BindingFlags.Instance ).OrderBy( p =&gt; p.Name );
    
        var lambda = Expression.Lambda&lt;Func&lt;TModel, <span class="kwrd">object</span>[]&gt;&gt;(
            Expression.NewArrayInit(
                <span class="kwrd">typeof</span>( <span class="kwrd">object</span> ),
                from p <span class="kwrd">in</span> properties
                select Expression.Convert( Expression.MakeMemberAccess( modelParam, p ), <span class="kwrd">typeof</span>( <span class="kwrd">object</span> ) ) ),
            modelParam );

        Dump = lambda.Compile();
    }
}</pre>
<p>What’s great about this is .NET guarantees the static constructor will only be called once, and in a completely thread-safe manner.&#160; Since DumpDelegate is a generic class based on TModel, each specialization will only be initialized once &#8211; and only on first use.&#160; Our threading headache has just disappeared, and we&#8217;re building and compiling the tree just once for each model type <img style="border-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2012/04/wlemoticon-smile1.png?w=490" /></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fchriscavanagh.wordpress.com%2f2012%2f04%2f26%2fexpression-trees-generic-static-constructors%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%253a%252f%252fchriscavanagh.wordpress.com%252f2012%252f04%252f26%252fexpression-trees-generic-static-constructors%252f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/718/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/718/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=718&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/04/26/expression-trees-generic-static-constructors/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2012/04/wlemoticon-smile1.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%253a%252f%252fchriscavanagh.wordpress.com%252f2012%252f04%252f26%252fexpression-trees-generic-static-constructors%252f" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Twin Cities Code Camp 2012</title>
		<link>http://chriscavanagh.wordpress.com/2012/04/05/twin-cities-code-camp-2012/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/04/05/twin-cities-code-camp-2012/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 22:04:50 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=710</guid>
		<description><![CDATA[Live in Minnesota?&#160; http://tccc12.eventbrite.com&#160;<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=710&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Live in Minnesota?&#160; <a title="http://tccc12.eventbrite.com" href="http://tccc12.eventbrite.com">http://tccc12.eventbrite.com</a>&#160;<img style="border-style:none;" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://chriscavanagh.files.wordpress.com/2012/04/wlemoticon-smile.png?w=490" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/710/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/710/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=710&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/04/05/twin-cities-code-camp-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2012/04/wlemoticon-smile.png" medium="image">
			<media:title type="html">Smile</media:title>
		</media:content>
	</item>
		<item>
		<title>LOLCode Parser</title>
		<link>http://chriscavanagh.wordpress.com/2012/03/19/lolcode-parser/</link>
		<comments>http://chriscavanagh.wordpress.com/2012/03/19/lolcode-parser/#comments</comments>
		<pubDate>Tue, 20 Mar 2012 04:07:49 +0000</pubDate>
		<dc:creator>Chris Cavanagh</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">https://chriscavanagh.wordpress.com/?p=694</guid>
		<description><![CDATA[On the second Thursday of the month at 5pm, the Rochester, MN .NET User Group meets at Mann Hall.  You’re very welcome to join us if you’re in the area. We often have someone interesting presenting something exciting, but occasionally that doesn’t work out and I’ll present something instead   This is where the LOLCode [&#8230;]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=694&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>On the second Thursday of the month at 5pm, the Rochester, MN .NET User Group meets at Mann Hall.  You’re very welcome to join us if you’re in the area.</p>
<p>We often have someone interesting presenting something exciting, but occasionally that doesn’t work out and I’ll present something instead <img class="wlEmoticon wlEmoticon-winkingsmile" style="border-style:none;" src="http://chriscavanagh.files.wordpress.com/2012/03/wlemoticon-winkingsmile.png?w=490" alt="Winking smile" />  This is where the LOLCode Parser was born…</p>
<p>First you should try it out <a href="http://www.chriscavanagh.com/Chris/LOLCode/" target="_blank">here</a>.  It’ll ask you to write some LOLCode and optionally give it some inputs to pass in.  Let’s start with “Hai World”…</p>
<pre class="code">HAI
CAN HAS STDIO?
VISIBLE "HAI WORLD!" N " I SLEEPIN"
KTHXBYE</pre>
<p>Paste that and click the “PLZ RUN THE CODE 4 ME” button.  This demonstrates the <span style="font-family:'Courier New';">VISIBLE</span> statement and the <span style="font-family:'Courier New';">N</span> concatenation operator.</p>
<p>Let’s step it up a bit and add some conditions (to see this work its magic, you’ll need an input value in the second textbox):</p>
<pre class="code">HAI
CAN HAS STDIO?
I HAS A VAR
VISIBLE "GIMMEH INPUTZ!..."
GIMMEH VAR
VISIBLE "U SEZ " N VAR
IZ VAR BIGR THAN 10?
    YARLY
        BTW this is true
        VISIBLE VAR N " IZ BIG NUMBER!"
    NOWAI
        BTW this is false
        VISIBLE VAR N " IZ LITTLE NUMBER!"
KTHX
VISIBLE "I IZ DONE"
KTHXBYE</pre>
<p>Here we’ve added some user input (<span style="font-family:'Courier New';">GIMMEH VAR</span> will read a line from the input source to the <span style="font-family:'Courier New';">VAR</span> variable). The <span style="font-family:'Courier New';">IZ..YARLY..NOWAI..KTHX</span> construct lets us specify a condition based on its value. The <span style="font-family:'Courier New';">BTW</span> statement begins a comment.</p>
<p>Cats won’t usually chase their tails like dogs will, but they use loops to remind their owners it’s feeding time. This one just wants to count to 10 between meows:</p>
<pre class="code">HAI
CAN HAS STDIO?
VISIBLE "HAI WORLD!"
I HAS A VAR
IM IN YR KITCHN
    UPZ VAR!!1
    VISIBLE VAR
    IZ VAR BIGR THAN 9? GTFO. KTHX
KTHX
VISIBLE "FEED MEOW!"
KTHXBYE</pre>
<p>If you’re thinking this isn’t very impressive, you’re right.  Still, it does have some cool points:</p>
<ul>
<li>It’s using a parser generated by <a title="TinyPG on CodeProject" href="http://www.codeproject.com/Articles/28294/a-Tiny-Parser-Generator-v1-2" target="_blank">TinyPG</a> (awesome tool on <a title="CodeProject" href="http://www.codeproject.com" target="_blank">CodeProject</a> by <a title="Herre Kuijpers" href="http://www.codeproject.com/script/Membership/View.aspx?mid=2192187" target="_blank">Herre Kuijpers</a>).</li>
<li>The LOLCode is being parsed into a LINQ expression tree (similar to this <a title="Excel Expressions and the DLR" href="http://chriscavanagh.wordpress.com/2009/02/19/custom-expressions-and-the-dlr-part-1/" target="_blank">old post</a>, but no <a title="Dynamic Language Runtime on Wikipedia" href="http://en.wikipedia.org/wiki/Dynamic_Language_Runtime" target="_blank">DLR</a> and much simpler).</li>
<li>Because it’s an expression tree, it can be compiled and cached on the server.  This should run as fast as C#, so your cat will be happy.  For this demo, if you don’t change the code between requests it’ll just run the cached, pre-compiled code.  Anything in the Inputs box is passed as a parameter.</li>
<li>This isn’t just an expression returning a value; it’s building a full LOLCode program (with conditions, loops etc).</li>
<li>It allows your program to run for up to two seconds; if it overstays its welcome, it will be brutally terminated (putting your cat in an infinite loop is animal cruelty).</li>
</ul>
<p>You’re unlikely to want LOLCode in your own apps, but some of the ideas could be useful.  For example, you could use it to provide a custom scripting language for clients to automate aspects of your apps.</p>
<p>You can find the source code <a title="Source code" href="http://www.chriscavanagh.com/Chris/Cjc.LOLCode.Demo.zip" target="_blank">here</a>.  It’s pretty easy to use TinyPG to define your own parser (see the Cjc.LOLCode.tpg file for sample syntax), then extend the ParseTreeVisitor / Visitor classes to build an expression tree.</p>
<p>Finally, here’s some bonus LOLCode:</p>
<pre class="code">HAI
CAN HAS STDIO?
VISIBLE "HAI WORLD!"
I HAS A VAR
I HAS A INPUTZ
IM IN YR KITCHN
    UPZ VAR!!1
    GIMMEH INPUTZ
    VISIBLE VAR N ", " N INPUTZ
    IZ VAR BIGR THAN 9? GTFO. KTHX
KTHX
VISIBLE "FEED MEOW!"
KTHXBYE</pre>
<p>And some inputs to go with it:</p>
<pre class="code">10
9
8
7
6
5
4
3
2
1</pre>
<p>You might also want to take a look at a LOLQL parser (source <a title="LOLQL demo source code" href="http://www.chriscavanagh.com/Chris/Cjc.LOLQL.Demo.zip" target="_blank">here</a>); it allows your cat to query a database through Entity Framework!</p>
<div class="wlWriterHeaderFooter" style="text-align:left;margin:0;padding:4px;"><a href="http://chriscavanagh.wordpress.com/2012/03/19/lolcode-parser/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://chriscavanagh.wordpress.com/2012/03/19/lolcode-parser/&amp;bgcolor=0080C0&amp;fgcolor=FFFFFF&amp;border=000000&amp;cbgcolor=D4E1ED&amp;cfgcolor=000000" alt="DotNetKicks Image" border="0/"></a></div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/chriscavanagh.wordpress.com/694/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/chriscavanagh.wordpress.com/694/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=chriscavanagh.wordpress.com&#038;blog=313491&#038;post=694&#038;subd=chriscavanagh&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://chriscavanagh.wordpress.com/2012/03/19/lolcode-parser/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/8b8858c8a6022411fc9d48c1f4963928?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Chris</media:title>
		</media:content>

		<media:content url="http://chriscavanagh.files.wordpress.com/2012/03/wlemoticon-winkingsmile.png" medium="image">
			<media:title type="html">Winking smile</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://chriscavanagh.wordpress.com/2012/03/19/lolcode-parser/&#38;bgcolor=0080C0&#38;fgcolor=FFFFFF&#38;border=000000&#38;cbgcolor=D4E1ED&#38;cfgcolor=000000" medium="image">
			<media:title type="html">DotNetKicks Image</media:title>
		</media:content>
	</item>
	</channel>
</rss>
