<?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>Eugene Prystupa's Weblog</title>
	<atom:link href="http://eprystupa.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://eprystupa.wordpress.com</link>
	<description>Patterns, designs, automated testing and more...</description>
	<lastBuildDate>Wed, 23 Nov 2011 12:56:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='eprystupa.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Eugene Prystupa's Weblog</title>
		<link>http://eprystupa.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://eprystupa.wordpress.com/osd.xml" title="Eugene Prystupa&#039;s Weblog" />
	<atom:link rel='hub' href='http://eprystupa.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Generating Market Data Snapshot from a Tick Stream using Rx</title>
		<link>http://eprystupa.wordpress.com/2010/10/16/generating-market-data-snapshot-from-a-tick-stream-using-rx-2/</link>
		<comments>http://eprystupa.wordpress.com/2010/10/16/generating-market-data-snapshot-from-a-tick-stream-using-rx-2/#comments</comments>
		<pubDate>Sun, 17 Oct 2010 03:34:35 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Reactive Extensions for .NET]]></category>
		<category><![CDATA[Reactive Framework]]></category>

		<guid isPermaLink="false">https://eprystupa.wordpress.com/2010/10/16/generating-market-data-snapshot-from-a-tick-stream-using-rx-2/</guid>
		<description><![CDATA[One of my colleges (http://weblogs.asp.net/sweinstein/) brought up an interesting problem: there is a common theme in finance applications to subscribe to a market data source to receive real time updates on the instruments that this source covers. A late subscriber (the one that has not been subscribed since the start of the trading day, for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=190&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of my colleges (<a title="http://weblogs.asp.net/sweinstein/" href="http://weblogs.asp.net/sweinstein/">http://weblogs.asp.net/sweinstein/</a>) brought up an interesting problem: there is a common theme in finance applications to subscribe to a market data source to receive real time updates on the instruments that this source covers. A late subscriber (the one that has not been subscribed since the start of the trading day, for example) usually expects to receive a snapshot per instrument before real time updates. So what is the best way to support snapshot guarantee, per instrument, from a “hot” underlying source using Rx? There are multiple ways to do it, of course, and here is my version of it:</p>
<pre class="code"><span style="color:blue;">public static </span>IObservable&lt;T&gt; WithCachedSnapshot&lt;T, TKey&gt;(
    <span style="color:blue;">this </span>IObservable&lt;T&gt; source,
    <span style="color:#2b91af;">Func</span>&lt;T, TKey&gt; keySelector)
{
    <span style="color:blue;">var </span>cache = <span style="color:blue;">new </span><span style="color:#2b91af;">Dictionary</span>&lt;TKey, T&gt;();
    <span style="color:blue;">return </span><span style="color:#2b91af;">Observable</span>.Defer(() =&gt; {
            <span style="color:blue;">lock </span>(cache)
                <span style="color:blue;">return </span>cache.Values.ToList().ToObservable();
        })
        .Concat(source.Do(s =&gt; {
            <span style="color:blue;">lock </span>(cache) cache[keySelector(s)] = s;
        }));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>If you can’t take my word for it, here is the proof that it works:</p>
<pre class="code">[<span style="color:#2b91af;">TestMethod</span>()]
<span style="color:blue;">public void </span>CacheByKeyTestHelper()
{
    <span style="color:green;">// Arrange
    </span><span style="color:#2b91af;">TestScheduler </span>scheduler = <span style="color:blue;">new </span><span style="color:#2b91af;">TestScheduler</span>();
    <span style="color:blue;">var </span>source = scheduler.CreateHotObservable(
        OnNext(100, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"MSFT"</span>, Price = 30.5 }),
        OnNext(101, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"IBM"</span>, Price = 130.2 }),
        OnNext(102, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"MSFT"</span>, Price = 31.5 }),
        OnNext(103, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"IBM"</span>, Price = 130.1 }),
        OnNext(104, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"AAPL"</span>, Price = 150.5 }));

    <span style="color:green;">// Act
    </span><span style="color:blue;">var </span>target = <span style="color:#2b91af;">RxExtensions</span>.WithCachedSnapshot(
        source,
        quote =&gt; quote.Ticker);
    <span style="color:blue;">var </span>results = scheduler.Run(() =&gt; target, 0, 0, 105);
    <span style="color:blue;">var </span>cachedResults = scheduler.Run(() =&gt; target, 0, 0, 200);

    <span style="color:green;">// Assert
    </span>results.AssertEqual(
        OnNext(100, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"MSFT"</span>, Price = 30.5 }),
        OnNext(101, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"IBM"</span>, Price = 130.2 }),
        OnNext(102, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"MSFT"</span>, Price = 31.5 }),
        OnNext(103, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"IBM"</span>, Price = 130.1 }),
        OnNext(104, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"AAPL"</span>, Price = 150.5 }));

    cachedResults.AssertEqual(
        OnNext(105, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"MSFT"</span>, Price = 31.5 }),
        OnNext(105, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"IBM"</span>, Price = 130.1 }),
        OnNext(105, <span style="color:blue;">new </span>{ Ticker = <span style="color:#a31515;">"AAPL"</span>, Price = 150.5 }));
}

