<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>I Got Rhythm</title>
	
	<link>http://arbel.net</link>
	<description>A blog by Aelij (Eli) Arbel</description>
	<lastBuildDate>Thu, 27 Oct 2011 10:40:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/arbelnet" /><feedburner:info uri="arbelnet" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>E4D Expert Days – I’ll be there</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/UjYgEpOUCM8/</link>
		<comments>http://arbel.net/2011/06/04/e4d-expert-days-ill-be-there/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 11:12:33 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Lectures]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://arbel.net/2011/06/04/e4d-expert-days-ill-be-there/</guid>
		<description><![CDATA[Want to learn more about Windows Phone? Check out my lecture at E4D's Expert Days.]]></description>
			<content:encoded><![CDATA[<div dir="rtl">
<p><a href="http://www.expertdays.co.il/"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border-width: 0px;" title="image001" src="http://arbel.net/wp-content/uploads/2011/06/image001.jpg" alt="image001" width="640" height="182" border="0" /></a></p>
<p>חברת E4D עורכת גם השנה את כנס Expert Days  לטכנולוגיות מיקרוסופט, כך שאם אתם מפתחים, ראשי צוות, בודקי תוכנה או ארכיטקטים – זה המקום להיות בו.</p>
<p>הכנס נערך בין התאריכים 10-14.7.2011 ובמהלכו תוכלו למצוא עשרות הרצאות וסדנאות הנוגעות בכל הטכנולוגיות החמות והרלוונטיות ביותר של מיקרוסופט. כך לדוגמא נכללים בכנס סדנאות בנושא ‎.NET , Dynamic CRM, AZURE, WCF, Silverlight, Windows Phone ועוד רבות אחרות.  בכל סדנא תוכלו למצוא ידע מעשי רב וכלים של ממש שישמשו אתכם באופן מיידי, כך שהשקעת הזמן שלכם בסדנאות עומדת להשתלם לכם.</p>
<p><a href="http://www.e4d.co.il/Events/ExpertDays2011/Home/AllTracks"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="BannerExpertDays" src="http://arbel.net/wp-content/uploads/2011/06/BannerExpertDays.jpg" alt="BannerExpertDays" width="640" height="181" border="0" /></a></p>
<p>בין כל המומחים המרצים בכנס, תוכלו למצוא השנה גם אותי ואשמח מאוד אם תבואו לסדנא שאני מעביר בנושא <a href="http://www.e4d.co.il/Events/ExpertDays2011/Courses/Details/28">Windows Phone</a> (אם תציינו שהגעתם דרכי – קוד מרצה <strong>114</strong>– תקבלו 20% הנחה לרישום לסדנא שלי).</p>
<p>&nbsp;</p>
<p><a href="http://www.e4d.co.il/Events/ExpertDays2011/Home/OpeningEvent">אירוע הפתיחה</a>של Expert Days הוא אירוע ללא תשלום, המתקיים השנה בתאריך 10.7.2011. האירוע כולל מסיבת קוקטייל, מפגש מינגלינג וסדרה של הרצאות מקצועיות שגם הן כמובן חינמיות. באירוע הפתיחה עצמו תוגרל פלטפורמת XBOX + Kinnect.</p>
<p>&nbsp;</p>
<p><a href="http://www.e4d.co.il/Events/ExpertDays2011/Home/Xbox"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image003" src="http://arbel.net/wp-content/uploads/2011/06/image003.jpg" alt="image003" width="640" height="180" border="0" /></a></p>
<p>&nbsp;</p>
<p>מחכה לראות אתכם שם,</p>
<p>אלי ארבל.</p>
</div>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/UjYgEpOUCM8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2011/06/04/e4d-expert-days-ill-be-there/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2011/06/04/e4d-expert-days-ill-be-there/</feedburner:origLink></item>
		<item>
		<title>Slides from my Windows Phone + Azure lectures</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/R1J5JcwHwd4/</link>
		<comments>http://arbel.net/2011/06/04/slides-from-my-windows-phone-azure-lectures/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 10:30:15 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Windows Azure]]></category>
		<category><![CDATA[Windows Phone]]></category>

		<guid isPermaLink="false">http://arbel.net/2011/06/04/slides-from-my-windows-phone-azure-lectures/</guid>
		<description><![CDATA[<p>Last month I gave a series of lectures in various campuses around Israel about Windows Phone and Azure.</p> <p>The lecture included an introduction to Silverlight, Windows Phone, and a short overview of the Windows Azure Toolkit for Windows Phone.</p> <p>During August 11-12 there will be a workshop for any student who needs assistance in submitting [...]]]></description>
			<content:encoded><![CDATA[<p>Last month I gave a series of lectures in various campuses around Israel about Windows Phone and Azure.</p>
<p>The lecture included an introduction to Silverlight, Windows Phone, and a short overview of the Windows Azure Toolkit for Windows Phone.</p>
<p>During August 11-12 there will be a workshop for any student who needs assistance in submitting his app for the contest Microsoft is holding. You can find more details at the <a href="http://www.facebook.com/pages/Microsoft-Israel-Students/198910936798883">Microsoft Israel Students</a> Facebook page.</p>
<p>&nbsp;</p>
<p><a href="http://arbel.net/wp-content/uploads/2011/06/WPAzure.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="WPAzure" src="http://arbel.net/wp-content/uploads/2011/06/WPAzure_thumb.png" border="0" alt="WPAzure" width="600" height="126" /></a></p>
<p><a href="http://arbel.net/wp-content/uploads/2011/06/Windows-Phone-and-Azure.pptx">Download slides</a></p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/R1J5JcwHwd4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2011/06/04/slides-from-my-windows-phone-azure-lectures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2011/06/04/slides-from-my-windows-phone-azure-lectures/</feedburner:origLink></item>
		<item>
		<title>WCF + Tasks</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/WRSB554JKSM/</link>
		<comments>http://arbel.net/2011/06/04/wcf-tasks/#comments</comments>
		<pubDate>Sat, 04 Jun 2011 09:04:29 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://arbel.net/2011/06/04/wcf-tasks/</guid>
		<description><![CDATA[<p>In WCF we can use the <a href="http://msdn.microsoft.com/en-us/magazine/cc163467.aspx">APM</a> pattern to create an asynchronous client. For example, consider the following service contract:</p> [ServiceContract]<br /> public interface IHello<br /> {<br /> [OperationContract]<br /> string Greet(string name);<br /> } <p>&#160;</p> <p>&#160;</p> <p>An APM-enabled version of this interface would look like this:</p> [ServiceContract(Name = "IHello")]<br /> public interface IHelloApm<br [...]]]></description>
			<content:encoded><![CDATA[<p>In WCF we can use the <a href="http://msdn.microsoft.com/en-us/magazine/cc163467.aspx">APM</a> pattern to create an asynchronous client. For example, consider the following service contract:</p>
<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:47fb8b1a-d9aa-461e-9255-accaf7be613d" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background-color: #ffffff; overflow: auto; padding: 2px 5px;">[<span style="color: #2b91af;">ServiceContract</span>]<br />
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">interface</span> <span style="color: #2b91af;">IHello</span><br />
{<br />
[<span style="color: #2b91af;">OperationContract</span>]<br />
<span style="color: #0000ff;">string</span> Greet(<span style="color: #0000ff;">string</span> name);<br />
}</div>
<p>&nbsp;</p>
</div>
<p>&nbsp;</p>
</div>
<p>An APM-enabled version of this interface would look like this:</p>
<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:619941e5-3c1b-45d9-adc9-99e84743f8bd" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background-color: #ffffff; max-height: 300px; overflow: auto; padding: 2px 5px;">[<span style="color: #2b91af;">ServiceContract</span>(Name = <span style="color: #a31515;">"IHello"</span>)]<br />
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">interface</span> <span style="color: #2b91af;">IHelloApm</span><br />
{<br />
[<span style="color: #2b91af;">OperationContract</span>(AsyncPattern = <span style="color: #0000ff;">true</span>)]<br />
<span style="color: #2b91af;">IAsyncResult</span> BeginGreet(<span style="color: #0000ff;">string</span> name, <span style="color: #2b91af;">AsyncCallback</span> asyncCallback, <span style="color: #0000ff;">object</span> asyncState);<br />
<span style="color: #0000ff;">string</span> EndGreet(<span style="color: #2b91af;">IAsyncResult</span> asyncResult);<br />
}</div>
<p>&nbsp;</p>
</div>
<p>&nbsp;</p>
</div>
<p>WCF’s client can automatically generate a proxy that implements this interface (e.g. by inheriting from ClientBase&lt;IHelloApm&gt;).</p>
<p>However, in .NET 4.0, we now use Tasks, which provide a far more convenient API than APM. Fortunately, there’s an <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/06/09/9716439.aspx">easy way</a> to convert one to the other, by using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx">FromAsync</a> methods in TaskFactory. This would require you to:</p>
<ol>
<li>Create the above APM interface.</li>
<li>Create a client class.</li>
<li>Wrap each method pair (Begin &amp; End) in a method that calls FromAsync and returns a Task.</li>
</ol>
<p>I decided this was way too much of a hassle, and apparently the good folks at Microsoft thought along the same lines. One of the samples in the <a href="http://msdn.microsoft.com/en-us/vstudio/gg316360">Async CTP</a> contains an IWsdlImportExtension (called <em>TaskWsdlImportExtension</em>) that causes SvcUtil (the same mechanism used by “Add Service Reference” in VS) to generate methods that return Tasks. If you’re using SvcUtil to generate your proxies, you’re good to go. You can use the sample generator even without relying on the CTP itself.</p>
<p>But what if you write your own interfaces? Wouldn’t it be nice if you could simply create the following interface and have the runtime figure it out for you?</p>
<p>&nbsp;</p>
<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:dbf9f7b6-6bae-428a-b8e7-7eb41eeffad7" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background-color: #ffffff; overflow: auto; padding: 2px 5px;">[<span style="color: #2b91af;">ServiceContract</span>(Name = <span style="color: #a31515;">"IHello"</span>)]<br />
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">interface</span> <span style="color: #2b91af;">IHelloAsync</span><br />
{<br />
[<span style="color: #2b91af;">OperationContract</span>]<br />
<span style="color: #2b91af;">Task</span>&lt;<span style="color: #0000ff;">string</span>&gt; Greet(<span style="color: #0000ff;">string</span> name);<br />
}</div>
<p>&nbsp;</p>
</div>
<p>&nbsp;</p>
</div>
<p><strong>Side (but important) note:</strong> You may ponder &#8211; why not just use Task.Factory.StartNew() method and pass a delegate that calls the original (synchronous) method? Because then you’d be wasting a thread that will be kept waiting for I/O! .NET utilizes <a href="http://msdn.microsoft.com/en-us/library/aa365198">I/O Completion Ports</a> when you use the APM methods, which provides an efficient way of waiting for I/O to complete.</p>
<h2>Introducing TaskClient&lt;T&gt;</h2>
<p>TaskClient is very much like ClientBase (in fact, it implements the same interface, ICommunicationObject), only it uses code generation (Reflection Emit) to generate both the async interface <strong>and</strong> a class that implements the above (IHelloAsync) interface, by invoking FromAsync for each method. Sample usage:</p>
<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:1b8ee9b0-cfc4-4f90-b705-74edfbc8e1b3" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background-color: #ffffff; overflow: auto; padding: 2px 5px;"><span style="color: #0000ff;">var</span> taskClient = <span style="color: #0000ff;">new</span> <span style="color: #2b91af;">TaskClient</span>&lt;<span style="color: #2b91af;">IHelloAsync</span>&gt;();<br />
taskClient.Channel.Greet(<span style="color: #a31515;">&#8220;Seattle&#8221;</span>).ContinueWith(t =&gt; <span style="color: #2b91af;">Console</span>.WriteLine(t.Result));</div>
<p>&nbsp;</p>
</div>
<p>&nbsp;</p>
</div>
<p>Channel is IHelloAsync, and Greet returns a Task. We use a continuation to write the result to the console. When combined with Async CTP’s <em>await</em> keyword, this makes calling services that much easier.</p>
<p>The generated class looks something like this:</p>
<div id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ac30520c-f45e-48d9-89df-745c16308523" class="wlWriterEditableSmartContent" style="margin: 0px; display: inline; float: none; padding: 0px;">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt;">
<div style="background-color: #ffffff; overflow: auto; padding: 2px 5px;"><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #2b91af;">HelloAsyncClient</span> : <span style="color: #2b91af;">IHelloAsync</span><br />
{<br />
<span style="color: #0000ff;">private</span> <span style="color: #0000ff;">readonly</span> <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">IHelloApm</span>&gt; _channel;&nbsp;</p>
<p><span style="color: #0000ff;">public</span> HelloAsyncClient(<span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">IHelloApm</span>&gt; channel)<br />
{<br />
_channel = channel;<br />
}</p>
<p><span style="color: #0000ff;">public</span> <span style="color: #2b91af;">Task</span>&lt;<span style="color: #0000ff;">string</span>&gt; Greet(<span style="color: #0000ff;">string</span> name)<br />
{<br />
<span style="color: #2b91af;">IHelloApm</span> channel = _channel();<br />
<span style="color: #0000ff;">return</span><br />
<span style="color: #2b91af;">Task</span>.Factory.FromAsync(<br />
<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">Func</span>&lt;<span style="color: #0000ff;">string</span>, <span style="color: #2b91af;">AsyncCallback</span>, <span style="color: #0000ff;">object</span>, <span style="color: #2b91af;">IAsyncResult</span>&gt;(channel.BeginGreet),<br />
<span style="color: #0000ff;">new</span> <span style="color: #2b91af;">Func</span>&lt;<span style="color: #2b91af;">IAsyncResult</span>, <span style="color: #0000ff;">string</span>&gt;(channel.EndGreet), name, <span style="color: #0000ff;">null</span>, TaskCreationOptions);<br />
}</p>
<p><span style="color: #0000ff;">public</span> <span style="color: #2b91af;">TaskCreationOptions</span> TaskCreationOptions { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }<br />
}</p>
</div>
<p>&nbsp;</p>
</div>
<p>&nbsp;</p>
</div>
<p>Note that the channel is lazily evaluated on each call. This allows for more sophisticated channel management options.</p>
<p><strong>Known limitations:</strong></p>
<ul>
<li>TaskClient currently won’t handle overloaded methods in the interface.</li>
<li>Ref/Out parameters are not supported (nor will they be; they do not make sense in async interfaces).</li>
<li>The interface must be public.</li>
</ul>
<p><strong>A word of caution:</strong> While the code attached to this post works, it wasn’t thoroughly tested. So, if you would like to use this in a production environment, we are planning on making it available in a future release <a href="http://wcfcontrib.codeplex.com/">WCF Contrib</a>. This is a well established library of WCF extensions. I suggest checking it out, and waiting for more news.</p>
<p><strong>Attachment:</strong> <a href="http://arbel.net/wp-content/uploads/2011/06/ServiceModelTasks.zip">ServiceModelTasks.zip</a></p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/WRSB554JKSM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2011/06/04/wcf-tasks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2011/06/04/wcf-tasks/</feedburner:origLink></item>
		<item>
		<title>*N Async, Part 1</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/Qbfj6nBAe8o/</link>
		<comments>http://arbel.net/2010/11/12/n-async-part-1/#comments</comments>
		<pubDate>Fri, 12 Nov 2010 17:49:07 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Experiments]]></category>

		<guid isPermaLink="false">/blog/archive/2010/11/12/n-async-part-1.aspx</guid>
		<description><![CDATA[<p>You’ve all read about the asynchrony promise of C# 5 (if you haven’t, I highly recommend reading Eric Lippert’s <a href="http://blogs.msdn.com/b/ericlippert/archive/tags/c_2300_+5-0/">series</a> about the subject or this post won’t make much sense). I think it’s a great step forward, and it would make asynchronous programming all a lot easier.</p> <p>We already know how to think in [...]]]></description>
			<content:encoded><![CDATA[<p>You’ve all read about the asynchrony promise of C# 5 (if you haven’t, I highly recommend reading Eric Lippert’s <a href="http://blogs.msdn.com/b/ericlippert/archive/tags/c_2300_+5-0/">series</a> about the subject or this post won’t make much sense). I think it’s a great step forward, and it would make asynchronous programming all a lot easier.</p>
<p>We already know how to think in Tasks instead of threads, .NET 4.0 taught us that.</p>
<p>We already know how to use continuations (or at least some weak form of it), C# 2.0 iterators taught us that.</p>
<p>&#160;</p>
<p>So, as an experiment*, I went ahead and implemented a weak form of the await/async magic** using “the materials in the room”, i.e. tasks and iterators – minus the syntactic sugar, of course. Let’s have a look.</p>
<p>&#160;</p>
<p><strong>First, A Sample</strong></p>
<p>In C# 5 we would have (taken from Anders’ Netflix sample):</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:fc4bf446-502c-45ff-a58a-7dac46187cf8" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">async</span> <span style="color:#0000ff">void</span> LoadMoviesAsync(<span style="color:#0000ff">int</span> year)</li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">while</span> (<span style="color:#0000ff">true</span>)</li>
<li style="background: #f3f3f3">    {</li>
<li>        <span style="color:#0000ff">var</span> movies = <span style="color:#0000ff">await</span> QueryMoviesAsync(year, imageCount, pageSize, cts.Token);</li>
<li style="background: #f3f3f3">        <span style="color:#0000ff">if</span> (movies.Length == 0) <span style="color:#0000ff">break</span>;</li>
<li>        DisplayMovies(movies);</li>
<li style="background: #f3f3f3">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>While in my implementation it would look like this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:d4fe6661-dddf-4009-842f-66c543f7af39" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px; white-space: nowrap">
<li><span style="color:#2b91af">IEnumerable</span>&lt;<span style="color:#2b91af">Task</span>&gt; LoadMovies(<span style="color:#0000ff">int</span> year)</li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">while</span> (<span style="color:#0000ff">true</span>)</li>
<li style="background: #f3f3f3">    {</li>
<li>        <span style="color:#0000ff">var</span> moviesTask = <span style="color:#2b91af">Async</span>.Await&lt;<span style="color:#2b91af">Movie</span>[]&gt;(result =&gt;</li>
<li style="background: #f3f3f3">            QueryMovies(result, year, imageCount, pageSize, cts.Token));</li>
<li>        <span style="color:#0000ff">yield</span> <span style="color:#0000ff">return</span> moviesTask;</li>
<li style="background: #f3f3f3">        <span style="color:#0000ff">var</span> movies = moviesTask.Result;</li>
<li>        <span style="color:#0000ff">if</span> (movies.Length == 0) <span style="color:#0000ff">break</span>;</li>
<li style="background: #f3f3f3">        DisplayMovies(movies);</li>
<li>    }</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p><strong></strong></p>
<p><strong>What’s going on here?</strong></p>
<p>First of all, as you can see, the methods look very similar. We have created an iterator that allows us to start running the method and break after every <em>yield</em>. The implementation of Async.Await() method is surprisingly simple:</p>
<ul>
<li>The Await() method simply creates an enumerator, which starts up the state machine.</li>
<li>It calls MoveNext(), which executes the method up to the next <em>yield</em>.</li>
<li>We get a Task from the yield, and attach a <em>continuation</em> to it, which calls MoveNext() again, and so on.</li>
</ul>
<p>&#160;</p>
<p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ae958bf2-7644-4c6e-8aca-01399dbeb6ee" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px; white-space: nowrap">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#2b91af">Task</span>&lt;T&gt; Await&lt;T&gt;(<span style="color:#2b91af">Func</span>&lt;<span style="color:#2b91af">TaskCompletionSource</span>&lt;T&gt;, <span style="color:#2b91af">IEnumerable</span>&lt;<span style="color:#2b91af">Task</span>&gt;&gt; func)</li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">var</span> completionSource = <span style="color:#0000ff">new</span> <span style="color:#2b91af">TaskCompletionSource</span>&lt;T&gt;();</li>
<li style="background: #f3f3f3">    Await(func(completionSource));</li>
<li>    <span style="color:#0000ff">return</span> completionSource.Task;</li>
<li style="background: #f3f3f3">}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> Await(<span style="color:#2b91af">IEnumerable</span>&lt;<span style="color:#2b91af">Task</span>&gt; iterator)</li>
<li>{</li>
<li style="background: #f3f3f3">    <span style="color:#2b91af">IEnumerator</span>&lt;<span style="color:#2b91af">Task</span>&gt; enumerator = iterator.GetEnumerator();</li>
<li>    Run(enumerator);</li>
<li style="background: #f3f3f3">}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">private</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> Run(<span style="color:#2b91af">IEnumerator</span>&lt;<span style="color:#2b91af">Task</span>&gt; enumerator)</li>
<li>{</li>
<li style="background: #f3f3f3">    <span style="color:#0000ff">if</span> (enumerator.MoveNext())</li>
<li>    {</li>
<li style="background: #f3f3f3">        enumerator.Current.ContinueWith(t =&gt; Run(enumerator));</li>
<li>    }</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
</p>
<p><strong></strong></p>
<p><strong>Why do we need TaskCompletionSource?</strong></p>
<p>The return value of the iterator method must always be <em>IEnumerable&lt;Task&gt;</em>. But what if we want to return a value from a method? Remember, it doesn’t execute synchronously anymore! That is why methods that (originally) do not return <em>void</em>, have the option of adding an argument of TaskCompletionSource. In the method, we can call TaskCompletionSource.SetResult() to set the result. We also return the Task the TCS creates, so the caller could access the result. The overload of Await() that we use in this case simply wraps around this functionality, and enables a more concise syntax.</p>
<p>When an asynchronous method has no return value, TaskCompletionSource is not needed.</p>
<p>&#160;</p>
<p><strong>What’s missing?</strong></p>
<p>In the next installment(s) we will discuss:</p>
<ul>
<li>Task Schedulers (how to make sure we’re in the right context for UI operations)</li>
<li>Limited exception handling</li>
</ul>
<p>&#160;</p>
<p>* Yes, it means I wouldn’t recommend using this in “real” code – just wait for C# 5. This is just for fun.</p>
<p>** And I use the term very <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/03/20/it-s-not-magic.aspx">figuratively</a>.</p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/Qbfj6nBAe8o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/11/12/n-async-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/11/12/n-async-part-1/</feedburner:origLink></item>
		<item>
		<title>Creating the CodeValue Blogs Pivot</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/Cprf34GI1rc/</link>
		<comments>http://arbel.net/2010/11/12/creating-the-codevalue-blogs-pivot/#comments</comments>
		<pubDate>Fri, 12 Nov 2010 12:23:00 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[CodeValue]]></category>
		<category><![CDATA[Deep Zoom]]></category>
		<category><![CDATA[Pivot]]></category>

		<guid isPermaLink="false">/blog/archive/2010/11/12/creating-the-codevalue-blogs-pivot.aspx</guid>
		<description><![CDATA[<p><a href="http://www.microsoft.com/silverlight/pivotviewer/">Pivot</a> is a Microsoft Silverlight control which can visualize collections of data, filter and sort them in a very appealing manner. To see what I mean, check out the <a href="http://codevalue.net/">CodeValue</a> Blogs Pivot:</p> <p><a title="http://codevalue.net/blogspivot/" href="http://codevalue.net/blogspivot/">http://codevalue.net/blogspivot/</a></p> <p>This allows you to browse through our blogs, and to filter them by tags, dates and authors.</p> <p>&#160;</p> [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.microsoft.com/silverlight/pivotviewer/">Pivot</a> is a Microsoft Silverlight control which can visualize collections of data, filter and sort them in a very appealing manner. To see what I mean, check out the <a href="http://codevalue.net/">CodeValue</a> Blogs Pivot:</p>
<blockquote><p><a title="http://codevalue.net/blogspivot/" href="http://codevalue.net/blogspivot/">http://codevalue.net/blogspivot/</a></p>
</blockquote>
<p>This allows you to browse through our blogs, and to filter them by tags, dates and authors.</p>
<p>&#160;</p>
<p>Pivot uses a proprietary XML format, called <a href="http://www.silverlight.net/learn/pivotviewer/collection-xml-schema/">CXML</a>. An item in the collection is comprised of an image, a URI and any other metadata you choose to add. I’ve created a small utility which takes an RSS feed, transforms it into CXML, creates snapshots of all site images and adds metadata (author, date and tags).</p>
<p>In addition, because Pivot presents many large images, you can optionally (highly recommended!) configure the collection to use <a href="http://www.microsoft.com/silverlight/deep-zoom/">Deep Zoom</a> (which breaks down your images to pyramids, much like how Google Maps works). To do that, you can use <a href="http://pauthor.codeplex.com/">Pauthor</a>, a free utility that can be found on CodePlex. The attached code contains a batch file with a sample that shows how to use it.</p>
<p>Lastly, since Deep Zoom uses many files (for example, 140 Pivot items might generate ~7500 Deep Zoom files – depending on image sizes), uploading them individually can be a real pain. Fortunately, many website hosts support uploading archives (such as ZIP files) and unarchiving them on the server.</p>
<p>&#160;</p>
<p><strong>Some interesting facts about the code:</strong></p>
<ul>
<li>I used <strong>Parallel.ForEach()</strong> to parallelize the creation of items. Note that I’m assuming LINQ to XML is okay for cross-threaded <em>reading</em> (which is not documented, and I wouldn’t use in production code), but for writing (a single point in the end) I added a lock.</li>
<li>The <strong>UriImageCreator</strong> class relies on the Windows Forms WebBrowser control, but uses WPF’s Dispatcher to handle the message loop. This is because Dispatcher makes it easier to marshal calls into the message loop. I’ve borrowed some of this code from Pauthor (which uses it for its HTML template feature), and made it thread-safe. Note it is using a single thread to load the WebBrowser controls (so we only have one message loop), but websites will be loaded asynchronously because of how the WebBrowser control works.</li>
<li>I used <strong>NDesk.Options </strong>to parse command-line arguments. It provides a very neat interface with object initializers and lambda expressions.</li>
</ul>
<p>Attachment: <a href="http://arbel.net/attachments/Rss2Cxml.zip">Rss2Cxml.zip</a></p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/Cprf34GI1rc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/11/12/creating-the-codevalue-blogs-pivot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/11/12/creating-the-codevalue-blogs-pivot/</feedburner:origLink></item>
		<item>
		<title>Goodbye and hello, as always</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/1zWqZM9mI5s/</link>
		<comments>http://arbel.net/2010/08/22/goodbye-and-hello-as-always/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 13:53:11 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[CodeValue]]></category>
		<category><![CDATA[Sela]]></category>

		<guid isPermaLink="false">/blog/archive/2010/08/22/goodbye-and-hello-as-always.aspx</guid>
		<description><![CDATA[<p>Today I’m saying goodbye to Sela. I’ve been a senior consultant at Sela for the past 9 months, and it has been a good experience for me; I’m much more experienced with giving lectures and teaching classes. I’ve also had a chance to meet and work with some of the leading experts in their fields.</p> [...]]]></description>
			<content:encoded><![CDATA[<p>Today I’m saying goodbye to Sela. I’ve been a senior consultant at Sela for the past 9 months, and it has been a good experience for me; I’m much more experienced with giving lectures and teaching classes. I’ve also had a chance to meet and work with some of the leading experts in their fields.</p>
<p>But today is a new day. I’m off to a completely new adventure for me – starting a new company, called <a href="http://codevalue.net/">CodeValue</a>. Along with a group of very talented people, we intend to form a company that would build extremely essential developer tools, and also provide consulting services of the highest quality.</p>
<p>Go on, browse to our new website and check out the team. You’ll want to book us for your next project.</p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/1zWqZM9mI5s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/08/22/goodbye-and-hello-as-always/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/08/22/goodbye-and-hello-as-always/</feedburner:origLink></item>
		<item>
		<title>Reflectoron: Transform and Roll Out!</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/y6I63Hw6vWw/</link>
		<comments>http://arbel.net/2010/07/15/reflectoron-transform-and-roll-out/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 07:35:00 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Prism]]></category>
		<category><![CDATA[Reflector]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">/blog/archive/2010/07/15/reflectoron-transform-and-roll-out.aspx</guid>
		<description><![CDATA[<p>A few months ago I&#8217;ve decided to write a Prism tutorial by building a WPF UI for the <a href="http://www.red-gate.com/products/reflector/">.NET Reflector</a>.</p> <p>Red Gate, the owner of Reflector, liked the idea so they asked me to write it for their magazine, Simple Talk.</p> <p>Today the article was published, and you may read it on the Simple [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago I&#8217;ve decided to write a Prism tutorial by building a WPF UI for the <a href="http://www.red-gate.com/products/reflector/">.NET Reflector</a>.</p>
<p>Red Gate, the owner of Reflector, liked the idea so they asked me to write it for their magazine, Simple Talk.</p>
<p>Today the article was published, and you may read it on the Simple Talk website. I hope you enjoy it.</p>
<p><a href="http://www.simple-talk.com/dotnet/.net-framework/reflectoron-in-prism-a-wpf-mvvm-tutorial/">http://www.simple-talk.com/dotnet/.net-framework/reflectoron-in-prism-a-wpf-mvvm-tutorial/</a></p>
<p>&nbsp;</p>
<p>* My whimsical choice of titles continues; I&#8217;ve decided to name the thing &#8220;Reflectoron&#8221; because it&#8217;s Reflector + Avalon. It also reminded me of the Transformers, hence the blog post title. <img src='http://arbel.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/y6I63Hw6vWw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/07/15/reflectoron-transform-and-roll-out/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/07/15/reflectoron-transform-and-roll-out/</feedburner:origLink></item>
		<item>
		<title>WPF Controls Class Diagram</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/a3qT-mGA0yo/</link>
		<comments>http://arbel.net/2010/06/25/wpf-controls-class-diagram/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 18:36:00 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Modeling]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">/blog/archive/2010/06/25/wpf-controls-class-diagram.aspx</guid>
		<description><![CDATA[<p>I&#8217;ve prepared a class diagram for my students of main WPF controls, divided into Decorators, Panels, Content Controls and Items Controls. The diagram was generated using the new <a href="http://msdn.microsoft.com/en-us/library/57b85fsc.aspx">Visual Studio 2010 Visualization and Modeling Tools</a> (with a bit of manual cleanup). </p> <p>I&#8217;ve also attached an XPS version and the DGML source.</p> <p>&#160;</p> <p></a></p> [...]]]></description>
			<content:encoded><![CDATA[<p>I&rsquo;ve prepared a class diagram for my students of main WPF controls, divided into Decorators, Panels, Content Controls and Items Controls. The diagram was generated using the new <a href="http://msdn.microsoft.com/en-us/library/57b85fsc.aspx">Visual Studio 2010 Visualization and Modeling Tools</a> (with a bit of manual cleanup). </p>
<p>I&rsquo;ve also attached an XPS version and the DGML source.</p>
<p>&nbsp;</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" alt="image" src="http://arbel.net/attachments/images/image_5F00_thumb_5F00_1F91DC37.png" border="0" height="399" width="644" /></a></p>
<p>Attachment: <a href="http://arbel.net/attachments/WPF Controls Class Diagram.zip">WPF Controls Class Diagram.zip</a></p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/a3qT-mGA0yo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/06/25/wpf-controls-class-diagram/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/06/25/wpf-controls-class-diagram/</feedburner:origLink></item>
		<item>
		<title>Peaceful Coexistence</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/S-CQI2LzmK0/</link>
		<comments>http://arbel.net/2010/06/25/peaceful-coexistence/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 18:21:00 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">/blog/archive/2010/06/25/peaceful-coexistence.aspx</guid>
		<description><![CDATA[<p>One of the new features in .NET 4.0 is Side-By-Side In-Process (SxS InProc) execution of older CLRs (e.g. .NET 2.0). Previously, SxS was supported only in different processes. If you look it up, you&#8217;ll find <a href="http://blogs.msdn.com/clrteam/archive/2009/06/03/in-process-side-by-side-part1.aspx">these</a> <a href="http://blogs.msdn.com/clrteam/archive/2009/06/07/in-process-side-by-side-part-2-common-in-proc-sxs-scenarios.aspx">two</a> (yet to be updated) blog posts by the CLR team, an MSDN Magazine <a href="http://msdn.microsoft.com/en-us/magazine/ee819091.aspx">article</a> as [...]]]></description>
			<content:encoded><![CDATA[<p>One of the new features in .NET 4.0 is <b>Side-By-Side In-Process</b> (SxS InProc) execution of older CLRs (e.g. .NET 2.0). Previously, SxS was supported only in different processes. If you look it up, you&rsquo;ll find <a href="http://blogs.msdn.com/clrteam/archive/2009/06/03/in-process-side-by-side-part1.aspx">these</a> <a href="http://blogs.msdn.com/clrteam/archive/2009/06/07/in-process-side-by-side-part-2-common-in-proc-sxs-scenarios.aspx">two</a> (yet to be updated) blog posts by the CLR team, an MSDN Magazine <a href="http://msdn.microsoft.com/en-us/magazine/ee819091.aspx">article</a> as well as <a href="http://msdn.microsoft.com/en-us/library/ee518876.aspx">one</a> in the MSDN Library. You can get a good review of supported scenarios and some code, but what they all sorely lack is a working sample. (<b>Update:</b> There&rsquo;s a new detailed <a href="http://blogs.msdn.com/clrteam/archive/2010/06/23/in-proc-sxs-and-migration-quick-start.aspx">article</a> from the CLR team.)</p>
<p>The common scenario for SxS would be a host (such as Outlook) that loads .NET add-ins which are configured to run in different versions of the CLR. In this case, it is sufficient to provide an app.config that would tell the host which .NET version you need. The default COM activation behavior in .NET 4 is to use the CLR version the component was compiled with.</p>
<p>The scenario I&rsquo;ve been trying to solve isn&rsquo;t mentioned in any of these articles; I would like to host a WPF 3.5 control in a WPF 4 application. Why? Because I&rsquo;m using a crucial 3rd party control that unfortunately doesn&rsquo;t work with .NET 4.</p>
<p>I remembered that there was already a way to host WPF controls from different AppDomains, by using the .NET Add-In framework (System.AddIn). This <a href="http://blogs.msdn.com/clraddins/archive/2007/08/06/appdomain-isolated-wpf-add-ins-jesse-kaplan.aspx">article</a> from the CLR Add-In team blog has a nice <a href="http://clraddins.codeplex.com/releases/view/9454">sample</a> that shows how it&rsquo;s done.</p>
<p>So, we will utilize the FrameworkElementAdapters class to help us convert a FrameworkElement to a Win32 handle, pass it from the CLR v2 component via COM and then convert it back to a FrameworkElement in CLR v4. Sounds complicated? Maybe. But it will take only a handful of code lines to accomplish.</p>
<h3>Creating the Control</h3>
<p>First, we create a WPF user control. Then, we create a COM interface that contains the handle and any other properties we may want to use on &ldquo;the other side&rdquo;.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:9deedec7-4ab5-4ffe-ad31-1339c44d6e11" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px;">
<li>[<span style="color:#2b91af">Guid</span>(<span style="color:#a31515">"45421E7C-EA8E-4987-A669-5334795D1627"</span>)]</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">public</span> <span style="color:#0000ff">interface</span> <span style="color:#2b91af">IMyControl</span></li>
<li>{</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af">IntPtr</span> Handle { <span style="color:#0000ff">get</span>; }</li>
<li>}</li>
</ol></div>
</div>
</div>
<p>Now, we implement the interface using the FrameworkElementAdapters class:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:8c65ce44-3119-40ef-8ae9-54b38bf1ff9d" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li>[<span style="color:#2b91af">Guid</span>(<span style="color:#a31515">"4F03582A-8ECA-4A27-9E4E-00AB54078592"</span>)]</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">MyControl</span> : <span style="color:#2b91af">IMyControl</span></li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#0000ff">private</span> <span style="color:#2b91af">UserControl1</span> _instance;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#0000ff">private</span> <span style="color:#2b91af">INativeHandleContract</span> _contract;</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#0000ff">public</span> MyControl()</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_instance = <span style="color:#0000ff">new</span> <span style="color:#2b91af">UserControl1</span>();</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_contract = <span style="color:#2b91af">FrameworkElementAdapters</span>.ViewToContractAdapter(_instance);</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Handle = _contract.GetHandle();</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#0000ff">public</span> <span style="color:#2b91af">IntPtr</span> Handle { <span style="color:#0000ff">get</span>; <span style="color:#0000ff">private</span> <span style="color:#0000ff">set</span>; }</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;}</li>
</ol></div>
</div>
</div>
<p>We must also tag the assembly (or the required types) with the [ComVisible(true)] attribute.</p>
<p>Now, for the host, we simply reference the assembly containing the user control and instantiate the COM object. We also need to provide a simple implementation of INativeHandleContract (see the sample code).</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:7bfe535a-a393-4700-8e6a-f6709ebe0afb" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li>_control = (WpfSxsControls.<span style="color:#2b91af">IMyControl</span>)<span style="color:#2b91af">Activator</span>.CreateInstance(</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#2b91af">Type</span>.GetTypeFromCLSID(<span style="color:#0000ff">new</span> <span style="color:#2b91af">Guid</span>(<span style="color:#a31515">&#8220;{4F03582A-8ECA-4A27-9E4E-00AB54078592}&#8221;</span>)));</li>
<li>Content = <span style="color:#2b91af">FrameworkElementAdapters</span>.ContractToViewAdapter(</li>
<li style="background: #f3f3f3">&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#0000ff">new</span> <span style="color:#2b91af">NativeHandleContract</span>(_control.Handle));</li>
</ol></div>
</div>
</div>
<p>Lastly, there&rsquo;s the issue of COM registration. You can either register the COM object in the registry, which can cause deployment problems (mainly during uninstall). To do it quickly from VS, simply check the following box in the Build tab of the control assembly&rsquo;s project properties:</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" alt="image" src="http://arbel.net/attachments/images/image_5F00_thumb_5F00_31039729.png" border="0" height="74" width="244" /> </p>
<p><b>Or</b> you can use <a href="http://msdn.microsoft.com/en-us/library/ms973913.aspx">Registration-Free COM</a>. The provided sample code uses the latter method.</p>
<h3>Caveats</h3>
<ul>
<li>You&rsquo;re using COM, which means everything you&rsquo;re exposing from your control needs to be COM-patible.</li>
<li>You&rsquo;re using COM, which means passing delegates (and that includes registering to .NET events) becomes a lot less trivial.</li>
<li>Debugging can be a serious issue; it seems VS is not capable of attaching to the other (older) CLR.</li>
<li>Some work needs to be done to handle focus changes.</li>
</ul>
<p>You can ameliorate some of these issues by using COM only to activate the older CLR and then use some IPC technology (e.g. WCF, Remoting) to communicate with your control. I strongly recommend this approach if you have a complex object model.</p>
<h3>Running the Sample</h3>
<p>Just compile and run. The C++ project in the solution is used only to generate a Win32 Resource file which embeds the manifest that is required for reg-free COM. You can see that it is working if the title of the windows shows CLR v4 and above the first text box there&rsquo;s a text indicating it&rsquo;s coming from CLR v2.</p>
<p>Attachment: <a href="http://arbel.net/attachments/WpfSxs.zip">WpfSxs.zip</a></p>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/S-CQI2LzmK0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/06/25/peaceful-coexistence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/06/25/peaceful-coexistence/</feedburner:origLink></item>
		<item>
		<title>MIX10</title>
		<link>http://feedproxy.google.com/~r/arbelnet/~3/CYMZqYDxuQo/</link>
		<comments>http://arbel.net/2010/03/21/mix10/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 20:59:54 +0000</pubDate>
		<dc:creator>aelij</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">/blog/archive/2010/03/21/mix10.aspx</guid>
		<description><![CDATA[<p>I recently attended the Microsoft <a href="http://live.visitmix.com/">MIX10</a> conference in Las Vegas. I had a nice time, but mostly because of the location; Las Vegas is an interesting place. The conference itself was mainly a PR for the new Windows Phone, but there were a couple of very interesting lectures I would like to share:</p> The [...]]]></description>
			<content:encoded><![CDATA[<p>I recently attended the Microsoft <a href="http://live.visitmix.com/">MIX10</a> conference in Las Vegas. I had a nice time, but mostly because of the location; Las Vegas is an interesting place. The conference itself was mainly a PR for the new Windows Phone, but there were a couple of very interesting lectures I would like to share:</p>
<ul>
<li><strong>The Art, Technology and Science of Reading</strong>      <br />by Kevin Larson (<a href="http://blogs.msdn.com/fontblog/">blog</a>)      <br /><a title="http://live.visitmix.com/MIX10/Sessions/DS07" href="http://live.visitmix.com/MIX10/Sessions/DS07">http://live.visitmix.com/MIX10/Sessions/DS07</a>      <br />This is a fascinating lecture about how we (humans) process words visually. Kevin discusses several studies his group conducted on the subject, with some surprising results.</li>
</ul>
<p>&#160;</p>
<ul>
<li><strong>The Elephant in the Room</strong>      <br />by Nishant Kothary (<a href="http://www.rainypixels.com/">blog</a>)      <br /><a title="http://live.visitmix.com/MIX10/Sessions/DS13" href="http://live.visitmix.com/MIX10/Sessions/DS13">http://live.visitmix.com/MIX10/Sessions/DS13</a>      <br />Nishant effectively demonstrates how we tend to form ill-advised bias towards our peers, and how it applies to the process of software design.</li>
</ul>
<img src="http://feeds.feedburner.com/~r/arbelnet/~4/CYMZqYDxuQo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://arbel.net/2010/03/21/mix10/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://arbel.net/2010/03/21/mix10/</feedburner:origLink></item>
	</channel>
</rss>

