<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-891889700878195825</atom:id><lastBuildDate>Thu, 02 Oct 2025 15:07:59 +0000</lastBuildDate><category>WPF</category><category>MEF</category><category>MefContrib</category><category>Unity</category><category>Attached Behavior</category><category>KGD.NET</category><category>Wizard</category><category>CompositeWPF</category><category>Mammoth</category><category>Silverlight</category><category>Blend</category><category>CLR</category><category>Castle</category><category>Common Language Runtime</category><category>Effects</category><category>Git</category><category>ITAD</category><category>Parallel Coordinates</category><category>Sharp3D</category><category>Watermark</category><category>WinRT</category><category>Window</category><category>pixel shaders</category><title>Piotr Włodek&#39;s Tech Blog</title><description>My thoughts about programming, particularly on .NET platform</description><link>http://pwlodek.blogspot.com/</link><managingEditor>noreply@blogger.com (Piotr Włodek)</managingEditor><generator>Blogger</generator><openSearch:totalResults>33</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-3112160219388393409</guid><pubDate>Mon, 27 Feb 2012 21:56:00 +0000</pubDate><atom:updated>2012-02-27T23:04:38.971+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Attached Behavior</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Fill up a WPF progress bar with a linear gradient</title><description>Not so long ago I was faced with a problem how to fill a rectangle with a gradient, which shows a progress, with the gradient stops depending on the current progress. I know I know, this probably tells you nothing. I believe a good visual example will save me a thousand words, so here it comes. This is what I wanted to say:&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjc57buABAZnva9nFDOq6OrwEvExZERnejKFCzvtPLyX51pw-OM6frKfbs0JUkdcpz7Z1La88xK7tb8gT2IVQdRvU-9v0uVIKrObrBRLsv-c0zCQFOHnaBIeR1QJU5bmgYUW9G6bbT36QS_/s1600-h/image%25255B20%25255D.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;254&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXJj8lxiIh0pKxcB_ux0-gTd5a-kOvqeCd-tub6ik6EkG8_0GCDdRcG0v0xqJNoQQXih1g_RK3xP5o-Ylqk2b8BaL7Ez5y2M1IjMJpw6zFXVft8opDwSnvbG_3GF_XkaE3E7iYt-sHFXnO/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;359&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhgjHR5n0E3bYWL0aFCDpERX9QIdY4dNXvvEUOzpy1VkBxMox7Fzra6xK8SVex8z2sidhOnCDMvndQXq2Uc_ZF721ZOw3pi5Iwd7gtPpGihaC-GsjyAJDTtfmF53eU2g1Jy6neVrj-fA9dE/s1600-h/image%25255B19%25255D.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;254&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikxaVJgX_cBBbWC7SKYe5y6d11nn3RXLBdFG4sQXtg8dxtu03odH14tDX09ZDHK-MRYgO0bQJFis3PNxgzLb_wnktn2-lntGSoxfDyiTemQV9TrWulOSvZM1kHHyzl2D4qvTvtPlPv2G2L/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;359&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhC1edBcOcP374jv6qtYeR8Wmk95rzWLOaxnpTghCAj7OCETo_yTiYXCUtvJBCI53LCATWlSsX1xPX7erMgMALli30fw-od7Eb-QVTqEhtvRWiSvy_0Tng8WMfVcwJJHf-m3Syryla93i53/s1600-h/image%25255B18%25255D.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;254&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWtBUdEA_sxvlo5u6nNG6w2rLc_LbDplJ6M-8sNYxk8hGW21f6WxsmLm5N-VZTJBVVW52Vss_OCLZ6dCfCKvzVxGlmPDcNwtNKIxYa3kZDp97tPpdHEpQ2H48rxAiFoA1LsW3XpUvOCoay/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;359&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
So lets discuss what we see here. We have three styled progress bars, each filled with the same background. The middle one serves as a reference point only. The middle and the last text boxes are filled with a regular linear gradient brush. And I mean regular, absolutely no magic there. When we change the progress using the slider, you can see that the rectangle which is used to show current progress shrinks or expands, but the last gradient behaves in a weird way. &lt;strong&gt;This is actually the default bahavior here&lt;/strong&gt;. However, what I really expect is the behavior of the first progress bar – the fill gradient depends on the current progress. In other words, you can imagine 100% as the full gradient. Than, I want to crop it based on current progress.&lt;br /&gt;
&lt;br /&gt;
So how to write a custom brush which would do that ? Yes, yes, you’re right. It’s not possible. You cannot write custom brushes in WPF. That’s sad but it’s true. No luck ? No! Attached behavior comes to the rescue! Whenever progress changes the attached behavior will recreate LinearGradientBrush and recalculate gradient stops based on the original gradient. It’s actuall simple, let’s have a quick overview of the code itself. &lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class LinearGradientBrushBehavior : Behavior&amp;lt;RangeBase&amp;gt;
{
    protected override void OnAttached()
    {            
        AssociatedObject.Loaded += AssociatedObject_Loaded;
        AssociatedObject.ValueChanged += AssociatedObject_ValueChanged;

        var sourceBrush = AssociatedObject.Foreground as LinearGradientBrush;
        if (sourceBrush != null)
        {
            SourceBrush = sourceBrush;
        }
    }
        
    protected override void OnDetaching()
    {
        AssociatedObject.Loaded -= AssociatedObject_Loaded;
        AssociatedObject.ValueChanged -= AssociatedObject_ValueChanged;
    }

    private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        CalculateNewGradient(Progress);
    }

    private void AssociatedObject_ValueChanged(object sender, RoutedPropertyChangedEventArgs&amp;lt;double&amp;gt; e)
    {
        CalculateNewGradient(Progress);
    }

    private double Progress
    {
        get { return AssociatedObject.Value / (AssociatedObject.Maximum - AssociatedObject.Minimum); }
    }

    #region SourceBrush

    public LinearGradientBrush SourceBrush
    {
        get { return (LinearGradientBrush)GetValue(SourceBrushProperty); }
        set { SetValue(SourceBrushProperty, value); }
    }

    public static readonly DependencyProperty SourceBrushProperty =
        DependencyProperty.Register(
            &quot;SourceBrush&quot;, typeof(LinearGradientBrush), typeof(LinearGradientBrushBehavior), new UIPropertyMetadata(null));

    #endregion
        
    private void CalculateNewGradient(double progress)
    {
        var brush = new LinearGradientBrush();
        brush.StartPoint = SourceBrush.StartPoint;
        brush.EndPoint = SourceBrush.EndPoint;

        foreach (var gradientStop in SourceBrush.GradientStops)
        {
            var offset = (1 - gradientStop.Offset) / progress;
            var newGradientStop = new GradientStop(gradientStop.Color, 1 - offset);
            brush.GradientStops.Add(newGradientStop);
        }

        ApplyNewGradient(brush);
    }

    private void ApplyNewGradient(LinearGradientBrush brush)
    {
        AssociatedObject.Foreground = brush;
    }
}&lt;/pre&gt;
&lt;br /&gt;
The most important part is the &lt;em&gt;CalculateNewGradient&lt;/em&gt; method, which is called once when the control loads up and each time the progress changes. That method is responsible for calculating new offsets for all gradient stops. Recalculated gradient is than reapplied to the &lt;em&gt;Foreground&lt;/em&gt; property. I don’t have to add that rectangle’s Fill is bound to it :) It’s also worth pointing out that this behavior works with &lt;em&gt;RangeBase&lt;/em&gt; inherited controls, so you can utilize it to create nice looking &lt;em&gt;Slider&lt;/em&gt;!&lt;br /&gt;
&lt;br /&gt;
One thing to consider here is performance. I haven’t noticed any problems, even though each time progress changes, new instance of &lt;em&gt;LinearGradientBrush&lt;/em&gt; is created. Which is good :) You can find the sources on my &lt;a href=&quot;https://skydrive.live.com/redir.aspx?cid=bd15edd4d52f5329&amp;amp;resid=BD15EDD4D52F5329!239&amp;amp;parid=BD15EDD4D52F5329!115&amp;amp;authkey=!AMTzSY3pymU14Rg&quot;&gt;SkyDrive&lt;/a&gt;. Hope you like it!&lt;br /&gt;
&lt;br /&gt;
&lt;iframe style=&quot;padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; padding-right: 0px; padding-top: 0px&quot; title=&quot;GradientDemo&quot; height=&quot;120&quot; marginheight=&quot;0&quot; src=&quot;https://skydrive.live.com/embed?cid=BD15EDD4D52F5329&amp;amp;resid=BD15EDD4D52F5329%21239&amp;amp;authkey=AIQOXwk3DGuZgd0&quot; frameborder=&quot;0&quot; width=&quot;98&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;</description><link>http://pwlodek.blogspot.com/2012/02/fill-up-wpf-progress-bar-with-linear.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXJj8lxiIh0pKxcB_ux0-gTd5a-kOvqeCd-tub6ik6EkG8_0GCDdRcG0v0xqJNoQQXih1g_RK3xP5o-Ylqk2b8BaL7Ez5y2M1IjMJpw6zFXVft8opDwSnvbG_3GF_XkaE3E7iYt-sHFXnO/s72-c?imgmax=800" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-8203554736612680836</guid><pubDate>Wed, 02 Nov 2011 02:18:00 +0000</pubDate><atom:updated>2011-11-02T03:28:10.288+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Blend</category><category domain="http://www.blogger.com/atom/ns#">Effects</category><category domain="http://www.blogger.com/atom/ns#">pixel shaders</category><category domain="http://www.blogger.com/atom/ns#">Wizard</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>WPF transitions using pixel shaders and Blend SDK</title><description>WPF transitions are a very nice way to turn standard, boring application interactions into great user experiences, and show the author pays attention to details. There are basically two ways of implementing transitions in WPF. You can do a manual transition using &lt;em&gt;RenderTransform&lt;/em&gt; to modify the visuals’ position, scaling and rotation. Throwing in an opacity animation would improve the effect. This option is talked more in-depth &lt;a href=&quot;http://www.11011.net/wpf-transitions&quot;&gt;here&lt;/a&gt;. However, there is a couple of problems with this approach. The biggest issue is that such transitions are CPU bound, since the transition is &lt;em&gt;calculated&lt;/em&gt; on the main processor. The other problem is more prosaic – they are relatively hard to implement. The other way is to utilize pixel shaders to blend between two visuals’ images making the illusion of transition. Transitions done this way are GFX bound, offloading the CPU which can perform other useful tasks. Besides, they look just awesome, as you shall see in a moment :) There is a small problem associated with this approach, though. To write custom pixel shader, some GFX knowledge accompanied by HLSL might be required. Crafting nice effect probably would also require a bit of math :) Thankfully, there are some nice libraries packed with effects ready to use! So no worries, we will not be talking math here!&lt;br /&gt;
In this post I will discuss how to build a &lt;em&gt;TransitionControl&lt;/em&gt;, which beautifully animates transitions from one visual state into the other. To demonstrate the effect, I updated my wizard demo (discussed &lt;a href=&quot;http://pwlodek.blogspot.com/2008/11/wpf-wizard-control.html&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://pwlodek.blogspot.com/2009/02/wpf-wizard-control-part-ii.html&quot;&gt;here&lt;/a&gt;) so that transitions between consecutive steps are nicely animated. I will also show what it takes to add transition effect to regular &lt;em&gt;TabControl&lt;/em&gt;. The following screens show the &lt;u&gt;slide&lt;/u&gt; transition between two wizard steps.&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIBQVxWsdR8ZpKUGwYkggAuSZQiPIbcftD5CgEIQdk2WqaqfAHjXp_84WOr3RbNGhabkP7LEnzR1kvSQET6wSJNZZaPVxr8jmcRxzzmf8XxdRDL8FX_3-J-r1TjgLwqdi7Yf2wF7KXgI4a/s1600-h/image46.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;301&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFc1z07djocxhMpWggS9aQvAOvjklkiCAJY6WIIkeIa86naSBkM_08uJ7I7oVaoE9Vwma50a5h5I_l6gVP5YmIM9Y04_j1kmkdztor86y16A6R6QKs-_nIsLLg_rIjg-6TrdQ_i14r-b5X/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;361&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjihxY2yRwc0VOsngfrU6eXIxJj83_Yj_8m7RDCEF7skcDTzSViEQCx48TjkPyiZKrewuG_ETouh1paZ9nDpCAhmLsJ2Dx-HCu8DuSBK7b-x0tAbYYFfAmVONpLPGnG9ceGMHDctIxol6J4/s1600-h/image48.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;301&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiepNQ1rL6vX812wLr4yqPcxhllnuaNAP0cXR3K4uai2pZ3sDouQct4SQQzASCk4SWG8_IrVHG3vSfrkj1L5e_y50aAoUBe3mU2PYyMNBrKtHMBBT-VOTx8SEnKORLRp1qOEemJvTcr2-gQ/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;361&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSq1naJzEK0eIMLFQUJGmMKpTQg_G6LaLrXxtlSMlAcD4rDn39KBK-K-Fy2iyKyTsGCzxcKIfq6vqIxx5MC1rz2fgMNale1vCEfbDhpcj2esfYwwqjerFWfMePE96H5pLnbdyTxOh2Erp_/s1600-h/image47.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;301&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJZwUnysKTe957_STzd7wIwbI-YjmqAY-l3gdPXAgjEjPu3pWUq-2715ir5Yu3A0V1_4-iwa785nKVwF48KAUiHxg9KX5Fz7l4GfjnN6j63FZynKbw35x-oD10JHksAcC1jZpEqJJu0dyH/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;361&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
And the following shows a transition within TabControl.&lt;br /&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwiKCFEp5mm1a9WqOqYeuJ7i-iceqBeCqt2AUQOGN5KUvsn-BNREAEEYKtlPAjbrfdE5gd-6R2bkw_tCBi5aDr1nWDVuhCLLNnO-jTR3Z8XKNRlleNZacBRt6S3GJ-KL650Sww0a6aByln/s1600-h/image65.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;299&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWW5pkUJj01-bcc170f56pRqHdCzgVZQven-q0fKXiYB8TWQsg6DlnBOUYbJBNVo3A32cOd0lpgNIpeeZh35aVw4tf-0-DhWI4khM5_uTYMAj4ER0oky2Y-HQX-71-NJb6d6Au2u6rDDHu/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;357&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1HL0Vmi4d7k91z3M4gHJ75XI8h7feGmdkS4yXyhFUyIxMpB5Nulqr6gRNyXy5bnpL0V9IvzrkKUNd6ZIXNU3DJjQ3scnqWrQ-fMGZIRY_9OSgBIGxas9UYCn-bCo-M4pCyT1mmmZT3gqB/s1600-h/image64.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;299&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXO8JuUSyMiZvHNXKGywCyAuaXjW2h9OxxNQiv1d6bsGN8YCj-nsMSrHeaf7myD7qMGIFr9YrQW6sKhVKTZfxdds75NoCfA8AfjJnmcM-_5HI0iip9e-rJTDIhLcGJ7M25wuCoBhn3Yyf9/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;357&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEusCnFSLS9XSGB5AIw-DK0GLqK-rFp-z18RKX1GFHpj3DPcWyLjEnfoeZVT7etLEXefTF_8XUzJdszR2ikFmQiLzcodtz8gsU14Zu1psr4xjlH7gBqa4fdJOngh2QO3F7iNEFkyXnnJ6T/s1600-h/image63.png&quot;&gt;&lt;img alt=&quot;image&quot; border=&quot;0&quot; height=&quot;299&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhObFaW7jDMqHyW3aS4-rbER7B4qanRmfAVUmBlddKFfRdRufDsl_qDXnOZIxFQFHgB3KqmHH-vggf9J_ZzqLB7B9WAB-4OrqsDTUbL0vX_NM8dCkqMFBO2-1FqcVsuV3OVJKY-SKO1c5he/?imgmax=800&quot; style=&quot;background-image: none; border-bottom-width: 0px; border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; display: inline; padding-left: 0px; padding-right: 0px; padding-top: 0px;&quot; title=&quot;image&quot; width=&quot;357&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;Pixel shader libraries&lt;/strong&gt;&lt;br /&gt;
Pixel shaders were introduced in .NET Framework 3.5 SP1. By this time, Microsoft released really cool library called &lt;a href=&quot;http://wpffx.codeplex.com/&quot;&gt;WPF Effects Library&lt;/a&gt;. The library is composed of two types of components: &lt;u&gt;effects&lt;/u&gt; and &lt;u&gt;transitions&lt;/u&gt;. Effects are successors to well known bitmap effects, and provide a way to alter how a visual is rendered on the screen (see this &lt;a href=&quot;http://channel9.msdn.com/shows/Continuum/WPFFXDemo/&quot;&gt;video&lt;/a&gt;). Transitions, on the other hand, provide a means to.. transition from one visual state to the other. Easy, huh ? We will leverage them to build robust &lt;em&gt;TransitionControl&lt;/em&gt;.&lt;br /&gt;
These days the project seems not to be much updated, the latest version is 2.0 beta which targets .NET 3.5, but works with .NET 4.0 and Visual Studio 2010. The good news is that although this project is not longer maintained, most of the effects and transitions made its way to &lt;u&gt;Blend 4.0 SDK&lt;/u&gt;! They are available in &lt;u&gt;Microsoft.Expression.Effects.dll&lt;/u&gt; assembly.&lt;br /&gt;
Okay, so I introduced transitions, just show how to use them and probably we’re done here, right ? it turns out we’re not quite done here. Lets see what is the API for using a transition effect. The base &lt;em&gt;TransitionEffect&lt;/em&gt; class, from which all transitions derive, is located in &lt;em&gt;&lt;u&gt;Microsoft.Expression.Interactions.dll&lt;/u&gt;&lt;/em&gt; assembly, and its public API is defined as follows:&lt;br /&gt;
&lt;pre class=&quot;brush: c-sharp&quot;&gt;public abstract class TransitionEffect : ShaderEffect
{
    protected TransitionEffect();
    public Brush Input { get; set; }
    public Brush OldImage { get; set; }
    public double Progress { get; set; }
}&lt;/pre&gt;
The class inherits &lt;em&gt;ShaderEffect&lt;/em&gt;, which makes it essentially a regular pixel shader effect. So it can be assigned to the &lt;em&gt;Effect&lt;/em&gt; property of any &lt;em&gt;UIElement&lt;/em&gt;. There are also two important properties: &lt;u&gt;OldImage&lt;/u&gt; and &lt;u&gt;Progress&lt;/u&gt;. The &lt;em&gt;OldImage&lt;/em&gt; brush defines the look of the old visual, and the &lt;em&gt;Progress&lt;/em&gt;, between 0.0 and 1.0, denotes where we are within the transition. So the flow when using any &lt;em&gt;TransitionEffect&lt;/em&gt; is as follows:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Choose any transition effect and apply it to any &lt;em&gt;UIElement&lt;/em&gt; which is the target visual we want to transition to&lt;/li&gt;
&lt;li&gt;Get the &lt;em&gt;VisualBrush&lt;/em&gt; which depicts the visual we transition from, and assign it to the &lt;em&gt;OldImage&lt;/em&gt; property&lt;/li&gt;
&lt;li&gt;Animate &lt;em&gt;Progress&lt;/em&gt; property from 0.0 to 1.0 to perform the actual transition&lt;/li&gt;
&lt;/ol&gt;
As you can see, this is not very complicated, but far from being convenient. And this is where &lt;em&gt;TransitionControl&lt;/em&gt; comes to play (I believe Telerik offers &lt;a href=&quot;http://www.telerik.com/products/wpf/transition.aspx&quot;&gt;similar control&lt;/a&gt;).&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;Meet the TransitionControl&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;TransitionControl&lt;/em&gt; encapsulates the above three steps and provides a nice API to consume by the client. Let’s think for a moment, what is the most convenient API for the TransitionControl ? Yes, you’re right, it’s a &lt;em&gt;ContentControl&lt;/em&gt;! &lt;em&gt;ContentControl&lt;/em&gt; provides a &lt;em&gt;Content&lt;/em&gt; property which is almost everything we care about. Whenever we change the &lt;em&gt;Content&lt;/em&gt; property to something else, we expect to get a nice transition which smoothly goes from one visual state to the other. Having said that, let’s see the API of the &lt;em&gt;TransitionControl&lt;/em&gt;.&lt;br /&gt;
&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class TransitionControl : ContentControl
{    
    public TransitionSelector ContentTransitionSelector { get; set; }
    
    public TimeSpan Duration { get; set; }

    public IEasingFunction EasingFunction { get; set; }

    public bool EnableTransitions { get; set; }       
}&lt;/pre&gt;
You can see that the &lt;em&gt;TransitionControl&lt;/em&gt; is essentially a &lt;em&gt;ContentControl&lt;/em&gt;. This is good, because, whenever you use &lt;em&gt;ContentControl&lt;/em&gt;, you can swap it for &lt;em&gt;TransitionControl&lt;/em&gt; and get the transitions for free! The second important thing is how actually &lt;em&gt;TransitionControl&lt;/em&gt; knows about particular transition we want to use ? This is where TransitionSelector comes in. It is an abstract class which behaves similarly to DataTemplateSelector. It defines single method as show below.&lt;br /&gt;
&lt;pre class=&quot;brush: c-sharp&quot;&gt;public abstract class TransitionSelector
{
    public abstract TransitionEffect GetTransition(object oldContent, object newContent, DependencyObject container);
}&lt;/pre&gt;
You implement this class and hand over a new instance to &lt;em&gt;TransitionControl&lt;/em&gt;. You get both the old and new contents, so it is possible to write dynamic logic which selects transition based on a content. Nice, huh ? There are also two properties which drive the behavior of the transition. Duration determines the length of the transition, and EasingFunction allows to supply easing function :)&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;How does it work ?&lt;/strong&gt;&lt;br /&gt;
The transition kicks of when the Content property changes. If the previous content was empty, of course no transition occurs. But if both old and new contents are presents, transition is triggered. The “magic” sits in the &lt;em&gt;AnimateContent&lt;/em&gt; method, which is responsible for going through the three steps outlined previously.&lt;br /&gt;
&lt;pre class=&quot;brush: c-sharp&quot;&gt;private void AnimateContent(object oldContent, object newContent)
{
    var oldContentVisual = GetVisualChild();
    var tier = (RenderCapability.Tier &amp;gt;&amp;gt; 16);

    // if we dont have a selector, or the visual content is not a FE, do not animate
    if (EnableTransitions == false || ContentTransitionSelector == null || oldContentVisual == null || tier &amp;lt; 2)
    {
        SetNonVisualChild(newContent);
        return;
    }
    
    // create the transition
    TransitionEffect transitionEffect = ContentTransitionSelector.GetTransition(oldContent, newContent, this);
    if (transitionEffect == null)
    {
        throw new InvalidOperationException(&quot;Returned transition effect is null.&quot;);
    }

    // create the animation
    DoubleAnimation da = new DoubleAnimation(0.0, 1.0, new Duration(Duration), FillBehavior.HoldEnd);
    da.Completed += delegate
    {
        ApplyEffect(null);
    };
    if (EasingFunction != null)
    {
        da.EasingFunction = EasingFunction;
    }
    else
    {
        da.AccelerationRatio = 0.5;
        da.DecelerationRatio = 0.5;
    }
    transitionEffect.BeginAnimation(TransitionEffect.ProgressProperty, da);

    // create the visual brush which is the source of the &quot;old content&quot; image
    VisualBrush oldVisualBrush = new VisualBrush(oldContentVisual);
    transitionEffect.OldImage = oldVisualBrush;

    SetNonVisualChild(newContent);
    ApplyEffect(transitionEffect);
}&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;How to make transition aware TabControl&lt;/strong&gt;&lt;br /&gt;
This task is super easy task! Just extract the default template for TabControl, and remove ContentPresenter with name &lt;em&gt;PART_SelectedContentHost and provide the following XAML&lt;/em&gt;.&lt;br /&gt;
&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;Controls:TransitionControl 
  x:Name=&quot;PART_SelectedContentHost&quot;
  Duration=&quot;00:00:01&quot;
  Content=&quot;{TemplateBinding SelectedContent}&quot;
  ContentTransitionSelector=&quot;{StaticResource TabControlTransitionSelectorKey}&quot;
  Margin=&quot;{TemplateBinding Padding}&quot; SnapsToDevicePixels=&quot;{TemplateBinding SnapsToDevicePixels}&quot;/&amp;gt;&lt;/pre&gt;
&lt;br /&gt;
You will have to supply proper TransitionSelector. In the demo application, I used the following:&lt;br /&gt;
&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class TabControlTransitionSelector : TransitionSelector
{
    private readonly Random _random = new Random();

    private readonly TransitionEffect[] _transitions = new TransitionEffect[]
    {
        new SmoothSwirlGridTransitionEffect(),
        new BlindsTransitionEffect(),
        new CircleRevealTransitionEffect(),
        new CloudRevealTransitionEffect(),
        new FadeTransitionEffect(),
        new PixelateTransitionEffect(),
        new RadialBlurTransitionEffect(),
        new RippleTransitionEffect(),
        new WaveTransitionEffect(),
        new WipeTransitionEffect(),
        new SlideInTransitionEffect { SlideDirection = SlideDirection.TopToBottom }
    };
    public override TransitionEffect GetTransition(object oldContent, object newContent, DependencyObject container)
    {
        var index = _random.NextDouble() * _transitions.Length;
        return _transitions[(int) index];
    }
}&lt;/pre&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br /&gt;
In this post I presented how using pixel shader effects create really cool looking, GFX bound transitions. Since the control responsible for wiring up everything is a ContentControl, you can use it wherever you use regular ContentControl, and you will get the transitions for free.&lt;br /&gt;
&lt;strong&gt;&lt;br /&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;strong&gt;Download&lt;/strong&gt;&lt;br /&gt;
As always, you can download full sources from my Sky Drive.&lt;br /&gt;
&lt;iframe frameborder=&quot;0&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot; src=&quot;https://skydrive.live.com/embedicon.aspx/Public/TransitionDemo.zip?cid=bd15edd4d52f5329&amp;amp;sc=documents&quot; style=&quot;background-color: #fcfcfc; height: 115px; padding-bottom: 0px; padding-left: 0px; padding-right: 0px; padding-top: 0px; width: 98px;&quot; title=&quot;Preview&quot;&gt;&lt;/iframe&gt;</description><link>http://pwlodek.blogspot.com/2011/11/wpf-transitions-using-pixel-shaders-and.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFc1z07djocxhMpWggS9aQvAOvjklkiCAJY6WIIkeIa86naSBkM_08uJ7I7oVaoE9Vwma50a5h5I_l6gVP5YmIM9Y04_j1kmkdztor86y16A6R6QKs-_nIsLLg_rIjg-6TrdQ_i14r-b5X/s72-c?imgmax=800" height="72" width="72"/><thr:total>4</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-36906518584096243</guid><pubDate>Tue, 27 Sep 2011 19:35:00 +0000</pubDate><atom:updated>2011-09-27T21:47:29.768+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WinRT</category><title>Build your first WinRT component</title><description>&lt;p&gt;I think that the dust has cleared after the Build Windows conference which took place two weeks ago. Since then blog posts started to show up talking about Metro style apps, WinRT, its impact on current skills, etc. Also, Microsoft released public preview of Windows 8, so it is about a good time to give it a try. So I installed Win8 on the latest Virtual Box, and it seems to work fine, apart from a few systems crashes per hour ;) So in this post, &lt;u&gt;I want to show you what it takes to build simple yet functional &lt;strong&gt;WinRT&lt;/strong&gt; component in native C++&lt;/u&gt;, and also will talk why you would do that. But before we jump right to the code, I would like to provide a brief overview of Windows 8 developer platform, and &lt;strong&gt;WinRT&lt;/strong&gt; itself.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Windows Runtime&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Microsoft says that WinRT is “a solid, efficient foundation for the new Windows 8 developer platform”. I love such marketing slang! So what &lt;strong&gt;WinRT&lt;/strong&gt; really is? It is a framework (calling it a framework is a bit unfair, since &lt;strong&gt;WinRT&lt;/strong&gt; is a part of the core of Windows OS, and is compiled each time Windows is built) for building &lt;strong&gt;Metro style apps&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9VXkc-2SDzixhJMzryO6elS3ufPSGVxlURQ0qhoK4MJLB69E-W1USWJfuRabJuJLGUGYDSMR12S5Qtq-TH_K2IdaimndHuOU6YZPbztiwm91BX0wbds4BM8R3gcMH7bm4PE5jySxHnTj5/s1600-h/Metro-style-apps6.jpg&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;Metro style apps&quot; alt=&quot;Metro style apps&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRctF1jqEhdVqdUHJF8S7vL5QFO98eCYXHdIMSMuoa4ivGd_b7s4q5yW7O8LOOE_fVB6yfqR9WsqfLu7K4kRvPLhcWlZLtgEpDu8MlJme0nuH2rI4TI4U4CwnMqlCXv6jwxiezN9lclwUH/?imgmax=800&quot; width=&quot;569&quot; height=&quot;333&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;This is important information. It means WinRT can &lt;u&gt;only&lt;/u&gt; be used for developing metro style apps. Metro style apps, although perfectly legal on a desktop system, are especially meant for tablets. This is the environment where they truly shine! And tablets are the most important reason Microsoft has actually created it. Why ? How else would they provided fast and fluid user experience on an ARM based tabled cloacked at 1.6 GHz ? Would you run fully blown WPF apps there ? I doubt. Silverlight ? Better, but you can’t code it with C++. To compete with Apple iPad, they had to provide really fast solution. This is how MS come up with WinRT =)&lt;/p&gt;  &lt;p&gt;Let’s have a quick look over the architecture. Oh, don’t be fooled by metro style apps being three times bigger than desktop apps. Microsoft tries very hard to emphasis Metro style Apps, though, as I said, they are mostly meant for tablets, so still most of the LOB applications will be delivered as a standard smart client desktop apps.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrSaod1yIjb8U2vvxb97e0MAKDmJKXrwyvlbjQyvIcRrePVrUJNaLiLFOMoIgJnGOdQpLyZAXViBWnNnhuDRw7Rv2n-bbJbdhNKOHuMB0VA3w5dl97X8RVNOR-FsUb_KvCJ_ml5pGVWM8H/s1600-h/WinRT5.png&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;WinRT&quot; alt=&quot;WinRT&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi7PxwkB9naW5iaT580MO-Y4ldtNeG4vuD5FCMTJrj9AQkBnPS-hnEKUyES8RYdzrto05X3wSN3NQkX_JHKGIA8NMjfm2SxE2gkQzde8PPVfz-4G1DXbIb_QauxPqJLfNW3MEFSnV-IsFwf/?imgmax=800&quot; width=&quot;680&quot; height=&quot;397&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;From the slide above we clearly see that &lt;strong&gt;WinRT&lt;/strong&gt; is only about Metro style apps. There is also one more thing. &lt;u&gt;For regular Desktop Apps, nothing really changes&lt;/u&gt;. So let’s put an end to statements saying that WPF and Silverlight are dead. They’re not! Silverlight 5 is coming out soon, with the RC version already available, and we have WPF 4.5 preview available as well, with cool new feature coming (be sure to check &lt;a href=&quot;http://bit.ly/nbFWGu&quot;&gt;Jonathan Antoine’s blog&lt;/a&gt;).&lt;/p&gt;  &lt;p&gt;So as I said, it turned out that Silverlight and WPF are still there, they’re all good, and they are XAML based. As you see, the brand new WinRT is also XAML based, so another way of looking at it is that it is yet another manifestation of XAML framework. We have WPF, we have Silverlight, and now we have &lt;strong&gt;WinRT&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;WinRT has been entirely written in native C++. The did that because they wanted performance, and give the opportunity to C++ devs to build vNext apps for Windows. Besides, Microsoft is constantly saying that the performance is the top priority for them =) What is super important is that WinRT components can be consumed from a variety of languages, including C++, C#, VB, and JavaScript. To enable this scenario, MS baked in a support for metadata, which describes the WinRT objects. As a side note, the metadata uses standard CLR metadata format (ECMA 335), so it can be ILDASMed for instance ;) So each native WinRT component is packed up in a standard native dll, and is accompanied with *.winmd file, which carries all the metadata information for that dll. In the Win8 Developer Preview, all metadata files for standard WinRT dlls are located on C:\Windows\System32\WinMetadata.&lt;/p&gt;  &lt;p&gt;As far as the Graphics &amp;amp; Media part is concerned, the framework is a bit similar to Silverligh. UIElement, FrameworkElement, it’s all there. What is different though is the default namespace. We were used to System.Windows.*, now everything is in Windows.*, with the UI part being located in Windows.UI.XAML.* namespace.&lt;/p&gt;  &lt;p&gt;That is pretty much it when it comes to WinRT overview, at the end of this post are link to good articles discussing WinRT in more depth.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Why bother writing WinRT components&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;It comes without surprise that MS allows us to create custom &lt;strong&gt;WinRT&lt;/strong&gt; objects. What’s great about it, is that we can leverage the same metadata system MS is using in the “standard” WinRT, which means we can code our WinRT object in any supported languages (currently C++, C#, VB) and consume it from other languages without any effort. This means we can write performance critical code in C++ and consume it in C#, without resorting to COM interop or P/Invoke. Awesome!&lt;/p&gt;  &lt;p&gt;So answering the question, building WinRT components allows developers to share their codebase with other projects, written in any language, targeting any platform. Say you want to develop custom control. If you develop it in C# as a regular CLR dll, you will be able to consume it only in C#. But if you make it a WinRT object, you can leverage it from any Metro app. Okay, so why bother writing such component in C++ then? Because of performance! Do you know why Silverlight is faster than WPF ? Because it’s C++ under the hoods! Don’t believe ? Try reflecting Grid in SL ;)&lt;/p&gt;  &lt;p&gt;Summing up this short paragraph, you definitely want to write WinRT component if you want to share you code with other WinRT objects, running on different platforms. And you want to do it in C++ because of the performance.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Writing custom panel in native C++&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;So finally, we reached to the most interesting part, which is the code. So here I will demonstrate how to develop custom, native WinRT object. To do so, I will use custom panel as an example. Let’s say we want to develop &lt;em&gt;CircularPanel&lt;/em&gt;, which layouts all its children in a circle. Let’s begin, shall we ?&lt;/p&gt;  &lt;p&gt;Go to Visual Studio 2011 For Windows 8 Developer Preview, and add new C# empty project. Here we will consume our C++ WinRT object. Now go again and add new project, this time use C++ and &lt;em&gt;WinRT Component&lt;/em&gt; template. Delete the WinRTComponent1 source and header files, and add &lt;em&gt;CircularPanel.cpp&lt;/em&gt; and &lt;em&gt;CircularPanel.h&lt;/em&gt; files. You should have something similar in Solution Explorer.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgcCBy-MyqEPpqMW4Ig5lDxI8EmOujXpMCrCxfSJkazsLrrNMoPdR55bIbu6MW2aMdJdUS4xefD5vt_C_j8DfRdj1U4nIb6QC_5HcqOUat5UVYhWGZQycgYipyLVW8K_1gxg_8F_Qas13ZX/s1600-h/image21.png&quot;&gt;&lt;img style=&quot;display: inline&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFPopIh0djzyLkizKusIC6OEmrNEk_FnMrAfwogQrt5wMKk6o1gqemnnMQsR5JlPbwKpcf2yF_jPLPOoE8W5wJ57pv4jFbVFPncuh4FPkCe6N7h9YLQKfje0BfO3f4jv6oD4DFflvtI62l/?imgmax=800&quot; width=&quot;207&quot; height=&quot;301&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Time to fill in some code! Open up &lt;em&gt;CircularPanel.h&lt;/em&gt; file and paste in this code.&lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;#pragma once&lt;br /&gt;&lt;br /&gt;using namespace Windows::Foundation;&lt;br /&gt;&lt;br /&gt;namespace WinRT&lt;br /&gt;{&lt;br /&gt;	namespace Controls&lt;br /&gt;	{&lt;br /&gt;		public ref class CircularPanel sealed : public Windows::UI::Xaml::Controls::Panel&lt;br /&gt;		{&lt;br /&gt;		private:&lt;br /&gt;			float _maxChildHeight;&lt;br /&gt;			float _maxChildWidth;&lt;br /&gt;&lt;br /&gt;		public:&lt;br /&gt;			CircularPanel ();&lt;br /&gt;			~CircularPanel ();&lt;br /&gt;&lt;br /&gt;		protected:&lt;br /&gt;			virtual Size ArrangeOverride(Size finalSize) override;&lt;br /&gt;&lt;br /&gt;			virtual Size MeasureOverride(Size availableSize) override; &lt;br /&gt;		};&lt;br /&gt;	}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;As you can see no rocket science there. We define our &lt;em&gt;CircularPanel&lt;/em&gt; class as &lt;strong&gt;ref&lt;/strong&gt; so that it will act as a reference type, and we derive it from &lt;em&gt;Windows.UI.Xaml.Controls.Panel&lt;/em&gt; class. Please note we declare &lt;em&gt;MeasureOverride&lt;/em&gt; and &lt;em&gt;ArrangeOverride&lt;/em&gt; methods that we will override to provide panel’s functionality. Now let’s go to the pane source.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;// CircularPanel.cpp&lt;br /&gt;&lt;br /&gt;#include &amp;quot;pch.h&amp;quot;&lt;br /&gt;#include &amp;quot;CircularPanel.h&amp;quot;&lt;br /&gt;#include &amp;quot;math.h&amp;quot;&lt;br /&gt;&lt;br /&gt;#define PI 3.1415926&lt;br /&gt;&lt;br /&gt;using namespace WinRT::Controls;&lt;br /&gt;using namespace Windows::UI::Xaml;&lt;br /&gt;using namespace Windows::UI::Xaml::Controls;&lt;br /&gt;&lt;br /&gt;float Max(float x, float y)&lt;br /&gt;{&lt;br /&gt;	if (x &amp;gt; y) return x;&lt;br /&gt;&lt;br /&gt;	return y;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;float Min(float x, float y)&lt;br /&gt;{&lt;br /&gt;	if (x &amp;gt; y) return y;&lt;br /&gt;&lt;br /&gt;	return x;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;CircularPanel::CircularPanel ()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;CircularPanel::~CircularPanel ()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Size CircularPanel::ArrangeOverride(Size finalSize)&lt;br /&gt;{&lt;br /&gt;	Point centerPoint = Point();&lt;br /&gt;	centerPoint.X = finalSize.Width / 2;&lt;br /&gt;	centerPoint.Y = finalSize.Height / 2;&lt;br /&gt;&lt;br /&gt;	float radius = Min(centerPoint.X, centerPoint.Y) - (_maxChildWidth + _maxChildHeight) / 4;&lt;br /&gt;	float degreesPerChild = 360.0 / Children-&amp;gt;Size;&lt;br /&gt;	float currentDegree = 0;&lt;br /&gt;	&lt;br /&gt;	for (int i = 0; i &amp;lt; Children-&amp;gt;Size; i++)&lt;br /&gt;	{&lt;br /&gt;		UIElement^ element = Children-&amp;gt;GetAt(i);&lt;br /&gt;		float x = centerPoint.X + radius * cos(currentDegree * PI / 180);&lt;br /&gt;		float y = centerPoint.Y + radius * sin(currentDegree * PI / 180);&lt;br /&gt;				&lt;br /&gt;		Rect rect = Rect();&lt;br /&gt;		rect.X = x - element-&amp;gt;DesiredSize.Width / 2;&lt;br /&gt;		rect.Y = y - element-&amp;gt;DesiredSize.Height / 2;&lt;br /&gt;		rect.Width = element-&amp;gt;DesiredSize.Width;&lt;br /&gt;		rect.Height = element-&amp;gt;DesiredSize.Height;&lt;br /&gt;&lt;br /&gt;		// Arrange child element&lt;br /&gt;        element-&amp;gt;Arrange(rect);&lt;br /&gt;&lt;br /&gt;        currentDegree += degreesPerChild;&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	return finalSize;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;Size CircularPanel::MeasureOverride(Size availableSize)&lt;br /&gt;{&lt;br /&gt;	for (int i = 0; i &amp;lt; Children-&amp;gt;Size; i++)&lt;br /&gt;	{&lt;br /&gt;		UIElement^ element = Children-&amp;gt;GetAt(i);&lt;br /&gt;		element-&amp;gt;Measure(availableSize);&lt;br /&gt;&lt;br /&gt;		_maxChildWidth = Max(_maxChildWidth, element-&amp;gt;DesiredSize.Width);&lt;br /&gt;		_maxChildHeight = Max(_maxChildHeight, element-&amp;gt;DesiredSize.Height);&lt;br /&gt;	}&lt;br /&gt;&lt;br /&gt;	return availableSize;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;There is a little bit of math involved, but rather easy stuff. I don&#39;t want to discuss the code itself, just note the syntax. For example, we reference &lt;em&gt;reference types&lt;/em&gt; with ^ (like UIElement^). Children collection doesn’t have Count property but Size field instead. Yeah, we’re in C++ world! &lt;br /&gt;&lt;br /&gt;&lt;p&gt;Now its time to tell our C# app about our native WinRT project. And this is were troubles start ;) Normally, we would go to &lt;em&gt;Add Reference&lt;/em&gt; dialog and add it from Solution projects (no need to manually pick up the assembly), but this feature seems not working right now, although some say it is possible to add C++ WinRT project from &lt;em&gt;Add Reference&lt;/em&gt; dialog, just clean the native project before. Didn’t work for me, but who knows, maybe will work for you! So instead go to Add Reference dialog and hit the Browse button. Navigate to the root folder of your solution, go to Debug and select the &lt;em&gt;YourNativeProjectName.winmd &lt;/em&gt;file. This is quite interesting step – we reference a native dll using its Windows metadata file. So when you go ahead and compile the solution, you will see… a build error! At least on x64 bit machine.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-EzbcxH_DVwfYw319zw0JsU-MKV3Jh_Q-cxC-2uE-t8jJXNAJeOEPAvvG6Rgn6f2T6sIjiVfqLtt4HWXX2c1WoIJkP8D-U7tBPgVHZaTL9azRJHkHMY9xxJfa8PjsS0lLEOZHzr3hJ6vE/s1600-h/image5.png&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj39wSCuSIcYebzrdu4RCKnjoFicXzCAb8oSNwN8O-gmxBLQsbafnz4McdIySp0bgIPeH15InV11eBuAhsbRDmK-Xp9RXWznVoYizROJPjlUcn86TuPMfUgP0a5MxBEGthgxQfAVf9CySBy/?imgmax=800&quot; width=&quot;658&quot; height=&quot;249&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;I’m not sure if you get exactly the same error, although you should. So the problem is that our native component is targeting Win32 platform, which is x86, but we reference it from Any CPU C# project. This won’t work. Go to &lt;em&gt;Configuration Manager&lt;/em&gt; and change C# project to target x86.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh87a2FHGI5j7p-W_0a2X3v9f1K4wDxYY0TiZwsk_eb1LBQUpyhYnEpt8FVUZ3_0C2lFcuao52ZDY3bRV0zVybs3KFYUWCTu0bMYkAKBZF2tVdAMruGQ6D-Y9ftZ90qp777ref_lmM1uG-Z/s1600-h/image10.png&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1iIcCWtK8mbsJ4Xe-lW1uZYAVUCodIKg13dAIcRrvb5wJF6e0HDC1I1rZaHAxW6kiv6GfH_ylOCQkeOaGL-cjOwd4Eab7m8Zx_BG0-fslHyNBrJml8C8Cdkwak-cEC0r_GXSPZvx6uYBp/?imgmax=800&quot; width=&quot;458&quot; height=&quot;296&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;So now if you go ahead and compile, you will get another error.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgk2rd-kVafYMpFnhk_WLLblm0ukVijx6xTUZZAto_jUQ9D88_Vr3tW1SqqbiNYmCdu2pyEZUFRxZvQnyj6QtA4FQvDcl0lMklSqyvnJIpco6ExD_peaD83C-wTChjKwFjVnKAS5bqqwu-p/s1600-h/image16.png&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8WBV7Y4HANUE4OT2GhRsbPtUseHu9BSIlnt5p6Z0PLEiSfQdoyL9bw3U60Jl9HEuo-shWQLPlZrdM5BuZR1NtXKe3qUb5xXpGMh6I3oPU_Nn-dXTbvYlmSoVXPJhhgEEJfBXd34jS9300/?imgmax=800&quot; width=&quot;672&quot; height=&quot;110&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;This one is also easy to fix. So our component uses Platform.IDisposable, which needs to be referenced. So go back to Add Reference dialog and add Microsoft.VCLib dependency. Now the compilation should succeed.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;So since the compilation succeeded, let’s actually make use of our WinRT object. But there is yet another gotcha! For unknown reason, I couldn’t get this panel to work in XAML. I got compile error saying this component is unknown. Referencing it from code worked, however.&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;partial class MainPage&lt;br /&gt;{&lt;br /&gt;    public MainPage()&lt;br /&gt;    {&lt;br /&gt;        InitializeComponent();&lt;br /&gt;&lt;br /&gt;        Loaded += new RoutedEventHandler(MainPage_Loaded);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void MainPage_Loaded(object sender, RoutedEventArgs e)&lt;br /&gt;    {&lt;br /&gt;        CircularPanel panel = new CircularPanel();&lt;br /&gt;&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;1&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;2&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;3&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;4&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;5&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;6&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;7&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;8&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;        panel.Children.Add(new Button() { Content = &amp;quot;9&amp;quot;, Width = 100, Height = 100 });&lt;br /&gt;&lt;br /&gt;        LayoutRoot.Children.Add(panel);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;When you run the app, you should see a couple of buttons arranged in a circle :)&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Microsoft did pretty good job with latest Win8. The new metro style apps, though meant for tablets, are truly great. When it comes to development, the Developer Preview is still pretty rough on the edges, but its about a good time to start playing with it, and upgrading skills. When it comes to WinRT development, it feels like WPF/SL.The base concepts like dependency properties, routed events, XAML, it’s all the same! This is a big strength of this platform. Well done MS! &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Posts worth reading&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;http://dougseven.com/2011/09/15/a-bad-picture-is-worth-a-thousand-long-discussions/&quot;&gt;A bad picture is worth a thousand long discussions&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;http://blog.galasoft.ch/archive/2011/09/17/my-thoughts-about-build-windows-8-winrt-xaml-and-silverlight.aspx&quot;&gt;My thoughts about Build, Windows 8, WinRT, XAML and Silverlight&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;a href=&quot;http://kodierer.blogspot.com/2011/09/welcome-to-zombieland-metro-style-land.html&quot;&gt;Welcome to Zombieland, the Metro Style Land of WinRT and the Undead&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;a href=&quot;http://wildermuth.com/2011/9/20/Win8_Metro_Apps_and_Silverlight&quot;&gt;Win8, Metro Apps and Silverlight&lt;/a&gt;&lt;/p&gt;&lt;br /&gt;&lt;iframe style=&quot;padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px&quot; title=&quot;Preview&quot; marginheight=&quot;0&quot; src=&quot;https://skydrive.live.com/embedicon.aspx/Public/WinRT.Sample.zip?cid=bd15edd4d52f5329&amp;amp;sc=documents&quot; frameborder=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;  </description><link>http://pwlodek.blogspot.com/2011/09/build-your-first-winrt-component.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRctF1jqEhdVqdUHJF8S7vL5QFO98eCYXHdIMSMuoa4ivGd_b7s4q5yW7O8LOOE_fVB6yfqR9WsqfLu7K4kRvPLhcWlZLtgEpDu8MlJme0nuH2rI4TI4U4CwnMqlCXv6jwxiezN9lclwUH/s72-c?imgmax=800" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-1525061824362424658</guid><pubDate>Tue, 26 Jul 2011 21:56:00 +0000</pubDate><atom:updated>2011-07-26T23:59:28.424+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>Isolating MEF components</title><description>&lt;p&gt;What &lt;a href=&quot;http://mef.codeplex.com/&quot;&gt;Managed Extensibility Framework&lt;/a&gt; does well is component discovery and composition (when saying component I usually refer to MEF part). This is not a big surprise as it was designed to do so. However, one particular area where MEF has nothing to say about is &lt;strong&gt;component isolation&lt;/strong&gt;. What is it ? Component isolation allows for plugins to work together without impacting each other. If one component fails, the rest of the system remains stable as nothing has ever happened. Yes, I know – when designing custom software solutions, we rarely care about plugins (too bad), but about component isolation, we don’t care at all. Why ? Most notably because dealing with component isolation is not an easy task. Since the best way to isolate components is to host them in a separate process, there has to be a fast IPC mechanism, and there is no single address space. Because we have calls across process boundaries, we have to serialize arguments on one side, deserialize them on the other, etc. Quite a bit of work there.&lt;/p&gt;  &lt;p&gt;Some of you are probably familiar with &lt;em&gt;System.AddIn&lt;/em&gt; namespace, better known as Managed Addin Framework. It has shipped long time ago, in .NET 3.0 if I remember well. This framework provides robust plugin infrastructure, and yes, it supports component isolation on &lt;u&gt;App Domain&lt;/u&gt; and &lt;u&gt;Process&lt;/u&gt; levels (okay there is also &lt;u&gt;no isolation&lt;/u&gt; if you want to leverage plugins only). There is one problem with MAF, though. It has steep learning curve making it hard to jump into it. I never heard someone is using it in a production environment. Alternative ? Haven’t heard about yet. If you had, drop me a line please :)&lt;/p&gt;  &lt;p&gt;Recently I have been thinking about creating custom component isolation mechanism and integrating it with &lt;a href=&quot;http://mef.codeplex.com/&quot;&gt;Managed Extensibility Framework&lt;/a&gt;. Although not that straightforward, &lt;u&gt;I managed to create special, dedicated catalog which can instantiate MEF parts in a separate AppDomain or even a separate process!&lt;/u&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Meet the IsolatingCatalog&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The &lt;em&gt;IsolatingCatalog&lt;/em&gt; is responsible for doing all the magic. It is a decorating catalog, meaning it accepts another catalog, scans all its parts looking for those which need to be isolated, and then instantiates the parts accordingly. The API for the catalog is extremely simple. All you have to do is to tell MEF that a part has to be isolated. To do so, you can use custom export attribute or custom metadata attribute assuming you’re doing the export your way. Here is an example:&lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;[IsolatedExport(typeof(IFakePart), Isolation = IsolationLevel.Process)]&lt;br /&gt;public class FakePart1 : IFakePart&lt;br /&gt;{&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;&lt;em&gt;IsolatedExportAttribute&lt;/em&gt; is a custom export attribute which adds some metadata to the exported part, which is interpreted by the &lt;em&gt;IsolatingCatalog&lt;/em&gt; so that it knows what to do with the export. The core property is the &lt;em&gt;Isolation&lt;/em&gt; property of type &lt;em&gt;IsolationLevel&lt;/em&gt;. Not surprisingly, it defines the isolation level for the part :) And the isolation level can be &lt;em&gt;None&lt;/em&gt; (mostly used for testing only), &lt;em&gt;AppDomain&lt;/em&gt;, and &lt;em&gt;Process&lt;/em&gt;. I guess they are self explanatory. As I said, you can also use &lt;em&gt;IsolatedAttribute&lt;/em&gt;, which is a custom metadata attribute.&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[Export(typeof(IFakePart)), Isolated(Isolation = IsolationLevel.None)]&lt;br /&gt;public class DisposableFakePart1 : IFakePart, IDisposable&lt;br /&gt;{&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;What else can you define for an isolated export ? All properties are specified in the &lt;em&gt;IIsolationMetadata&lt;/em&gt; interface which is defined as follows:&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public interface IIsolationMetadata&lt;br /&gt;{&lt;br /&gt;   /// &amp;lt;summary&amp;gt;&lt;br /&gt;   /// Gets the isolation for a part.&lt;br /&gt;   /// &amp;lt;/summary&amp;gt;&lt;br /&gt;   IsolationLevel Isolation { get; }&lt;br /&gt;&lt;br /&gt;   /// &amp;lt;summary&amp;gt;&lt;br /&gt;   /// Indicates if a new host should be created for a new instance of the part.&lt;br /&gt;   /// &amp;lt;/summary&amp;gt;&lt;br /&gt;   bool HostPerInstance { get; }&lt;br /&gt;&lt;br /&gt;   /// &amp;lt;summary&amp;gt;&lt;br /&gt;   /// Gets the name of the isolation group. Used to make sure parts which&lt;br /&gt;   /// defined the same name will be hosted in the same activation host.&lt;br /&gt;   /// &amp;lt;/summary&amp;gt;&lt;br /&gt;   string IsolationGroup { get; }&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;With &lt;em&gt;HostPerInstance&lt;/em&gt; property you can instruct the runtime to create separate host each time a part is created. I will cover hosts in much more details later on, right now a host is an activation host which, heh, hosts the instance of the created part. And &lt;em&gt;IsolationGroup&lt;/em&gt; property is nothing more than a name for the activation host. If two or more parts specify the same name, they will be hosted in the same activation host, be in a separate AppDomain or a process. Note this interface is implemented by both the custom export and custom metadata attribute ensuring you can achieve the same results using either of the approaches.&lt;/p&gt;&lt;p&gt;Last thing to cover, although pretty straightforward, is how to use the catalog itself. As I said, it is a decorating catlog, and there is no philosophy is setting it up:&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;var typeCatalog = new TypeCatalog(typeof(TempPart), typeof(FakePart1));&lt;br /&gt;var isolatingCatalog = new IsolatingCatalog(typeCatalog);&lt;br /&gt;var container = new CompositionContainer(isolatingCatalog);&lt;br /&gt;&lt;br /&gt;var part = container.GetExportedValue&amp;lt;TempPart&amp;gt;();&lt;/pre&gt;&lt;p&gt;Let’s stop here for one second, and let’s assume &lt;em&gt;FakePart1&lt;/em&gt; is instantiated in isolation, with &lt;em&gt;TempPart&lt;/em&gt; consuming it:&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[Export]&lt;br /&gt;public class TempPart&lt;br /&gt;{&lt;br /&gt;   [Import]&lt;br /&gt;   public IFakePart Part { get; set; }&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;What gets injected into &lt;em&gt;Part&lt;/em&gt; property ? If we run this code in debug mode, we would see this:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVL8yJCNVjmZDd8wuds8PKjWHcqZGhbhkTVwHy-tyqv-uAKPJlWb-yjX-oTAuBZEW3aC79N_ZaWerJRXl8X19VagA_gMz83PXdMuanOe6IuDgEpzSRd8-wCBqowLE1uLyixd9MA29QE9UN/s1600-h/FakePartProxy4.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px&quot; title=&quot;FakePartProxy&quot; border=&quot;0&quot; alt=&quot;FakePartProxy&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwYcBBjSU2Pfak9FxJTSMK1BMwp47Ny3avme8WVO9OHOJtUVA0BISywzQhqhGK0g6yLV_VlB1xh6kFottyK8StyO2n2NSfiA7AtA2jUO6MN5Ve7F793E6NkGuxF7mC4blxONqWgW0kpEiG/?imgmax=800&quot; width=&quot;480&quot; height=&quot;138&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;This is very important. What gets injected is a &lt;u&gt;proxy&lt;/u&gt; supporting the &lt;em&gt;IFakePart&lt;/em&gt; contract rather than a concrete &lt;em&gt;FakePart1&lt;/em&gt; implementation. Why ? Of course because the original &lt;em&gt;FakePart1&lt;/em&gt; is instantiated in isolation, typically in a separate process or AppDomain, so what the client gets is a proxy which serializes all calls to the concrete implementation. Seems obvious, but I wanted to stress it :)&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Demo&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Now that you have seen how to make isolated parts, it’s time for a little demo. I put a simple app (I took a simple MDI sample from Caliburn project) which displays “movies” from various providers. It shouldn’t be a surprise that each movie provider is a MEF part, and some of them are working properly, and some of them are not.&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKqwWxbe_tjgoEk-8OfHL035Rfwj-UIbVbmNTtmt5wbjwoz9a0dMNRr5M-_avVlISgl5hCXe_-KzmObljfUWWUv4k4VLGlN66j5SiTLJZBaEHWtaQYIF5h0oefUqVIr_GL1v5CXggEfv25/s1600-h/image11.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px&quot; title=&quot;image&quot; border=&quot;0&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqjfQQzJsez6Rsbqtt096LIi2IaVd1sIBH53NOMpy6WTR0Neiz4puBS3GAf9FpQ7wYA8ScRgopqioO8S8BKwf813J0F9JD2q1itx8sE6EbfjDC1o-OLqLhTSJzlxD7r80nlMTqmVcVlEeW/?imgmax=800&quot; width=&quot;613&quot; height=&quot;476&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;Lets have a quick look at how each provider is exported:&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[IsolatedExport(typeof(IMovieProvider), HostPerInstance = true, Isolation = IsolationLevel.Process, IsolationGroup = &quot;SomeName&quot;)]&lt;br /&gt;public class Provider1 : IMovieProvider&lt;br /&gt;{&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;You can see that each provider is instantiated in a separate, named activation host. However, because all providers specify the same &lt;em&gt;IsolationGroup&lt;/em&gt;, there will be a separate process per each three instances of the providers. Also, the app supports tabbed interface, with each tab getting its own set of providers. This means each tab will have its own process hosting the providers, which can easily be verified in the Task Manager (three tabs above means three processes below):&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-dSjG15cx0c484K46tSvPXHrXa-Ri5Wfr0KYKFv8jypVs_MRDjuZQnMcc2S2UOWqdPVbwCZvZHs_Y16kT2oDuUXLlurm3GKXVGDD6Zq6uZCHHjknI8_CTV4q4fUG_KwFGryuCcynjupz7/s1600-h/TaskManager4.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px&quot; title=&quot;TaskManager&quot; border=&quot;0&quot; alt=&quot;TaskManager&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi25FFNikATlJMgzIEqVewBD_fiieD1CkTepjDalbIyjIBSMgf89qhwenfU2Zk6cwqYnC0X11Tq8OARJVJaSUMz1gnOX-6-fhC5HXBCM7KfkCxCcydnMaOwd2zbT1-hzrj0WFW0LTteA0bM/?imgmax=800&quot; width=&quot;674&quot; height=&quot;132&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;This mimics the Google Chrome browser approach, where each tab is hosted in a separate process. Okay, lets break something. Provider 3, when executed 2 times, will throw an exception on a separate thread. This is of course by design :) What will happen ? Normally, the application would crush and the process would terminate. However, because the logic which will fail is hosted in a separate process, that process would crush leaving the main app intact. As if this was not enough, the API allows to intercept failures, giving the ability to display error to the user:&lt;/p&gt;&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZKJJpBruWaAz8K5eYVJ2KQhboJe7-NMvAw4wVaGE20SjQC9j6lfORDCTBnG-S5_qx4edpxIzA9p0WHmbFWG_3ZGyBU2XNdBz2qwIhc-R2IZJ57xHrf0ldJVeGyBWVYdjP0yVNX8nquzE1/s1600-h/image12.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px&quot; title=&quot;image&quot; border=&quot;0&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJtmQwwzzaybR-sCeCol0kzf3G_lEsi6ddN4BJ_XAQCogt95Xos8BypEyf2SlJPBuMrSYT878_ylJtBMNpxIe-eYDnAyknYAgOehGIw9zldWclsU2aMFlSTOdb85F3_mtY1lzmbozbpjka/?imgmax=800&quot; width=&quot;613&quot; height=&quot;460&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;p&gt;As you see, even though there was a critical error in one of the providers, the application remains stable. If we go to the Task Manager we will see two processes hosting the providers, as the third one just failed. Btw, make sure you manually copy PluginContainer.exe (this guy can host MEF parts in it) to the bin folder. In feature releases, I will link this assembly directly to &lt;em&gt;IsolatingCatalog&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Lack of features&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Although working, this solution is not perfect. One of the drawbacks is that if a developer wants to isolate a part, it has to be &lt;u&gt;exported&lt;/u&gt; accordingly. I think it would be nice to have the ability to setup isolation on the &lt;u&gt;import level&lt;/u&gt;, so that even though the part developer didn’t plan for isolation, the import side would switch the isolation on. I imagine there would be &lt;em&gt;IsolatedImportAttribute&lt;/em&gt; which could do the trick. The other thing is I’m using WCF for IPC. At first it seems okay, but creating WCF host is a costly operation, thus you will notice a slight delay when opening new tabs in the above demo. Perhaps it would be good to craft custom IPC based on named pipes ? Last thing is lack of dependency injection, since we might operate in a different address space. The good news is that it should be possible to address this; WCF supports duplex channel communication on named pipes binding, so I could use proxy to communicate back with the host application. This is pending on my TODO list :)&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Download&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Although namespace suggests &lt;em&gt;IsolatingCatalog&lt;/em&gt; is part of &lt;a href=&quot;https://github.com/mefcontrib/mefcontrib&quot;&gt;MefContrib&lt;/a&gt;, it is not. It’s not because this is a POC rather than something production ready. I wrote it mainly to prove it is possible to isolate MEF parts. Having said that, I think the approach chosen is good (inproc WCF with named pipes binding is used for the IPC purposes), and I would love to see this being part of MefContrib someday. The only thing is time needed to add more test cases, doing a cleanup, etc. If you feel you could help me with that, drop me a line and we can work together!&lt;/p&gt;&lt;p&gt;To download the &lt;em&gt;IsolatingCatalog&lt;/em&gt;, just go to &lt;a href=&quot;https://github.com/pwlodek/MefContrib/tree/isolation&quot;&gt;my MefContrib fork&lt;/a&gt; and download &lt;strong&gt;isolation&lt;/strong&gt; branch. The demo presented above can be downloaded from my skydrive below.&lt;/p&gt;&lt;iframe style=&quot;padding-bottom: 0px; background-color: #fcfcfc; padding-left: 0px; width: 98px; padding-right: 0px; height: 115px; padding-top: 0px&quot; title=&quot;Preview&quot; marginheight=&quot;0&quot; src=&quot;https://skydrive.live.com/embedicon.aspx/Public/MefIsolation.zip?cid=bd15edd4d52f5329&amp;amp;sc=documents&quot; frameborder=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;This post covered a working solution which enables to activate MEF parts in a separate AppDomain or even a separate process. Next post will cover how the isolation is being handled by &lt;em&gt;IsolatingCatalog&lt;/em&gt;. Although not yet completed, my approach seems working fine, and after extensive testing I think it will make its way to the &lt;a href=&quot;https://github.com/mefcontrib/mefcontrib&quot;&gt;MefContrib&lt;/a&gt;. In the meantime, if you feel you could contribute to that catalog, either from MEF or isolation perspectives, fell free to contact me so that we might exchange ideas, etc. Hope you liked it!&lt;/p&gt;</description><link>http://pwlodek.blogspot.com/2011/07/isolating-mef-components.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwYcBBjSU2Pfak9FxJTSMK1BMwp47Ny3avme8WVO9OHOJtUVA0BISywzQhqhGK0g6yLV_VlB1xh6kFottyK8StyO2n2NSfiA7AtA2jUO6MN5Ve7F793E6NkGuxF7mC4blxONqWgW0kpEiG/s72-c?imgmax=800" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-6216714826496884367</guid><pubDate>Sat, 09 Apr 2011 12:23:00 +0000</pubDate><atom:updated>2011-04-09T14:33:29.986+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>Introducing convention based programming for Managed Extensibility Framework</title><description>&lt;p&gt;More than a year ago my friend &lt;a href=&quot;http://thecodejunkie.com&quot;&gt;@TheCodeJunkie&lt;/a&gt; wrote a very nice addition to Managed Extensibility Framework – the &lt;em&gt;ConventionCatalog&lt;/em&gt;. Since then it’s a part of &lt;a href=&quot;http://mefcontrib.com&quot;&gt;MefContrib&lt;/a&gt; project. However, I haven’t seen many people using it. My guess is that there is no much information about it, besides &lt;a href=&quot;http://thecodejunkie.com/2010/03/bringing-convention-based-registration.html&quot;&gt;this post&lt;/a&gt;. So in this post I will discuss what a convention model is, and how to use it!&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;What is ConventionCatalog ?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Convention model (aka. ConventionCatalog) allows you to specify &lt;u&gt;conventions&lt;/u&gt; to produce &lt;em&gt;parts&lt;/em&gt;, &lt;em&gt;exports&lt;/em&gt; and &lt;em&gt;imports&lt;/em&gt;. Okay, this is all fine, but give me an example! Here is a convention you can define: &lt;em&gt;For every type in assembly MyCompany.MyFantasticProgram, if a type implements IWidget, please export it with contract type IWidget and import property named ViewModel&lt;/em&gt;. Nice, huh? Say you have &lt;em&gt;Widget1&lt;/em&gt; and &lt;em&gt;Widget2&lt;/em&gt; classes implementing &lt;em&gt;IWidget&lt;/em&gt; interface. &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjrSXa0AwO01adP-Y3hiS27hyYEv4p62uA9EnVixNvOgw0MiM4GuqRJx8Mk-RM6O40zgBUe_wjcXz-Itn8AGeRJ6YybLjTQN-xj-JLlItAkesmzn3qFyBH2787rn2ajhUUlTVVUExLKy-K8/s1600-h/image12.png&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXwkVI_y9pw1zgnhhYCUoMbt-Miiil4fBTVX-JiXJnZPfCngHcRsc2M8navlzyRsWrUVFMs7iMwu5YD7avL-TcPHp4iT3mUovxEiGe5oMQZksHkgmoFHDWXX867uVrURdOpD8TGI1Qqrst/?imgmax=800&quot; width=&quot;314&quot; height=&quot;152&quot; /&gt;&lt;/a&gt; They will be automatically exported, and moreover, they &lt;u&gt;don’t have to be attributed&lt;/u&gt; using standard MEF attributes!!! This is because the &lt;em&gt;ConventionCatalog&lt;/em&gt; defines an extensible mechanism for writing such conventions! And you can write your own easily! One thing to note about the above convention – it will be applied to many types, particularly all implementing the &lt;em&gt;IWidget&lt;/em&gt; interface. This is important as you don’t have to explicitly export all the classes individually. At the same time, it is perfectly legal to apply a convention to a single type. Example? &lt;em&gt;If you ever encounter Widget123 type, please export it using IWidget contract type and add Location metadata with a value of Location.Left&lt;/em&gt; (enumeration). Here, only a single class (part) will be affected – the &lt;em&gt;Widget123&lt;/em&gt; class. Now you have a pretty good understanding what conventions are in the beautiful world of MEF, but how can I specify them in a program ? So as I stated previously, the catalog is extensible, so.. any possible way of specifying the conventions is… possible! Originally, @TheCodeJunkie developed a pretty nice fluent interface for defining them (as part of MefContrib 1.1 I’ve added some extension methods to ease the use of fi). Here is a code which defines the initial convention (it does not specify where to look for the types to apply it – be patient) &lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;Part()&lt;br /&gt;    .ForTypesAssignableFrom&amp;lt;IWidget&amp;gt;()&lt;br /&gt;    .ExportAs&amp;lt;IWidget&amp;gt;()&lt;br /&gt;    .ImportProperty(&amp;quot;ViewModel&amp;quot;);&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Recently, I have developed a registration mechanism which enables to specify parts via the configuration file – &lt;em&gt;App.config&lt;/em&gt;. Next section outlines both methods using a simple use case. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;How can I use it ?&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Let’s begin with a simple scenario. Let’s build a console application which can display a list of movies from various data sources. Here are the main classes and interfaces involved in the design: &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkZWaFYw2MyMO5hfQUA5xKOhpcafLIslOQysINdLLNwVE4u5cFNAuWUW2WW8i3UoosWftHEdmOOXo4A6OU_QbpWxOxlSrSIA0T_FdC9VXkSMq0qSlS8oCgWDOFXazaJbjFq3QfVQ6VVr7f/s1600-h/MovieClasses7.png&quot;&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; title=&quot;MovieClasses&quot; alt=&quot;MovieClasses&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLYcCkY1gdBT6PhmJfu-ppVukCpmiZNuUCCp3IUam0_ifwk52F9Mxot5bMHY3YS9iR0JTVVMi60WrDB5XPHGJxZOhe47zoi9R06kH_pDxDgUcJtKiBBCueAzNZZ65u-d12_sKZ6aLM3ZrY/?imgmax=800&quot; width=&quot;641&quot; height=&quot;412&quot; /&gt;&lt;/a&gt; The core interface is &lt;em&gt;IMovieProvider&lt;/em&gt; which provides an abstraction over any movie repository and has only one method returning a list of movies from a single movie source. It also has two dummy implementations – nothing interesting. This interface is consumed by the &lt;em&gt;MovieLister&lt;/em&gt; class which implements &lt;em&gt;IMovieLister&lt;/em&gt; and acts as a facade on top of the providers. It simply returns all movies from all providers available, with optional filtering by movie title. &lt;em&gt;MovieLister&lt;/em&gt; also performs some simple logging, and the logger is injected using the &lt;u&gt;constructor injection&lt;/u&gt;. The complete code for that class is right here: &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class MovieLister : IMovieLister&lt;br /&gt;{&lt;br /&gt;    private readonly ILogger _logger;&lt;br /&gt;&lt;br /&gt;    public MovieLister(ILogger logger)&lt;br /&gt;    {&lt;br /&gt;        _logger = logger;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public IMovieProvider[] Providers { get; set; }&lt;br /&gt;&lt;br /&gt;    public IEnumerable&amp;lt;Movie&amp;gt; GetMovies()&lt;br /&gt;    {&lt;br /&gt;        var movies = Providers&lt;br /&gt;            .SelectMany(movieProvider =&amp;gt; movieProvider.GetMovies())&lt;br /&gt;            .ToList();&lt;br /&gt;            &lt;br /&gt;        _logger.Log(string.Format(&amp;quot;Loaded {0} movies.&amp;quot;, movies.Count));&lt;br /&gt;&lt;br /&gt;        return movies;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public IEnumerable&amp;lt;Movie&amp;gt; GetMoviesByName(string name)&lt;br /&gt;    {&lt;br /&gt;        var movies = GetMovies()&lt;br /&gt;            .Where(m =&amp;gt; m.Name.Contains(name))&lt;br /&gt;            .ToList();&lt;br /&gt;&lt;br /&gt;        _logger.Log(string.Format(&amp;quot;Found {0} movies matching &#39;{1}&#39;.&amp;quot;, movies.Count, name));&lt;br /&gt;&lt;br /&gt;        return movies;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Note that there is no sign of standard MEF &lt;em&gt;Export&lt;/em&gt;/&lt;em&gt;Import&lt;/em&gt; attributes, and the constructor is not attributed with &lt;em&gt;ImportingConstructor&lt;/em&gt;! Finally, there is a &lt;em&gt;Program&lt;/em&gt; class which wraps the app. Here’s the code: &lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class Program&lt;br /&gt;{&lt;br /&gt;    [Import]&lt;br /&gt;    public IMovieLister MovieLister { get; set; }&lt;br /&gt;&lt;br /&gt;    public static void Main(string[] args)&lt;br /&gt;    {&lt;br /&gt;        var p = new Program();&lt;br /&gt;        p.Init();&lt;br /&gt;        p.Run();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void Init()&lt;br /&gt;    {&lt;br /&gt;        var conventionCatalog = new ConventionCatalog(new MoviePartRegistry());&lt;br /&gt;        var container = new CompositionContainer(conventionCatalog);&lt;br /&gt;&lt;br /&gt;        // Composing this part will inject MovieLister property&lt;br /&gt;        container.ComposeParts(this);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void Run()&lt;br /&gt;    {&lt;br /&gt;        var movies = MovieLister.GetMoviesByName(&amp;quot;Movie&amp;quot;);&lt;br /&gt;        foreach (var movie in movies)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(movie.Name);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;No doubt the most interesting part in the above code is the &lt;em&gt;Init()&lt;/em&gt; method. I create there the &lt;em&gt;ConventionCatalog&lt;/em&gt; (note this is the only catalog used in this example) and pass an instance of some registry. &lt;u&gt;And here we came to the very important thing: all conventions are defined (or I should rather say can be understood) thanks to the &lt;em&gt;IPartRegistry&lt;/em&gt; interface&lt;/u&gt;. So to introduce a custom way of defining&amp;#160; conventions, you have to implement that interface (if you want to understand some internals of how &lt;em&gt;ConventionCatalog&lt;/em&gt; works, read &lt;a href=&quot;http://thecodejunkie.com/2010/03/bringing-convention-based-registration.html&quot;&gt;this post&lt;/a&gt;). By default, MefContrib 1.1 ships with two implementations: &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;  &lt;li&gt;&lt;em&gt;PartRegistry&lt;/em&gt; – this class provides fluent interface to register part/export/import conventions, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;&lt;em&gt;ConfigurationPartRegistry&lt;/em&gt; – this class provide the XML way of specifying conventions. &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;Okay, so let’s see what it takes to register our parts using fluent interface. &lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class MoviePartRegistry : PartRegistry&lt;br /&gt;{&lt;br /&gt;    public MoviePartRegistry()&lt;br /&gt;    {&lt;br /&gt;        // Apply the conventions to all types int the specified assembly&lt;br /&gt;        Scan(c =&amp;gt; c.Assembly(typeof(Program).Assembly));&lt;br /&gt;            &lt;br /&gt;        Part&amp;lt;MovieLister&amp;gt;()&lt;br /&gt;            .MakeShared() // make this part shared&lt;br /&gt;            .ExportAs&amp;lt;IMovieLister&amp;gt;() // and export it with contract type IMovieLister&lt;br /&gt;            .ImportConstructor() // use constructor injection&lt;br /&gt;            .Imports(x =&amp;gt;&lt;br /&gt;            {&lt;br /&gt;                x.Import&amp;lt;MovieLister&amp;gt;() // import on part MovieLister&lt;br /&gt;                    .Member(m =&amp;gt; m.Providers) // member named &#39;Providers&#39;&lt;br /&gt;                    .ContractType&amp;lt;IMovieProvider&amp;gt;(); // with contract type IMovieProvider&lt;br /&gt;            });&lt;br /&gt;&lt;br /&gt;        Part()&lt;br /&gt;            .ForTypesAssignableFrom&amp;lt;IMovieProvider&amp;gt;()&lt;br /&gt;            .ExportAs&amp;lt;IMovieProvider&amp;gt;();&lt;br /&gt;&lt;br /&gt;        Part&amp;lt;LoggerImpl&amp;gt;()&lt;br /&gt;            .MakeShared()&lt;br /&gt;            .ExportAs&amp;lt;ILogger&amp;gt;();&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;I derive from PartRegistry (although this is not a requirement, I prefer to do this that way) and do two things there. First, I specify to which types I want to apply my conventions. This is done through a nice lambda expression. What it does under the hoods ? It creates appropriate type scanners. A type scanner (anything implementing &lt;em&gt;ITypeScanner&lt;/em&gt; interface) is responsible for returning all the types for which the user wants to assign conventions, if there are any applicable). Out of the box, there are: &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;  &lt;li&gt;TypeScanner, which can return user specified types, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;AssemblyTypeScanner – returns all the types from given assembly, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;DirectoryTypeScanner – returns all the types from all assemblies from a given disk folder, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;AggregateTypeScanner – aggregates types from various type scanners. &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;Does it resemble you something ? Yes! Catalogs from MEF of course! This is because MEF catalogs are responsible for pulling parts/exports/imports from types. Similarly, we obtain types for which we want to apply the conventions. Okay, that’s all in terms of how to specify types for conventions. Lets move on to how to actually specify a convention. There’s a single method called Part() which returns PartConventionBuilder which has a nice fluent API to define part conventions. Part() method comes in two flavours – generic and nongeneric. The difference is that the generic Part&amp;lt;PartType&amp;gt;() method creates a convention in a strongly typed manner &lt;u&gt;and&lt;/u&gt; applies that convention &lt;u&gt;only&lt;/u&gt; to the part type specified as a generic type argument. However, if you want to leverage strong typing and specify conventions for other types as well, you can force it using &lt;em&gt;ForTypesAssignableFrom()&lt;/em&gt; method. Actually, to specify types for which you want to apply the convention, you can use any of the &lt;em&gt;For*()&lt;/em&gt; methods. It would be pointless to further explain the API, please play with it and let us know how does it feel – we can always improve! You probably have noticed how nicely IMoveProvider instances are exported. But what if we wanted to be able to specify which providers we want to use ? Of course there are many ways of achieving this, including leveraging metadata facilities of MEF. One method could also be to specify movie providers in the App.config file rather than exporting all &lt;em&gt;IMovieProvider&lt;/em&gt; implementations using a convention. Let’s explore that possibility.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;To configure parts using XML, we need to add another part registry to convention catalog. Change the &lt;em&gt;Init()&lt;/em&gt; method to this: &lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;private void Init()&lt;br /&gt;{&lt;br /&gt;    var conventionCatalog = new ConventionCatalog(&lt;br /&gt;        new ConfigurationPartRegistry(&amp;quot;mef.configuration&amp;quot;),&lt;br /&gt;        new MoviePartRegistry());&lt;br /&gt;    var container = new CompositionContainer(conventionCatalog);&lt;br /&gt;&lt;br /&gt;    // Composing this part will inject MovieLister property&lt;br /&gt;    container.ComposeParts(this);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;em&gt;ConfigurationPartRegistry&lt;/em&gt; class accepts a string representing the name of the config section used to configure parts. Next, remove the fluent registration for &lt;em&gt;IMovieProviders&lt;/em&gt;. Finally, add the App.config with the following content: &lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;&amp;lt;configuration&amp;gt;&lt;br /&gt;  &amp;lt;configSections&amp;gt;&lt;br /&gt;    &amp;lt;section&lt;br /&gt;      name=&amp;quot;mef.configuration&amp;quot;&lt;br /&gt;      type=&amp;quot;MefContrib.Hosting.Conventions.Configuration.Section.ConventionConfigurationSection, MefContrib&amp;quot; /&amp;gt;&lt;br /&gt;  &amp;lt;/configSections&amp;gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;mef.configuration&amp;gt;&lt;br /&gt;    &amp;lt;parts&amp;gt;&lt;br /&gt;&lt;br /&gt;      &amp;lt;part type=&amp;quot;ConventionCatalogDemo.MovieProvider1, ConventionCatalogDemo&amp;quot; creationPolicy=&amp;quot;Shared&amp;quot;&amp;gt;&lt;br /&gt;        &amp;lt;exports&amp;gt;&lt;br /&gt;          &amp;lt;export contractType=&amp;quot;ConventionCatalogDemo.IMovieProvider, ConventionCatalogDemo&amp;quot; /&amp;gt;&lt;br /&gt;        &amp;lt;/exports&amp;gt;&lt;br /&gt;      &amp;lt;/part&amp;gt;&lt;br /&gt;&lt;br /&gt;      &amp;lt;part type=&amp;quot;ConventionCatalogDemo.MovieProvider2, ConventionCatalogDemo&amp;quot; creationPolicy=&amp;quot;Shared&amp;quot;&amp;gt;&lt;br /&gt;        &amp;lt;exports&amp;gt;&lt;br /&gt;          &amp;lt;export contractType=&amp;quot;ConventionCatalogDemo.IMovieProvider, ConventionCatalogDemo&amp;quot; /&amp;gt;&lt;br /&gt;        &amp;lt;/exports&amp;gt;&lt;br /&gt;      &amp;lt;/part&amp;gt;&lt;br /&gt;      &lt;br /&gt;    &amp;lt;/parts&amp;gt;&lt;br /&gt;  &amp;lt;/mef.configuration&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/configuration&amp;gt;&lt;/pre&gt;&lt;br /&gt;Well, what do we have in here ? :) We have a MEF configuration specifying a set of parts. Each part must have a full .NET type associated with it (type name + assembly). The part (not surprisingly) can have a set of exports it offers and of course a set of imports it consumes. Each export can specify: &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;  &lt;li&gt;contractType – type of the contract, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;contractName – name under which the export will be available, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;member – name of the member of the part to export (leave empty to export the whole part itself), &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;metadata – a collection of metadata-items specifying metadata that will be attached to the export. &lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;Each import can specify: &lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;  &lt;li&gt;contractType – type of the contract, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;contractName – name used to resolve the import, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;member – name of the member of the part to import, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;creationPolicy – required creation policy, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;allowDefault – whether the import allow default values, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;isRecomposable – whether the import is recomposable, &lt;/li&gt;&lt;br /&gt;&lt;br /&gt;  &lt;li&gt;required-metadata – a collection of metadata-items specifying required metadata. &lt;!--EndFragment--&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;To specify a set of imports for a part use &lt;em&gt;imports&lt;/em&gt; xml element and fill it with &lt;em&gt;import&lt;/em&gt; xml elements. I guess everything is self explanatory. If you have any doubts, pleas see MefContrib.Tests project to see some more examples. &lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;strong&gt;Where can I find it ?&lt;/strong&gt;&lt;/p&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;&lt;em&gt;ConventionCatalog&lt;/em&gt; discussed in this post is available in &lt;a href=&quot;http://mefcontrib.com&quot;&gt;MefContrib&lt;/a&gt; project. New &lt;em&gt;ConfigurationPartRegistry&lt;/em&gt; ships as part of the MefCotrinb 1.1. Please download sources and binaries from &lt;a href=&quot;http://mefcontrib.com&quot;&gt;mefcontrib.com&lt;/a&gt;. Sample code used in this post can be downloaded &lt;a href=&quot;https://github.com/downloads/pwlodek/CodeGallery/ConventionCatalogDemo.zip&quot;&gt;here&lt;/a&gt;. There is also another sample application (WPF based), which shows how &lt;em&gt;ConventionCatalog&lt;/em&gt; can be used. You can download it from our official &lt;a href=&quot;https://github.com/MefContrib/MefContrib-Samples&quot;&gt;MefContrib-Samples&lt;/a&gt; Github repository. Here’s the screenshot for that app: &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixxgafei8gX0hIBpbr_wKBk7bmzUjkAtHJ5-jrBh7R4pl5IPYc05bwa0vkBYm4FvqgKgXZK4mwjcQz624-3ajB9pjJ3GXFwiZDD0CIr9K0DTmNsyWlTd2jU0SOK-aYS6sbDxp_CvvvSC_m/s1600-h/ExtensibleDashboardOnConventions%5B4%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto; padding-top: 0px&quot; title=&quot;ExtensibleDashboardOnConventions&quot; border=&quot;0&quot; alt=&quot;ExtensibleDashboardOnConventions&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwz_MXpfvwch53fXyl3MXslfItY5-oqqxf-ODXfwgIqg2Mk9PHHbrV2cn0etle-yi0zexG5oaW-7r4DuAZAqedrzG-DKmq2UGR7s-UD8lHihIXKbmFVTh58Lj9Pypzn0dsIrKZn43lpNbF/?imgmax=800&quot; width=&quot;372&quot; height=&quot;267&quot; /&gt;&lt;/a&gt; Enjoy and let me know if you like it!&lt;/p&gt;  </description><link>http://pwlodek.blogspot.com/2011/04/introducing-convention-based.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiXwkVI_y9pw1zgnhhYCUoMbt-Miiil4fBTVX-JiXJnZPfCngHcRsc2M8navlzyRsWrUVFMs7iMwu5YD7avL-TcPHp4iT3mUovxEiGe5oMQZksHkgmoFHDWXX867uVrURdOpD8TGI1Qqrst/s72-c?imgmax=800" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-4841640897014938161</guid><pubDate>Tue, 29 Mar 2011 12:47:00 +0000</pubDate><atom:updated>2011-03-29T14:54:38.758+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Castle</category><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>Integrating Castle Windsor with MEF</title><description>&lt;p&gt;Some time ago I developed a small chunk of code which enabled &lt;a href=&quot;http://unity.codeplex.com/&quot;&gt;Unity&lt;/a&gt; and &lt;a href=&quot;http://mef.codeplex.com/&quot;&gt;Managed Extensibility Framework&lt;/a&gt; to consume each others components (see my posts &lt;a href=&quot;http://pwlodek.blogspot.com/2009/05/unity-mef-integration-layer.html&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://pwlodek.blogspot.com/2009/08/improved-mef-unity-integration-layer.html&quot;&gt;here&lt;/a&gt;). After a while I hooked up with &lt;a href=&quot;http://thecodejunkie.com/&quot;&gt;@TheCodeJunkie&lt;/a&gt; who was, and still is, responsible for managing &lt;a href=&quot;https://github.com/mefcontrib/mefcontrib&quot;&gt;MefContrib&lt;/a&gt; project, which aims at delivering high quality MEF extensions developed by the community. Soon, my integration layer became a part of that library! Yeah, I was excited =) After a while, I posted a refined version. Basically, I extracted some generic code from the existing Unity integration stuff which could be reused with other DI containers. So in this post I want to discuss a simple adapter for Castle Windsor which is built using that infrastructure and enables MEF to consume components registered in Windsor container.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;All the required stuff lives in &lt;em&gt;MefContrib.Containers&lt;/em&gt; namespace (MefContrib.dll assembly) which has been renamed from &lt;em&gt;MefContrib.Integration&lt;/em&gt; as the new name is more meaningful. There is one interface and one &lt;em&gt;ExportProvider&lt;/em&gt; which are interesting in this scenario. &lt;em&gt;IContainerAdapter&lt;/em&gt; is an interface which encapsulates basic behaviour of a typical IoC container. The &lt;em&gt;ContainerExportProvider&lt;/em&gt; class then uses that interface to extract relevant components from the IoC and provides them to MEF. So the only part missing from the equation is the actual IContainerAdapter implementation for Windsor Container. Unsurprisingly, it is very simple. Here it comes:&lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;public class WindsorContainerAdapter : ContainerAdapterBase&lt;br /&gt;{&lt;br /&gt;    private readonly WindsorContainer _container;&lt;br /&gt;&lt;br /&gt;    public WindsorContainerAdapter(WindsorContainer container)&lt;br /&gt;    {&lt;br /&gt;        if (container == null)&lt;br /&gt;        {&lt;br /&gt;            throw new ArgumentNullException(&amp;quot;container&amp;quot;);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        _container = container;&lt;br /&gt;        _container.Kernel.ComponentRegistered += ComponentRegisteredHandler;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void ComponentRegisteredHandler(string key, IHandler handler)&lt;br /&gt;    {&lt;br /&gt;        RegisterCastleComponent(handler);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public override object Resolve(Type type, string name)&lt;br /&gt;    {&lt;br /&gt;        return name == null&lt;br /&gt;                    ? _container.Resolve(type)&lt;br /&gt;                    : _container.Resolve(name, type);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public override void Initialize()&lt;br /&gt;    {&lt;br /&gt;        var handlers = _container.Kernel.GetAssignableHandlers(typeof (object));&lt;br /&gt;        foreach (var handler in handlers)&lt;br /&gt;        {&lt;br /&gt;            RegisterCastleComponent(handler);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private void RegisterCastleComponent(IHandler handler)&lt;br /&gt;    {&lt;br /&gt;        var name = handler.ComponentModel.Name;&lt;br /&gt;        var type = handler.Service;&lt;br /&gt;&lt;br /&gt;        // By default, Windsor assigns implementation&#39;s full name for the key,&lt;br /&gt;        // but for a default key we want to pass null instead&lt;br /&gt;        if (handler.ComponentModel.Implementation.FullName == name)&lt;br /&gt;        {&lt;br /&gt;            name = null;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        OnRegisteringComponent(type, name);&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;All we have to do is to inform &lt;em&gt;ContainerAdapterBase&lt;/em&gt; that a component has been registered within the container so that the &lt;em&gt;ContainerExportProvider&lt;/em&gt; knows which types are available. In the &lt;em&gt;Initialize&lt;/em&gt; method we have a chance to register components which were registered in the IoC container before the adapter had a chance to intercept this information itself. The &lt;em&gt;Resolve&lt;/em&gt; method will be called by MEF in order to get a component from IoC.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Usage&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;The usage is pretty straightforward. Let’s assume we have &lt;em&gt;IFoo&lt;/em&gt; service which maps to &lt;em&gt;Foo&lt;/em&gt; implementation. Here’s the code which registers these types within Castle Windsor and then &lt;em&gt;IFoo&lt;/em&gt; is consumed by MEF.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;var windsorContainer = new WindsorContainer();&lt;br /&gt;var provider = new ContainerExportProvider(new WindsorContainerAdapter(windsorContainer));&lt;br /&gt;var compositionContainer = new CompositionContainer(provider);&lt;br /&gt;&lt;br /&gt;// Setup Castle Windsor&lt;br /&gt;windsorContainer.Register(Component.For&amp;lt;IFoo&amp;gt;().ImplementedBy&amp;lt;Foo&amp;gt;());&lt;br /&gt;&lt;br /&gt;var fooExport = compositionContainer.GetExport&amp;lt;IFoo&amp;gt;();&lt;/pre&gt;&lt;br /&gt;Of course, named registration is supported. Also MEF can resolve all &lt;em&gt;IFoo&lt;/em&gt; implementations if it happens that &lt;em&gt;IFoo&lt;/em&gt; is mapped to more than one implementation (thanks to named registration). See all the tests available in the provided solution.&amp;#160;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Where can I find this ?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;This code with some NUnit tests is available as a sample for the MefContrib project. You can find its sources at &lt;a title=&quot;https://github.com/MefContrib/MefContrib-Samples&quot; href=&quot;https://github.com/MefContrib/MefContrib-Samples&quot;&gt;https://github.com/MefContrib/MefContrib-Samples&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Enjoy!  </description><link>http://pwlodek.blogspot.com/2011/03/integrating-castle-windsor-with-mef.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-6803294071014807489</guid><pubDate>Tue, 22 Mar 2011 17:06:00 +0000</pubDate><atom:updated>2011-04-18T09:24:39.270+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">KGD.NET</category><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>Geeks On Tour – Me speaking about MEF/MefContrib / Extensibility</title><description>&lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiauPBnZka_d9vRbXEDiTf3kzVu2UA68_HOcjjwhKOsj2gHGQSDn7WbeHNOKR66bScdJM52rwGwSxpUH4_Y6EwpOCcvmaXadPt4LxwV7fWFqvhvjPcgOblO0t1oraPC2_n6Bi9O27GlEG3e/s1600-h/3rd-Geeks-on-Tour%20logo%5B5%5D.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;3rd-Geeks-on-Tour logo&quot; border=&quot;0&quot; alt=&quot;3rd-Geeks-on-Tour logo&quot; align=&quot;left&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiH3jucr9UomgREf0VnEhzdFVYL6mBVQpbFdJIcm7HzHYuv4AcEj5iP_pfgW3Z-e7P1cIN56ij5mwMVq5p9t6RIg-Udq-uBWFyts5D25ChiG8AIRyNlWaerh7gCOmdAlmhQxh6YWMsO0mRV/?imgmax=800&quot; width=&quot;240&quot; height=&quot;48&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I’m happy to announce that between April 18th and 20th 2011 I will be speaking on Geeks on Tour roadshow! Three days, three cities – Katowice, Wrocław, Poznań, two presentations each day. Wondering what MEF is ? How does it relate to IoC and Managed Addin Framework ? When to choose which ? What’s MefContrib and how it can help you ? How to write your custom MEF extensions ? Join me on the talks to find out this and many more! You can find more details about the event, including detailed agenda, on &lt;a href=&quot;http://geeksontour.pl/&quot;&gt;geeksontour.pl&lt;/a&gt; official page!&lt;/p&gt;  &lt;p&gt;I will be covering &lt;strong&gt;all&lt;/strong&gt; the aspects regarding MEF, its strong and week sides, how does MEF relate to other technologies. I will be showing some of the cool features MEF team is preparing as part of MEF 2 release. I will show some cool features which are part of MefContrib project. Finally, I will deep dive into MEF internals, I will show how to write custom exporters and catalogs. The presentations will be held in Polish. Entrance is free :) See you there!  &lt;br /&gt;&lt;iframe src=&quot;http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FGeeks-On-Tour-2011%2F215910878419490&amp;amp;width=292&amp;amp;colorscheme=light&amp;amp;show_faces=false&amp;amp;stream=false&amp;amp;header=false&amp;amp;height=62&quot; scrolling=&quot;no&quot; frameborder=&quot;0&quot; style=&quot;border:none; overflow:hidden; width:292px; height:62px;&quot; allowTransparency=&quot;true&quot;&gt;&lt;/iframe&gt;&lt;br /&gt;&lt;em&gt;&lt;u&gt;Presentation and full source code is available below.&lt;br /&gt;&lt;/u&gt;&lt;/em&gt;&lt;iframe style=&quot;padding: 0px; width: 98px; height: 115px; background-color: rgb(252, 252, 252);&quot; title=&quot;Preview&quot; marginheight=&quot;0&quot; src=&quot;http://cid-bd15edd4d52f5329.office.live.com/embedicon.aspx/Public/GeeksOnTour%202011.zip&quot; frameborder=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;&lt;/p&gt;</description><link>http://pwlodek.blogspot.com/2011/03/geeks-on-tour-me-speaking-about.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiH3jucr9UomgREf0VnEhzdFVYL6mBVQpbFdJIcm7HzHYuv4AcEj5iP_pfgW3Z-e7P1cIN56ij5mwMVq5p9t6RIg-Udq-uBWFyts5D25ChiG8AIRyNlWaerh7gCOmdAlmhQxh6YWMsO0mRV/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-1005267334216437111</guid><pubDate>Sun, 19 Dec 2010 18:31:00 +0000</pubDate><atom:updated>2010-12-19T19:59:52.296+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>Introduction to InterceptingCatalog – Part II – Open Generics Support</title><description>&lt;p&gt;In the &lt;a href=&quot;http://pwlodek.blogspot.com/2010/11/introduction-to-interceptingcatalog.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt; I have described how to setup interception using the &lt;em&gt;InterceptingCatalog&lt;/em&gt; and &lt;em&gt;InterceptionConfiguration &lt;/em&gt;class. Just to remind you, the interception allows you to take control over the exported instances thanks to the &lt;em&gt;IExportedValueInterceptor&lt;/em&gt; interface. Although this is the primary functionality, there is other bunch of stuff possible to do with the catalog. In this post I am going to show how to enable open-generics support for MEF using both the &lt;em&gt;InterceptingCatalog &lt;/em&gt;and the decorating &lt;em&gt;GenericCatalog&lt;/em&gt;. I will then introduce the &lt;em&gt;IExportHandler&lt;/em&gt; interface which gives the ability to do some nice filtering based on a given criteria as well as to add new exports on the fly. The open generics support implementation is based on the &lt;u&gt;on the fly export creation&lt;/u&gt; (thanks to the &lt;em&gt;IExportHandler&lt;/em&gt; interface) as well as thing called &lt;u&gt;part rewriting&lt;/u&gt;. Keep reading to find out more!&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The problem&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;One of the biggest problem people complain about is the lack of open-generics support in MEF. You can read about this issue &lt;a href=&quot;http://codebetter.com/blogs/glenn.block/archive/2009/03/21/why-doesn-t-mef-support-open-generics-for-exports-because-mef-is-not-type-based.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;, &lt;a href=&quot;http://ayende.com/Blog/archive/2009/03/22/mef-open-generic-types.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://codebetter.com/blogs/glenn.block/archive/2009/08/20/open-generic-support-in-mef.aspx&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; (I advise you see these entries!). The canonical example folks use concerns IRepository&amp;lt;T&amp;gt;. Imagine the following code:&lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;public interface IRepository&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;  T Get(int id);&lt;br /&gt;&lt;br /&gt;  void Save(T instance);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Export(typeof(IRepository&amp;lt;&amp;gt;))]&lt;br /&gt;public class Repository&amp;lt;T&amp;gt; : IRepository&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;  public T Get(int id)&lt;br /&gt;  {&lt;br /&gt;      return (...);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public void Save(T instance)&lt;br /&gt;  {&lt;br /&gt;      Console.WriteLine(&quot;Saving {0} instance.&quot;, instance.GetType().Name);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;/// &amp;lt;summary&amp;gt;&lt;br /&gt;/// Fake customer.&lt;br /&gt;/// &amp;lt;/summary&amp;gt;&lt;br /&gt;public class Customer { }&lt;br /&gt;&lt;br /&gt;[Export]&lt;br /&gt;public class CustomerViewModel&lt;br /&gt;{&lt;br /&gt;  [Import]&lt;br /&gt;  public IRepository&amp;lt;Customer&amp;gt; Repository { get; set; }&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;So what happens here ? We simply export a generic implementation of the generic interface IRepository&amp;lt;T&amp;gt; with an &lt;u&gt;open-generic contract type&lt;/u&gt;, and we import a closed-generic part based on the open generic contract. Unfortunately, this isn’t supported out of the box in MEF. &lt;u&gt;However, thanks to MefContrib, it is!&lt;/u&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;How can I get it ?&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Open generics support shipped initially in the &lt;a href=&quot;https://github.com/downloads/MefContrib/MefContrib/MefContrib-v1.0.0.0.zip&quot; target=&quot;_blank&quot;&gt;MefContrib 1.0 release&lt;/a&gt;. However, it had limited capabilities as the open generics worked only when generic types were exported using the &lt;em&gt;InheritedExport&lt;/em&gt; attribute. To get the updated version, which enables to do things like the above, you have to download &lt;a href=&quot;https://github.com/MefContrib/MefContrib&quot; target=&quot;_blank&quot;&gt;MefContrib&lt;/a&gt; repo and compile the sources yourself. Updated samples, including those presented here, are available in the &lt;a href=&quot;https://github.com/MefContrib/MefContrib-Samples&quot; target=&quot;_blank&quot;&gt;MefContrib-Samples&lt;/a&gt; repo. Go and get them =)&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Container setup&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;There are two ways of enabling open generics support. You can either use more verbose syntax using the InterceptingCatalog, or you can leverage the GenericCatalog. The GenericCatalog is noting more than a convenient decorating catalog which internally uses the InterceptingCatalog.&lt;/p&gt;&lt;p&gt;The first thing to do is to provide mapping between open generic interface and its implementation. This step is mandatory since the underlying infrastructure requires to produce export based on the concrete implementation. This export is produced on the fly, which means it is not contained in any composable catalog, but is created when it is needed. To map the contract type to its implementation you can either implement &lt;em&gt;IGenericContractRegistry&lt;/em&gt; interface or inherit the &lt;em&gt;GenericContractRegistryBase&lt;/em&gt; class. The implementation which supports the above example is presented below.&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[Export(typeof(IGenericContractRegistry))]&lt;br /&gt;public class MyGenericContractRegistry : GenericContractRegistryBase&lt;br /&gt;{&lt;br /&gt;  protected override void Initialize()&lt;br /&gt;  {&lt;br /&gt;      Register(typeof(IRepository&amp;lt;&amp;gt;), typeof(Repository&amp;lt;&amp;gt;));&lt;br /&gt;  }&lt;br /&gt;} &lt;/pre&gt;&lt;p&gt;&lt;u&gt;Important:&lt;/u&gt; the mapping is required only when you export the generic class with explicitly given contract type (like in the example). If you export generic class with its default contract type, no mapping is required!&lt;/p&gt;&lt;p&gt;Next is what you have probably expected – the catalog setup.&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;// Create source catalog&lt;br /&gt;var typeCatalog = new TypeCatalog(typeof(CustomerViewModel), typeof(MyGenericContractRegistry));&lt;br /&gt;&lt;br /&gt;// Create the interception configuration and add support for open generics&lt;br /&gt;var cfg = new InterceptionConfiguration()&lt;br /&gt;  .AddHandler(new GenericExportHandler());&lt;br /&gt;&lt;br /&gt;// Create the InterceptingCatalog and pass the configuration&lt;br /&gt;var interceptingCatalog = new InterceptingCatalog(typeCatalog, cfg);&lt;br /&gt;&lt;br /&gt;// Create the container&lt;br /&gt;var container = new CompositionContainer(interceptingCatalog);&lt;br /&gt;&lt;br /&gt;// Get the repository&lt;br /&gt;var repository = container.GetExportedValue&amp;lt;CustomerViewModel&amp;gt;().Repository;&lt;/pre&gt;After creating the interception configuration, we add the &lt;em&gt;GenericExportHandler&lt;/em&gt; instance which is responsible for creating closed generic parts. This class implements the &lt;em&gt;IExportHandler&lt;/em&gt; interface, which I will introduce in a moment. Meanwhile, let’s see the less verbose and cleaner setup routine.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;// Create source catalog&lt;br /&gt;var typeCatalog = new TypeCatalog(typeof(CustomerViewModel));&lt;br /&gt;&lt;br /&gt;// Create catalog which supports open-generics, pass in the registry&lt;br /&gt;var genericCatalog = new GenericCatalog(new MyGenericContractRegistry());&lt;br /&gt;&lt;br /&gt;// Aggregate both catalogs&lt;br /&gt;var aggregateCatalog = new AggregateCatalog(typeCatalog, genericCatalog);&lt;br /&gt;&lt;br /&gt;// Create the container&lt;br /&gt;var container = new CompositionContainer(aggregateCatalog);&lt;br /&gt;&lt;br /&gt;// Get the repository&lt;br /&gt;var repository = container.GetExportedValue&amp;lt;CustomerViewModel&amp;gt;().Repository;&lt;/pre&gt;&lt;p&gt;Instead of creating the InterceptingCatalog, the GenericCatalog is created. This concludes how to setup MEF to support open generics. Next sections explain how stuff works, without digging into implementation details though. If you are curious, keep reading! &lt;/p&gt;&lt;strong&gt;How does it work ?&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;You are maybe asking yourself – given the export definition below – how does MEF know that when importing say &lt;em&gt;IRepository&amp;lt;Order&amp;gt;&lt;/em&gt;, it should inject &lt;em&gt;Repository&amp;lt;Order&amp;gt;&lt;/em&gt; ?!  &lt;pre class=&quot;brush: c-sharp&quot;&gt;[Export(typeof(IRepository&amp;lt;&amp;gt;))]&lt;br /&gt;public class Repository&amp;lt;T&amp;gt; : IRepository&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;In fact MEF only knows there is an export Repository&amp;lt;T&amp;gt; which is &lt;u&gt;NOT&lt;/u&gt; the required one! And this is not the only question! Attentive reader will also observe the the contract type (which is a string) of the given export will be ‘&lt;em&gt;SomeCleverNamespace.IRepository()&lt;/em&gt;’ which is an open generic. But the import’s contract type will be ‘&lt;em&gt;SomeCleverNamespace.IRepository(SomeOtherCleverNamespace.Order)&lt;/em&gt;’ which is a closed generic. So even though MEF somehow knew the export Repository&amp;lt;Order&amp;gt;, the contract types wouldn’t match resulting in ImportCardinalityMismatchException. &lt;/p&gt;&lt;p&gt;The answer to the first question is &lt;u&gt;on the fly export creation&lt;/u&gt;. Earlier I have introduced the concept of mapping contract type to its implementation(s). So when we import &lt;em&gt;IRepository&amp;lt;&amp;gt;&lt;/em&gt;, MEF knows its implementation is &lt;em&gt;Repository&amp;lt;&amp;gt;&lt;/em&gt;. But of course we import closed generic, like I said &lt;em&gt;IReposiotry&amp;lt;Order&amp;gt;&lt;/em&gt;, so MEF knows the implementing type is &lt;em&gt;Repository&amp;lt;Order&amp;gt;&lt;/em&gt;. Of course there is no export &lt;em&gt;Repository&amp;lt;Order&amp;gt;&lt;/em&gt;, only Repository&amp;lt;T&amp;gt;. So it have to be introduced in runtime! This is where &lt;em&gt;IExportHandler&lt;/em&gt; comes to play. The open generics support is all implemented in the &lt;em&gt;GenericExportHandler&lt;/em&gt; class which is responsible for creating closed generic exports on the fly.&lt;/p&gt;&lt;p&gt;Finally, the answer to the second question is &lt;u&gt;part rewriting&lt;/u&gt;. When we create Repository&amp;lt;Order&amp;gt; export on the fly (I mean in runtime), the export’s contract type will remain ‘&lt;em&gt;SomeCleverNamespace.IRepository()&lt;/em&gt;’. So we have to rewrite the part so that the contract type and optionally contract name will be set properly. To do the &lt;em&gt;part rewriting&lt;/em&gt;, special catalog is used – &lt;em&gt;GenericTypeCatalog&lt;/em&gt;. It accepts two types – the concrete type being exported (e.g. &lt;em&gt;Repository&amp;lt;Order&amp;gt;&lt;/em&gt;) and the open-generic contract type (e.g. &lt;em&gt;IRepository&amp;lt;&amp;gt;&lt;/em&gt;). What the catalog does in its internals is to rewrite all open-generic exports which match the contract type to be closed-generic. In our example, the contract type will be rewritten from ‘&lt;em&gt;SomeCleverNamespace.IRepository()&lt;/em&gt;’ to ‘&lt;em&gt;SomeCleverNamespace.IRepository(SomeOtherCleverNamespace.Order)&lt;/em&gt;’. Same for contract name.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Meet the IExportHandler interface&lt;/strong&gt;&lt;/p&gt;The purpose of this interface is to filter out exports based on any criteria you want, as well as to dynamically create new exports. Let’s have a look at the &lt;em&gt;IExportHandler&lt;/em&gt; signature.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public interface IExportHandler&lt;br /&gt;{&lt;br /&gt;  void Initialize(ComposablePartCatalog interceptedCatalog);&lt;br /&gt;&lt;br /&gt;  IEnumerable&amp;lt;Tuple&amp;lt;ComposablePartDefinition, ExportDefinition&amp;gt;&amp;gt;&lt;br /&gt;      GetExports(&lt;br /&gt;          ImportDefinition definition,&lt;br /&gt;          IEnumerable&amp;lt;Tuple&amp;lt;ComposablePartDefinition,ExportDefinition&amp;gt;&amp;gt; exports);&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;Wow! This looks complicated! Hopefully, it is not :) The initialize method gets called once when the export handler is initialized. Within this method you get a reference to the catalog being intercepted. The main player here is the &lt;em&gt;GetExports&lt;/em&gt; method which has the exact same signature as the &lt;em&gt;GetExports&lt;/em&gt; method in the &lt;em&gt;ComposablePartCatalog&lt;/em&gt; class. It is called whenever an &lt;em&gt;InterceptingCatalog&lt;/em&gt; is asked for exports which match the given import. The import definition is passed as the first argument. The second argument is a collection of matching export definitions along with theirs &lt;em&gt;ComposablePartDefinition&lt;/em&gt; instances. The initial collection is the collection of exports from the &lt;u&gt;intercepted catalog&lt;/u&gt;. Because the method returns the collection of matching exports, we can filter out the original exports we don’t want to show up, or what is more interesting, we can add our own export definitions!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Known limitations&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Although support for open-generics in MefContrib is pretty amazing, it is not perfect. The first and probably the biggest limitation is the lack of support for recomposition. The other problem is that type being imported is inferred from the language construct rather than the import itself. Consider the following two imports.&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[Import]&lt;br /&gt;public IRepository&amp;lt;Order&amp;gt; OrderRepository { get; set; }&lt;br /&gt;&lt;br /&gt;[Import(typeof(IRepository&amp;lt;Order&amp;gt;))]&lt;br /&gt;public object OrderRepository { get; set; }&lt;/pre&gt;&lt;p&gt;Both imports are perfectly legal. But only the former works as expected. This is because the type being imported is inferred from the property’s type, which is IRepository&amp;lt;Order&amp;gt;. In the latter example, the contract type is explicitly given in the &lt;em&gt;Import&lt;/em&gt; attribute, but the property’s type is &lt;em&gt;object&lt;/em&gt;, hence the inferred type will be &lt;em&gt;object&lt;/em&gt;, which is not the case. You may want to know why is that. As you probably know, the import in MEF is represented by the &lt;em&gt;ImportDefinition&lt;/em&gt; class. Unfortunately, it is NOT possible to get the &lt;em&gt;Type&lt;/em&gt; instance representing the import from the &lt;em&gt;ImportDefinition&lt;/em&gt; instance, only the defining construct (like property, field, etc.) and only for those &lt;em&gt;ImportDefinition&lt;/em&gt; instances created by MEF’s &lt;u&gt;Reflection Model&lt;/u&gt;.&lt;/p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;div&gt;&lt;strong&gt;&lt;/strong&gt;&lt;b&gt;&lt;br /&gt;&lt;/b&gt;In this post I have presented MefContrib’s approach to enable open-generic type composition. Hope you like it!  &lt;/div&gt;</description><link>http://pwlodek.blogspot.com/2010/12/introduction-to-interceptingcatalog.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-3205336749996714179</guid><pubDate>Tue, 14 Dec 2010 22:36:00 +0000</pubDate><atom:updated>2010-12-14T23:36:50.248+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ITAD</category><category domain="http://www.blogger.com/atom/ns#">KGD.NET</category><category domain="http://www.blogger.com/atom/ns#">MEF</category><title>MEF Deep Dive Talk</title><description>&lt;p&gt;Recently, I gave 2 talks about Managed Extensibility Framework. One on &lt;a href=&quot;http://ms-groups.pl/kgd.net/default.aspx&quot; target=&quot;_blank&quot;&gt;KGD.NET&lt;/a&gt;, which is our local .NET group (on Nov 24th 2010), and one on IT Academic Day at &lt;a href=&quot;http://www.uj.edu.pl/&quot; target=&quot;_blank&quot;&gt;Uniwersytet Jagielloński&lt;/a&gt; in Kraków (Dec 14th 2010). Both of my talks went good! I do enjoy spreading knowledge about MEF and MefContrib! When it comes to the presentations, both were mostly the same, although on ITAD I was speaking more about MEF itself and less about hard stuff, so it was kind a MEF Deep Dive Light Edition =) I covered the following:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Basics of developing loosely coupled components&lt;/li&gt;    &lt;li&gt;MEF basics (parts, exports, imports, composition)&lt;/li&gt;    &lt;li&gt;Catalogs&lt;/li&gt;    &lt;li&gt;Metadata&lt;/li&gt;    &lt;li&gt;Custom export attributes&lt;/li&gt;    &lt;li&gt;Recomposition&lt;/li&gt;    &lt;li&gt;Stable composition&lt;/li&gt;    &lt;li&gt;Debugging MEF&lt;/li&gt;    &lt;li&gt;MefContrib&lt;/li&gt;    &lt;li&gt;MEF Extensibility&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;You can find all the materials (slides + source code) from the KGD.NET meeting &lt;a href=&quot;http://cid-bd15edd4d52f5329.office.live.com/self.aspx/Public/KGD.NET^_Mef-DeepDive.zip&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt; and from the ITAD &lt;a href=&quot;http://cid-bd15edd4d52f5329.office.live.com/self.aspx/Public/ITAD-UJ-Mef-Deep-Dive.zip&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. If you haven’t attended any of the talks, you might still want to go through the slides (these are nice!) and run the demos (VS 2010). Finally, I want thank &lt;a href=&quot;http://mtaulty.com/communityserver/blogs/mike_taultys_blog/default.aspx&quot; target=&quot;_blank&quot;&gt;Mike Taulty&lt;/a&gt; for letting me use some of the slides from his MEF talk =)&lt;/p&gt;  </description><link>http://pwlodek.blogspot.com/2010/12/mef-deep-dive-talk.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-4964815024463078474</guid><pubDate>Sat, 04 Dec 2010 18:22:00 +0000</pubDate><atom:updated>2010-12-04T19:30:30.720+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>MatrixAnimation for WPF</title><description>&lt;p&gt;Windows Presentation Foundation has a powerful animation system. It comes with various classes which enable dependency properties’ values to be animated, i.e. to be automatically changed during a given period of time. WPF supports four types of animations:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Linear animation – a value of a property linearly changes from a starting value (referred as &lt;em&gt;From&lt;/em&gt;) to a destination value (referred as &lt;em&gt;To&lt;/em&gt;). &lt;/li&gt;    &lt;li&gt;Key frame animation – animation is specified using key frames, each key frame specifies the &lt;em&gt;time&lt;/em&gt; and the desired value. The animated property will be assigned once the timeline hits the give &lt;em&gt;time.&lt;/em&gt; &lt;/li&gt;    &lt;li&gt;Path-based animation – property value is given by a geometric path. &lt;/li&gt;    &lt;li&gt;Frame-based animation – this is the most powerful animation approach, the &lt;strong&gt;CompositionTarget&lt;/strong&gt; class is used to create custom animations based on a per-frame callback. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The first three animation types are supported by &lt;em&gt;&amp;lt;Type&amp;gt;Animation&lt;/em&gt;, &lt;em&gt;&amp;lt;Type&amp;gt;AnimationUsingKeyFrames&lt;/em&gt; and &lt;em&gt;&amp;lt;Type&amp;gt;AnimationUsingPath&lt;/em&gt; classes, respectively. For example, consider the &lt;strong&gt;double&lt;/strong&gt; type. Its animation is supported by DoubleAnimation, Double&lt;em&gt;AnimationUsingKeyFrames&lt;/em&gt; and Double&lt;em&gt;AnimationUsingPath&lt;/em&gt; classes.&lt;/p&gt;  &lt;p&gt;WPF also supports matrix animations. However, out of the box, only key frame and path-based animations are supported for the &lt;strong&gt;Matrix&lt;/strong&gt; type. This post introduces &lt;strong&gt;MatrixAnimation&lt;/strong&gt; class, which performs linear, &lt;u&gt;smooth&lt;/u&gt; animation of the Matrix type. The animation supports translation, scaling and rotation along with easing functions. The following 14 sec-length video shows an early preview of a multi-touch MDI interface whose windows are being animated using the &lt;strong&gt;MatrixAnimation&lt;/strong&gt; class.&lt;/p&gt;  &lt;p&gt;&lt;iframe height=&quot;300&quot; src=&quot;http://player.vimeo.com/video/17469496?portrait=0&quot; frameborder=&quot;0&quot; width=&quot;400&quot;&gt;&lt;/iframe&gt;&lt;/p&gt; The following code snippet represents the MatrixAnimation class.   &lt;pre class=&quot;brush: c-sharp&quot;&gt;public class MatrixAnimation : MatrixAnimationBase&lt;br /&gt;{&lt;br /&gt;    public Matrix? From&lt;br /&gt;    {&lt;br /&gt;        set { SetValue(FromProperty, value); }&lt;br /&gt;        get { return (Matrix)GetValue(FromProperty); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static DependencyProperty FromProperty =&lt;br /&gt;        DependencyProperty.Register(&amp;quot;From&amp;quot;, typeof(Matrix?), typeof(MatrixAnimation),&lt;br /&gt;            new PropertyMetadata(null));&lt;br /&gt;&lt;br /&gt;    public Matrix? To&lt;br /&gt;    {&lt;br /&gt;        set { SetValue(ToProperty, value); }&lt;br /&gt;        get { return (Matrix)GetValue(ToProperty); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static DependencyProperty ToProperty =&lt;br /&gt;        DependencyProperty.Register(&amp;quot;To&amp;quot;, typeof(Matrix?), typeof(MatrixAnimation),&lt;br /&gt;            new PropertyMetadata(null));&lt;br /&gt;&lt;br /&gt;    public IEasingFunction EasingFunction&lt;br /&gt;    {&lt;br /&gt;        get { return (IEasingFunction)GetValue(EasingFunctionProperty); }&lt;br /&gt;        set { SetValue(EasingFunctionProperty, value); }&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static readonly DependencyProperty EasingFunctionProperty =&lt;br /&gt;        DependencyProperty.Register(&amp;quot;EasingFunction&amp;quot;, typeof(IEasingFunction), typeof(MatrixAnimation),&lt;br /&gt;            new UIPropertyMetadata(null));&lt;br /&gt;&lt;br /&gt;    public MatrixAnimation()&lt;br /&gt;    {&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public MatrixAnimation(Matrix toValue, Duration duration)&lt;br /&gt;    {&lt;br /&gt;        To = toValue;&lt;br /&gt;        Duration = duration;&lt;br /&gt;    }&lt;br /&gt;        &lt;br /&gt;    public MatrixAnimation(Matrix toValue, Duration duration, FillBehavior fillBehavior)&lt;br /&gt;    {&lt;br /&gt;        To = toValue;&lt;br /&gt;        Duration = duration;&lt;br /&gt;        FillBehavior = fillBehavior;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public MatrixAnimation(Matrix fromValue, Matrix toValue, Duration duration)&lt;br /&gt;    {&lt;br /&gt;        From = fromValue;&lt;br /&gt;        To = toValue;&lt;br /&gt;        Duration = duration;&lt;br /&gt;    }&lt;br /&gt;        &lt;br /&gt;    public MatrixAnimation(Matrix fromValue, Matrix toValue, Duration duration, FillBehavior fillBehavior)&lt;br /&gt;    {&lt;br /&gt;        From = fromValue;&lt;br /&gt;        To = toValue;&lt;br /&gt;        Duration = duration;&lt;br /&gt;        FillBehavior = fillBehavior;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected override Freezable CreateInstanceCore()&lt;br /&gt;    {&lt;br /&gt;        return new MatrixAnimation();&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    protected override Matrix GetCurrentValueCore(Matrix defaultOriginValue, Matrix defaultDestinationValue, AnimationClock animationClock)&lt;br /&gt;    {&lt;br /&gt;        if (animationClock.CurrentProgress == null)&lt;br /&gt;        {&lt;br /&gt;            return Matrix.Identity;&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        var normalizedTime = animationClock.CurrentProgress.Value;&lt;br /&gt;        if (EasingFunction != null)&lt;br /&gt;        {&lt;br /&gt;            normalizedTime = EasingFunction.Ease(normalizedTime);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        var from = From ?? defaultOriginValue;&lt;br /&gt;        var to = To ?? defaultDestinationValue;&lt;br /&gt;&lt;br /&gt;        var newMatrix = new Matrix(&lt;br /&gt;                ((to.M11 - from.M11) * normalizedTime) + from.M11,&lt;br /&gt;                ((to.M12 - from.M12) * normalizedTime) + from.M12,&lt;br /&gt;                ((to.M21 - from.M21) * normalizedTime) + from.M21,&lt;br /&gt;                ((to.M22 - from.M22) * normalizedTime) + from.M22,&lt;br /&gt;                ((to.OffsetX - from.OffsetX) * normalizedTime) + from.OffsetX,&lt;br /&gt;                ((to.OffsetY - from.OffsetY) * normalizedTime) + from.OffsetY);&lt;br /&gt;&lt;br /&gt;        return newMatrix;&lt;br /&gt;    }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The code is actually quite simple. The class is derived from the abstract &lt;strong&gt;MatrixAnimationBase&lt;/strong&gt; class. Firstly, three dependency properties are defined, namely &lt;em&gt;From&lt;/em&gt;, &lt;em&gt;To&lt;/em&gt; and &lt;em&gt;EasingFunction&lt;/em&gt;. Next comes a bunch of useful constructors. The interesting part resides in the &lt;em&gt;GetCurrentValueCore&lt;/em&gt; method. At first, the current animation time is retrieved. Also, the animation time is eased with the easing function if it is available. Lastly, new matrix is calculated based on the &lt;em&gt;From&lt;/em&gt; and &lt;em&gt;To&lt;/em&gt; values. Each matrix cell is linearly scaled with the time value. And that’s it! This provides smooth animation for the matrix type!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;  </description><link>http://pwlodek.blogspot.com/2010/12/matrixanimation-for-wpf.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>7</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-9220414909596258307</guid><pubDate>Tue, 09 Nov 2010 20:16:00 +0000</pubDate><atom:updated>2011-03-09T16:02:52.511+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>Introduction to InterceptingCatalog – Part I</title><description>&lt;p&gt;Managed Extensibility Framework uses the concept of catalogs. A single catalog is responsible for providing access to parts, which are mostly components in the system (ordinary .NET classes). I said mostly because MEF is not limited to operating on types, it also supports method, property and field composition. The catalog is then used by the &lt;em&gt;CompositionContainer&lt;/em&gt; to pull parts from it. Out of the box MEF ships with 4 core catalogs, which are meant to discover attributed parts (an attributed part is simply a component which uses attributed programming model for discovery purposes). These catalogs are TypeCatalog, DirectoryCatalog, AssemblyCatalog, and AggregateCatalog. Catalogs serve one other crucial purpose – they are responsible for instantiating parts. The thing is that the underlying infrastructure (aka Reflection Model) responsible for that process is hidden from the developer and it is not possible to attach anything to the creation pipeline. People who just begin their MEF adventure might feel a little disappointed at first, because all of the IoC containers available today provide neat infrastructure for integrating custom build strategies into the creation pipeline. Furthermore, some of them, support interception out of the box (like the &lt;a href=&quot;http://unity.codeplex.com/&quot;&gt;Unity&lt;/a&gt; container from MS Patterns &amp;amp; Practices).&lt;/p&gt;  &lt;p&gt;The &lt;em&gt;InterceptingCatalog&lt;/em&gt;, initially written by &lt;a href=&quot;http://blogs.msdn.com/b/gblock/&quot;&gt;Glenn Block&lt;/a&gt;, has been introduced to fix this gap. It provides a convenient mechanism which allows to intercept values exported via MEF, it allows to chain interceptors together to form custom instance processing pipeline (&lt;em&gt;Chain of Responsibility&lt;/em&gt; design pattern). The catalog also enables to create exports on the fly (which is used to provide open-generics support for MEF) and to filter existing exports based on some criteria. The catalog itself has been built around the &lt;em&gt;Decorator&lt;/em&gt; pattern – it decorates any &lt;em&gt;ComposablePartCatalog&lt;/em&gt;. You can find it in the &lt;strong&gt;MefContrib&lt;/strong&gt; project available at &lt;a href=&quot;http://www.mefcontrib.com/&quot; target=&quot;_blank&quot;&gt;mefcontrib.com&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;In this series of posts I am going to discuss all the benefits of using the &lt;em&gt;InterceptingCatalog&lt;/em&gt;. In the first part I will focus on intercepting capabilities of the catalog, and in subsequent posts I will cover filtering scenario and show how to enable the open-generics support.&lt;/p&gt;  &lt;h4&gt;Interception&lt;/h4&gt; Let’s begin with a simple example and then build on top of it. Assume we have &lt;em&gt;IStartable&lt;/em&gt; interface defined as follows:   &lt;pre class=&quot;brush: c-sharp&quot;&gt;public interface IStartable&lt;br /&gt;{&lt;br /&gt;   bool IsStarted { get; }&lt;br /&gt;&lt;br /&gt;   void Start();&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;We want every component, which implements the &lt;em&gt;IStartable&lt;/em&gt; interface, have its &lt;em&gt;Start&lt;/em&gt; method automatically called by the IoC container as part of the creation process. First, lets investigate the solution on the &lt;em&gt;Unity&lt;/em&gt; IoC example. Note that the interception term does not apply to the Unity solution as the Unity fully supports custom build strategies =)&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class MyExtension : UnityContainerExtension&lt;br /&gt;{&lt;br /&gt;   protected override void Initialize()&lt;br /&gt;   {&lt;br /&gt;       Context.Strategies.AddNew&amp;lt;StartableStrategy&amp;gt;(UnityBuildStage.Initialization);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public class StartableStrategy : BuilderStrategy&lt;br /&gt;   {&lt;br /&gt;       public override void PreBuildUp(IBuilderContext context)&lt;br /&gt;       {&lt;br /&gt;           var instance = context.Existing as IStartable;&lt;br /&gt;           if (instance != null)&lt;br /&gt;           {&lt;br /&gt;               instance.Start();&lt;br /&gt;           }&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The code is dead simple. We define our own extension named &lt;em&gt;MyExtension&lt;/em&gt;, which does nothing more than registering the &lt;em&gt;StartableStrategy&lt;/em&gt; during the instance initialization phase. The inner &lt;em&gt;StartableStrategy&lt;/em&gt; does all the job - if the instance being created implements &lt;em&gt;IStartable&lt;/em&gt;, it calls its &lt;em&gt;Start&lt;/em&gt; method. The usage is also pretty straightforward. All we have to do is to add &lt;em&gt;MyExtension&lt;/em&gt; to the container!&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;IUnityContainer container = new UnityContainer();&lt;br /&gt;container.AddNewExtension&amp;lt;MyExtension&amp;gt;();&lt;br /&gt;&lt;br /&gt;var foo = container.Resolve&amp;lt;StartableFoo&amp;gt;();&lt;br /&gt;Console.WriteLine(foo.IsStarted); // Prints True&lt;/pre&gt;&lt;br /&gt;Assuming that the &lt;em&gt;StartableFoo&lt;/em&gt; part implements the &lt;em&gt;IStartable&lt;/em&gt; interface, it will have its &lt;em&gt;Start&lt;/em&gt; method called during the &lt;em&gt;Resolve&lt;/em&gt; method call. Now let&#39;s look at how this scenario could be implemented in MEF. As I stated previously, MEF doesn&#39;t allow the developer to register custom build strategies within the build process. Hence, we need to use interception. This is where the &lt;em&gt;InterceptingCatalog&lt;/em&gt; comes to play. To use the InterceptingCatalog, we first need to create proper configuration. The configuration is provided by means of InterceptionConfiguration class:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class InterceptionConfiguration : IInterceptionConfiguration&lt;br /&gt;{&lt;br /&gt;   public InterceptionConfiguration AddInterceptor(IExportedValueInterceptor interceptor);&lt;br /&gt;   public InterceptionConfiguration AddHandler(IExportHandler handler);&lt;br /&gt;   public InterceptionConfiguration AddInterceptionCriteria(IPartInterceptionCriteria partInterceptionCriteria);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In this example we are interested in the &lt;em&gt;AddInterceptor&lt;/em&gt; and &lt;em&gt;AddInterceptionCriteria&lt;/em&gt; methods which add interceptors to the catalog. The two methods correspond to two interception levels supported by the catalog. The first is the &lt;u&gt;catalog wide interception level&lt;/u&gt;. Interceptors registered on this level are applied to all parts available in the decorated catalog. The second level is the &lt;u&gt;per part interception level&lt;/u&gt;. Interceptors registered on that level apply only to selected parts, and the developer specifies to which parts the interceptor should be applied by specifying a predicate which accepts &lt;em&gt;ComposablePartDefinition&lt;/em&gt; and returns &lt;em&gt;bool&lt;/em&gt;. Next example will show this in action. Meanwhile, this is how our &lt;em&gt;StartableStrategy&lt;/em&gt; might look like:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class StartableStrategy : IExportedValueInterceptor&lt;br /&gt;{&lt;br /&gt;   public object Intercept(object value)&lt;br /&gt;   {&lt;br /&gt;       var startable = value as IStartable;&lt;br /&gt;       if (startable != null)&lt;br /&gt;       {&lt;br /&gt;           startable.Start();&lt;br /&gt;       }&lt;br /&gt;&lt;br /&gt;       return value;&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;As you can see, all interceptors have to implement the &lt;em&gt;IExportedValueInterceptor&lt;/em&gt; interface, which defines single &lt;em&gt;Intercept&lt;/em&gt; method. The method gets called as soon as the exported value is requested, and the value itself is passed as the parameter. To demonstrate the usage, we will use two parts, namely &lt;em&gt;IFoo&lt;/em&gt; and &lt;em&gt;IBar&lt;/em&gt;. The &lt;em&gt;IBar&lt;/em&gt; part is defined as follows:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public interface IBar&lt;br /&gt;{&lt;br /&gt;   void Foo();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Export(typeof(IBar))]&lt;br /&gt;public class Bar : IBar, IStartable&lt;br /&gt;{&lt;br /&gt;   public Bar()&lt;br /&gt;   {&lt;br /&gt;       Console.WriteLine(&quot;Bar()&quot;);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public bool IsStarted { get; private set; }&lt;br /&gt;&lt;br /&gt;   public void Start()&lt;br /&gt;   {&lt;br /&gt;       IsStarted = true;&lt;br /&gt;       Console.WriteLine(&quot;Bar.Start()&quot;);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public void Foo()&lt;br /&gt;   {&lt;br /&gt;       Console.WriteLine(&quot;Bar.Foo()&quot;);&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The code which uses the &lt;em&gt;StartableStrategy&lt;/em&gt; is also very simple.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;// Create the catalog which will be intercepted&lt;br /&gt;var catalog = new TypeCatalog(typeof(Bar), typeof(Foo));&lt;br /&gt;&lt;br /&gt;// Create interception configuration&lt;br /&gt;var cfg = new InterceptionConfiguration()&lt;br /&gt;&lt;br /&gt;   // Add catalog wide startable interceptor&lt;br /&gt;   .AddInterceptor(new StartableStrategy());&lt;br /&gt;&lt;br /&gt;// Create the InterceptingCatalog with above configuration&lt;br /&gt;var interceptingCatalog = new InterceptingCatalog(catalog, cfg);&lt;br /&gt;          &lt;br /&gt;// Create the container&lt;br /&gt;var container = new CompositionContainer(interceptingCatalog);&lt;br /&gt;&lt;br /&gt;var barPart = container.GetExportedValue&amp;lt;IBar&amp;gt;();&lt;/pre&gt;&lt;br /&gt;Because the &lt;em&gt;IBar&lt;/em&gt; part implements the &lt;em&gt;IStartable&lt;/em&gt; interface, it will have its &lt;em&gt;Start&lt;/em&gt; method called as part of &lt;em&gt;GetExportedValue&lt;/em&gt; call. This example concludes the basics of using &lt;em&gt;InterceptingCatalog&lt;/em&gt;. Lets move on to the next interception example which uses &lt;em&gt;Castle.DynamicProxy&lt;/em&gt; to create proxies for objects. We will add logging capabilities to the &lt;em&gt;IFoo&lt;/em&gt; part. We do not want to log method execution on the &lt;em&gt;IBar&lt;/em&gt; part, so we are going to leverage the &lt;u&gt;per part interception&lt;/u&gt;. The &lt;em&gt;IFoo&lt;/em&gt; part looks identical to the &lt;em&gt;IBar&lt;/em&gt; part, except it is decorated with &lt;em&gt;ExportMetadata&lt;/em&gt; attribute, which tells the system that we want to log method execution on that part.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public interface IFoo&lt;br /&gt;{&lt;br /&gt;   void Bar();&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Export(typeof(IFoo))]&lt;br /&gt;[ExportMetadata(&quot;Log&quot;, true)]&lt;br /&gt;public class Foo : IFoo, IStartable&lt;br /&gt;{&lt;br /&gt;   public Foo()&lt;br /&gt;   {&lt;br /&gt;       Console.WriteLine(&quot;Foo()&quot;);&lt;br /&gt;   }&lt;br /&gt;      &lt;br /&gt;   public bool IsStarted { get; private set; }&lt;br /&gt;&lt;br /&gt;   public void Bar()&lt;br /&gt;   {&lt;br /&gt;       Console.WriteLine(&quot;Foo.Bar()&quot;);&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   public void Start()&lt;br /&gt;   {&lt;br /&gt;       IsStarted = true;&lt;br /&gt;       Console.WriteLine(&quot;Foo.Start()&quot;);&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Next comes the logging interceptor which implements Castle&#39;s IInterceptor interface.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class LoggingInterceptor : IInterceptor&lt;br /&gt;{&lt;br /&gt;   public void Intercept(IInvocation invocation)&lt;br /&gt;   {&lt;br /&gt;       Console.WriteLine(&quot;--- LOG: About to invoke [{0}] on [{1}] ---&quot;,&lt;br /&gt;           invocation.Method.Name,&lt;br /&gt;           invocation.InvocationTarget.GetType().Name);&lt;br /&gt;&lt;br /&gt;       // Invoke the intercepted method&lt;br /&gt;       invocation.Proceed();&lt;br /&gt;          &lt;br /&gt;       Console.WriteLine(&quot;--- LOG: Invoked [{0}] ---&quot;, invocation.Method.Name);&lt;br /&gt;   }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The interceptor simply prints information to the console before and after a method execution. The code which puts this sample together is almost a copy of the previous bootstrapping code:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;var catalog = new TypeCatalog(typeof(Bar), typeof(Foo));&lt;br /&gt;&lt;br /&gt;// Create interception configuration&lt;br /&gt;var cfg = new InterceptionConfiguration()&lt;br /&gt;&lt;br /&gt;   // Add Castle DynamicProxy based logging interceptor for parts&lt;br /&gt;   // which we want to be logged&lt;br /&gt;   .AddInterceptionCriteria(&lt;br /&gt;       new PredicateInterceptionCriteria(&lt;br /&gt;           new DynamicProxyInterceptor(new LoggingInterceptor()), def =&amp;gt;&lt;br /&gt;               def.ExportDefinitions.First().Metadata.ContainsKey(&quot;Log&quot;) &amp;amp;&amp;amp;&lt;br /&gt;               def.ExportDefinitions.First().Metadata[&quot;Log&quot;].Equals(true)));&lt;br /&gt;&lt;br /&gt;// Create the InterceptingCatalog with above configuration&lt;br /&gt;var interceptingCatalog = new InterceptingCatalog(catalog, cfg);&lt;br /&gt;          &lt;br /&gt;// Create the container&lt;br /&gt;var container = new CompositionContainer(interceptingCatalog);&lt;br /&gt;&lt;br /&gt;var barPart = container.GetExportedValue&amp;lt;IBar&amp;gt;();&lt;br /&gt;barPart.Foo();&lt;br /&gt;&lt;br /&gt;var fooPart = container.GetExportedValue&amp;lt;IFoo&amp;gt;();&lt;br /&gt;fooPart.Bar();&lt;/pre&gt;&lt;br /&gt;Because we wanted to apply the logging interceptor on a per part basis, we use the &lt;em&gt;AddInterceptionCriteria&lt;/em&gt; method, and pass the &lt;em&gt;PredicateInterceptionCriteria&lt;/em&gt; instance. The &lt;em&gt;PredicateInterceptionCriteria&lt;/em&gt; object takes any instance implementing the &lt;em&gt;IExportedValueInterceptor&lt;/em&gt; interface along with a predicate which is used to determine which parts should be intercepted with the given interceptor. In the above example we intercept all parts declaring &lt;u&gt;Export metadata&lt;/u&gt; named &lt;em&gt;Log&lt;/em&gt; which equals to &lt;em&gt;True&lt;/em&gt;. Note that our logging interceptor is based on &lt;em&gt;Castle.DynamicProxy&lt;/em&gt;. To use it with the catalog, we need to wrap it with &lt;em&gt;DynamicProxyInterceptor&lt;/em&gt; which implements &lt;em&gt;IExportedValueInterceptor&lt;/em&gt; and can take any number of &lt;em&gt;IInterceptor&lt;/em&gt; implementations. The sample produces the following output:&lt;br /&gt;&lt;br /&gt;&lt;p&gt; &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtjaOFehTCHt_t1Zaxj1mRw2rRpWS8BG9-saXTma8vmE6MPtFrGZyeWIe75GyulwXnQrn6I_vJ8sal6poLO64w3RbHfL1D6o_WtjHXSMuI5ojs2LkNa6LCCDkhOjWqn3UTrxMF4em1gOfp/s1600-h/Interception3.png&quot;&gt;&lt;img style=&quot;background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px&quot; title=&quot;Interception&quot; border=&quot;0&quot; alt=&quot;Interception&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIuLz5EjeyOwkPIrIywD4pIKmI5DucxY-poS77eP5watHA_evWYARckmU0rk22oY76u-LoiLRvkrOuNIam_cb-kcY0PQVREG4c-YdTA_ik3ZBH1amzPwCLqQcyCyOH-myzWqIue81LzrfD/?imgmax=800&quot; width=&quot;351&quot; height=&quot;133&quot; /&gt;&lt;/a&gt; &lt;/p&gt;&lt;br /&gt;You can see that indeed the logging interceptor has only been applied to the &lt;em&gt;IFoo&lt;/em&gt; part. Please note also that the IFoo has actually been intercepted by a chain of two interceptors, the &lt;em&gt;StartableStartegy&lt;/em&gt; and the &lt;em&gt;LoggingInterceptor&lt;/em&gt; (although the above sample code omits the first one for clarity). This forms a processing pipeline similar to pipelines found in regular IoC containers. This is all about interception in MEF. You can download sample code from my code gallery &lt;a href=&quot;http://github.com/downloads/pwlodek/CodeGallery/MefContribDemo.zip&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. In the next post I will look at filtering capabilities. Stay tuned!</description><link>http://pwlodek.blogspot.com/2010/11/introduction-to-interceptingcatalog.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIuLz5EjeyOwkPIrIywD4pIKmI5DucxY-poS77eP5watHA_evWYARckmU0rk22oY76u-LoiLRvkrOuNIam_cb-kcY0PQVREG4c-YdTA_ik3ZBH1amzPwCLqQcyCyOH-myzWqIue81LzrfD/s72-c?imgmax=800" height="72" width="72"/><thr:total>5</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-8467771503097225930</guid><pubDate>Sat, 16 Oct 2010 18:50:00 +0000</pubDate><atom:updated>2010-10-16T20:58:42.243+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">MefContrib</category><title>MEF + Object Factories using Export Provider</title><description>&lt;p&gt;MEF is a great composition platform. It is great because the power and flexibility it delivers, and at the same time, the learning curve is low. When it comes to part registration, MEF out of the box supports so called attributed programming model, which allows the discoverability simply by applying &lt;strong&gt;Export&lt;/strong&gt; attributes on the parts we want to make available to the world, and &lt;strong&gt;Import&lt;/strong&gt; attributes on the parts which need to consume other parts. However, using this default programming model, the developer has &lt;u&gt;no way&lt;/u&gt; of introducing any build strategies which get executed during part’s creation when a concrete part is requested. This concept, know as &lt;em&gt;Chain of Responsibility&lt;/em&gt; design pattern, is implemented by many (if not all) dependency injection containers. Most of them allow the developer to add new actions which are executed as part of object creation. Sadly enough, there’s no such facility in MEF. This implies yet another limitation – lack of support for custom object factories. This means it is always MEF who creates parts’ instances.&lt;/p&gt;  &lt;p&gt;Luckily, MEF is extensible. It allows to develop completely new programming models by implementing custom catalogs (like the &lt;strong&gt;ConventionCatalog&lt;/strong&gt; which is a part of &lt;a href=&quot;http://mefcontrib.com/&quot;&gt;MefContrib&lt;/a&gt;). It also enables the developers to implement custom export providers, whose role it to provide exports from various sources =) In this post I am going to introduce the &lt;strong&gt;FactoryExportProvider&lt;/strong&gt; which extends MEF by allowing to define object factories. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Introducing Custom Factories&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;When you want co take control over instance creation in MEF, you basically have two options. Either create part manually and then call &lt;em&gt;ComposeExportedValue&lt;/em&gt; method on that part as presented on the following listing&lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;var component = new ExternalComponent2();&lt;br /&gt;container.ComposeExportedValue(component);&lt;/pre&gt;&lt;p&gt;or use property export as presented below.&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[Export]&lt;br /&gt;public IExternalComponent Component1&lt;br /&gt;{&lt;br /&gt;  get&lt;br /&gt;  {&lt;br /&gt;      return new ExternalComponent3(/* Constructor Initialization */);&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;p&gt;The first solution, however, is not very elegant. It also registers new part as singleton. The second one is better, but still the part will be created only once, and reused across many requests. Also note that in both solutions, a problem arises when it comes to injecting target part’s constructor – we don’t have access to the container so we can’t pull required parts from it. Of course we could get a reference to the container, but doing so only for this purpose will make the code more sloppy.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Meet FactoryExportProvider&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;The FactoryExportProvider is an elegant solution to the outlined problems. Consider the following sample code:&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;var provider = new FactoryExportProvider()&lt;br /&gt;  .RegisterInstance&amp;lt;IExternalComponent&amp;gt;(ep =&amp;gt; new ExternalComponent2())&lt;br /&gt;  .Register&amp;lt;IExternalComponent&amp;gt;(&quot;part4&quot;, ep =&amp;gt; new ExternalComponent4(&lt;br /&gt;                                                  ep.GetExportedValue&amp;lt;IExternalComponent&amp;gt;(),&lt;br /&gt;                                                  ep.GetExportedValue&amp;lt;IMefComponent&amp;gt;()));&lt;br /&gt;&lt;br /&gt;var container = new CompositionContainer(anyCatalog, provider);&lt;br /&gt;provider.SourceProvider = container;&lt;/pre&gt;&lt;p&gt;You can clearly see two parts being registered, both with the same interface. The first one is registered as a singleton (shared in MEF), but more interestingly, the second is registered as transient (non shared in MEF) and will be created each time the part is requested. As part of the registration process, a factory method should be passed (this is not required, read on to find out why) which is responsible for delivering instances. Note also an elegant, though widely adapted, solution to resolving complex constructors. In the example, the &lt;em&gt;ExternalComponent4&lt;/em&gt; has a dependency on &lt;em&gt;IExternalComponent&lt;/em&gt; and &lt;em&gt;IMefComponent&lt;/em&gt; parts. However, thanks to the fact that the resolution method has access to the source provider (&lt;em&gt;ExportProvider&lt;/em&gt; instance), we can use it to satisfy additional imports. Just remember to set &lt;em&gt;SourceProvider&lt;/em&gt; property of the &lt;i&gt;FactoryExportProvider&lt;/i&gt; to something meaningful (at least to the &lt;em&gt;FactoryExportProvider&lt;/em&gt; instance itself as the &lt;em&gt;SourceProvider&lt;/em&gt; is null by default). More common is to set it to the &lt;em&gt;CompositionContainer&lt;/em&gt; instance.&lt;/p&gt;&lt;p&gt;&lt;em&gt;FactoryExportProvider&lt;/em&gt; is quite flexible. It allows to register a fallback factory method which gets executed whenever part is registered without supplying the factory method enabling to design single resolution method for a subset or all parts registered in the factory. See the following example.&lt;/p&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;private static object FactoryMethod1(Type type, string registrationName)&lt;br /&gt;{&lt;br /&gt;  if (type == typeof(IExternalComponent) &amp;amp;&amp;amp; registrationName == null)&lt;br /&gt;      return new ExternalComponent1();&lt;br /&gt;&lt;br /&gt;  if (type == typeof(IExternalComponent) &amp;amp;&amp;amp; registrationName == &quot;external2&quot;)&lt;br /&gt;      return new ExternalComponent2();&lt;br /&gt;&lt;br /&gt;  return null;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var provider = new FactoryExportProvider(FactoryMethod1);&lt;br /&gt;var container = new CompositionContainer(someCatalog, provider);&lt;br /&gt;&lt;br /&gt;// Registration&lt;br /&gt;provider.Register(typeof(IExternalComponent));&lt;br /&gt;provider.Register(typeof(IExternalComponent), &quot;external2&quot;);&lt;/pre&gt;&lt;p&gt;The code presented in this post is available as part of &lt;a href=&quot;http://mefcontrib.com/&quot;&gt;MefContrib&lt;/a&gt; Project. Latest version is available on my &lt;a href=&quot;http://github.com/pwlodek/MefContrib&quot;&gt;fork&lt;/a&gt;. In the coming days I will push it to the &lt;a href=&quot;http://github.com/MefContrib/MefContrib&quot;&gt;main repo&lt;/a&gt; though! This export provider is also used by IoC plumbing infrastructure, which is also part of &lt;a href=&quot;http://mefcontrib.com/&quot;&gt;MefContrib&lt;/a&gt; Project, which enables integration of IoC and MEF. I blogged about particular implementations for Unity container &lt;a href=&quot;http://pwlodek.blogspot.com/2009/05/unity-mef-integration-layer.html&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://pwlodek.blogspot.com/2009/08/improved-mef-unity-integration-layer.html&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Hope you like it!&lt;/p&gt;</description><link>http://pwlodek.blogspot.com/2010/10/mef-object-factories-using-export.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-2357942848061013761</guid><pubDate>Sat, 04 Sep 2010 17:19:00 +0000</pubDate><atom:updated>2010-11-14T23:28:20.662+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Git</category><title>Git on Windows with Console and PowerShell</title><description>&lt;p&gt;Windows people like to do everything on their computers using GUI tools and WYSIWYG editors. And nothing is wrong with that. Personally, I like this approach – it conserves time while giving fast access to the most used options of a given tool (at least usually). Consider the SVN version control system. Initially, it was a console-based tool, but thanks to the great TortoiseSVN project, people may now forget about the command line. However, working with Git is different. Git was designed to be used from the command line, and using it in that way is a pure pleasure! Git commands are well crafted and easy to remember. If you are holding out on Git because it doesn’t give you the right GUI tools, you are holding out for a wrong reason.&lt;/p&gt;  &lt;p&gt;Git comes with a bash like prompt which is very powerful. However, there is one problem. The bash prompt is launched within the standard Windows command line, and as probably anyone knows, the command prompt on Windows is one, big misery. &lt;u&gt;So in this post I’m going to address this issue by showing how to set up a convenient command line environment for Git on Windows&lt;/u&gt;.&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Installing Git&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;Git can easily be installed on Windows. Head over to &lt;a href=&quot;http://code.google.com/p/msysgit/&quot;&gt;http://code.google.com/p/msysgit/&lt;/a&gt; and download &lt;a href=&quot;http://code.google.com/p/msysgit/downloads/detail?name=Git-1.7.0.2-preview20100309.exe&amp;amp;can=2&amp;amp;q=&quot;&gt;Git-1.7.0.2-preview20100309.exe&lt;/a&gt; which is the latest version of Git as of this writing. When the installer asks about [&lt;i&gt;Adjusting the PATH environment&lt;/i&gt;], select [&lt;i&gt;Run Git from the Windows Command Prompt&lt;/i&gt;]&lt;i&gt; &lt;/i&gt;as shown on the following screen.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9EPw2ir6XE0y9WCfioJGUgEYcd5HnCSf7JgqJkkxMa_hkXeeRhOtka_yQq_j1JSq4m8MT07EOOQXVJcP2NBUUa0RkMTkksx-rbA_2YvelCOhAtivMOxjMEVzYxqxqqJaUHJ3vWhDABT7m/s1600-h/clip_image001%5B6%5D.png&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto&quot; title=&quot;clip_image001&quot; border=&quot;0&quot; alt=&quot;clip_image001&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxzFueC9vIFSDK2gR28Ihyphenhyphen2gauDYCwYfc6YaRAmHiCNyudkWW0ybthEo0pzMPnsLyG1jMOT5o3xNn4RvW4ewxAiygkvrQ1xFm11cuqj_5ResyEDgikEDH6gwkn98wsY_E3SAetjzi5dXVt/?imgmax=800&quot; width=&quot;484&quot; height=&quot;381&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Selecting this option allows to use Git from different shells, like PowerShell. Now that Git is installed, we can open a command line and verify it’s there.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcycp6vMB0LO4_vZmcJwXbzGr6w9FCMDeWad6ay8q3391O-MkBz4QKI01s_2GAnD78cNu8bmWJCDi-ifIcLxapY7CHEFADPbiwCGzirp6FLH8Pql7J1LYjeZFEXtveXnqersQXmsCKDbic/s1600-h/clip_image003%5B4%5D.jpg&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto&quot; title=&quot;clip_image003&quot; border=&quot;0&quot; alt=&quot;clip_image003&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEha0HpHthBQV-MIg69jSGd2NQdADuSdomvfN7gH6xi_ZFXyqYHFDyjdugO4sbIW3MdVvoO_L7a0yGzknRW10KoI1O-DFCrljIpTozVwzJd3c1misvupCSq4CTUPCY9jQfw3_Cefiwg3zLk4/?imgmax=800&quot; width=&quot;484&quot; height=&quot;282&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;We can also right click any folder in the Windows Explorer and select &lt;em&gt;Git Bash Here&lt;/em&gt; – this will launch Git’s default bash shell.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsUsK809YjhQwgFqlyyCZG_je0ZHCBD0DiHDTJuGGjRd_NK_60a5luBr98IEXZwv9DsH2GSwVv8ognZZATOWEFlXGALUoDQbnv6pMwo9Z9Rnsj6qOdAPHjRg9Led56YEO-8mNoFqIJQITu/s1600-h/clip_image005%5B4%5D.jpg&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto&quot; title=&quot;clip_image005&quot; border=&quot;0&quot; alt=&quot;clip_image005&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRHSJRwXnwLIDI6KT_0W3qlrlpphbR-x8jvjr3VmSNoteh_jMjUte43h_fjnWAE4XZiyG3Hq_R2JSBPUCEPAmk40nASf7Y-La5eA5PDqXnNUkjp0YeAM3UFS4znsFoj67fuJtVneWiYAcv/?imgmax=800&quot; width=&quot;484&quot; height=&quot;282&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Installing Console&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;Now it’s time to get rid of the ugly prompts shown above. Head over to the &lt;a href=&quot;http://sourceforge.net/projects/console/&quot;&gt;http://sourceforge.net/projects/console/&lt;/a&gt; and download the latest version of the &lt;em&gt;Console&lt;/em&gt; project. Launch it, and go to &lt;b&gt;Edit-&amp;gt;Settings&lt;/b&gt;, select &lt;b&gt;Console&lt;/b&gt; from the tree on the left and pick up a new shell – the &lt;strong&gt;PoweShell&lt;/strong&gt;. Under Windows 7/2008, it is located at &lt;em&gt;%Windows_Dir%\System32\WindowsPowerShell\v1.0\powershell.exe&lt;/em&gt;. On previous versions of Windows, I believe it must be downloaded separately. Click &lt;em&gt;OK&lt;/em&gt; and close the &lt;em&gt;Console&lt;/em&gt;. Now launch it again, but this time with Administrator privileges, and issue the following command: [&lt;em&gt;Set-ExecutionPolicy Unrestricted&lt;/em&gt;]. This command will allow running custom PowerShell scripts, which is needed for Git integration. Now you have a working PowerShell within nice, tabbed environment. We’re almost there!&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Installing PoshGit&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;It’s time to enable PowerShell-Git integration. To do that, download &lt;em&gt;Posh-Git&lt;/em&gt; latest sources available at &lt;a href=&quot;http://github.com/dahlbyk/posh-git&quot;&gt;http://github.com/dahlbyk/posh-git&lt;/a&gt; and unpack them to %Sys_Drive%:\Users\%Login%\Documents\WindowsPowerShell. Change profile.example.ps1 to profile.ps1. Hurray! You have enabled Git integration! What does it give? When you are inside Git repository, the command prompt changes to show on which branch you are, and whether there are any modifications, and if there are any untracked files (via exclamation mark). To enable output coloring, issue the [&lt;i&gt;git config –global color.ui auto&lt;/i&gt;] command.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhnEgoCX5SfilF-IFCTVOKmv4DAAeBk21fdBU27niruBbf8Mf_iOYFYWGISyC_141yjWFpGBxYYwQIKa93cubYjk-T-cgyyAqABc7qc8fkG4yaDmPQ1Khd_7oFT31V-Kz4km4WO7XooDhVT/s1600-h/clip_image007%5B4%5D.jpg&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto&quot; title=&quot;clip_image007&quot; border=&quot;0&quot; alt=&quot;clip_image007&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWX6tOf_yyCZ68Ft1_RsS77APAUEbeiVMLWj6KmoGhS_UPTCjq2qA9t2aEKchYdsN-Rr8M77uEpyJCyqVKF6m_b99FUYU-CytXX3c4vGkIr3qHFQ42jRmRjuG9thiskzMMPYNEaRCpPGmP/?imgmax=800&quot; width=&quot;484&quot; height=&quot;276&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Enjoy your cool, command line interface for Git!&lt;/p&gt;  </description><link>http://pwlodek.blogspot.com/2010/09/git-on-windows-with-console-and.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxzFueC9vIFSDK2gR28Ihyphenhyphen2gauDYCwYfc6YaRAmHiCNyudkWW0ybthEo0pzMPnsLyG1jMOT5o3xNn4RvW4ewxAiygkvrQ1xFm11cuqj_5ResyEDgikEDH6gwkn98wsY_E3SAetjzi5dXVt/s72-c?imgmax=800" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-6402702077815954140</guid><pubDate>Thu, 02 Sep 2010 19:06:00 +0000</pubDate><atom:updated>2010-09-02T21:48:17.564+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Sharp3D</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Sharp3D – The Beginning</title><description>&lt;p&gt;Back when I was on holidays, I’ve read a post by Maciej Aniserowicz about the “Daj się poznać” contest. The aim of the contest is to write an open source project of any kind in any technology, and blog about it at least twice a week, for ten weeks period. There’s also pretty nice collection of software to win. And because a crazy idea is floating in my head for a while, I thought – why don’t give it a try?&lt;/p&gt;  &lt;p&gt;So what am I going to create? I’m going to build a research application for manipulating 3D objects, perhaps with the ability to define materials for them, modify existing objects, add new objects to the scene, and render them using custom crafted raytracing algorithm. As if this were not enough, application will fully support multi-touch displays.&lt;/p&gt;  &lt;p&gt;Currently, I have a basic skeleton of the application, with my own scene objects (I want to abstract from WPF elements). Here’s the screenshot from the initial drop.&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizdP6-pIxY6Rr7EkCMrrOwueD_7T1zaEBMPGR7o3O4buMqU6_UOYsV6jeTrGTZgKo7UwRvXFmvWckS_2_j_bsWb61kUNZsrUMRNh42S_3BQFZEZalufebs-UyPi6ApSktKfsDiyicxoOSb/s1600-h/Sharp3D%5B7%5D.png&quot;&gt;&lt;img style=&quot;border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto&quot; title=&quot;Sharp3D&quot; border=&quot;0&quot; alt=&quot;Sharp3D&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXl9MOss-O5KAIPsKbsoUv2bkXI4I0dnpU_Bc6CRNkhwJ3kfiTSoJjVjWiouCIjKDh1sVquRtmS7prB1zw09URXgpqSXTLMUcF-ulGnIFCCets_NsXLqTfSWABYaQdwSjVR6OA1ClMllbx/?imgmax=800&quot; width=&quot;339&quot; height=&quot;258&quot; /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;b&gt;Motivation&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;There are a couple of reasons I’m writing this project. By no means, the most important thing for me is to learn strong basics of 3D programming. Triangles, tessellation, normals, materials, lightning, raytracing and more – there is a whole bunch of 3D stuff to master. I also want to learn this in context of WPF 3D – hope this will help me in building better looking apps in the future. I also want to see if the WPF 3D is suitable for project which does more than displaying 3D cubes with buttons on the sides. And last but not least – 3D programming is fun!&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Goals&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;I want Sharp3D to be an extensible foundation for writing 3D applications by others. Thus, the main goal is the extensibility and component design. The application will span several components which can be used in standalone manner – this will support others in developing their own 3D applications! I want to provide many ways of interacting with the 3D model. So besides the standard mouse and keyboard, I will utilize multi-touch capabilities of today’s monitors, and the Wiimote. Because editing capabilities, if any, will be very limited, an important part is to write a loader which will take existing scene and import it to the program. I plan to implement 3ds file importer, because this is de facto the standard in the 3D industry – all known modeling applications support it. Having that, another cool feature will be XAML exporter.&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Tools&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;Because this is a research project, I’m going to use the latest and greatest tools available J This includes:&lt;/p&gt;  &lt;p&gt;· .NET Framework 4.0&lt;/p&gt;  &lt;p&gt;· Visual Studio 2010&lt;/p&gt;  &lt;p&gt;· WPF 4.0&lt;/p&gt;  &lt;p&gt;· Blend 4.0&lt;/p&gt;  &lt;p&gt;· Git&lt;/p&gt;  &lt;p&gt;· Multi-touch / Wiimote&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Sources&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;I decided to use Git which is a fast, distributed version control system. The distributed means that the code repository lives not only on the server (which by the way is not a requirement) but on the user’s computer. This allows committing changes locally, and then pushing them back to the server. When using Git, the natural choice for open source repository is GitHub. The Sharp3D sources can be found at &lt;a href=&quot;http://github.com/pwlodek/Sharp3D&quot;&gt;http://github.com/pwlodek/Sharp3D&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;There are two important branches. The most important is the &lt;b&gt;master&lt;/b&gt; branch. It will contain, latest, stable version. The development will be done on the &lt;b&gt;dev&lt;/b&gt; branch. Besides, I will try to use the branch-per-feature approach, which I presume is self-explanatory. After I decide a feature is complete, it will be merged into dev branch, and then into master.&lt;/p&gt;  &lt;p&gt;&lt;b&gt;Contribution&lt;/b&gt;&lt;/p&gt;  &lt;p&gt;If you are interested in contributing to the project – you are more than welcome! Just drop me an email so we can discuss the details. To begin your contribution, register on GitHub and fork the main repo and work on your part. Once ready, issue a pull request – and I will do the rest ;) The one thing is that I won’t pull till the end of the contest as the participants are supposed to work on their own.&lt;/p&gt;  </description><link>http://pwlodek.blogspot.com/2010/09/sharp3d-beginning.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXl9MOss-O5KAIPsKbsoUv2bkXI4I0dnpU_Bc6CRNkhwJ3kfiTSoJjVjWiouCIjKDh1sVquRtmS7prB1zw09URXgpqSXTLMUcF-ulGnIFCCets_NsXLqTfSWABYaQdwSjVR6OA1ClMllbx/s72-c?imgmax=800" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-2118507988351148919</guid><pubDate>Thu, 13 May 2010 18:10:00 +0000</pubDate><atom:updated>2010-05-15T14:08:50.183+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Unity</category><title>Lazy&amp;lt;T&amp;gt; and IEnumerable&amp;lt;Lazy&amp;lt;T&amp;gt;&amp;gt; support comes to Unity</title><description>If you are familiar with .NET Framework 4.0 or Managed Extensibility Framework, you probably know that there&#39;s a type called &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/dd642331.aspx&quot;&gt;Lazy&amp;lt;T&amp;gt;&lt;/a&gt; which enables lazy instantiation. This type comes in handy when used with any form of dependency injection. Instead of injecting a concrete instance of a service or whatever you want, you can inject instance which wraps the requested type and instantiates it only when the program really needs to use it. Consider the following code which uses - guess what -  MEF =)&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;[Export]&lt;br /&gt;public class Account&lt;br /&gt;{&lt;br /&gt;[Import]&lt;br /&gt;public Lazy&amp;lt;ILogger&amp;gt; Logger { get; set; }&lt;br /&gt;&lt;br /&gt;public void Deposit(decimal amount)&lt;br /&gt;{&lt;br /&gt;if (amount &amp;lt; 0)&lt;br /&gt;{&lt;br /&gt;  Logger.Value.Log(&quot;Amount is less than 0.&quot;);&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;Here you can see a fragment of an &lt;i&gt;Account &lt;/i&gt;class implementation which has an &lt;i&gt;ILogger &lt;/i&gt;instance injected in lazy manner. As long as the &lt;i&gt;Deposit &lt;/i&gt;method is not invoked with a value less than 0, the logger instance is not used, thus, it is actually not created at all! Lazy instantiation is particularly usefull when you are dealing with objects which are expensive to create.&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;There are some IoC containers which support Lazy&amp;lt;T&amp;gt; out of the box, namely Autofac 2, or Managed Extensibility Framework to name a few (I don&#39;t like calling MEF an IoC container, it&#39;s rather a composition engine since it is not constrained to inject types, but methods, fields and properties as well - sorry for that). Unfortunately, &lt;a href=&quot;http://unity.codeplex.com/&quot;&gt;Unity&lt;/a&gt; IoC (even the latest Unity 2.0) is not on that list. Yes, I know. Unity 2.0 has a support for a concept known as automatic factories (you can read more on that &lt;a href=&quot;http://www.davidhayden.me/2010/01/automatic-factories-in-unity-2-unity-2-tutorials-and-samples.html&quot;&gt;here&lt;/a&gt;). Basically speaking, automatic factories allow to pull Func&amp;lt;T&amp;gt; - which is a delegate to a function which returns the concrete instance of the requested component when called. The idea is to fire this delegate when the instance is really needed. So you can say this serves the same purpose as Lazy&amp;lt;T&amp;gt;. Yeah, but it is not Lazy&amp;lt;T&amp;gt; ;) Besides, having the ability to pull Lazy&amp;lt;T&amp;gt; enables even better usage of the &lt;a href=&quot;http://pwlodek.blogspot.com/2009/05/unity-mef-integration-layer.html&quot;&gt;Unity+MEF integration layer&lt;/a&gt;, which is a part of MEF Contrib initiative. You can always find lates sources hosted on &lt;a href=&quot;http://github.com/MefContrib&quot;&gt;github&lt;/a&gt;.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;OK. How to leverage the Lazy&amp;lt;T&amp;gt; and IEnumerable&amp;lt;Lazy&amp;lt;T&amp;gt;&amp;gt; ? This is a piece of cake. There are three ways of using the extension. If you want to pull a single component, here&#39;s how to do that:&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;unityContainer.RegisterType&amp;lt;IComponent, Component1&amp;gt;();&lt;br /&gt;var lazyComponent = unityContainer.Resolve&amp;lt;Lazy&amp;lt;IComponent&amp;gt;&amp;gt;();&lt;br /&gt;&lt;/pre&gt;If you want to pull all components registered under a common type, you can do the following:&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;unityContainer.RegisterType&amp;lt;IComponent, Component1&amp;gt;(&quot;component1&quot;);&lt;br /&gt;unityContainer.RegisterType&amp;lt;IComponent, Component2&amp;gt;(&quot;component2&quot;);&lt;br /&gt;unityContainer.RegisterType&amp;lt;IComponent, Component3&amp;gt;();&lt;br /&gt;&lt;br /&gt;// A collection of non-lazy components&lt;br /&gt;var collectionOComponents = unityContainer.Resolve&amp;lt;IEnumerable&amp;lt;IComponent&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;// Lazy collection of components, once resolved, all the components get resolved&lt;br /&gt;var lazyCollectionOfComponents = unityContainer.Resolve&amp;lt;Lazy&amp;lt;IEnumerable&amp;lt;IComponent&amp;gt;&amp;gt;&amp;gt;();&lt;br /&gt;&lt;br /&gt;// Concrete collection of lazy loaded components&lt;br /&gt;var collectionOfLazyComponents = unityContainer.Resolve&amp;lt;IEnumerable&amp;lt;Lazy&amp;lt;IComponent&amp;gt;&amp;gt;&amp;gt;();;&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;div&gt;One thing to note. Resolving an &lt;i&gt;IEnumerable &lt;/i&gt;is not the same as calling &lt;i&gt;ResolveAll&lt;/i&gt;! &lt;i&gt;ResolveAll&lt;/i&gt; returns only named types, whereas &lt;i&gt;IEnumerable &lt;/i&gt;returns everything!&lt;/div&gt;&lt;div&gt;Either way, before you can use anything presented so far, you have to add the extension the the container. It is as simple as calling:&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;unityContainer.AddNewExtension&amp;lt;LazySupportExtension&amp;gt;();&lt;/pre&gt;&lt;br /&gt;An important, and nice thing as well, is that the presented stuff is already the part of MEF Contrib. If you use MEF+Unity integration layer, you automatically get this behavior out of the box!&lt;br /&gt;&lt;/div&gt;&lt;div&gt;The code sample can be downloaded, as always, from my code gallery &lt;a href=&quot;http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=PierreCode&amp;amp;ReleaseId=4357&quot;&gt;here&lt;/a&gt;. Enjoy!&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpwlodek.blogspot.com%2f&quot;&gt;&lt;img src=&quot;http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpwlodek.blogspot.com%2f&quot; border=&quot;0&quot; alt=&quot;kick it on DotNetKicks.com&quot; /&gt;&lt;/a&gt;</description><link>http://pwlodek.blogspot.com/2010/05/lazy-and-ienumerable-support-comes-to.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-6653654045750822539</guid><pubDate>Tue, 24 Nov 2009 21:55:00 +0000</pubDate><atom:updated>2009-12-28T12:33:07.958+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">Silverlight</category><category domain="http://www.blogger.com/atom/ns#">Unity</category><title>MEF Contrib for Silverlight 3 (Unofficial)</title><description>I’m happy to announce that I’ve completed porting the most recent MEF Contrib (0.7) project to SL3. The project has also been updated to use the most recent MEF release which is beta 2 (Preview 8) as of this writing. All the unit tests from the project pass in the SL environment, here are the screenshots:  &lt;p&gt; &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzKh0W4nqMoHHCjyXu17HuxVhM7gekyD3eOQSQdxF3mmhQF84WBHWgzpK1GNmwMdEn80kz_kDPbIiTQlh5qx5cLQdpKY6yTRJ5mdcd29Uby_Ibw9aKz4EPtgys7-zS1PC3HCID45PwcHrw/s1600-h/image%5B14%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif7oFGK0i-P5O2FZQEJpR6KANSUdmgSTnWBstburEqup7KQjvDKPB_gZOvsMjbbP4eWjzLWZxrRRDiysyxSfp76xp6Fluovrt1LJg2_Xzlrj-tpM3nkq0txQkVzWwV4JZH2YpzfkxHY5jX/?imgmax=800&quot; width=&quot;244&quot; border=&quot;0&quot; height=&quot;103&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhEThcGRlCfY2etfPWc-V4m5DvmIRMp67OwNhkQKxUj_M2CFLFb-WYM9qOxgnGcSJ_2PDd_0ZFIaCUqlikCpAVDq06T0UY_Ze2NQtib82Huqstd7n6duXjPYnIzqpcaNRqYL-SFsa63Rrgm/s1600-h/image%5B11%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcKNIs-othjpJ_K7ajHzEp_Z2Sga9rmTFuE6So_kM7HIgmC8JP5MOIb74yquW2d05aYhTjOSX5Th4RsslrXn351SFE9core2OZMFXaGziFLhhfveurgGqdmQv5WqNtqqqe59fyh5L5Aywc/?imgmax=800&quot; width=&quot;244&quot; border=&quot;0&quot; height=&quot;103&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEje7w-YfMGR11aMpzYPGh-VcRerDl7KyjlVZNyYVv1ZHgF5GhNjBxT0cLr34sVOTduU7HrMShZJXGY-pdML8lHMqxxotrjh3mfXFphBQ6bhmYwdvqVhtbb06ViGcCSuWRR1-sNNjAAbgind/s1600-h/image%5B5%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2db_7hHmUlh1CeNkOr8jCtMKKg0cDXB9IaqUAYLKIcLUh3ZPYmJI951cXpI8KVfX51oOUo_XDczF7lA4brcOE5oYMNQ1lLE86-ZfxAnu6J5sV9rr_lSg1kL0P2ypcH2bSWoAaQBQ-T4Zw/?imgmax=800&quot; width=&quot;244&quot; border=&quot;0&quot; height=&quot;104&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Before I dig into the changes I had to make in order to make it work on SL3, I will focus on NUnit for SL.&lt;/p&gt;  &lt;p&gt;As all of you probably know, it is possible to run NUnit tests in SL environment. Microsoft has released a library called &lt;em&gt;Microsoft.Silverlight.Testing&lt;/em&gt; which enables developers to execute tests on SL’s CLR. This library ships out of the box with the implementation of MS Tests. However, its extensibility allows to write custom providers for other testing frameworks. Jeff Wilcox wrote a post about running NUnit tests in the SL environment &lt;a href=&quot;http://www.jeff.wilcox.name/2009/01/nunit-and-silverlight/&quot;&gt;here&lt;/a&gt;. He did two things: ported a subset of NUnit to SL, and wrote a provider which enables running NUnit tests using &lt;em&gt;Microsoft.Silverlight.Testing &lt;/em&gt;framework. However, his NUnit implementation is very limited, so I googled a little and found a guy who ported NUnit 2.5.1 to SL (you can find his post &lt;a href=&quot;http://wesmcclure.tumblr.com/post/152727000&quot;&gt;here&lt;/a&gt;). So, for the testing purposes I used mentioned NUnit 2.5.1 SL port together with a provider developed by Jeff. I must admit here, that I’m not sure whether all the features from NU 2.5.1 work correctly in the SL environment. Hopefully, it seems that all the &lt;em&gt;Assert&lt;/em&gt; methods including &lt;em&gt;Assert.That&lt;/em&gt; and &lt;em&gt;Throws&lt;/em&gt; work as expected.&lt;/p&gt;  &lt;p&gt;As far as MEFContrib project is concerted, I didn’t have to introduce many modifications. &lt;em&gt;MefContrib.Extensions.Generic&lt;/em&gt; project runs without any changes. &lt;em&gt;MefContrib.Integration.Unity&lt;/em&gt; project didn’t need to be changed in terms of its implementation. However, all stubs used in unit tests were declared as internal, and it seems MEF for SL has some troubles while instantiating non public members (or SL policy doesn’t allow this?) so most tests were failing. Fortunately, changing access to public repaired everything :) The story is a bit different for the &lt;em&gt;MefContrib.Models.Provider&lt;/em&gt; project. This project adds to MEF custom provider model with three programming models built on top of it. These three programming models are&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Attributed – as it name suggest, parts are registered using attributes, &lt;/li&gt;    &lt;li&gt;Configurable – parts get registered via App.config, &lt;/li&gt;    &lt;li&gt;Fluent – parts are registered through method invocation. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The problem lays in the Configurable programming model, because it is implemented using System.Configuration namespace, which is not available to SL programmers. Thus, MefContrib.SIlverlight does not support this model.&lt;/p&gt;  &lt;p&gt;The last trouble I had was with two test, which reside in MemberInfoServicesTests test fixture, namely &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;GetMemberInfoShouldReturnMemberIfMemberNameIsSupplied, &lt;/li&gt;    &lt;li&gt;GetMemberInfoShouldReturnTypeIfMemberNameNotIsSupplied. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Both unit tests test MemberInfoServices class. Both were throwing an exception telling that the test assembly (MefContrib.Models.Provider.Tests) cannot be loaded or the assembly has already been loaded but the versions doesn’t match. To cut the long story short, it turned out that the following code was the root cause (code like the presented below is executed in MemberInfoServices.GetMemberInfo method in both tests) :&lt;/p&gt;  &lt;pre class=&quot;brush: c-sharp&quot;&gt;Type.GetType(&quot;MefContrib.Models.Provider.Tests.FakePropertyPart, MefContrib.Models.Provider.Testsl&quot;, false, true)&lt;/pre&gt;Don’t know why this doesn’t work. However, a simple modification like follows did the job :)&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;Type.GetType(&quot;MefContrib.Models.Provider.Tests.FakePropertyPart, MefContrib.Models.Provider.Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null&quot;, false, true)&lt;/pre&gt;To maintain separate versions of both tests for regular CLR and SL, I used SILVERLIGHT compiler flag.&lt;br /&gt;&lt;br /&gt;Please note that this version is an unofficial release, not available through codeplex.com site. However, I will put an effort to make this an official release or make next MefContrib release based on this one.&lt;br /&gt;&lt;br /&gt;Full source code is available on my code gallery &lt;a href=&quot;https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=PierreCode&amp;amp;ReleaseId=3603&quot;&gt;here&lt;/a&gt;.</description><link>http://pwlodek.blogspot.com/2009/11/mef-contrib-for-silverlight-3.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEif7oFGK0i-P5O2FZQEJpR6KANSUdmgSTnWBstburEqup7KQjvDKPB_gZOvsMjbbP4eWjzLWZxrRRDiysyxSfp76xp6Fluovrt1LJg2_Xzlrj-tpM3nkq0txQkVzWwV4JZH2YpzfkxHY5jX/s72-c?imgmax=800" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-5567892739825159374</guid><pubDate>Sat, 21 Nov 2009 16:31:00 +0000</pubDate><atom:updated>2010-01-17T18:50:37.466+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Attached Behavior</category><category domain="http://www.blogger.com/atom/ns#">Watermark</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Watermark effect for WPF’s TextBox and ComboBox controls</title><description>&lt;p&gt;&lt;span style=&quot;color:#ff0000;&quot;&gt;&lt;strong&gt;Update&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;  &lt;p&gt;I have updated this sample to contain the watermark effect for the ComboBox control too. Its implementation is almost identical to the TextBox’s one. Here are the screens showing the effect being applied to the ComboBox control:&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3yObDYwYs3k2rga3HeHD4gBZb4Onv4-9Drf5fjkvESba887IeFmz3A_i5edYnhXjjeaeYeXYniciDzLc_6PegG2A6_-KXfK7UGpa79z56dC9ECgUImRaFdTgQsXBaO1bkQiGhcRfzerVS/s1600-h/image%5B5%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO9RA7ea-J5EfTDi07or_AZdaltMxQ6VSqrl52cVWtDBLzc6LyB4YQrUBJW6eqaeKWA_4VB3hHf0XP631ItHsP6KSq5E1oZ5Ng7-PvecvMXVSxnl0Uqgoh8Go-t2q7kv2IwOK3-iYTf5-7/?imgmax=800&quot; border=&quot;0&quot; width=&quot;244&quot; height=&quot;244&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKokit0_skqnlsc3JagLyeW19hgEdZZm-BE0iQCeoek6G8GyOzA_ltwxpPP1ibZxMlgLE3zFIYhF10PAtslGqu5cCXU4cPD9uZT9XJpJfN7ezt7sftlpG6suxFN9sQ4zb29J1_HICnK9yh/s1600-h/image%5B11%5D.png&quot;&gt;&lt;img style=&quot;border: 0px none ; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjMSVBiUpTLGD7zJoGwVqVDz18g_RGVDY_HliF42IvSLUTp7YTCYj-S8UEgEzitS7PTlPsQoPBJaGnvJyQQJOhyyqRAwWTEUGvWokeRG-HsA59WX_HmnMuu7U7wGvsiiBNC7VpAfzKxBNhU/?imgmax=800&quot; border=&quot;0&quot; width=&quot;244&quot; height=&quot;244&quot; /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;And here comes the original post.&lt;/p&gt;  &lt;p&gt;In this post I’m going to show a nice watermark effect for WPF’s TextBox control. Sample application (link to the sources at the end of this post) looks as follows:&lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-sot_ETJ4mm7Nb4T6pku5RrXkhD9Bb93o2KSdJE6p55mGKTnm3RdScj32ydQPlzoEfG7r4MWjFZR31bd4L6ODu-dsmeaZqjrlZ5NRw_C1Wl3aqn1NIo2X7l7TVc2fZhqRePztJ5P59BPx/s1600-h/image%5B5%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZCi0kly1ARUKpthqm4dAZz_goqHjYjJDisL3e63SVKhbIXxGeobgQlUNCJ-bfpONHGzAt2T1D9AuVjOCt1D4F8ANP4KQCClPNzoEgpkZJuF5DaVUfmz4nT7uOTqJk9xOaUUZfiaUsdH4G/?imgmax=800&quot; border=&quot;0&quot; width=&quot;244&quot; height=&quot;244&quot; /&gt;&lt;/a&gt; &lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhN8j2hqLv_xfWwIJiiPoVzXqAq9AcWCYEOnxwYOwqrNKFdWHieRbEKT6SB1jP2RZmyq5ErH5DNyWz1mPaThKadswAWpgBY37t0wzpfrm-qGygVTlJikXXs3_jw2_gxq-UH-udMEScg_eSg/s1600-h/image%5B11%5D.png&quot;&gt;&lt;img style=&quot;border-width: 0px; display: inline;&quot; title=&quot;image&quot; alt=&quot;image&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtGzZm-jW0EifR3latY6dKqRDOveyHSu_wm6ljM1h50zmmeN6OH9lZujNJpJW90cYvDiHwj8XVVBlPcSLfoEUjphvJ2W-W3vfpGzC9cripzR84pDM4BsJQw4yjLpK3IhZL1YmTW33s7HRa/?imgmax=800&quot; border=&quot;0&quot; width=&quot;244&quot; height=&quot;244&quot; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;As you can see, non focused text box containing no text, displays a useful clue to the user informing what kind of information should be entered. Focusing a textbox immediately removes that clue.&lt;/p&gt;  &lt;p&gt;There are probably as many ways to introduce such a behavior as there are developers all over the world :) However, one particular solution is to be considered in this case. The above effect has been achieved using adorners. The adorner used for the effect contains a single TextBlock with optional style applied to it. A good introduction to adorners is available &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/ms743737.aspx&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;The effect has been implemented using &lt;strong&gt;attached behavior pattern&lt;/strong&gt;, so no inheritance was introduced.&lt;/p&gt;  &lt;p&gt;Using the behavior is a piece of cake. Here’s how to apply the behavior to a TextBox control:&lt;/p&gt;  &lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;TextBox Height=&quot;25&quot; Margin=&quot;0,5,0,5&quot;&lt;br /&gt;Behaviors:WatermarkTextBoxBehavior.EnableWatermark=&quot;True&quot;&lt;br /&gt;Behaviors:WatermarkTextBoxBehavior.Label=&quot;Label&quot;&lt;br /&gt;Behaviors:WatermarkTextBoxBehavior.LabelStyle=&quot;{StaticResource watermarkLabelStyle2}&quot; /&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;p&gt;The first property, &lt;em&gt;EnableWatermark&lt;/em&gt;, as its name suggests, enables the effect ;) The &lt;em&gt;Label&lt;/em&gt; property holds the text to be displayed as a watermark. Finally, the &lt;em&gt;LabelStyle&lt;/em&gt; property contains the style to be applied to the label. And the style, defined in Window’s &lt;em&gt;Resources&lt;/em&gt; collection, might look as follows:&lt;/p&gt;&lt;br /&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;Style x:Key=&quot;watermarkLabelStyle&quot;&amp;gt;&lt;br /&gt;&amp;lt;Setter Property=&quot;TextBlock.Foreground&quot; Value=&quot;{x:Static SystemColors.ControlDarkBrush}&quot; /&amp;gt;&lt;br /&gt;&amp;lt;Setter Property=&quot;FrameworkElement.Opacity&quot; Value=&quot;0.8&quot; /&amp;gt;&lt;br /&gt;&amp;lt;Setter Property=&quot;TextBlock.FontSize&quot; Value=&quot;12&quot; /&amp;gt;&lt;br /&gt;&amp;lt;Setter Property=&quot;TextBlock.FontStyle&quot; Value=&quot;Italic&quot; /&amp;gt;&lt;br /&gt;&amp;lt;Setter Property=&quot;TextBlock.Margin&quot; Value=&quot;8,4,4,4&quot; /&amp;gt;&lt;br /&gt;&amp;lt;/Style&amp;gt;&lt;/pre&gt;&lt;br /&gt;I’m not going to discuss any implementation details here since the adorner itself is trivial, and the behavior is quite easy as well. Maybe I will tell you that the watermark is displayed when the TextBox fires its &lt;em&gt;Loaded&lt;/em&gt; event. Why is that important to know? Keep reading… ;P Besides, skim the code and you immediately know how stuff works :)&lt;br /&gt;&lt;br /&gt;&lt;p&gt;Finally, one thing, which deserves to give attention to, is control loading and the adorner layer (adorner layer is a place always rendered over the control where all adorners for that control get displayed). When a control is contained within a portion of UI that is being displayed, but the control itself is not visible, it normally fires &lt;em&gt;Loaded&lt;/em&gt; event, but because it is not visible, it has no adorner layer! So don’t assume that call to AdornerLayer.GetAdornerLayer(Visual) always returns the adorner layer! This is why the sample shown above contains a TabControl – the second tab, named Tab 2, contains a TextBox with the watermark effect applied to it, and this still works :)&lt;/p&gt;&lt;br /&gt;As always, code sample is available through my Code Gallery &lt;a href=&quot;https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=PierreCode&amp;amp;ReleaseId=3546&quot;&gt;here&lt;/a&gt;.</description><link>http://pwlodek.blogspot.com/2009/11/watermark-effect-for-wpfs-textbox.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhO9RA7ea-J5EfTDi07or_AZdaltMxQ6VSqrl52cVWtDBLzc6LyB4YQrUBJW6eqaeKWA_4VB3hHf0XP631ItHsP6KSq5E1oZ5Ng7-PvecvMXVSxnl0Uqgoh8Go-t2q7kv2IwOK3-iYTf5-7/s72-c?imgmax=800" height="72" width="72"/><thr:total>8</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-7235070475179413030</guid><pubDate>Sat, 22 Aug 2009 08:17:00 +0000</pubDate><atom:updated>2009-08-22T12:36:41.268+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">Unity</category><title>Improved MEF + Unity Integration Layer</title><description>In my &lt;a href=&quot;http://pwlodek.blogspot.com/2009/05/unity-mef-integration-layer.html&quot;&gt;last post&lt;/a&gt; about Managed Extensibility Framework and Unity DI container I proposed a solution to make both frameworks work together in tandem, which in turn lets the developer leverage all the features from them at the same time.&lt;span style=&quot;font-weight: bold;&quot;&gt; Now, the improved version is out, and it&#39;s a part of the &lt;/span&gt;&lt;a style=&quot;font-weight: bold;&quot; href=&quot;http://www.codeplex.com/MEFContrib&quot;&gt;MEFContrib&lt;/a&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt; project!&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Having learned from developing the previous version, I decided to reimplement  the integration layer from the ground up. The API changed very little, though ;)&lt;br /&gt;&lt;br /&gt;The &quot;biggest&quot; change since the initial version is that you no longer need to provide boolean parameter during component registration in Unity to say that you want the component to be available to MEF. Now, this is done automatically using Unity container extension. So, the initialization of the layer now is super easy as it requires only single line of code :) Consider this:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;// Setup&lt;br /&gt;var unityContainer = new UnityContainer();&lt;br /&gt;var aggregateCatalog = new AggregateCatalog();&lt;br /&gt;&lt;br /&gt;// Register catalog and types&lt;br /&gt;unityContainer.RegisterCatalog(aggregateCatalog);  // this call initializes the layer&lt;br /&gt;unityContainer.RegisterType&amp;lt;IUnityOnlyComponent, UnityOnlyComponent1&amp;gt;();&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The first call to &lt;span style=&quot;font-style: italic;&quot;&gt;RegisterCatalog&lt;/span&gt; method does the initialization - under the hoods, &lt;span style=&quot;font-style: italic;&quot;&gt;ComposiotionContainer&lt;/span&gt; is created, and a link between it and Unity is established. Pretty easy, huh ? :)&lt;br /&gt;&lt;br /&gt;Next, all the types are public, so for example, if the standard &lt;span style=&quot;font-style: italic;&quot;&gt;RegisterCatalog&lt;/span&gt; method doesn&#39;t fit your needs, you can easily create your own using all the provided types as building blocks. The one concrete use case that comes to my mind is that the current implementation of the &lt;span style=&quot;font-style: italic;&quot;&gt;RegisterCatalog &lt;/span&gt;method does not allow you to attach any additional export providers (your own root &lt;span style=&quot;font-style: italic;&quot;&gt;CompositionContainer&lt;/span&gt; for instance)  to the underlying &lt;span style=&quot;font-style: italic;&quot;&gt;CompositionContainer&lt;/span&gt;. In such a case, you can easily create separate method which accepts export providers and initializes the layer. Investigating &lt;span style=&quot;font-style: italic;&quot;&gt;RegisterCatalog&lt;/span&gt; method might be beneficial :)&lt;br /&gt;&lt;br /&gt;One neat implication of having all types public is that you can now establish one-way synchronization, being MEF to Unity, in which Unity container knows about MEF parts and can resolve them, and Unity to MEF, in which MEF can pull Unity&#39;s components.&lt;br /&gt;&lt;br /&gt;Finally, I&#39;ve added support for closed generics, i.e. you can pull components from Unity and MEF using generics.&lt;br /&gt;&lt;br /&gt;The usage of this layer is quite well described on &lt;a href=&quot;http://mefcontrib.codeplex.com/Wiki/View.aspx?title=Unity%20Integration&amp;amp;referringTitle=Home&quot;&gt;MEFContrib wiki page&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpwlodek.blogspot.com%2f2009%2f08%2fimproved-mef-unity-integration-layer.html&quot;&gt;&lt;img src=&quot;http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpwlodek.blogspot.com%2f2009%2f08%2fimproved-mef-unity-integration-layer.html&quot; border=&quot;0&quot; alt=&quot;kick it on DotNetKicks.com&quot; /&gt;&lt;/a&gt;</description><link>http://pwlodek.blogspot.com/2009/08/improved-mef-unity-integration-layer.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>8</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-2518895403871672004</guid><pubDate>Fri, 10 Jul 2009 20:59:00 +0000</pubDate><atom:updated>2009-07-10T23:59:15.538+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Statically Typed Dependency Properties</title><description>Recently, I found a nice post written by a friend of mine, regarding statically typed property names. His post can be found &lt;a href=&quot;http://blog.m.jedynak.pl/2009/02/static-typed-propety-names.html&quot;&gt;here&lt;/a&gt;. What I simply did was to put his concept into WPF world :)&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Problem&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Typical registration of a WPF&#39;s dependency property looks like follows:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public int MyInteger1&lt;br /&gt;{&lt;br /&gt;get { return (int)GetValue(MyInteger1Property); }&lt;br /&gt;set { SetValue(MyInteger1Property, value); }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static readonly DependencyProperty MyInteger1Property =&lt;br /&gt;DependencyProperty.Register(&quot;MyInteger1&quot;, typeof(int), typeof(Window1));&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Hmm, what&#39;s wrong with it ? It &quot;breakes&quot; the DRY (Don&#39;t Repeat Yourself) principle. Given code defines a property named MyInteger of type int, but this information is coded twice, in the property itself and during its registration. If you want to change the name or type of a single property, you have to update the code in two places.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Solution&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Now consider the following code:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public int MyInteger2&lt;br /&gt;{&lt;br /&gt;get { return (int)GetValue(MyInteger2Property); }&lt;br /&gt;set { SetValue(MyInteger2Property, value); }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;public static readonly DependencyProperty MyInteger2Property =&lt;br /&gt;DependencyPropertyHelper.Register&amp;lt;Window1&amp;gt;(t =&amp;gt; t.MyInteger2);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;What has changed here is the way the property is registered. Now, changing the name or the type of a property is done through its getter. Nice, isn&#39;t it ? This approach works with both regular and read only properties but does not with attached properties, because the latter does not use property to access its value but uses methods instead. Implementation behind the Register&amp;lt;TOwner&amp;gt; method used above is fairly simple and looks like this:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public static class DependencyPropertyHelper&lt;br /&gt;{&lt;br /&gt;    public static DependencyProperty Register&amp;lt;TOwner&amp;gt;(&lt;br /&gt;        Expression&amp;lt;Func&amp;lt;TOwner, object&amp;gt;&amp;gt; property)&lt;br /&gt;    {&lt;br /&gt;        return DependencyProperty.Register(typeof(TOwner).GetPropertyName(property),&lt;br /&gt;                                           typeof(TOwner).GetPropertyType(property),&lt;br /&gt;                                           typeof(TOwner));&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;GetPropertyName and GetPropertyType methods come from the post I&#39;ve mention at the beginning.&lt;br /&gt;&lt;br /&gt;Full code can be downloaded from my &lt;a href=&quot;https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=PierreCode&amp;amp;ReleaseId=2971&quot;&gt;code gallery&lt;/a&gt;.</description><link>http://pwlodek.blogspot.com/2009/07/statically-typed-dependency-properties.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-4433368262290631622</guid><pubDate>Wed, 10 Jun 2009 16:36:00 +0000</pubDate><atom:updated>2009-06-10T19:30:45.187+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>WPF 3.5 (70-502) Exam Passed</title><description>Yesterday, I&#39;ve successfully completed my first developer&#39;s certification by passing exam 70-502 TS: Microsoft .NET Framework 3.5 – Windows Presentation Foundation Application Development. My score was &lt;span style=&quot;font-weight: bold;&quot;&gt;921&lt;/span&gt; out of 1000 which is also my personal best so far :)&lt;br /&gt;I had 51 question, most of which were single choice, and 150 minutes to complete. Not all the questions were taken into account when computing the final score. Although I&#39;ve chosen my questions in C#, I got one question in VB, so be prepared ;)&lt;br /&gt;&lt;br /&gt;What can you expect from the exam as far as questions are concerned? Putting it simple, everything. Questions cover all the WPF&#39; topics including WPF 3D, ClickOnce deployment, XPS and Flow documents, and Windows Forms interoperability.&lt;br /&gt;&lt;br /&gt;As far as WPF 3D is concerned, the questions are rather easy and cover only the basics like cameras or meshes. If you are a novice, I recommend a brief reading about this subject (not because this appears on the exam, but because WPF 3D is a big fun). ClickOnce was heavily covered on the exam, so make sure you get your hands dirty playing with it. Besides basic knowledge, you should know how to download parts of the application on demand (parts which are not required for the application to run). Regarding flow documents, you should know what annotations are, how to manage them, display, persist, etc. Printing both flow and XPS documents is also covered on the exam, so brush up on this subject as well.&lt;br /&gt;&lt;br /&gt;In my last words, I want to speak a little about books :) Generally, if you&#39;re already familiar with WPF, official Training Kit from MS is mostly sufficient, but it doesn&#39;t cover WPF 3D, and some subjects are touched rather briefly. But if you are at the very beginning, or if you simply want to broader you knowledge, I highly recommend picking up Adam Nathan&#39;s &lt;a href=&quot;http://blogs.msdn.com/adam_nathan/archive/2006/05/17/599301.aspx&quot;&gt;WPF Unleashed&lt;/a&gt;. Actually, if You are serious about WPF development, this book is a must read :)&lt;br /&gt;&lt;br /&gt;Wish You good luck!</description><link>http://pwlodek.blogspot.com/2009/06/wpf-35-70-502-exam-passed.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-2187916733575092168</guid><pubDate>Sun, 24 May 2009 09:44:00 +0000</pubDate><atom:updated>2009-08-22T12:33:38.161+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">MEF</category><category domain="http://www.blogger.com/atom/ns#">Unity</category><title>Unity + MEF Integration Layer</title><description>In this post, I’m going to discuss two of probable many solutions to the problem of making use of the &lt;a href=&quot;http://mef.codeplex.com/&quot;&gt;Managed Extensibility Framework&lt;/a&gt; together with Microsoft’s Unity Application Block in an enterprise application. Presented solution combines the power of both frameworks, and exposes an intuitive and easy to use interface. If you are interested in putting MEF together with Unity, this post is definitely 4U. If you use Unity and want to get some basic knowledge about writing extension to it, you still might want to go briefly through the code, as the provided solution is based on the Unity Container Extensions (and MEF extensions as well). This post also assumes that you have a basic idea of Dependency Injection and how it relates to the design of an application. Basics of MEF will be helpful as well.&lt;br /&gt;Divagations presented here are partially based on a great post titled &lt;a href=&quot;http://blogs.msdn.com/nblumhardt/archive/2009/03/16/hosting-mef-extensions-in-an-ioc-container.aspx&quot;&gt;Hosting MEF Extensions in an IoC Container&lt;/a&gt; by Nicholas Blumhardt, and I recommend you take a look at it before further reading this post :).&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Problem&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;People around are sometimes/often confused about the role MEF plays in the world of the Dependency Injection – should MEF be treated as an Injection of Control solution, and thus should supersede it, or it is something else and should be used differently? Well, this is a little bit tricky question, but in what I understand, MEF is all about composition and robust components loading, thus is best suited for providing well-known extension (plug-ins) to the application, whereas IoC serves more as a backbone of an application, which is primary responsible for making all application’s internal modules work together. To sum up, MEF and Unity are very flexible and in many cases may be used interchangeably, but a general idea is that:&lt;br /&gt;&lt;ul&gt;&lt;li&gt;if you want to provide a plug-ins infrastructure so that 3rd parties were able to provide extensions for the app, use MEF (or Managed Add-in Framework + MEF if you want robust plug-in isolation :)),&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;ul&gt;&lt;li&gt;if you want to structure your application’s architecture, use modules that are decoupled but with the ability to communicate, etc., use Unity or any existing IoC.&lt;/li&gt;&lt;/ul&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Solution 1&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;The first solution is pretty easy – simply use both frameworks independently of each other.&lt;br /&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQnoqHwmeHkhHF4T6HhmfconvHiz7ogcbVY9NEG5WB9TLY0DLI1AGKalefD7W6UaTW2jQIGrGocLaxDL2pXML1Ix-JIJ4ojKXChUjvqyOJgs2T7Uft1WXlPCR2LtUqm5n7SGkP9L7rkzX7/s1600-h/Solution1.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 306px; height: 320px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQnoqHwmeHkhHF4T6HhmfconvHiz7ogcbVY9NEG5WB9TLY0DLI1AGKalefD7W6UaTW2jQIGrGocLaxDL2pXML1Ix-JIJ4ojKXChUjvqyOJgs2T7Uft1WXlPCR2LtUqm5n7SGkP9L7rkzX7/s320/Solution1.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5339326177416865458&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The definite plus of this approach is its ease of putting it into action in the application. But it has some drawbacks, mainly that MEF and Unity components can’t make use of each other. In other words, MEF component cannot contain any dependencies on Unity components that can be automatically satisfied via dependency injection. The same holds true for the Unity components, they simply cannot have dependencies on MEF components (note that by MEF component I mean component initially instantiated by MEF, and by Unity component I mean a component initially created by Unity container). Another drawback is that unity does know nothing about MEF, and vice versa. And why is that important ? Consider the following sample showing a dummy Presentation Model in presenter first approach (a typical scenario):&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class MyViewPresentationModel&lt;br /&gt;{&lt;br /&gt;public MyViewPresentationModel(IMyView view, IUnityService1 service1,&lt;br /&gt;IMefComponent1 mefComponent1)&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Note that in the constructor, I have both Unity service and MEF component, and because the &lt;span style=&quot;font-style: italic;&quot;&gt;MyViewPresentationModel&lt;/span&gt; class is instantiated via Unity and Unity knows nothing about IMefComponent1, this won’t work. But it should! Argh...&lt;br /&gt;&lt;br /&gt;Although this solution is fairly simple to implement, it has several drawbacks that makes using it painful. So let’s go to the second :)&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Solution 2&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;This solution uses a middle component, Unity + MEF Integration Layer (implemented as Unity.Integration.Mef.dll), which allows full interoperability between Unity and MEF, as you can see from the following figure.&lt;br /&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnA3_wlV0Swq3pz5cL7hQ1E1dq5fdmpUVK_TpDrDvZTvxacevcZ1nTeCcCLctsaCNAvpaKQD3hNu-vgXetGQkWIH0OMKNStsqwpDKI3TYvcCZSScn2HtX4qcnCiieO6JRJh1xZaeQpWYT_/s1600-h/Solution2.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnA3_wlV0Swq3pz5cL7hQ1E1dq5fdmpUVK_TpDrDvZTvxacevcZ1nTeCcCLctsaCNAvpaKQD3hNu-vgXetGQkWIH0OMKNStsqwpDKI3TYvcCZSScn2HtX4qcnCiieO6JRJh1xZaeQpWYT_/s320/Solution2.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5339326769201196866&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;As you can see, Unity is the backbone component, that uses the integration layer to communicate with MEF. In this solution, Unity components may have dependencies on MEF components, and vice versa. Of course, all dependencies will by injected automatically! So the following code will work (ICoreService is a Unity service whereas IMefService is instantiated by MEF):&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;&lt;br /&gt;public class CoreService2 : ICoreService&lt;br /&gt;{&lt;br /&gt;public CoreService2()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Import(&quot;MefService3&quot;)]&lt;br /&gt;private IMefService m_MefService3;&lt;br /&gt;&lt;br /&gt;public void Foo()&lt;br /&gt;{&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;What&#39;s even more important, with this approach, it&#39;s possible to mix components in the constructors, so the following both classes will work as well. Please note, that if you have a MEF component exported by name, you can reference it using the Unity&#39;s &lt;span style=&quot;font-style: italic;&quot;&gt;DependencyAttribute&lt;/span&gt;, and if you have a Unity component registered using a name, you can reference it in a MEF component using MEF&#39;s &lt;span style=&quot;font-style: italic;&quot;&gt;ImportAttribute &lt;/span&gt;! :)&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;public class CoreComponent : (...)&lt;br /&gt;{&lt;br /&gt; private readonly IMefService m_MefService3;&lt;br /&gt; private readonly ICoreService m_CoreService;&lt;br /&gt;&lt;br /&gt; // Interesting thing happens here: Unity injects components created&lt;br /&gt; // by both MEF and Unity&lt;br /&gt; public CoreComponent(&lt;br /&gt;    [Dependency(&quot;MefService3&quot;)] IMefService mefService3,&lt;br /&gt;    ICoreService coreService)&lt;br /&gt; {&lt;br /&gt;    m_MefService3 = mefService3;&lt;br /&gt;    m_CoreService = coreService;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; [Import(AllowDefault = true)]&lt;br /&gt; private IEnumerable&amp;lt;imefservice&amp;gt; m_MefServices;&lt;br /&gt;&lt;br /&gt; public void FooBar()&lt;br /&gt; {&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;[Export(typeof(IMefService))]&lt;br /&gt;[PartCreationPolicy(CreationPolicy.Shared)]&lt;br /&gt;public class MefService2 : IMefService&lt;br /&gt;{&lt;br /&gt; private readonly IUnityContainer m_UnityContainer;&lt;br /&gt; private readonly ICoreService m_CoreService;&lt;br /&gt;&lt;br /&gt; // Interesting thing happens here: MEF injects components created&lt;br /&gt; // by both MEF and Unity&lt;br /&gt; [ImportingConstructor]&lt;br /&gt; public MefService2(IUnityContainer unityContainer,&lt;br /&gt;    [Import(&quot;CoreService2&quot;)] ICoreService coreService)&lt;br /&gt; {&lt;br /&gt;    m_UnityContainer = unityContainer;&lt;br /&gt;    m_CoreService = coreService;&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public void Bar()&lt;br /&gt; {&lt;br /&gt; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Using the Unity + MEF Integration Layer is very simple, just reference Unity.Integration.Mef.dll in your project and you&#39;re almost done! Here&#39;s a sample:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;&lt;br /&gt;// Create the Unity container and self-register&lt;br /&gt;var unity = new UnityContainer();&lt;br /&gt;unity.RegisterInstance&amp;lt;IUnityContainer&amp;gt;(unity);&lt;br /&gt;&lt;br /&gt;// Register MEF catalogs in Unity&lt;br /&gt;unity.RegisterCatalog(new AssemblyCatalog(Assembly.GetEntryAssembly()));&lt;br /&gt;unity.RegisterCatalog(new DirectoryCatalog(&quot;.&quot;));&lt;br /&gt;&lt;br /&gt;// Register unity components&lt;br /&gt;unity.RegisterType&amp;lt;CoreComponent&amp;gt;();&lt;br /&gt;unity.RegisterType&amp;lt;ICoreService, CoreService1&amp;gt;(new ContainerControlledLifetimeManager(), true);&lt;br /&gt;unity.RegisterType&amp;lt;ICoreService, CoreService2&amp;gt;(&quot;CoreService2&quot;, new ContainerControlledLifetimeManager(), true);&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The public interface is defined using extension methods on the IUnityContainer interface. There are two thing you have to do. Firstly, register all the MEF&#39;s catalogs in the Unity. Secondly, register the types in the Unity as you normally do. Note, however, that in order to make a type registered in the Unity container available to MEF, you must register it with an overloaded &lt;span style=&quot;font-style: italic;&quot;&gt;Register(Type|Instance)&lt;/span&gt; method that accepts a boolean as the last parameter. If it is true, registered type/instance will be available to MEF.&lt;br /&gt;Sometimes you will want to suppress MEF injections into Unity created instances. Why? Because it costs you a CPU cycles (believe me, lots of them!). This is where &lt;span style=&quot;font-style: italic;&quot;&gt;PartNotComposableAttribute &lt;/span&gt;attribute comes in. Just mark a class with it, and when an instance from the Unity is returned, no MEF&#39;s imports will be satisfied, conserving CPU time. This is particularly useful for presenters.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Limitations&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;For now, MEF components can have Unity dependencies resolved only via constructor injection, so method injection on MEF components currently won&#39;t work.&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Implementation details&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The implementation is rather straightforward. It uses two Unity extensions and one custom MEF ExportProvider. As stated before, public interface is delivered as a set of extension methods on the &lt;span style=&quot;font-style: italic;&quot;&gt;IUnityContainer&lt;/span&gt; interface. I&#39;ve also considered deriving directly from &lt;span style=&quot;font-style: italic;&quot;&gt;UnityContainer &lt;/span&gt;class, but the former approach (the one I&#39;ve chosen) appears better suited for me. What do You think ? You can leave a comment on that :)&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Conclusion&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The idea of bringing the power of both frameworks is very tempting. And provided solution, although definitely not the only one, seems like a good one. The code + tests (NUnit 2.5) + demo app is available on my &lt;a href=&quot;http://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=PierreCode&amp;amp;ReleaseId=2731&quot;&gt;code gallery&lt;/a&gt;. Hope you like it!&lt;br /&gt;&lt;br /&gt;&lt;a href=&quot;http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fpwlodek.blogspot.com%2f2009%2f05%2funity-mef-integration-layer.html&quot;&gt;&lt;img src=&quot;http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fpwlodek.blogspot.com%2f2009%2f05%2funity-mef-integration-layer.html&quot; border=&quot;0&quot; alt=&quot;kick it on DotNetKicks.com&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style=&quot;color: rgb(255, 0, 0); font-weight: bold;&quot;&gt;Update&lt;/span&gt;&lt;br /&gt;I&#39;ve reimplemented most of the layer from the ground up, now it&#39;s a part of the &lt;a href=&quot;http://mefcontrib.codeplex.com/&quot;&gt;MEFContrib&lt;/a&gt; project. Please see my post about it &lt;a href=&quot;http://pwlodek.blogspot.com/2009/08/improved-mef-unity-integration-layer.html&quot;&gt;here&lt;/a&gt;.</description><link>http://pwlodek.blogspot.com/2009/05/unity-mef-integration-layer.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQnoqHwmeHkhHF4T6HhmfconvHiz7ogcbVY9NEG5WB9TLY0DLI1AGKalefD7W6UaTW2jQIGrGocLaxDL2pXML1Ix-JIJ4ojKXChUjvqyOJgs2T7Uft1WXlPCR2LtUqm5n7SGkP9L7rkzX7/s72-c/Solution1.jpg" height="72" width="72"/><thr:total>12</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-7056582682796324487</guid><pubDate>Tue, 05 May 2009 08:03:00 +0000</pubDate><atom:updated>2009-05-05T11:11:34.019+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Mammoth</category><title>Mammoth Pattern Miner 2009 April CTP Showcase</title><description>As promised in my&lt;a href=&quot;http://pwlodek.blogspot.com/2009/01/mammoth-pattern-miner-cool-wpf.html&quot;&gt; last post&lt;/a&gt; about Mammoth some time ago, here&#39;s a four minute video presenting Mammoth in action. The video was made by co-author of Mammoth, my friend Arkadiusz Świerczek, and was presented on &lt;a href=&quot;http://www.europoltech.pl/&quot;&gt;Europoltech 2009&lt;/a&gt; conference in Warsaw. The video is soundless and is in polish, but if you&#39;re not polish, you can still get the idea of what Mammoth is all about :)&lt;br /&gt;&lt;br /&gt;&lt;object width=&quot;400&quot; height=&quot;300&quot;&gt;&lt;param name=&quot;allowfullscreen&quot; value=&quot;true&quot;&gt;&lt;param name=&quot;allowscriptaccess&quot; value=&quot;always&quot;&gt;&lt;param name=&quot;movie&quot; value=&quot;http://vimeo.com/moogaloop.swf?clip_id=4471487&amp;amp;server=vimeo.com&amp;amp;show_title=1&amp;amp;show_byline=1&amp;amp;show_portrait=0&amp;amp;color=&amp;amp;fullscreen=1&quot;&gt;&lt;embed src=&quot;http://vimeo.com/moogaloop.swf?clip_id=4471487&amp;amp;server=vimeo.com&amp;amp;show_title=1&amp;amp;show_byline=1&amp;amp;show_portrait=0&amp;amp;color=&amp;amp;fullscreen=1&quot; type=&quot;application/x-shockwave-flash&quot; allowfullscreen=&quot;true&quot; allowscriptaccess=&quot;always&quot; width=&quot;400&quot; height=&quot;300&quot;&gt;&lt;/embed&gt;&lt;/object&gt;&lt;br /&gt;&lt;br /&gt;Just to let you know (if you already don&#39;t), Mammoth is a data mining and visualization solution that can discover frequent and user defined patterns in various sets of data. The program is easily extensible, so adding new algorithms, visualizations, etc., is a piece of cake.&lt;br /&gt;&lt;br /&gt;We plan to release public, free version by the end of august 2009.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Since the last CTP, we have slightly updated technologies that are behind Mammoth. So besides .NET 3.5 SP1, WPF, &lt;a href=&quot;http://www.codeplex.com/CompositeWPF&quot;&gt;Prism 2.0&lt;/a&gt;, Unity 1.2, Enterprise Library 4.1 and SQL Server 2005, we are using &lt;a href=&quot;http://www.codeplex.com/MEF&quot;&gt;Managed Extensibility Framework&lt;/a&gt; Preview 5 which is labeled as a stable release.&lt;br /&gt;&lt;br /&gt;As far as MEF is concerned, we&#39;ve developed custom, simple yet robust Unity + MEF integration layer. As far as I can say for now, our MEF + Unity integration layer works flawlesly and provides combined power of both frameworks. If you are curious how we did it, check it out on my &lt;a href=&quot;http://code.google.com/p/piotr-wlodek-code-gallery/&quot;&gt;SVN Code Gallery&lt;/a&gt;. I will also write a separate post entirely devoted to MEF + Unity integration related stuff.&lt;br /&gt;&lt;br /&gt;Meanwhile, enjoy the vid!</description><link>http://pwlodek.blogspot.com/2009/05/mammoth-pattern-miner-2009-april-ctp.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-839024133026364608</guid><pubDate>Mon, 06 Apr 2009 12:15:00 +0000</pubDate><atom:updated>2009-04-06T17:05:34.905+02:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Parallel Coordinates</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Parallel Coordinates in WPF - Part 1</title><description>A few days ago I have completed working on a first version of a parallel coordinates chart, that has been incorporated into Mammoth Pattern Miner 2009 (see my post &lt;a href=&quot;http://pwlodek.blogspot.com/2009/01/mammoth-pattern-miner-cool-wpf.html&quot;&gt;about it&lt;/a&gt;). Before rolling out my own implementation, I went through the internet trying to find any implementation with the attached source code. As a result, I found a nice post &lt;a href=&quot;http://www.orbifold.net/default/?p=1886&quot;&gt;here&lt;/a&gt;, but without the sources. Thus, I have developed a nice looking, styleable (via custom control templates) parallel coordinates chart myself :) And despite the fact that I did it under my &quot;company&quot; time, my boss and I decided that it would be great if I posted the sources as well. So I did! :) This is how the diagram looks like:&lt;br /&gt;&lt;br /&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjChRETMTxOrLss-JLkpa6ogq5J35KoxdZPSSbGazeyXmbeVwdhuhpO8VCLHYL1RFOp7FYJBqFdfYcmJ-_aOOz1N6lGCjicusGF4xtaQws2r2mTaToucPfttA6ffI_lulvwevhgRaTD_xok/s1600-h/PC8.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjChRETMTxOrLss-JLkpa6ogq5J35KoxdZPSSbGazeyXmbeVwdhuhpO8VCLHYL1RFOp7FYJBqFdfYcmJ-_aOOz1N6lGCjicusGF4xtaQws2r2mTaToucPfttA6ffI_lulvwevhgRaTD_xok/s320/PC8.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321586146969308546&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;span&gt;Overall look and feel of the demo application&lt;/span&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;This is a first post about PC chart. It covers all the functionality the chart contains, and info about using it from the code. Next posts in this series will cover the chart internals.&lt;span style=&quot;font-weight: bold;&quot;&gt;&lt;br /&gt;&lt;br /&gt;Feature List&lt;br /&gt;&lt;br /&gt;&lt;/span&gt;&lt;span&gt;1.&lt;/span&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt; &lt;/span&gt;Lines highlighting / selecting and tooltips&lt;br /&gt;&lt;br /&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimzr9SlNW-c_JlQkkUIBA5f4qnvJHN5BxYxnx6St3VwC4YnT_dnyL5QMc5Qx3TmHYjPIiZWHeuzcUHxefR31qyn_qexPJ5st29kdvJVhhwpPk__IjQldFXXvZ621MsyiOFrAZDScoOrS_b/s1600-h/PC1.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimzr9SlNW-c_JlQkkUIBA5f4qnvJHN5BxYxnx6St3VwC4YnT_dnyL5QMc5Qx3TmHYjPIiZWHeuzcUHxefR31qyn_qexPJ5st29kdvJVhhwpPk__IjQldFXXvZ621MsyiOFrAZDScoOrS_b/s320/PC1.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321561480169126882&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;1. Axes labels and range labels, helper axis&lt;br /&gt;&lt;/div&gt;&lt;div style=&quot;text-align: left;&quot;&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqRRx8hh7Ha0UNWbKh6mx4wdBIJq3e2wLddVY5xTHmdlVuTPWR23l5Z4RExUQ1aY0hD1GrbNnkeL3_gTRl9h46e95lFEvUDE1eIVVDuiJvMXjWInFMcmSv-sEY9pGqAGIuPUNGxlx9frcy/s1600-h/PC2.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 174px; height: 279px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqRRx8hh7Ha0UNWbKh6mx4wdBIJq3e2wLddVY5xTHmdlVuTPWR23l5Z4RExUQ1aY0hD1GrbNnkeL3_gTRl9h46e95lFEvUDE1eIVVDuiJvMXjWInFMcmSv-sEY9pGqAGIuPUNGxlx9frcy/s320/PC2.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321562837555958738&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;2. Diagram manipulation&lt;br /&gt;Anytime you resize the window or manipulate the axes, you can fit the diagram to the current view. Simply right click anywhere on the diagram and choose &quot;Fit To Screen&quot; command as shown below.&lt;br /&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSo1_tZV2rNztF-lBL-yB0pYIxeEJKKCcx1ApfysvP9bW5umRSBbkOpMGGMfNLpJNaBp3n43546pEjOrya3SCDjHx7J5503a8VP-z9zrnE1ftXO-ZAskSpoknrzzyvZroJeeKCC9AXNq6O/s1600-h/PC3.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 221px; height: 320px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSo1_tZV2rNztF-lBL-yB0pYIxeEJKKCcx1ApfysvP9bW5umRSBbkOpMGGMfNLpJNaBp3n43546pEjOrya3SCDjHx7J5503a8VP-z9zrnE1ftXO-ZAskSpoknrzzyvZroJeeKCC9AXNq6O/s320/PC3.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321563935910921138&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;Besides, you can interact with the diagram using two tools: Select and Grab. If you pick the Select Tool (default), you can select/deselect lines, rotate/swap/move/scale axes. And if you pick the Grab Tool, you can move the diagram. Bear in mind that anytime you manipulate the diagram, you can execute the &quot;Fit To Screen&quot; command to return to the optimal view.&lt;br /&gt;&lt;br /&gt;3. Axis scaling / Points Moving&lt;br /&gt;&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZ3pBmrwDfREwjM09kKiuO87ucsaUy64hPUGz19LSQo0ICltUfWmjvu7D4TMDDmBYD0c9MLuAkcNeS0eBQGkqIiEx_qNAtuEqtreskSfo7tnCgmojPsuE7bYz8-_K4yfhwu68ZS3d6NjTP/s1600-h/PC4.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiZ3pBmrwDfREwjM09kKiuO87ucsaUy64hPUGz19LSQo0ICltUfWmjvu7D4TMDDmBYD0c9MLuAkcNeS0eBQGkqIiEx_qNAtuEqtreskSfo7tnCgmojPsuE7bYz8-_K4yfhwu68ZS3d6NjTP/s320/PC4.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321572206127859922&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;When your mouse is over any axis, you can move the points on it simply by clicking LMB and moving the mouse up and down or  you can scale it using the mouse wheel. When the mouse cursor isn&#39;t over any axis, using the mouse wheel will scale all the axes. You can scale/move the helper axis as well :)&lt;br /&gt;&lt;br /&gt;4. Axis rotating&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQZn0GcdF4OdUNV_ysxa_k2Tk72D6HuvNnwAXJ2SpkcuBxg4k40QrFUytO_XsZhHFJygdi6ZgGuc6wtDYBLWBaOhQ7LGESpWnUHPiKNeybDssXIDg9V_HZhxPFK7PM2yeFfZGujLzcgBY_/s1600-h/PC5.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQZn0GcdF4OdUNV_ysxa_k2Tk72D6HuvNnwAXJ2SpkcuBxg4k40QrFUytO_XsZhHFJygdi6ZgGuc6wtDYBLWBaOhQ7LGESpWnUHPiKNeybDssXIDg9V_HZhxPFK7PM2yeFfZGujLzcgBY_/s320/PC5.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321580318061183474&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;Axis rotating simply reverses the axis direction. To rotate the axis, move the mouse cursor over it and click the button that will appear at the bottom of the highlighted axis.&lt;br /&gt;&lt;br /&gt;5. Axis swapping&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYeEtDWyUUVrZ23CFH4n5dZyEYpdT8lmp6PKGh2devURm-AG6wKPlgfm_u0cXR3UxmWJjOQuX0iQF50OIRZdfgeQryEpqs_sb5jg498Kmg7rBseKrSH7uejH-pNw6MD5d3eSOSk5J8MC75/s1600-h/PC6.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiYeEtDWyUUVrZ23CFH4n5dZyEYpdT8lmp6PKGh2devURm-AG6wKPlgfm_u0cXR3UxmWJjOQuX0iQF50OIRZdfgeQryEpqs_sb5jg498Kmg7rBseKrSH7uejH-pNw6MD5d3eSOSk5J8MC75/s320/PC6.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321581970188365666&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;You can swap two axes by dragging the source axis (with left CTRL button pressed) and dropping it on the destination axis. After this, the source and the destination axes will swap their placements (see the picture below).&lt;br /&gt;&lt;a onblur=&quot;try {parent.deselectBloggerImageGracefully();} catch(e) {}&quot; href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkEVhSv0BECZFl-Y471kZIxb62uNFkRRrcjWM6A_Gu8VZtRb6SMnLOIyYvIM3Q2vu1OhA3sWdijkgYsJcMiMhfktZisGR09QYnMrFrvqR7YlOV2_K2dfBj6nDqD7t7zXf7pigRVYQvp9vp/s1600-h/PC7.jpg&quot;&gt;&lt;img style=&quot;margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 246px;&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkEVhSv0BECZFl-Y471kZIxb62uNFkRRrcjWM6A_Gu8VZtRb6SMnLOIyYvIM3Q2vu1OhA3sWdijkgYsJcMiMhfktZisGR09QYnMrFrvqR7YlOV2_K2dfBj6nDqD7t7zXf7pigRVYQvp9vp/s320/PC7.jpg&quot; alt=&quot;&quot; id=&quot;BLOGGER_PHOTO_ID_5321583193993319618&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;span style=&quot;font-weight: bold;&quot;&gt;Using the PC chart&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Using the chart is very straightforward. First, you need to add the &lt;span style=&quot;font-style: italic;&quot;&gt;Chart &lt;/span&gt;control. This is done in XAML like so:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&lt;br /&gt;&amp;lt;Charts:Chart DataSource=&quot;{Binding DataSource}&quot; /&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now, you have to prepare the data. Suppose you want to visualize a collection of the following class.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;&lt;br /&gt;public class DemoInfo&lt;br /&gt;{&lt;br /&gt;public double X { get; set; }&lt;br /&gt;public double Y { get; set; }&lt;br /&gt;public double Z { get; set; }&lt;br /&gt;public double V { get; set; }&lt;br /&gt;public double K { get; set; }&lt;br /&gt;public double M { get; set; }&lt;br /&gt;public int Tag { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;All you have to do is: grab the data, create an appropriate data source, add property to axis mapping, name the labels, and that&#39;s it!&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;&lt;br /&gt;public void DataBind()&lt;br /&gt;{&lt;br /&gt; IList&amp;lt;DemoInfo&amp;gt; infos = new List&amp;lt;DemoInfo&amp;gt;();&lt;br /&gt;&lt;br /&gt; // Generate random data&lt;br /&gt; for (int i = 0; i &amp;lt; ObjectsCount; i++)&lt;br /&gt; {&lt;br /&gt;     var x = new DemoInfo();&lt;br /&gt;     x.X = m_Random.NextDouble() * 400 - 100;&lt;br /&gt;     x.Y = m_Random.NextDouble() * 500 - 100;&lt;br /&gt;     x.Z = m_Random.NextDouble() * 600 - 300;&lt;br /&gt;     x.V = m_Random.NextDouble() * 800 - 100;&lt;br /&gt;     x.K = 1.0;&lt;br /&gt;     x.M = i;&lt;br /&gt;     x.Tag = i + 1;&lt;br /&gt;&lt;br /&gt;     infos.Add(x);&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; // Create the data source and apply mappings&lt;br /&gt; var dataSource = new MultiDimensionalDataSource&amp;lt;DemoInfo&amp;gt;(infos, 6);&lt;br /&gt; dataSource.MapDimension(0, info =&amp;gt; info.X);&lt;br /&gt; dataSource.MapDimension(1, info =&amp;gt; info.Y);&lt;br /&gt; dataSource.MapDimension(2, info =&amp;gt; info.Z);&lt;br /&gt; dataSource.MapDimension(3, info =&amp;gt; info.V);&lt;br /&gt; dataSource.MapDimension(4, info =&amp;gt; info.K);&lt;br /&gt; dataSource.MapDimension(5, info =&amp;gt; info.M);&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; // Name the labels&lt;br /&gt; dataSource.Labels[0] = &quot;X&quot;;&lt;br /&gt; dataSource.Labels[1] = &quot;Y&quot;;&lt;br /&gt; dataSource.Labels[2] = &quot;Z&quot;;&lt;br /&gt; dataSource.Labels[3] = &quot;V&quot;;&lt;br /&gt; dataSource.Labels[4] = &quot;K&quot;;&lt;br /&gt; dataSource.Labels[5] = &quot;M&quot;;&lt;br /&gt; dataSource.HelperAxisLabel = &quot;Helper axis&quot;;&lt;br /&gt;&lt;br /&gt; myChart.DataSource = dataSource;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Full source code is available &lt;a href=&quot;https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=PierreCode&amp;amp;ReleaseId=2478&quot;&gt;here&lt;/a&gt;. Note that I use M-V-VM approach :)&lt;br /&gt;Hope you like it!&lt;br /&gt;&lt;/div&gt;&lt;/div&gt;</description><link>http://pwlodek.blogspot.com/2009/04/parallel-coordinates-in-wpf-part-1.html</link><author>noreply@blogger.com (Piotr Włodek)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjChRETMTxOrLss-JLkpa6ogq5J35KoxdZPSSbGazeyXmbeVwdhuhpO8VCLHYL1RFOp7FYJBqFdfYcmJ-_aOOz1N6lGCjicusGF4xtaQws2r2mTaToucPfttA6ffI_lulvwevhgRaTD_xok/s72-c/PC8.jpg" height="72" width="72"/><thr:total>6</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-4636093631500939304</guid><pubDate>Sun, 15 Mar 2009 21:23:00 +0000</pubDate><atom:updated>2009-03-16T19:59:59.991+01:00</atom:updated><title>Exam 70-536 passed :)</title><description>Three days ago (being more specific, on Friday 13th ;) ) I&#39;ve passed my first Microsoft developer&#39;s exam, &lt;a href=&quot;http://www.microsoft.com/learning/en/us/exams/70-536.aspx&quot;&gt;70-536 TS: Microsoft .NET Framework - Application Development Foundation&lt;/a&gt;, scoring &lt;span style=&quot;font-weight: bold;&quot;&gt;876 points&lt;/span&gt; out of 1000. In short, I had 40 question and 135 minutes. As far as questions are concerned, there were many about serialization (rather not very straightforward), interoperability and globalization. No questions about mailing functionality. The questions ranged from very simple to quite though. Most of them were single choice questions, I got maybe three or four multiple choice ones.&lt;br /&gt;&lt;br /&gt;Some say this is an easy exam. Well, I wouldn&#39;t say so, because the exam covers almost every .NET basic subject. In order to pass, you need to have solid theoretical background, but at the same time you need to get you hands dirty by playing with some code samples too. I recommend examining the official &lt;a href=&quot;http://www.microsoft.com/learning/en/us/books/12915.aspx&quot;&gt;Training Kit&lt;/a&gt; (now there&#39;s 2nd edition, the first one was quite buggy so don&#39;t rely only on that book). Skimming MSDN seems like a good idea too ;) However, there&#39;s no better source of knowledge than the developer&#39;s head and experience.  Most of the questions I answered because of my experience and not because of the books!&lt;br /&gt;&lt;br /&gt;Next, I&#39;m going for the exam 70-502: &lt;a href=&quot;http://www.microsoft.com/learning/en/us/books/12485.aspx&quot;&gt;Microsoft® .NET Framework 3.5—Windows® Presentation Foundation&lt;/a&gt;. Good luck with your own certifications!</description><link>http://pwlodek.blogspot.com/2009/03/exam-70-536-passed.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-891889700878195825.post-8783664368976165951</guid><pubDate>Tue, 24 Feb 2009 21:38:00 +0000</pubDate><atom:updated>2009-02-24T23:10:13.634+01:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">CompositeWPF</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Lack of AttachNewRegion method in Prism 2.0</title><description>Today I have switched to &lt;a href=&quot;http://www.codeplex.com/CompositeWPF&quot;&gt;Composite WPF and Silverlight 2.0&lt;/a&gt; (known as &lt;a href=&quot;http://www.codeplex.com/CompositeWPF&quot;&gt;Prism 2.0&lt;/a&gt;) in one of my current projects. The transition was quite smooth (I used a guide which I found &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/dd490816.aspx&quot;&gt;here&lt;/a&gt;), although I found one issue - the &lt;span style=&quot;font-style: italic;&quot;&gt;IRegionManager&lt;/span&gt; interface does not contain the &lt;span style=&quot;font-style: italic;&quot;&gt;AttachNewRegion&lt;/span&gt; method :( This made me very unhappy because I used this method in the implementation of a &lt;span style=&quot;font-style: italic;&quot;&gt;IMenuService&lt;/span&gt; which is responsible for managing the main menu control within my application by exposing a friendly interface to all modules. After small source code investigation I realized that indeed there&#39;s no sign of the mentioned method. After reading interesting post &lt;a href=&quot;http://www.codeplex.com/CompositeWPF/Thread/View.aspx?ThreadId=45847&quot;&gt;here&lt;/a&gt;, I decided to write one myself, which was a trivial task ;) Here&#39;s the code:&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;brush: c-sharp&quot;&gt;&lt;br /&gt;&lt;br /&gt;using System;&lt;br /&gt;using System.Windows;&lt;br /&gt;using Microsoft.Practices.Composite.Presentation.Regions;&lt;br /&gt;using Microsoft.Practices.Composite.Regions;&lt;br /&gt;&lt;br /&gt;namespace Mammoth.Presentation.Infrastructure.Common&lt;br /&gt;{&lt;br /&gt;   public static class RegionManagerExtensions&lt;br /&gt;   {&lt;br /&gt;       public static void AttachNewRegion(this IRegionManager regionManager, object regionTarget, string regionName)&lt;br /&gt;       {&lt;br /&gt;           if (regionManager.Regions.ContainsRegionWithName(regionName))&lt;br /&gt;               throw new ArgumentException(&quot;Region already exists.&quot;, regionName);&lt;br /&gt;&lt;br /&gt;           RegionManager.SetRegionManager((DependencyObject) regionTarget, regionManager);&lt;br /&gt;           RegionManager.SetRegionName((DependencyObject) regionTarget, regionName);&lt;br /&gt;       }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As you can see, this is a very simple extension method that extends the IRegionManger interface. Inside, I simply set the region manager and the region name on the desired UI element.&lt;br /&gt;&lt;br /&gt;This solution is very simple, still it works fine (at least for me). If you have any troubles with it, let me know.</description><link>http://pwlodek.blogspot.com/2009/02/lack-of-attachnewregion-method-in-prism.html</link><author>noreply@blogger.com (Piotr Włodek)</author><thr:total>0</thr:total></item></channel></rss>