<span style="color:blue;">private </span><span style="color:#2b91af;">Recorded</span>&lt;<span style="color:#2b91af;">Notification</span>&lt;T&gt;&gt; OnNext&lt;T&gt;(
    <span style="color:blue;">long </span>ticks, T value)
{
    <span style="color:blue;">return new </span><span style="color:#2b91af;">Recorded</span>&lt;<span style="color:#2b91af;">Notification</span>&lt;T&gt;&gt;(
        ticks,
        <span style="color:blue;">new </span><span style="color:#2b91af;">Notification</span>&lt;T&gt;.<span style="color:#2b91af;">OnNext</span>(value));
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/190/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=190&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2010/10/16/generating-market-data-snapshot-from-a-tick-stream-using-rx-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>Detecting Running High/Low Prices Using Reactive Framework &#8211; Follow-up</title>
		<link>http://eprystupa.wordpress.com/2010/01/01/detecting-running-highlow-prices-using-reactive-framework-follow-up/</link>
		<comments>http://eprystupa.wordpress.com/2010/01/01/detecting-running-highlow-prices-using-reactive-framework-follow-up/#comments</comments>
		<pubDate>Fri, 01 Jan 2010 14:08:17 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Reactive Extensions for .NET]]></category>
		<category><![CDATA[Reactive Framework]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/2010/01/01/detecting-running-highlow-prices-using-reactive-framework-follow-up/</guid>
		<description><![CDATA[This article shows some improvements to the original code presented in my previous post. Improvements are based on the feedback I received from Erik Meijer and his team and mainly focus on some built-in opportunities in Rx framework that I missed. Here is an extract from the original implementation of the running low feed: // [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=179&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This article shows some improvements to the original code presented in my <a href="http://eprystupa.wordpress.com/2009/12/18/detecting-running-highlow-prices-using-reactive-extensions-for-net/">previous post</a>. Improvements are based on the feedback I received from Erik Meijer and his team and mainly focus on some built-in opportunities in Rx framework that I missed. Here is an extract from the original implementation of the running low feed:</p>
<pre class="code"><span style="color:green;">// Daily low price feed
</span><span style="color:blue;">double </span>min = <span style="color:blue;">double</span>.MaxValue;
<span style="color:blue;">var </span>feedLo = feed
    .Where(p =&gt; p &lt; min)
    .Do(p =&gt; min = <span style="color:#2b91af;">Math</span>.Min(min, p))
    .Select(p =&gt; <span style="color:#a31515;">&quot;New LO: &quot; </span>+ p);</pre>
<p><a href="http://11011.net/software/vspaste"></a>This implementation depends on the external (to the framework) state (current low value stored in “min” local variable), “Do” combinator to continuously update this state with every price tick, and a “Where” combinator to suppress the ticks that do not represent running low value. Turns out, there is a better, more elegant and framework friendly way to implement this. It relies on the built-in “Scan” and “HoldUntilChanged” combinators:</p>
<pre class="code"><span style="color:green;">// Daily low price feed
</span><span style="color:blue;">var </span>feedLo = feed
    .Scan(<span style="color:#2b91af;">Math</span>.Min)
    .HoldUntilChanged()
    .Select(p =&gt; <span style="color:#a31515;">&quot;New LO: &quot; </span>+ p);</pre>
<p><a href="http://11011.net/software/vspaste"></a>The code above is functionally equivalent to the original one but is cleaner, more compact, and easier to read. This is how it works:</p>
<ul>
<li>“Scan” operator is used to accumulate the running min value. “Scan” is similar to “Aggregate” in the LINQ-to-Objects world but, instead of collapsing the sequence to a single accumulated value, it keeps outputting the current accumulated value with every tick. As a result “Math.Min” function is continuously applied with every new tick with accumulated min value and new price as arguments and its result is “ticked out”. This produces a stream where every successive number is either less than or equal to the previous one. Close to what we need except we want to suppress duplicates. </li>
<li>“HoldUntilChanged” is another built-in combinator that wraps an underlying stream and only repeats a value from it if this value differs from the previous one. Perfect for removing successive duplicates (please, note, it will NOT remove ALL the duplicates, only successive ones, so it is not a proper substitute to Distinct, when such a combinator exists) . We use “HoldUntilChanged” instead of original “Where” clause. </li>
</ul>
<p><span id="more-179"></span></p>
<p>Here is the full code:</p>
<pre class="code"><span style="color:green;">// simulate market data
</span><span style="color:blue;">var </span>rnd = <span style="color:blue;">new </span><span style="color:#2b91af;">Random</span>();
<span style="color:blue;">var </span>feed = <span style="color:#2b91af;">Observable</span>.Defer(() =&gt;
    <span style="color:#2b91af;">Observable</span>.Return(<span style="color:#2b91af;">Math</span>.Round(<span style="color:brown;">30.0 </span>+ rnd.NextDouble(), <span style="color:brown;">2</span>))
    .Delay(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">1 </span>* rnd.NextDouble())))
    .Repeat();

<span style="color:green;">// Daily low price feed
</span><span style="color:blue;">var </span>feedLo = feed
    .Scan(<span style="color:#2b91af;">Math</span>.Min)
    .HoldUntilChanged()
    .Select(p =&gt; <span style="color:#a31515;">&quot;New LO: &quot; </span>+ p);

<span style="color:green;">// Daily high price feed
</span><span style="color:blue;">var </span>feedHi = feed
    .Scan(<span style="color:#2b91af;">Math</span>.Max)
    .HoldUntilChanged()
    .Select(p =&gt; <span style="color:#a31515;">&quot;New HI: &quot; </span>+ p);

<span style="color:green;">// Combine hi and lo in one feed and subscribe to it
</span>feedLo.Merge(feedHi).Subscribe(<span style="color:#2b91af;">Console</span>.WriteLine);

<span style="color:#2b91af;">Console</span>.ReadKey(<span style="color:blue;">true</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a>Happy holidays!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/179/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=179&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2010/01/01/detecting-running-highlow-prices-using-reactive-framework-follow-up/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>Running VWAP Calculation Using Reactive Extensions for .NET</title>
		<link>http://eprystupa.wordpress.com/2009/12/20/running-vwap-calculation-using-reactive-extensions-for-net/</link>
		<comments>http://eprystupa.wordpress.com/2009/12/20/running-vwap-calculation-using-reactive-extensions-for-net/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 23:07:29 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Reactive Extensions for .NET]]></category>
		<category><![CDATA[Reactive Framework]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=149</guid>
		<description><![CDATA[Reactive Framework Labs This article is one from the “Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)” series of articles that demonstrate some basic applications of Rx framework to financial data. This article shows how to calculate a running VWAP (volume weighted average price over a defined window of time). Other articles [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=149&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Reactive Framework Labs</h6>
<p>This article is one from the “<a href="http://eprystupa.wordpress.com/?p=135">Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)</a>” series of articles that demonstrate some basic applications of Rx framework to financial data. This article shows how to calculate a running VWAP (volume weighted average price over a defined window of time). Other articles in the series are:</p>
<ul>
<li><a href="http://eprystupa.wordpress.com/?p=140">Detecting daily Hi/Lo prices</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=143">Throttling high-frequency data feed</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=144">Data feed failover</a> </li>
</ul>
<p>Visual Studio 2008 solution containing full source code for all examples can be downloaded <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/RxLabs.zip">here</a>.</p>
<h6>Calculating VWAP/Sliding Window Implementation</h6>
<p>We will use this simple “Trade” type to represent a trade event. To simplify things we will only consider Price and Volume:</p>
<pre class="code"><span style="color:blue;">class </span><span style="color:#2b91af;">Trade
</span>{
    <span style="color:blue;">public double </span>Price { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public int </span>Volume { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}</pre>
<p>The following “TradeWithVWAP” type wraps underlying trade and attaches running VWAP value to it. It is used for calculation output:</p>
<pre class="code"><span style="color:blue;">class </span><span style="color:#2b91af;">TradeWithVWAP
</span>{
    <span style="color:blue;">public </span><span style="color:#2b91af;">Trade </span>Trade { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    <span style="color:blue;">public double </span>VWAP { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
}</pre>
<p>Our main module starts with a simple market data generator that produces infinite stream of random prices ($30 to $33 range) at random volumes (1,000 to 100,000 shares) at a random frequency (0 to 3 seconds between trades). BuildVwapFeed functions takes generated trade stream and converts it to another stream with running VWAP attached to every trade. And finally we simply subscribe to VWAP-wrapped feed and output the results.<span style="color:blue;"></span></p>
<pre class="code"><span style="color:blue;"></span></pre>
<p><span id="more-149"></span></p>
<pre class="code"><span style="color:blue;">static void </span>Main(<span style="color:blue;">string</span>[] args)
{
    <span style="color:green;">// Market data simulator
    </span><span style="color:blue;">var </span>rnd = <span style="color:blue;">new </span><span style="color:#2b91af;">Random</span>();
    <span style="color:#2b91af;">IObservable</span>&lt;<span style="color:#2b91af;">Trade</span>&gt; feed =
        <span style="color:#2b91af;">Observable</span>.Defer(() =&gt;
            <span style="color:#2b91af;">Observable</span>.Return(<span style="color:blue;">new </span><span style="color:#2b91af;">Trade
            </span>{
                Price = <span style="color:#2b91af;">Math</span>.Round(<span style="color:brown;">30.0 </span>+ <span style="color:brown;">3 </span>* rnd.NextDouble(), <span style="color:brown;">2</span>),
                Volume = <span style="color:brown;">1000 </span>+ rnd.Next(<span style="color:brown;">0</span>, <span style="color:brown;">100000</span>) / <span style="color:brown;">100 </span>* <span style="color:brown;">100
            </span>})
            .Delay(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">3 </span>* rnd.NextDouble())))
        .Repeat();

    <span style="color:green;">// Build a wrapper feed to add running VWAP to each trade
    </span><span style="color:#2b91af;">IObservable</span>&lt;<span style="color:#2b91af;">TradeWithVWAP</span>&gt; vwap = BuildVwapFeed(
        feed,
        <span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">5</span>));

    <span style="color:green;">// Subsribe and print results
    </span>vwap.Subscribe(f =&gt; <span style="color:#2b91af;">Console</span>.WriteLine(
        <span style="color:#a31515;">&quot;Price={0}, Volume={1:#,##0}, VWAP={2}&quot;</span>,
        f.Trade.Price,
        f.Trade.Volume,
        f.VWAP));
    <span style="color:#2b91af;">Console</span>.ReadKey(<span style="color:blue;">true</span>);
}</pre>
</p>
<p>“BuildVwapFeed” takes two parameters: underlying feed and desired sliding window for VWAP calculation. The first thing it does is time stamping the incoming feed. This is to keep track of an individual trade position within a sliding window. Time stamping is built into Reactive Framework and is as simple as applying a “Timestamp” operator. Timestamp&lt;T&gt; takes a stream of type T and converts it to a stream of Timestampted&lt;T&gt;. Then we allocate a list of Timestampted&lt;T&gt; – this is where we keep the trades currently inside our sliding window.</p>
<p>The “Do” operator is used to maintain the sliding window. The “Do” operator simply repeats the stream it wraps but can produce arbitrary side effects. We use the operator to add new trades to sliding window and to remove trades that have expired.</p>
<p>After the sliding window is updated we no longer need the timestamp. We get rid of it using another Rx built-in operator: RemoveTimestamp&lt;T&gt;. The last code block transforms incoming feed into “VWAP-stampted” by using the sliding window to calculate and attach running VWAP to each trade:</p>
<pre class="code"><span style="color:blue;">private static </span><span style="color:#2b91af;">IObservable</span>&lt;<span style="color:#2b91af;">TradeWithVWAP</span>&gt; BuildVwapFeed(
    <span style="color:#2b91af;">IObservable</span>&lt;<span style="color:#2b91af;">Trade</span>&gt; feed,
    <span style="color:#2b91af;">TimeSpan </span>slidingWndLen)
{
    <span style="color:green;">// Timestamp original feed
    </span><span style="color:blue;">var </span>timestampted = feed.Timestamp();

    <span style="color:green;">// Maintain a sliding window of recent trades
    </span><span style="color:blue;">var </span>wnd = <span style="color:blue;">new </span><span style="color:#2b91af;">List</span>&lt;<span style="color:#2b91af;">Timestamped</span>&lt;<span style="color:#2b91af;">Trade</span>&gt;&gt;();
    <span style="color:blue;">var </span>slidingWindowFeed = timestampted.Do(f =&gt;
    {
        <span style="color:green;">// remove expired trades
        </span><span style="color:blue;">while </span>(
            wnd.Count &gt; <span style="color:brown;">0 </span>&amp;&amp;
            f.Timestamp - wnd.First().Timestamp &gt; slidingWndLen)
        {
            wnd.RemoveAt(<span style="color:brown;">0</span>);
        }
        <span style="color:green;">// add newest trade
        </span>wnd.Add(f);
    });

    <span style="color:green;">// Calculate running VWAP from trades in the sliding window
    </span><span style="color:blue;">var </span>vwap =
        <span style="color:blue;">from </span>w <span style="color:blue;">in </span>slidingWindowFeed.RemoveTimestamp()
        <span style="color:blue;">let </span>windowVolume = wnd.Sum(l =&gt; l.Value.Volume)
        <span style="color:blue;">let </span>windowTotal = wnd.Sum(
            l =&gt; l.Value.Volume * l.Value.Price)
        <span style="color:blue;">select new </span><span style="color:#2b91af;">TradeWithVWAP
        </span>{
            Trade = w,
            VWAP = <span style="color:#2b91af;">Math</span>.Round(windowTotal / windowVolume, <span style="color:brown;">2</span>)
        };
    <span style="color:blue;">return </span>vwap;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>There are many other ways to produce VWAP on-the-fly. The implementation shown does not claim to be very efficient. But it does demonstrate how easy, almost trivial, it is to implement non-trivial stream transformations with Rx. Building your own CEP engine may soon become as easy as LINQ, Rx, and .NET…</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/149/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/149/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/149/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=149&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/12/20/running-vwap-calculation-using-reactive-extensions-for-net/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>Data Feed Failover Using Reactive Extensions for .NET</title>
		<link>http://eprystupa.wordpress.com/2009/12/20/data-feed-failover-using-reactive-extensions-for-net/</link>
		<comments>http://eprystupa.wordpress.com/2009/12/20/data-feed-failover-using-reactive-extensions-for-net/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 04:46:48 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Reactive Extensions for .NET]]></category>
		<category><![CDATA[Reactive Framework]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=144</guid>
		<description><![CDATA[Reactive Framework Labs This article is one from the “Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)” series of articles that demonstrate some basic applications of Rx framework to financial data streams. This article demonstrates automatic and transparent failover from primary data feed to a backup one implemented in terms of Microsoft [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=144&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Reactive Framework Labs</h6>
<p>This article is one from the “<a href="http://eprystupa.wordpress.com/?p=135">Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)</a>” series of articles that demonstrate some basic applications of Rx framework to financial data streams. This article demonstrates automatic and transparent failover from primary data feed to a backup one implemented in terms of Microsoft Reactive Framework. Other articles in the series are:</p>
<ul>
<li><a href="http://eprystupa.wordpress.com/?p=140">Detecting daily Hi/Lo prices</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=143">Throttling high-frequency data feed</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=149">Running VWAP calculation</a> </li>
</ul>
<p>Visual Studio 2008 solution containing full source code for all examples in this article can be downloaded <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/RxLabs.zip">here</a>.</p>
<h6>Failover Implementation</h6>
<p>The effect of automatic failover is implemented using the “Catch” operator built into the Rx framework.&#160; The “Catch” operator simply repeats the first stream until it fails. When the first stream fails, exception is swallowed and the second stream is subscribed to and repeated. You can chain any number of streams this way. Here is a code sample that uses “Catch” to switch from some primary feed to a backup:</p>
<pre class="code"><span style="color:green;"></span></pre>
<p><span id="more-144"></span></p>
<pre class="code"><span style="color:green;">// simulate market data feed
</span><span style="color:blue;">var </span>rnd = <span style="color:blue;">new </span><span style="color:#2b91af;">Random</span>();
<span style="color:blue;">var </span>feedSimulator = <span style="color:#2b91af;">Observable</span>.Defer(() =&gt;
    <span style="color:#2b91af;">Observable</span>.Return(<span style="color:#2b91af;">Math</span>.Round(<span style="color:brown;">30.0 </span>+ rnd.NextDouble(), <span style="color:brown;">2</span>))
    .Delay(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(rnd.NextDouble())))
    .Repeat();

<span style="color:green;">// Simulate fatal problem with feed 5 seconds down the road
</span><span style="color:blue;">var </span>feedProblem =
    <span style="color:#2b91af;">Observable</span>.Throw&lt;<span style="color:blue;">double</span>&gt;(<span style="color:blue;">new </span><span style="color:#2b91af;">Exception</span>(<span style="color:#a31515;">&quot;Fatal Error!&quot;</span>))
    .Delay(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">5</span>));

<span style="color:green;">// Bloomberg feed: merging simulator with error generator
</span><span style="color:blue;">var </span>bloombergFeed = <span style="color:blue;">from </span>p <span style="color:blue;">in </span>feedSimulator.Merge(feedProblem)
                    <span style="color:blue;">select new </span>{ Feed = <span style="color:#a31515;">&quot;Bloomberg&quot;</span>, Price = p };
<span style="color:green;">// Reuters feed
</span><span style="color:blue;">var </span>reutersFeed = <span style="color:blue;">from </span>p <span style="color:blue;">in </span>feedSimulator
                  <span style="color:blue;">select new </span>{ Feed = <span style="color:#a31515;">&quot;Reuters&quot;</span>, Price = p };

<span style="color:green;">// Automatic, transparent failover feed
</span><span style="color:blue;">var </span>failoverFeed = bloombergFeed.Catch(reutersFeed);

<span style="color:green;">// Subscribe and print results to console
</span>bloombergFeed.Subscribe(
    p =&gt; { },
    x =&gt; <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&quot;Bloomberg feed: {0}&quot;</span>, x.Message));
failoverFeed.Subscribe(
    price =&gt; <span style="color:#2b91af;">Console</span>.WriteLine(price));

<span style="color:#2b91af;">Console</span>.ReadKey(<span style="color:blue;">true</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>The first code block is a simple market data simulator implemented using Reactive Framework.</p>
<p>The second code block simulates a feed problem. It never produces any values and, when subscribed to, throws an exception after 5 seconds. We will combine market data simulator with problem simulator to simulate a feed that breaks down the road.</p>
<p>The third and forth code blocks create two feeds: Bloomberg and Reuters. Bloomberg feed is constructed to “break” after 5 seconds and Reuters is simply based on our market simulator.</p>
<p>Next code block is “<span style="color:blue;">var </span>failoverFeed = bloombergFeed.Catch(reutersFeed);”. This statement creates a wrapper feed that starts with Bloomberg and when it fails automatically and transparently switches to Reuters. A subscriber will not notice an interruption. Notice that Reuters feed is not going to be subscribed to until failover happens.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=144&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/12/20/data-feed-failover-using-reactive-extensions-for-net/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>Throttling High-Frequency Data Feed Using Reactive Extensions for .NET</title>
		<link>http://eprystupa.wordpress.com/2009/12/19/throttling-high-frequency-data-feed-using-reactive-extensions-for-net/</link>
		<comments>http://eprystupa.wordpress.com/2009/12/19/throttling-high-frequency-data-feed-using-reactive-extensions-for-net/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 02:35:04 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Reactive Extensions for .NET]]></category>
		<category><![CDATA[Reactive Framework]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=143</guid>
		<description><![CDATA[Reactive Framework Labs This article is one from the “Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)” series of articles that demonstrate some basic applications of Rx framework to financial data. This article shows how to throttle your incoming feed to a desired frequency. Other articles in the series are: Detecting daily [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=143&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Reactive Framework Labs</h6>
<p>This article is one from the “<a href="http://eprystupa.wordpress.com/?p=135">Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)</a>” series of articles that demonstrate some basic applications of Rx framework to financial data. This article shows how to throttle your incoming feed to a desired frequency. Other articles in the series are:</p>
<ul>
<li><a href="http://eprystupa.wordpress.com/?p=140">Detecting daily Hi/Lo prices</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=144">Data feed failover</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=149">Running VWAP calculation</a> </li>
</ul>
<p>Visual Studio 2008 solution containing full source code for all examples can be downloaded <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/RxLabs.zip">here</a>.</p>
<h6>Throttling Implementation</h6>
<p>The key operator here is “Sample”. Sampling at a desired rate effectively returns your a throttled stream. My intuition was that if underlying feed does not produce a value during the sampling interval, “Sample” will repeat the most recent available value when sampling is due. But it doesn’t and this makes it a perfect fit for throttling. Note that there is also an operator called “Throttle” but its name is misleading and its behavior most likely will not match your definition of throttling. The way implemented it will not emit any values at all if underlying feed produces faster than throttling interval, so it looks more like “Choke” to me.</p>
<p> <span id="more-143"></span>
<p>Lets look at the following code sample:</p>
<pre class="code"><span style="color:green;">// simulate very fast (no delays) market data feed
</span><span style="color:blue;">var </span>rnd = <span style="color:blue;">new </span><span style="color:#2b91af;">Random</span>();
<span style="color:blue;">var </span>unthrottledFeed = <span style="color:#2b91af;">Observable</span>.Defer(() =&gt;
    <span style="color:#2b91af;">Observable</span>.Return(<span style="color:brown;">30.0</span>)
    .Select(p =&gt; <span style="color:#2b91af;">Math</span>.Round(p + rnd.NextDouble(), <span style="color:brown;">2</span>))
    .Repeat());

<span style="color:green;">// running unthottled feed as a demo
</span><span style="color:#2b91af;">ManualResetEvent </span>unthrottledDone = <span style="color:blue;">new </span><span style="color:#2b91af;">ManualResetEvent</span>(<span style="color:blue;">false</span>);
<span style="color:blue;">int </span>count = <span style="color:brown;">0</span>;
unthrottledFeed
    .Do(p =&gt; ++count)
    .Until(<span style="color:#2b91af;">Observable</span>.Return(<span style="color:#a31515;">&quot;Done unthrottled feed&quot;</span>)
    .Delay(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">5</span>)))
    .Subscribe(<span style="color:#2b91af;">Console</span>.WriteLine, () =&gt; unthrottledDone.Set());
unthrottledDone.WaitOne();
<span style="color:#2b91af;">Console</span>.WriteLine(
    <span style="color:#a31515;">&quot;\nDone unthrottled feed. Avg rate: {0} values per second&quot;</span>,
    count / <span style="color:brown;">5</span>);

<span style="color:green;">// running same feed, now throttled
</span><span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">&quot;Now throttlig at 1 value per second...\n&quot;</span>);
<span style="color:blue;">var </span>throttledFeed = unthrottledFeed.Sample(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">1</span>));
throttledFeed.Subscribe(<span style="color:#2b91af;">Console</span>.WriteLine);

<span style="color:#2b91af;">Console</span>.ReadKey(<span style="color:blue;">true</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The first code block is a simple fast feed simulator. It produces the values as fast as you CPU allows, or about 3,000 per second (with printing to the console) on my laptop. Most UI data binding engines will not be happy to accommodate this rate.</p>
<p>Second code block runs non-throttled feed for about 5 seconds just so you can get a feel that frequency is pretty high.</p>
<p>Third code block wraps non-throttled feed with a “Sample” operator with one second sampling interval. As discussed above current implementation of “Sample” is effectively throttling. When you subscribe to the throttled feed values are emitted with frequency of one value per second, with any values in-between dropped.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/143/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/143/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/143/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=143&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/12/19/throttling-high-frequency-data-feed-using-reactive-extensions-for-net/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>Detecting Running High/Low Prices Using Reactive Extensions for .NET</title>
		<link>http://eprystupa.wordpress.com/2009/12/18/detecting-running-highlow-prices-using-reactive-extensions-for-net/</link>
		<comments>http://eprystupa.wordpress.com/2009/12/18/detecting-running-highlow-prices-using-reactive-extensions-for-net/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 03:23:16 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=140</guid>
		<description><![CDATA[Reactive Framework Labs This article is one from the “Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)” series of articles that demonstrate some basic applications of Rx framework to financial data. This article focuses on detecting running high/low values (like daily max and min) from a market data feed. Other articles in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=140&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Reactive Framework Labs</h6>
<p>This article is one from the “<a href="http://eprystupa.wordpress.com/?p=135">Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)</a>” series of articles that demonstrate some basic applications of Rx framework to financial data. This article focuses on detecting running high/low values (like daily max and min) from a market data feed. Other articles in the series are:</p>
<ul>
<li><a href="http://eprystupa.wordpress.com/?p=143">Throttling high-frequency data feed</a></li>
<li><a href="http://eprystupa.wordpress.com/?p=144">Data feed failover</a></li>
<li><a href="http://eprystupa.wordpress.com/?p=149">Running VWAP calculation</a></li>
</ul>
<p>Visual Studio 2008 solution containing full source code for all examples can be downloaded <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/RxLabs.zip">here</a>.</p>
<h6>Detecting Running High/Low Prices</h6>
<p>The key operators in this implementation are “Do” and “Where”, both built into the Reactive Framework. The first one is used to produce side effect of recording the running High or Low value, and the second is used to filter incoming values that do not produce newest High or Low:</p>
<pre class="code"><span style="color:green;"></span></pre>
<p><span id="more-140"></span></p>
<pre class="code"><span style="color:green;">// simulate market data
</span><span style="color:blue;">var </span>rnd = <span style="color:blue;">new </span><span style="color:#2b91af;">Random</span>();
<span style="color:blue;">var </span>feed = <span style="color:#2b91af;">Observable</span>.Defer(() =&gt;
    <span style="color:#2b91af;">Observable</span>.Return(<span style="color:#2b91af;">Math</span>.Round(<span style="color:brown;">30.0 </span>+ rnd.NextDouble(), <span style="color:brown;">2</span>))
    .Delay(<span style="color:#2b91af;">TimeSpan</span>.FromSeconds(<span style="color:brown;">1 </span>* rnd.NextDouble())))
    .Repeat();

<span style="color:green;">// Daily low price feed
</span><span style="color:blue;">double </span>min = <span style="color:blue;">double</span>.MaxValue;
<span style="color:blue;">var </span>feedLo = feed
    .Where(p =&gt; p &lt; min)
    .Do(p =&gt; min = <span style="color:#2b91af;">Math</span>.Min(min, p))
    .Select(p =&gt; <span style="color:#a31515;">&quot;New LO: &quot; </span>+ p);

<span style="color:green;">// Daily high price feed
</span><span style="color:blue;">double </span>max = <span style="color:blue;">double</span>.MinValue;
<span style="color:blue;">var </span>feedHi = feed
    .Where(p =&gt; p &gt; max)
    .Do(p =&gt; max = <span style="color:#2b91af;">Math</span>.Max(max, p))
    .Select(p =&gt; <span style="color:#a31515;">&quot;New HI: &quot; </span>+ p);

<span style="color:green;">// Combine hi and lo in one feed and subscribe to it
</span>feedLo.Merge(feedHi).Subscribe(<span style="color:#2b91af;">Console</span>.WriteLine);

<span style="color:#2b91af;">Console</span>.ReadKey(<span style="color:blue;">true</span>);</pre>
<p>The first block of code is a simple market data feed simulator. It generates random prices in the $30-$31 range at random intervals of zero to one second. Market simulator itself is written using Rx (all in one statement, isn’t this cool?).</p>
<p>The second block of code extracts ticks from the base feed only if they represent running lowest prices received from the feed. This is achieved by composition of the following:</p>
<ul>
<li>base stream of prices</li>
<li>“Where” clause to filter away ticks that are greater or equal to the current running minimum price</li>
<li>“Do” operator to record the current minimum value; “Do” operator simply wraps underlying stream and repeats the values it receives; its power comes from being able to execute arbitrary code per each received value and thus produce side effects (recording min value in our case)</li>
<li>“Select” projection is simply used here to label the values with “New LO: “ prefix for presentational purposes</li>
</ul>
<p>The third block of code does the same for capturing running High values.</p>
<p>At the end we merge both feeds into one and subscribe to it.</p>
<p>If you run the code you should see something similar to this run:</p>
<p><a href="http://eprystupa.files.wordpress.com/2009/12/hilorun1.png"><img style="border-bottom:0;border-left:0;display:inline;border-top:0;border-right:0;" title="HiLoRun" border="0" alt="HiLoRun" src="http://eprystupa.files.wordpress.com/2009/12/hilorun_thumb1.png?w=546&#038;h=284" width="546" height="284" /></a> </p>
<p>The feed slowly but surely converges to $30 for low and $31 for high (limits of our feed generator). Once extreme&#160; values are reached, no additional ticks will come out.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/140/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/140/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/140/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=140&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/12/18/detecting-running-highlow-prices-using-reactive-extensions-for-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>

		<media:content url="http://eprystupa.files.wordpress.com/2009/12/hilorun_thumb1.png" medium="image">
			<media:title type="html">HiLoRun</media:title>
		</media:content>
	</item>
		<item>
		<title>Processing Financial Data with Microsoft Reactive Framework (Reactive Extensions for .NET)</title>
		<link>http://eprystupa.wordpress.com/2009/12/18/processing-financial-data-with-microsoft-reactive-framework-reactive-extensions-for-net/</link>
		<comments>http://eprystupa.wordpress.com/2009/12/18/processing-financial-data-with-microsoft-reactive-framework-reactive-extensions-for-net/#comments</comments>
		<pubDate>Sat, 19 Dec 2009 02:49:25 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Reactive Extensions for .NET]]></category>
		<category><![CDATA[Reactive Framework]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=135</guid>
		<description><![CDATA[Reactive Framework Labs I have recently discovered Microsoft Reactive Framework (thanks to spontaneous introduction at New York .Net Meetup Group) and have been playing with it a lot trying to apply it to many financial problems I’ve coded over the last years. I am truly amazed with the technology and the power it unleashes for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=135&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Reactive Framework Labs</h6>
<p>I have recently discovered <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx" target="_blank">Microsoft Reactive Framework</a> (thanks to spontaneous introduction at <a href="http://www.meetup.com/NY-Dotnet/" target="_blank">New York .Net Meetup Group</a>) and have been playing with it a lot trying to apply it to many financial problems I’ve coded over the last years. I am truly amazed with the technology and the power it unleashes for processing and analyzing streaming financial data (like quotes, market data feeds, trade executions, etc.). Seamless integration with LINQ combined with very powerful support for composition makes self coded CEP in .Net a low hanging fruit. In the following series of articles I am going to demonstrate sample Rx-based implementations for some commonly occurring tasks in finance, including:</p>
<ul>
<li><a href="http://eprystupa.wordpress.com/?p=140">Detecting daily Hi/Lo prices</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=143">Throttling high-frequency data feed</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=144">Data feed failover</a> </li>
<li><a href="http://eprystupa.wordpress.com/?p=149">Running VWAP calculation</a> </li>
</ul>
<p>Visual Studio 2008 solution containing full source code for all examples can be downloaded <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/RxLabs.zip">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/135/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/135/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/135/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=135&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/12/18/processing-financial-data-with-microsoft-reactive-framework-reactive-extensions-for-net/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>Advance Your Composite Application MVVM to the Next Level &#8211; Use Attributes to Automatically Populate Your View Model with Service Calls</title>
		<link>http://eprystupa.wordpress.com/2009/12/06/advance-your-composite-application-mvvm-to-the-next-level-use-attributes-to-automatically-populate-your-view-model-with-service-calls/</link>
		<comments>http://eprystupa.wordpress.com/2009/12/06/advance-your-composite-application-mvvm-to-the-next-level-use-attributes-to-automatically-populate-your-view-model-with-service-calls/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 19:47:29 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Attributes]]></category>
		<category><![CDATA[Composite WPF]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Framework]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=125</guid>
		<description><![CDATA[Abstract MVVM is a proven design pattern in WFP/Silverlight world. Its use helps achieve separation of concerns, frees UI from any logic to enhance testing, and generally makes the code easier to understand and maintain. In many LOB multi-tier applications MVVM is extended to include a presenter class. Presenter usually controls the view model, receives [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=125&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Abstract</h6>
<p>MVVM is a proven design pattern in WFP/Silverlight world. Its use helps achieve separation of concerns, frees UI from any logic to enhance testing, and generally makes the code easier to understand and maintain. In many LOB multi-tier applications MVVM is extended to include a presenter class. Presenter usually controls the view model, receives necessary services from dependency injection container and has some logic to populate the view model with business entities and/or reference data and send any changes back. The resulting code is usually pretty clean, easy to maintain and test. This article argues though that most of the code in such presenters to populate the view models is also very mechanical, routine, boring and can be avoided all together by introducing small attribute-based view model framework to declaratively populate view models from service calls and avoid extra coding, and, thus, avoid writing extra mechanical, routine, and boring tests.</p>
<p>If you prefer the “code first” approach VS 2008 solution can be downloaded here: <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/MVVMAttributes.zip" target="_blank">MVVMAttributes.zip</a></p>
<h6></h6>
<p> <span id="more-125"></span><br />
<h6>The Base Line</h6>
<p>Consider the following simplified application as our baseline: one of the application’s views is the “CustomerView” which gets customer information from the customer service, lets user edit the information (name and state of residency in our example) and allows saving the data back (omitted in our example). The following is the baseline Prism/MVVM implementation:</p>
<p><em>Business Entities</em></p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.BusinessObjects
{
    <span style="color:blue;">public class </span><span style="color:#2b91af;">CustomerData
    </span>{
        <span style="color:blue;">public string </span>Name { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
        <span style="color:blue;">public string </span>State { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>This class represents very simple transfer object to pass customer info between tiers. </p>
<p><em>View Model</em></p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">CustomerViewModel </span>: <span style="color:#2b91af;">DependencyObject
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt; _states
        = <span style="color:blue;">new </span><span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt;();

    <span style="color:green;">// Customer model DP wrapper
    </span><span style="color:blue;">public </span><span style="color:#2b91af;">CustomerData </span>Customer
    {
        <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>(<span style="color:#2b91af;">CustomerData</span>)GetValue(CustomerProperty); }
        <span style="color:blue;">set </span>{ SetValue(CustomerProperty, <span style="color:blue;">value</span>); }
    }
    <span style="color:blue;">public static readonly </span><span style="color:#2b91af;">DependencyProperty </span>CustomerProperty =
        <span style="color:#2b91af;">DependencyProperty</span>.Register(<span style="color:#a31515;">&quot;Customer&quot;</span>,
        <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">CustomerData</span>), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">CustomerViewModel</span>));

    <span style="color:green;">// Observable list of states
    </span><span style="color:blue;">public </span><span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt; States
    {
        <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>_states; }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>This is a typical view model that encapsulates business model (Customer property) and reference data (States observable collection to present the user with the list of all states to pick from).</p>
<p><em>View</em></p>
<pre class="code"><span style="color:blue;">&lt;</span><span style="color:#a31515;">UserControl
    </span><span style="color:red;">xmlns</span><span style="color:blue;">=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
    </span><span style="color:red;">xmlns</span><span style="color:blue;">:</span><span style="color:red;">x</span><span style="color:blue;">=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;
    </span><span style="color:red;">x</span><span style="color:blue;">:</span><span style="color:red;">Class</span><span style="color:blue;">=&quot;MVVMAttributes.Customer.CustomerView&quot;
&gt;
    &lt;</span><span style="color:#a31515;">Grid</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">Grid.RowDefinitions</span><span style="color:blue;">&gt;
            &lt;</span><span style="color:#a31515;">RowDefinition </span><span style="color:red;">Height</span><span style="color:blue;">=&quot;Auto&quot;/&gt;
            &lt;</span><span style="color:#a31515;">RowDefinition </span><span style="color:red;">Height</span><span style="color:blue;">=&quot;Auto&quot;/&gt;
        &lt;/</span><span style="color:#a31515;">Grid.RowDefinitions</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">Grid.ColumnDefinitions</span><span style="color:blue;">&gt;
            &lt;</span><span style="color:#a31515;">ColumnDefinition </span><span style="color:red;">Width</span><span style="color:blue;">=&quot;Auto&quot;/&gt;
            &lt;</span><span style="color:#a31515;">ColumnDefinition </span><span style="color:red;">Width</span><span style="color:blue;">=&quot;200&quot;/&gt;
        &lt;/</span><span style="color:#a31515;">Grid.ColumnDefinitions</span><span style="color:blue;">&gt;
        &lt;</span><span style="color:#a31515;">TextBlock </span><span style="color:red;">Text</span><span style="color:blue;">=&quot;First Name:&quot;/&gt;
        &lt;</span><span style="color:#a31515;">TextBlock </span><span style="color:red;">Text</span><span style="color:blue;">=&quot;State:&quot; </span><span style="color:red;">Grid.Row</span><span style="color:blue;">=&quot;1&quot;/&gt;
        &lt;</span><span style="color:#a31515;">TextBox </span><span style="color:red;">Text</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Customer</span><span style="color:blue;">.Name}&quot;
                 </span><span style="color:red;">Grid.Column</span><span style="color:blue;">=&quot;1&quot;/&gt;
        &lt;</span><span style="color:#a31515;">ComboBox </span><span style="color:red;">Grid.Row</span><span style="color:blue;">=&quot;1&quot; </span><span style="color:red;">Grid.Column</span><span style="color:blue;">=&quot;1&quot;
                  </span><span style="color:red;">SelectedItem</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">Customer</span><span style="color:blue;">.State}&quot;
                  </span><span style="color:red;">ItemsSource</span><span style="color:blue;">=&quot;{</span><span style="color:#a31515;">Binding </span><span style="color:red;">States</span><span style="color:blue;">}&quot;/&gt;
    &lt;/</span><span style="color:#a31515;">Grid</span><span style="color:blue;">&gt;
&lt;/</span><span style="color:#a31515;">UserControl</span><span style="color:blue;">&gt;
</span></pre>
<p>The view binds its view model to the UI elements. In particular, it binds customer name to a text box (Text property) and customer’s state to a ComboBox (SelectedItem property). It also binds ComboBox’s ItemsSource to the full list of available states exposed by the view model. View contains no additional code (except implementing ICustomerView) so code behind file is not shown. This is ICustomerView interface:</p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.Customer
{
    <span style="color:blue;">public interface </span><span style="color:#2b91af;">ICustomerView
    </span>{
        <span style="color:blue;">object </span>DataContext { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><em>Presenter</em></p>
<p>Presenter code is below. Code walk-through follows.</p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.Customer
{
    <span style="color:blue;">public class </span><span style="color:#2b91af;">CustomerPresenterWithServices
    </span>{
        <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ICustomerView </span>_view;
        <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ICustomerService </span>_service;
        <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IReferenceDataService </span>_refDataService;
        <span style="color:blue;">private </span><span style="color:#2b91af;">CustomerViewModel </span>_viewModel;

        <span style="color:blue;">public </span>CustomerPresenterWithServices(
            <span style="color:#2b91af;">ICustomerView </span>view,
            <span style="color:#2b91af;">ICustomerService </span>service,
            <span style="color:#2b91af;">IReferenceDataService </span>refDataService)
        {
            _view = view;
            _service = service;
            _refDataService = refDataService;
        }

        <span style="color:blue;">public void </span>ShowCustomer(<span style="color:blue;">int </span>customerId)
        {
            _viewModel = <span style="color:blue;">new </span><span style="color:#2b91af;">CustomerViewModel</span>();
            _viewModel.Customer = _service.GetCustomer(customerId);
            ReplaceList(
                _viewModel.States,
                _refDataService.GetStates());

            _view.DataContext = _viewModel;
        }

        <span style="color:blue;">private void </span>ReplaceList(
            <span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt; list,
            <span style="color:blue;">string</span>[] values)
        {
            list.Clear();
            <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>item <span style="color:blue;">in </span>values)
            {
                list.Add(item);
            }
        }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Presenter implementation is typical for MVVM designs with dependency injection frameworks. Constructor injects and caches the view, customer service, and reference data service. The ShowCustomer public method creates the view model, calls services to get domain model (customer data) and reference data. When view model is built up, it is assigned to view’s DataContext for data binding to take over. </p>
<p>As you can see the wiring code to cache services, call them and update the view model is nothing fancy, highly repetitive code, with a risk of being “cut-and-paste” in high volume in a real application with dozens of views/presenters and maybe hundreds of service calls. Now add a requirement to populate the view model asynchronously and the wiring code to do that will likely be repeated (and thus need to be tested) in all those presenters. This is where the view model framework I introduced in the abstract comes to rescue.</p>
<h6>The View Model Attribute-based Framework</h6>
<p><em>Attributes</em></p>
<p>Lets introduce the following two attributes that constitute the core of the declarative part of the framework:</p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.Infrastructure
{
    <span style="color:blue;">public abstract class </span><span style="color:#2b91af;">ServiceCallAttribute </span>: <span style="color:#2b91af;">Attribute
    </span>{
        <span style="color:blue;">public </span><span style="color:#2b91af;">Type </span>ServiceType { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
        <span style="color:blue;">public string </span>MethodName { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
        <span style="color:blue;">public string </span>MethodParameters { <span style="color:blue;">get</span>; <span style="color:blue;">set</span>; }
    }

    [<span style="color:#2b91af;">AttributeUsage</span>(
        <span style="color:#2b91af;">AttributeTargets</span>.Property,
        AllowMultiple = <span style="color:blue;">false</span>)]
    <span style="color:blue;">public class </span><span style="color:#2b91af;">ServiceEntityAttribute </span>: <span style="color:#2b91af;">ServiceCallAttribute
    </span>{
    }

    [<span style="color:#2b91af;">AttributeUsage</span>(
        <span style="color:#2b91af;">AttributeTargets</span>.Property,
        AllowMultiple = <span style="color:blue;">false</span>)]
    <span style="color:blue;">public class </span><span style="color:#2b91af;">ServiceListAttribute </span>: <span style="color:#2b91af;">ServiceCallAttribute
    </span>{
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Two attributes (ServiceEntityAttribute and ServiceListAttribute) share the same base class that defines the type of the service to use, the method to call, and, if method has any parameters, the names to use to resolve the parameters values.</p>
<p><em>Attributed View Model</em></p>
<p>Now when we have the attributes we can amend our original model to declaratively specify how to get data to populate it:</p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.Customer
{
    <span style="color:blue;">public class </span><span style="color:#2b91af;">CustomerViewModel </span>: <span style="color:#2b91af;">DependencyObject
    </span>{
        <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt; _states
            = <span style="color:blue;">new </span><span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt;();

        <span style="color:green;">// Customer model DP wrapper
        </span><strong>[<span style="color:#2b91af;">ServiceEntity</span>(
            ServiceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">ICustomerService</span>),
            MethodName = <span style="color:#a31515;">&quot;GetCustomer&quot;</span>,
            MethodParameters = <span style="color:#a31515;">&quot;customerId&quot;</span>)]</strong>
        <span style="color:blue;">public </span><span style="color:#2b91af;">CustomerData </span>Customer
        {
            <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>(<span style="color:#2b91af;">CustomerData</span>)GetValue(CustomerProperty); }
            <span style="color:blue;">set </span>{ SetValue(CustomerProperty, <span style="color:blue;">value</span>); }
        }
        <span style="color:blue;">public static readonly </span><span style="color:#2b91af;">DependencyProperty </span>CustomerProperty =
            <span style="color:#2b91af;">DependencyProperty</span>.Register(
            <span style="color:#a31515;">&quot;Customer&quot;</span>,
            <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">CustomerData</span>), <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">CustomerViewModel</span>));

        <span style="color:green;">// Observable list of states
        </span><strong>[<span style="color:#2b91af;">ServiceList</span>(
            ServiceType = <span style="color:blue;">typeof</span>(<span style="color:#2b91af;">IReferenceDataService</span>),
            MethodName = <span style="color:#a31515;">&quot;GetStates&quot;</span>)]</strong>
        <span style="color:blue;">public </span><span style="color:#2b91af;">ObservableCollection</span>&lt;<span style="color:blue;">string</span>&gt; States {
            <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>_states; }
        }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>The “ServiceEntity” attribute on the “Customer” property specifies that this property should be populated by call to “GetCustomer” method on the “ICustomerService” service. The method expects one parameter and the caller will resolve its value using “customerId” name.</p>
<p>The “ServiceList” attribute labels the “States” property and states that this collection should be filled in using the “GetStates” method of the “IReferenceDataService” service. The method expects no parameters.</p>
<p>Now that view model is tagged with “service call” attributes we can use some generic factory to create and populate it. Once the code to populate view model is moved to a generic factory, our original presenter simplifies to this:</p>
<pre class="code"><span style="color:blue;">public class </span><span style="color:#2b91af;">CustomerPresenter
</span>{
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">ICustomerView </span>_view;
    <span style="color:blue;">private </span><span style="color:#2b91af;">CustomerViewModel </span>_viewModel;
    <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IViewModelFactory </span>_viewModelFactory;

    <span style="color:blue;">public </span><span style="color:#2b91af;">ICustomerView </span>View { <span style="color:blue;">get </span>{ <span style="color:blue;">return </span>_view; } }

    <span style="color:blue;">public </span>CustomerPresenter(
        <span style="color:#2b91af;">ICustomerView </span>view,
        <span style="color:#2b91af;">IViewModelFactory </span>viewModelFactory)
    {
        _view = view;
        _viewModelFactory = viewModelFactory;
    }

    <span style="color:blue;">public void </span>ShowCustomer(<span style="color:blue;">int </span>customerId)
    {
        _viewModel =
            _viewModelFactory.BuildViewModel&lt;<span style="color:#2b91af;">CustomerViewModel</span>&gt;(
            <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:#a31515;">&quot;customerId&quot;</span>, customerId } });

        _view.DataContext = _viewModel;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>The presenter still injects the view but is no longer concerned with services and populating of its view model. Instead, it injects a generic view model factory to create the view model and “build it up” with service calls.</p>
<h6>The magic behind it all – View Model Factory</h6>
<p>The last and most interesting part of the framework is view model factory. It creates a view model, inspects its properties and their attributes using reflection, dynamically resolves necessary services, calls required methods and updates the view model. Below is the code and walk-though:</p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.Infrastructure
{
    <span style="color:blue;">public interface </span><span style="color:#2b91af;">IViewModelFactory
    </span>{
        TViewModel BuildViewModel&lt;TViewModel&gt;(
            <span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; parameters);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>The above declares the public API for the view model factory. The view model is requested by specifying BuildViewModel’s generic type, and the “parameters” dictionary is used to resolve values for any parameters for the service calls necessary. Here is the implementation itself (partitioned to facilitate the walk-through):</p>
<pre class="code"><span style="color:blue;">namespace </span>MVVMAttributes.Infrastructure
{
    <span style="color:blue;">public class </span><span style="color:#2b91af;">ViewModelFactory </span>: <span style="color:#2b91af;">IViewModelFactory
    </span>{
        <span style="color:blue;">private readonly </span><span style="color:#2b91af;">IUnityContainer </span>_container;

        <span style="color:blue;">public </span>ViewModelFactory(<span style="color:#2b91af;">IUnityContainer </span>container)
        {
            _container = container;
        }

        <span style="color:blue;">public </span>TViewModel BuildViewModel&lt;TViewModel&gt;(
            <span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; parameters)
        {
            TViewModel viewModel = _container.Resolve&lt;TViewModel&gt;();

            BuildUp&lt;<span style="color:#2b91af;">ServiceEntityAttribute</span>&gt;(
                viewModel, parameters, SetEntity);
            BuildUp&lt;<span style="color:#2b91af;">ServiceListAttribute</span>&gt;(
                viewModel, parameters, ReplaceList); 

            <span style="color:blue;">return </span>viewModel;
        }</pre>
<p><a href="http://11011.net/software/vspaste"></a>…</p>
<p>ViewModelFactory’s constructor injects the container, so it later can resolve requested services. The “BuildViewModel” method constructs the view model (again using the container) and “builds it up” by scanning for “ServiceEntityAttribute” first to populate “entities” and then for “ServiceListAttribute” to populate collection type data. Here is the code for “BuildUp&lt;TAttribute&gt;” method:</p>
<pre class="code"><span style="color:blue;">private void </span>BuildUp&lt;TAttribute&gt;(
    <span style="color:blue;">object </span>viewModel,
    <span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; parameterLookup,
    <span style="color:#2b91af;">Action</span>&lt;<span style="color:#2b91af;">PropertyInfo</span>, <span style="color:blue;">object</span>, <span style="color:blue;">object</span>&gt; setProperty)
    <span style="color:blue;">where </span>TAttribute : <span style="color:#2b91af;">ServiceCallAttribute
</span>{
    <span style="color:blue;">var </span>q =
        <span style="color:blue;">from </span>p <span style="color:blue;">in </span>viewModel.GetType().GetProperties()
        <span style="color:blue;">from </span>a <span style="color:blue;">in </span>p.GetCustomAttributes(<span style="color:blue;">typeof</span>(TAttribute), <span style="color:blue;">false</span>)
        <span style="color:blue;">select new </span>{ Property = p, Attribute = (TAttribute)a };

    <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>item <span style="color:blue;">in </span>q)
    {
        <span style="color:blue;">object </span>result = CallService(
            item.Attribute, item.Property, parameterLookup);
        setProperty(item.Property, viewModel, result);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a>A simple LINQ to reflection query is used to scan for properties marked for auto-population with service calls. For each found property specified service call is made by “CallService” and then view model is updated using one of the two “setProperty” strategies: property assignment or list replacement. Here is the “CallService” implementation:</p>
<pre class="code"><span style="color:blue;">private object </span>CallService(
    <span style="color:#2b91af;">ServiceCallAttribute </span>attribute,
    <span style="color:#2b91af;">PropertyInfo </span>property,
    <span style="color:#2b91af;">IDictionary</span>&lt;<span style="color:blue;">string</span>, <span style="color:blue;">object</span>&gt; parameterLookup)
{
    <span style="color:#2b91af;">Type </span>serviceType = attribute.ServiceType;
    <span style="color:blue;">object </span>service = _container.Resolve(serviceType);
    <span style="color:#2b91af;">MethodInfo </span>method = serviceType.GetMethod(attribute.MethodName);
    <span style="color:blue;">string</span>[] parameterNames = attribute.MethodParameters != <span style="color:blue;">null </span>?
        attribute.MethodParameters.Split(<span style="color:#a31515;">','</span>) :
        <span style="color:blue;">new string</span>[] { };
    <span style="color:blue;">object</span>[] parameters = parameterNames.Select(
        name =&gt; parameterLookup[name]).ToArray();

    <span style="color:blue;">return </span>method.Invoke(service, parameters);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Here the service specified in the attribute is first resolved using the DI container. Then specified method from the attribute is called on this service using reflection. Any parameters are resolved against caller provided parameter lookup dictionary.</p>
<h6></h6>
<h6>Conclusion</h6>
<p>In the article we explored how custom attribute based frameworks can leverage composite application frameworks (like Prism) and MVVM pattern to remove any “wiring” code necessary to create and populate a view model in a typical n-tier application. We have created a simple declarative framework that takes care of instantiating required services, calling them, and automatically updating view model with service call results.</p>
<p>The framework we built is extremely simple to keep the article from bloating. There are several improvements and enhancements that can be applied to it, like:</p>
<ul>
<li>Additional attributes to specify different types of service call results processing; in addition to property assignment and list replacing that we implemented, we can also have an attribute that specifies an optional translator between service call result and view model property </li>
<li>ViewModelFactory can take on responsibility to populate view model asynchronously; the benefit of this approach is that we only need to implement the asynchronous behavior once in the factory and none of the presenters need to change </li>
<li>To complete interaction with middle tier the framework should also provide a declarative way to submit modified business entities back using service calls; this can be achieved, for example, by mapping view model’s properties to “Save” service calls and providing declarative way to translate these properties into “Save” call parameters. </li>
</ul>
<p>The complete solution (VS 2008) demonstrating the framework can be downloaded here: <a href="http://cid-fd7bfb078a7a66be.skydrive.live.com/self.aspx/Public/MVVMAttributes.zip" target="_blank">MVVMAttributes.zip</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/125/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/125/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/125/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=125&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/12/06/advance-your-composite-application-mvvm-to-the-next-level-use-attributes-to-automatically-populate-your-view-model-with-service-calls/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>
	</item>
		<item>
		<title>LINQ to SQL Tricks: Building Efficient Queries that Include Reference Data or Child Entities</title>
		<link>http://eprystupa.wordpress.com/2009/11/26/linq-to-sql-tricks-building-efficient-queries-that-include-reference-data-or-child-entities/</link>
		<comments>http://eprystupa.wordpress.com/2009/11/26/linq-to-sql-tricks-building-efficient-queries-that-include-reference-data-or-child-entities/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 00:05:35 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[LINQ to SQL]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=77</guid>
		<description><![CDATA[Problem Summary Some times you need to read entities from a table along with some properties that are reference data or child entities. This relationship is usually represented by foreign keys in your database. LINQ to SQL makes this job extremely easy but, by default, also very inefficient. There are multiple ways this inefficiency can [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=77&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h6>Problem Summary</h6>
<p>Some times you need to read entities from a table along with some properties that are reference data or child entities. This relationship is usually represented by foreign keys in your database. LINQ to SQL makes this job extremely easy but, by default, also very inefficient. There are multiple ways this inefficiency can be addressed. Some of these alternatives are standard facilities provided by LINQ to SQL and some are custom coded patterns and tricks. This article walks your through these solutions, explaining their pros and cons and helping you decide which one is right for you.</p>
<h6>Default Behavior</h6>
<p>Consider the following simple subset from the AdventureWorksLT database:</p>
<p><a href="http://eprystupa.files.wordpress.com/2009/11/adventureworkscustomeraddress.png"><img style="display:inline;border-width:0;" title="AdventureWorksCustomerAddress" src="http://eprystupa.files.wordpress.com/2009/11/adventureworkscustomeraddress_thumb.png?w=473&#038;h=258" border="0" alt="AdventureWorksCustomerAddress" width="473" height="258" /></a></p>
<p>Lets say your job is to select and display all the customer addresses in the database (we will limit results to first 3 to simplify output), with the following fields: First Name, Last Name, City, State, and Modified Date. You have your Data Access Layer (DAL) to get the data and your driver code to print the results. Something like this:</p>
<p><span id="more-77"></span></p>
<p><span style="color:blue;">using</span>(<span style="color:#2b91af;">AdventureWorksDataContext </span>ctx = <span style="color:blue;">new </span><span style="color:#2b91af;">AdventureWorksDataContext</span>())<br />
{<br />
<span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt; q = BuildQuery(ctx);</p>
<p><span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>ca <span style="color:blue;">in </span>q)<br />
{<br />
<span style="color:#2b91af;">Console</span>.Out.WriteLine(<span style="color:#a31515;">&#8220;{0}, {1} lives in {2}, {3} as of {4}&#8221;</span>,<br />
ca.Customer.LastName,<br />
ca.Customer.FirstName,<br />
ca.Address.City,<br />
ca.Address.StateProvince,<br />
ca.ModifiedDate);<br />
}<br />
}</p>
<pre class="code"><span style="color:blue;">private static </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt; BuildQuery(
    <span style="color:#2b91af;">AdventureWorksDataContext </span>ctx)
{
    <span style="color:blue;">var </span>q = (<span style="color:blue;">from </span>ca <span style="color:blue;">in </span>ctx.CustomerAddresses
             <span style="color:blue;">select </span>ca).Take(<span style="color:brown;">3</span>);
    <span style="color:blue;">return </span>q;
}</pre>
<p>Very simple but also very inefficient. If you turn on the logger (ctx.Log = Console.Out;) you can see actual SQL statements generated and issued during program execution:</p>
<pre class="code"><span style="color:blue;">SELECT TOP </span><span style="color:gray;">(</span><span style="color:brown;">3</span><span style="color:gray;">) </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressType]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerAddress] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:green;">-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1

</span><span style="color:blue;">SELECT </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[NameStyle]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Title]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[FirstName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[MiddleName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[LastName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Suffix]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CompanyName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[SalesPerson]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[EmailAddress]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Phone]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordHash]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordSalt]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Customer] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:blue;">WHERE </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID] </span><span style="color:gray;">= </span><span style="color:teal;">@p0
</span><span style="color:green;">-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [29485]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1

</span><span style="color:blue;">SELECT </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine1]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine2]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[City]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[StateProvince]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CountryRegion]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PostalCode]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Address] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:blue;">WHERE </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID] </span><span style="color:gray;">= </span><span style="color:teal;">@p0
</span><span style="color:green;">-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1086]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1

</span><span style="color:blue;">SELECT </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[NameStyle]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Title]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[FirstName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[MiddleName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[LastName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Suffix]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CompanyName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[SalesPerson]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[EmailAddress]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Phone]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordHash]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordSalt]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Customer] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:blue;">WHERE </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID] </span><span style="color:gray;">= </span><span style="color:teal;">@p0
</span><span style="color:green;">-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [29486]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1

</span><span style="color:blue;">SELECT </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine1]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine2]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[City]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[StateProvince]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CountryRegion]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PostalCode]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Address] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:blue;">WHERE </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID] </span><span style="color:gray;">= </span><span style="color:teal;">@p0
</span><span style="color:green;">-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [621]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1

</span><span style="color:blue;">SELECT </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[NameStyle]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Title]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[FirstName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[MiddleName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[LastName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Suffix]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CompanyName]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[SalesPerson]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[EmailAddress]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[Phone]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordHash]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordSalt]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Customer] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:blue;">WHERE </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID] </span><span style="color:gray;">= </span><span style="color:teal;">@p0
</span><span style="color:green;">-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [29489]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1

</span><span style="color:blue;">SELECT </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine1]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine2]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[City]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[StateProvince]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CountryRegion]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[PostalCode]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Address] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:blue;">WHERE </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID] </span><span style="color:gray;">= </span><span style="color:teal;">@p0
</span><span style="color:green;">-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1069]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now you can see why it is inefficient. The first query reads top 3 rows from CustomerAddress table as we would expect. What is not expected is that it doesn’t try to make joins to Customer and Address tables, as you would, if you write SQL query yourself. This is because LINQ to SQL does not know about your intention to access child entities upfront. Instead, it issues two separate queries on-demand for EACH row in CustomerAddress table, one to fetch the Customer data, and one to fetch the Address. For a 3 row recordset we got 7(!) queries total. For a recordset of 1000 rows that would be 2001(!) queries. We clearly need to address this.</p>
<p>There are many ways to solve this and we are going to examine the following three solutions:</p>
<ol>
<li>Using the LoadWith() option provided by LINQ to SQL</li>
<li>Hinting LINQ to SQL to use joins by explicitly including child data in the compound object returned from the LINQ query</li>
<li>Hinting LINQ to SQL to use joins by using intermediate anonymous compound objects while still returning “clean” LINQ to SQL entity (CustomerAddress class in our case)</li>
</ol>
<p>The last solution is by far my favorite when it comes to DAL API, so, please, bear with me.</p>
<h6>LoadWith() option</h6>
<p>Using the LoadWith() data option we can hint LINQ to SQL that every time entity X is being requested its child entity Y should be requested as well. Since now LINQ to SQL “knows” upfront we are interested in child entity (entities) it can optimize the query using joins to retrieve all the data in one shot. In fact, this is how our modified code may look like:</p>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color:blue;">private static </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt; BuildQuery(
    <span style="color:#2b91af;">AdventureWorksDataContext </span>ctx)
{
    <span style="color:green;">// NEW CODE - LoadWith options
    </span><span style="color:blue;">var </span>dataOptions = <span style="color:blue;">new </span>System.Data.Linq.<span style="color:#2b91af;">DataLoadOptions</span>();
    dataOptions.LoadWith&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt;(ca =&gt; ca.Address);
    dataOptions.LoadWith&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt;(ca =&gt; ca.Customer);
    ctx.LoadOptions = dataOptions;
    <span style="color:green;">// END NEW CODE - LoadWith options

    </span><span style="color:blue;">var </span>q = (<span style="color:blue;">from </span>ca <span style="color:blue;">in </span>ctx.CustomerAddresses
             <span style="color:blue;">select </span>ca).Take(<span style="color:brown;">3</span>);
    <span style="color:blue;">return </span>q;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now, if we run our driver code with logging we see the following SINGLE(!) SQL query is generated:</p>
<pre class="code"><span style="color:blue;">SELECT TOP </span><span style="color:gray;">(</span><span style="color:brown;">3</span><span style="color:gray;">) </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressType]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid]</span><span style="color:gray;">, </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID] </span><span style="color:blue;">AS </span><span style="color:teal;">[AddressID2]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine1]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressLine2]</span><span style="color:gray;">,
</span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[City]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[StateProvince]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[CountryRegion]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[PostalCode]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid] </span><span style="color:blue;">AS </span><span style="color:teal;">[rowguid2]</span><span style="color:gray;">, </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate] </span><span style="color:blue;">AS </span><span style="color:teal;">[ModifiedDate2]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID] </span><span style="color:blue;">AS </span><span style="color:teal;">[CustomerID2]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[NameStyle]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[Title]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[FirstName]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[MiddleName]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[LastName]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[Suffix]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[CompanyName]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[SalesPerson]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[EmailAddress]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[Phone]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordHash]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[PasswordSalt]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[rowguid] </span><span style="color:blue;">AS </span><span style="color:teal;">[rowguid3]</span><span style="color:gray;">, </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[ModifiedDate] </span><span style="color:blue;">AS </span><span style="color:teal;">[ModifiedDate3]
</span><span style="color:blue;">FROM </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerAddress] </span><span style="color:blue;">AS </span><span style="color:teal;">[t0]
</span><span style="color:gray;">INNER JOIN </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Address] </span><span style="color:blue;">AS </span><span style="color:teal;">[t1] </span><span style="color:blue;">ON </span><span style="color:teal;">[t1]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID] </span><span style="color:gray;">= </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[AddressID]
</span><span style="color:gray;">INNER JOIN </span><span style="color:teal;">[SalesLT]</span><span style="color:gray;">.</span><span style="color:teal;">[Customer] </span><span style="color:blue;">AS </span><span style="color:teal;">[t2] </span><span style="color:blue;">ON </span><span style="color:teal;">[t2]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID] </span><span style="color:gray;">= </span><span style="color:teal;">[t0]</span><span style="color:gray;">.</span><span style="color:teal;">[CustomerID]
</span><span style="color:green;">-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.21006.1
</span></pre>
<p>We got the perfect query using the proper joins. Why do we need to look into alternative solutions? Well, the LoadWith() option has several limitations that may prevent us from using it in some scenarios:</p>
<ul>
<li>LoadWith() option has a global scope and can’t be applied selectively to specific queries. Once applied, ALL the queries requesting the entity will automatically include joins to pull registered child entities. This is not desired in many cases since we want to keep unrelated queries lightweight and free of “LoadWith()” joins. Also, once applied LoadWith() option can not be revoked.</li>
<li>Since LoadWith() option applies to the data context it needs to be passed around to various classes that construct the queries. This is a “smell” since in most cases we would prefer to deal with data context at the higher levels only.</li>
<li>Setting load options is not allowed after results have been returned from query involving base or child entity. For example the following [simplified] code throws InvalidOperationException:</li>
</ul>
<pre class="code"><span style="color:blue;">using </span>(<span style="color:#2b91af;">AdventureWorksDataContext </span>ctx = <span style="color:blue;">new </span><span style="color:#2b91af;">AdventureWorksDataContext</span>())
{
    <span style="color:blue;">var </span>q2 = <span style="color:blue;">from </span>ca <span style="color:blue;">in </span>ctx.Customers
             <span style="color:blue;">select </span>ca;
    q2.ToArray();   <span style="color:green;">// this forces query execution

    // this will throw if using LoadWith()
    </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt; q = BuildQuery(ctx);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<h6>Using compound object (projection) to hint LINQ to SQL into an efficient join</h6>
<p>Take a look at the following changes to the code:</p>
<pre class="code"><span style="color:blue;">using </span>(<span style="color:#2b91af;">AdventureWorksDataContext </span>ctx = <span style="color:blue;">new </span><span style="color:#2b91af;">AdventureWorksDataContext</span>())
{
    <span style="color:blue;">var </span>q = (<span style="color:blue;">from </span>ca <span style="color:blue;">in </span>ctx.CustomerAddresses
             <span style="color:blue;">select new </span>{
                 CustomerAddress = ca,
                 ca.Customer,
                 ca.Address
             }).Take(<span style="color:brown;">3</span>);

    <span style="color:blue;">foreach </span>(<span style="color:blue;">var </span>item <span style="color:blue;">in </span>q)
    {
        <span style="color:#2b91af;">Console</span>.Out.WriteLine(<span style="color:#a31515;">"{0}, {1} lives in {2}, {3} as of {4}"</span>,
            item.CustomerAddress.Customer.LastName,
            item.CustomerAddress.Customer.FirstName,
            item.CustomerAddress.Address.City,
            item.CustomerAddress.Address.StateProvince,            item.CustomerAddress.ModifiedDate);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>The main thing that is different here from our original solution is the use of anonymous type in the select statement. In this type we explicitly mention child entities, so LINQ to SQL optimize the select query to include them upfront with JOIN. In fact, if we run this with logging turned on, we will see exact same single statement that was generated when using LoadWith() options.</p>
<p>This solution does not rely on any global settings like LoadWith(), which eliminates unwanted side effects and much easier to manage in a component/layered architecture.  The obvious drawback of this method is using anonymous type. For example, we aren’t able to simply return resulting IEnumerable from our Data Access Layer. We can replace the anonymous type with a composite class, but would it be nice if we can simply return IEnumerable&lt;CustomerAddress&gt; where access to child properties won’t cause additional database roundtrips?</p>
<h6>The perfect solution – the best of both worlds</h6>
<p>Here is solution I like the best and I use it a lot in my DAL code:</p>
<pre class="code"><span style="color:blue;">private static </span><span style="color:#2b91af;">IEnumerable</span>&lt;<span style="color:#2b91af;">CustomerAddress</span>&gt; BuildQuery(
    <span style="color:#2b91af;">AdventureWorksDataContext </span>ctx)
{
    <span style="color:blue;">var </span>q = (<span style="color:blue;">from </span>ca <span style="color:blue;">in </span>ctx.CustomerAddresses
             <span style="color:blue;">select new
             </span>{
                 CustomerAddress = ca,
                 ca.Customer,
                 ca.Address
             }).Take(<span style="color:brown;">3</span>)
             .AsEnumerable()
             .Select(ca =&gt; ca.CustomerAddress);
    <span style="color:blue;">return </span>q;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>Here is how this works. The select part of it starts exactly the same as the one we used in the “anonymous type” solution. Using anonymous composite type forces the JOINs. Then there is “.AsEnumerable()” – very important part of the solution that I explain later. The last part (.Select(ca =&gt; ca.CustomerAddress)) simply “cleanses” anonymous type and “converts” it back to “clean” CustomerAddress class that we want to use/expose. If we don’t use AsEnumerable() before cleansing the whole expression will be evaluated as IQueryable by LINQ to SQL implementation and cleansing will “optimize away” the composite anonymous type benefits, and LINQ to SQL will no longer assume you need child properties, and will NOT generate JOINs. Injecting .AsEnumerable() takes control away from LINQ to SQL at the time when JOINs are assumed, and gives control to LINQ to Objects for cleansing.</p>
<p>The end result is the best of both world: single efficient query that uses JOINs and clean DAL API (IEnumerable&lt;CustomerAddress&gt;).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=77&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2009/11/26/linq-to-sql-tricks-building-efficient-queries-that-include-reference-data-or-child-entities/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>

		<media:content url="http://eprystupa.files.wordpress.com/2009/11/adventureworkscustomeraddress_thumb.png" medium="image">
			<media:title type="html">AdventureWorksCustomerAddress</media:title>
		</media:content>
	</item>
		<item>
		<title>Running multiple WPF applications in the same process using AppDomains</title>
		<link>http://eprystupa.wordpress.com/2008/07/31/running-multiple-wpf-applications-in-the-same-process-using-appdomains/</link>
		<comments>http://eprystupa.wordpress.com/2008/07/31/running-multiple-wpf-applications-in-the-same-process-using-appdomains/#comments</comments>
		<pubDate>Thu, 31 Jul 2008 21:02:07 +0000</pubDate>
		<dc:creator>eprystupa</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[AppDomain]]></category>

		<guid isPermaLink="false">http://eprystupa.wordpress.com/?p=54</guid>
		<description><![CDATA[Why? There are various reasons you may want to run several full-blown independent WPF applications side-by-side in the same process. In my particular case this was a client project where we were building a composite WPF trading desk. One of the requirements was to be able to run different versions of the same component (montage, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=54&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h5>Why?</h5>
<p>There are various reasons you may want to run several full-blown independent WPF applications side-by-side in the same process. In my particular case this was a client project where we were building a composite WPF trading desk. One of the requirements was to be able to run different versions of the same component (montage, P&amp;L, blotter, etc.) side-by-side but within seemingly integrated environment. The best solution turned out to be running different versions in completely independent environment (application) and only communicate across domains using a thin protocol to provide &#8220;integrated&#8221; look and feel. Running components in separate domains let us avoid all the problems that come with signing, versioning, evolving dependencies, and many more.</p>
<p>This post is a step by step guide to demonstrate the techniques involved.</p>
<p><span id="more-54"></span><br />
<h5>Step 1: Creating basic WPF application</h5>
<p>The first step is to create a simple host application. Select &#8220;File/New/Project&#8230;&#8221; in Visual Studio and pick &#8220;Visual C#/Windows/WPF Application&#8221;. Give it a name of &#8220;WPFDomainLab&#8221; and click OK. <br />The default application with a single main window is generated. Now go to the properties for &#8220;App.xaml&#8221; and change its &#8220;Build Action&#8221; from &#8220;Application Definition&#8221; to &#8220;Page&#8221;. This allows us to add our own Main() method with explicit WPF application startup code. If you try to compile at this point you should be getting &#8220;Program &#8216;XXXX.exe&#8217; does not contain a static &#8216;Main&#8217; method suitable for an entry point&#8221;.</p>
<p>We now need to add Main method to handle WPF startup. The following class will do it:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">using</span> System;

<span style="color:#0000ff;">namespace</span> WPFDomainLab
{
    <span style="color:#0000ff;">class</span> Startup
    {
        [STAThread()]
        <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main()
        {
            App app = <span style="color:#0000ff;">new</span> App();
            app.MainWindow = <span style="color:#0000ff;">new</span> Window1();
            app.MainWindow.Show();
            app.Run();
        }
    }
}</pre>
</div>
<p>Save this as Startup.cs and include it in your project. Now the project should compile. Before running it open Window1.xaml and have it display something interesting:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Window</span> <span style="color:#ff0000;">x:Class</span><span style="color:#0000ff;">="WPFDomainLab.Window1"</span>
    <span style="color:#ff0000;">xmlns</span><span style="color:#0000ff;">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"</span>
    <span style="color:#ff0000;">xmlns:x</span><span style="color:#0000ff;">="http://schemas.microsoft.com/winfx/2006/xaml"</span>
    <span style="color:#ff0000;">Title</span><span style="color:#0000ff;">="Window1"</span> <span style="color:#ff0000;">Height</span><span style="color:#0000ff;">="100"</span> <span style="color:#ff0000;">Width</span><span style="color:#0000ff;">="300"</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ContentControl</span>
            <span style="color:#ff0000;">Content</span><span style="color:#0000ff;">="{Binding DomainName}"</span><span style="color:#0000ff;">/&gt;</span>
    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Window</span><span style="color:#0000ff;">&gt;</span></pre>
</div>
<p>This will display the current domain’s friendly name. We now need to open the code-behind file (Window1.xaml.cs) and add the code to provide binding data context:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">using</span> System;
<span style="color:#0000ff;">using</span> System.Windows;

<span style="color:#0000ff;">namespace</span> WPFDomainLab
{
  <span style="color:#008000;">/// &lt;summary&gt;</span>
  <span style="color:#008000;">/// Interaction logic for Window1.xaml</span>
  <span style="color:#008000;">/// &lt;/summary&gt;</span>
  <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">partial</span> <span style="color:#0000ff;">class</span> Window1 : Window
  {
    <span style="color:#0000ff;">public</span> Window1()
    {
      InitializeComponent();
      <span style="color:#0000ff;">this</span>.DataContext = <span style="color:#0000ff;">new</span> {
        DomainName =
          <span style="color:#006080;">"I live in "</span> +
          AppDomain.CurrentDomain.FriendlyName
      };
    }
  }
}</pre>
</div>
<p>If you compile and run the app at this point you should get the following window:</p>
<pre class="csharpcode"><a href="http://blog.lab49.com/wp-content/uploads/2008/06/image.png"><img style="border-width:0;" height="118" alt="image" src="http://blog.lab49.com/wp-content/uploads/2008/06/image-thumb.png" width="346" border="0"></a> </pre>
<p>At this point we have a single WPF application running in the default application domain.</p>
<h5>Step 2: Moving WPF app into a dedicated domain</h5>
<p>Lets go ahead and move this application to its own dedicated domain. These are the changes needed to accomplish this in a simple way (Startup.cs):</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">1:  <span style="color:#0000ff;">using</span> System;
2:
3:  <span style="color:#0000ff;">namespace</span> WPFDomainLab
4:  {
5:    <span style="color:#0000ff;">class</span> Startup
6:    {
7:      [STAThread()]
8:      <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main()
9:      {
10:        AppDomain domain =
11:          AppDomain.CreateDomain(
12:            <span style="color:#006080;">"another domain"</span>);
13:        CrossAppDomainDelegate action = () =&gt;
14:        {
15:            App app = <span style="color:#0000ff;">new</span> App();
16:            app.MainWindow = <span style="color:#0000ff;">new</span> Window1();
17:            app.MainWindow.Show();
18:            app.Run();
19:        };
20:        domain.DoCallBack(action);
21:      }
22:    }
23:  }</pre>
</div>
<p>Lines 10-12 create another domain.</p>
<p>Lines 13-19 are used to package application startup logic in a delegate that will be remotely executed in another domain.</p>
<p>Line 20 actually runs the delegate in “another domain” and creates full-blown WPF application there. If you compile and run the app now you should get the following:</p>
<pre class="csharpcode">

<a href="http://blog.lab49.com/wp-content/uploads/2008/06/image1.png"><img style="border-width:0;" height="113" alt="image" src="http://blog.lab49.com/wp-content/uploads/2008/06/image-thumb1.png" width="331" border="0"></a> </pre>
<h5>Step 3: Starting second WPF application in its own domain</h5>
<p>Adding a second instance of our WPF application running in yet another domain looks simple now, but it has some caveats. Consider the following changes to create two separate domains each running a WPF app (Startup.cs):</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">1:  <span style="color:#0000ff;">using</span> System;
2:
3:  <span style="color:#0000ff;">namespace</span> WPFDomainLab
4:  {
5:    <span style="color:#0000ff;">class</span> Startup
6:    {
7:      [STAThread()]
8:      <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main()
9:      {
10:        var domain1 = AppDomain.CreateDomain(
11:          <span style="color:#006080;">"first dedicated domain"</span>);
12:        var domain2 = AppDomain.CreateDomain(
13:          <span style="color:#006080;">"second dedicated domain"</span>);
14:
15:        CrossAppDomainDelegate action = () =&gt;
16:        {
17:          App app = <span style="color:#0000ff;">new</span> App();
18:          app.MainWindow = <span style="color:#0000ff;">new</span> Window1();
19:          app.MainWindow.Show();
20:          app.Run();
21:        };
22:
23:        domain1.DoCallBack(action);
24:        domain2.DoCallBack(action);
25:      }
26:    }
27:  }</pre>
</div>
<p>Lines 10-13 create two different domains.</p>
<p>Lines 23-24 actually create WPF applications in respective domains.</p>
<p>If you run host application at this point you will find that it doesn’t quite work as expected. First a single window appears stating “I live in ‘first dedicated domain’ domain”. Only when you close the first window, the second one appears (after a pause), now stating “I live in ‘second dedicated domain’ domain”.</p>
<p>The reason for this strange behavior is that all three domains (default one created by CLR and two domains we explicitly created) share the same execution thread. The first WPF app “hijacks” Window message pump and blocks the thread at “app.Run()”, so “domain2.DoCallBack(action);” is not even executed until the first app terminates. </p>
<h5>Step 4: Starting a dedicated thread for each domain</h5>
<p>To remedy this we need to create a dedicated thread for each of the domains that we create. The following changes accomplish the task (Startup.cs):</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">1:  <span style="color:#0000ff;">using</span> System;
2:  <span style="color:#0000ff;">using</span> System.Threading;
3:
4:  <span style="color:#0000ff;">namespace</span> WPFDomainLab
5:  {
6:    <span style="color:#0000ff;">class</span> Startup
7:    {
8:      [STAThread()]
9:      <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main()
10:      {
11:        var domain1 = AppDomain.CreateDomain(
12:          <span style="color:#006080;">"first dedicated domain"</span>);
13:        var domain2 = AppDomain.CreateDomain(
14:          <span style="color:#006080;">"second dedicated domain"</span>);
15:
16:        CrossAppDomainDelegate action = () =&gt;
17:        {
18:          Thread thread = <span style="color:#0000ff;">new</span> Thread(() =&gt;
19:          {
20:            App app = <span style="color:#0000ff;">new</span> App();
21:            app.MainWindow = <span style="color:#0000ff;">new</span> Window1();
22:            app.MainWindow.Show();
23:            app.Run();
24:          });
25:          thread.SetApartmentState(
26:            ApartmentState.STA);
27:          thread.Start();
28:        };
29:
30:        domain1.DoCallBack(action);
31:        domain2.DoCallBack(action);
32:      }
33:    }
34:  }</pre>
</div>
<p>Lines 18-24 create a dedicated thread object to run WPF app and package WPF app startup code inside this thread’s start method.</p>
<p>Lines 25-26 sets the thread’s apartment to STA, this is a WPF requirement, otherwise it will not run (it will throw).</p>
<p>Lines 27 actually starts a dedicated thread in the given domain.</p>
<p class="csharpcode">If you run application host now you will see both windows running in the same process in two different domains happily coexisting side by side. Applications are fully isolated, each getting its own static variables, base directory and configuration file (if customized). The performance is sluggish though and we are going to address this next.</p>
<h5>Step 5: Optimizing assembly loading</h5>
<p class="csharpcode">When you ran the final application from step 4 you probably noticed that its startup time is extremely bad. Depending on your system it may take up to 10 seconds for the second application UI to show up.</p>
<p class="csharpcode">The reason is the default .Net loader behavior. By default every domain gets its own copy of assemblies loaded into domain’s context independently of other domains. It means that all .Net Framework and WPF assemblies will need to be loaded and JIT-ed twice (once in each domain). In addition to duplicating the work loading assemblies in non-default domain is extremely slow (I haven’t figured out why). Fortunately there is a simple solution for the problem and a simple change will do it:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">1:  <span style="color:#0000ff;">using</span> System;
2:  <span style="color:#0000ff;">using</span> System.Threading;
3:
4:  <span style="color:#0000ff;">namespace</span> WPFDomainLab
5:  {
6:    <span style="color:#0000ff;">class</span> Startup
7:    {
8:      [STAThread()]
9:      [LoaderOptimization(
10:        LoaderOptimization.MultiDomainHost)]
11:      <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> Main()
12:      {
13:        ...
14:      }
15:    }
16:  }</pre>
</div>
<p>The attribute on line 9 does the trick. Basically it instructs .Net loader to load all GAC-installed assemblies in a domain-neutral way, thus sharing the assembly code between domains. This avoids loading and JIT-ing assemblies multiple times.</p>
<p>You can read more about domain-neutral assemblies <a href="http://blogs.msdn.com/junfeng/archive/2004/08/05/208375.aspx" target="_blank">here</a>.</p>
<p>The final solution can be downloaded from <a href="http://44fszq.bay.livefilestore.com/y1pNkhTjn_Pa9ite627yMQ2n6o-5rlv6iVu-fMyuVAh6ycE0qSLoLFNUmd0R6YU3-YviI16xxPHp9Q/WPFDomainLab.zip?download">here</a>.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/eprystupa.wordpress.com/54/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/eprystupa.wordpress.com/54/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/eprystupa.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/eprystupa.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/eprystupa.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/eprystupa.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/eprystupa.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/eprystupa.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/eprystupa.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/eprystupa.wordpress.com/54/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=eprystupa.wordpress.com&amp;blog=4150554&amp;post=54&amp;subd=eprystupa&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://eprystupa.wordpress.com/2008/07/31/running-multiple-wpf-applications-in-the-same-process-using-appdomains/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c4af36a9f573526c5ae8dca621ba356f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">eprystupa</media:title>
		</media:content>

		<media:content url="http://blog.lab49.com/wp-content/uploads/2008/06/image-thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://blog.lab49.com/wp-content/uploads/2008/06/image-thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
	</channel>
</rss>
