tag:blogger.com,1999:blog-69867692569442132842024-03-08T12:26:17.056-08:00SeeR MindFlowseerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.comBlogger11125tag:blogger.com,1999:blog-6986769256944213284.post-13841615207985529102010-11-22T13:46:00.001-08:002010-11-22T14:29:38.819-08:00Make Internet Explorer Feeds/podcasts available in Windows Media Player DLNA server with names instead of GUIDs<p>Last time I found that you can <a href="http://seermindflow.blogspot.com/2010/11/podcast-client-that-can-use-bits-ie8.html" target="_blank">download podcasts using Internet Explorer</a>. <br />Reasonable next step was to make it available to DLNA Player, so I can watch videocasts on my SONY Bravia KDL-40EX700, or listen podcasts on <a href="http://europe.nokia.com/find-products/accessories/all-accessories/music/music-streaming/nokia-home-music" target="_blank">Nokia Home Music</a> (which I will have soon) in my bedroom.</p> <p>Windows Media player can share folders, this one is simple to setup. Problem is that Internet Explorer saves all feed attachments in folders named as GUID numbers and it seems that it’s hardcoded and not configurable. <br /><img src="http://lh6.ggpht.com/_fMibvjBHyKw/TOrd73PENRI/AAAAAAAAAKo/MUs5G-AXy0I/feeds_enclosures.png" /> <br /> <br />On the other side Windows media Player cannot rename folders it shares through DLNA.</p> <p>But <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Uśmiech" src="http://lh6.ggpht.com/_fMibvjBHyKw/TOrkrGsDvDI/AAAAAAAAALA/SLc4CpC2rYQ/wlEmoticon-smile%5B2%5D.png?imgmax=800" />.</p> <p>NTFS has ability to create junctions – which means hard link to folder – which means shortcut but on file system level, not a file with .lnk extension. <br />So we can cheat WMP by creating “<strong>podcasts</strong>” and “<strong>videocasts</strong>” folders than create a junctions in it pointing to each podcast or videocast GUID named folder.</p> <p>Seems simple - but how?</p> <p>Fortunately I found <a href="http://schinagl.priv.at/nt/hardlinkshellext/hardlinkshellext.html" target="_blank">Link Shell Extension</a> which make it stupid simple. Just “right click” + “drag& drop” GUID named folder to our podcasts folder, choose option to create junction and rename it.</p> <p><img src="http://lh5.ggpht.com/_fMibvjBHyKw/TOrjAVQp0PI/AAAAAAAAAKw/FuBTH_Anstk/junction_drag_and_drop.png" /> <br /> <br /> <br /><a title="Yeah I know - it's in Polish, but in english it's exactly in the same place." href="http://lh6.ggpht.com/_fMibvjBHyKw/TOrjA1XI9pI/AAAAAAAAAK0/hhSNDxgw1rI/junction_choose_option.png" target="_blank"><img src="http://lh6.ggpht.com/_fMibvjBHyKw/TOrjA1XI9pI/AAAAAAAAAK0/hhSNDxgw1rI/junction_choose_option.png" /></a> <br /> <br /> <br /><img src="http://lh4.ggpht.com/_fMibvjBHyKw/TOrjBCqxY3I/AAAAAAAAAK4/bFUz_maBNhQ/junction_rename.png" /></p> <p> </p> <p>And now I can listen/watch my podcasts on TV or Nokia Home Music</p> <p><img src="http://lh4.ggpht.com/_fMibvjBHyKw/TOruQExR7jI/AAAAAAAAALM/fvZ3Qg0R9Ko/s800/podcasts_through_DLNA.JPG" /> <br /> <br /><img src="http://lh5.ggpht.com/_fMibvjBHyKw/TOruQS-RlbI/AAAAAAAAALQ/NY62oikS1yQ/s800/podcasts_through_DLNA1.JPG" /></p> <p> </p> <p>Simple, but only when you know what to do.</p> <p>Dear Microsoft – can you make it a little simpler?</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-52689585845159811512010-11-22T12:25:00.001-08:002010-11-22T12:25:46.157-08:00Podcast client that can use BITS – IE8<p>For two years I was looking for some podcast download client that I will be happy with. After few tries I <br />1) Started to realize what I want, <br />2) None of available alternatives gived me what I wanted.</p> <p>So first, my requiremets:</p> <ul> <li>It should download podcasts/videocasts correctly – sadly it’s not so obvious.</li> <li>I want to be able to set up how frequently it should check for new podcasts</li> <li>I want to be able to set how much old podcasts should be in download folder (older should be deleted)</li> <li>It should use BITS to download podcasts, so that I use internet for other things also.</li> </ul> <p>I was trying few clients and their quality was really bad. I was so frustrated that almost wanted to create a such. <br />Then I bought PSP for my son and found that it’s a <a href="http://manuals.playstation.net/document/en/psp/current/network/rss/index.html" target="_blank">great podcast client/downloader/viewer</a>. The minor drawback is that it is downloading with full speed, but in exchange you can set it up so that it’s doing it at night (let say at 4:00 PM). The bigger one is that you can only watch MPEG4 AVC videos.</p> <p>Until now I’m using PSP, but 2 days ago I found that Internet Explorer has everything I want from version 7. <br />Uhh.</p> <p>So how to do it</p> <ol> <li>Subscribe to podcast – add it to your <strong>Feeds</strong></li> <li>Right click on it and choose <strong>Properties <br /><img src="http://lh6.ggpht.com/_fMibvjBHyKw/TOrI1-wAKFI/AAAAAAAAAKQ/r4L6wZW5-lc/feed_properties.png" /> <br /></strong></li> <li>Check  “<strong>Automatically download attached files</strong>” and change the number of items that will be stored on your machine to some reasonable value (to avoid filling up your HD) <br /> <br /><img src="http://lh3.ggpht.com/_fMibvjBHyKw/TOrKNIu4PwI/AAAAAAAAAKY/Kl4es4JAwdM/feed_properties2.png" /> <br /></li> <li>Now your computer will download podcasts/videocasts in the background using <a href="http://en.wikipedia.org/wiki/Background_Intelligent_Transfer_Service" target="_blank">BITS</a>. You can check status of your download by clicking on the feed and reading gray text next to file link. When it changes to <font color="#a5a5a5">(Downloaded)</font><font color="#000000">, link will point to your disk. <br /> <br /><img src="http://lh6.ggpht.com/_fMibvjBHyKw/TOrNAP3LjeI/AAAAAAAAAKg/_VlS2o_NNyM/feed_download_status.png" /> <br /></font></li> <li>If you receive error “<strong>File size exceeds download limit”</strong> check <a href="http://msdn.microsoft.com/en-us/library/ms686401(VS.85).aspx" target="_blank">this MSDN documentation</a> for FDE_DOWNLOAD_SIZE_LIMIT_EXCEEDED error code and set appropriate value in registry.</li> </ol> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-48083093438016446342009-09-11T15:48:00.001-07:002009-09-11T15:54:39.501-07:00My virtual static implementation<p>What I want is to be able to write code like this:</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red163\green21\blue21;}??\fs20 \cf1 public\cf0 T Create<T>() \cf1 where\cf0 T : \cf1 new\cf0 (\cf1 string\cf0 )\par ??\{\par ?? \cf1 return\cf0 \cf1 new\cf0 T(\cf4 "something"\cf0 );\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> T Create<T>() <span style="color: blue">where</span> T : <span style="color: blue">new</span>(<span style="color: blue">string</span>)</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">return</span> <span style="color: blue">new</span> T(<span style="color: #a31515">"something"</span>);</p> <p style="margin: 0px">}</p> </div> <p>or this:</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 interface\cf0 \cf4 IConverter\cf0 <Tin, Tout>\par ??\{\par ?? Tout Convert(Tin value);\par ??\}\par ??\par ??\cf1 public\cf0 \cf1 static\cf0 Tout Convert<TConverter, Tin, Tout>(Tin value) \par ?? \cf1 where\cf0 TConverter : \cf4 IConverter\cf0 <Tin, Tout>\par ??\{\par ?? \cf1 return\cf0 TConverter.Convert(value);\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IConverter</span><Tin, Tout></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">static</span> Tout Convert(Tin value);</p> <p style="margin: 0px">}</p> <p style="margin: 0px"> </p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> Tout Convert<TConverter, Tin, Tout>(Tin value) </p> <p style="margin: 0px">    <span style="color: blue">where</span> TConverter : <span style="color: #2b91af">IConverter</span><Tin, Tout></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">return</span> TConverter.Convert(value);</p> <p style="margin: 0px">}</p> </div> <p>but current (4.0) version of C#/CLR doesn’t allow me to do it, so I was forced to think about substitute solution.</p> <p>If we think about virtual methods we need class that has them and we need instance of this class.</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 class\cf0 \cf4 IntStringConverter\cf0 : \cf4 IConverter\cf0 <\cf1 int\cf0 , \cf1 string\cf0 >\par ??\{\par ?? \cf1 public\cf0 \cf1 static\cf0 \cf1 readonly\cf0 \cf4 IntStringConverter\cf0 Instance = \cf1 new\cf0 \cf4 IntStringConverter\cf0 (); \par ?? \cf1 public\cf0 \cf1 virtual\cf0 \cf1 string\cf0 Convert(\cf1 int\cf0 value)\par ?? \{\par ?? \cf1 return\cf0 value.ToString();\par ?? \}\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">IntStringConverter</span> : <span style="color: #2b91af">IConverter</span><<span style="color: blue">int</span>, <span style="color: blue">string</span>></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IntStringConverter</span> Instance = <span style="color: blue">new</span> <span style="color: #2b91af">IntStringConverter</span>(); </p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Convert(<span style="color: blue">int</span> value)</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">return</span> value.ToString();</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> </div> <p>But this gives us nothing because we need to know exact type. So I’ve created following class</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 static\cf0 \cf1 class\cf0 \cf4 Static\cf0 <T> \cf1 where\cf0 T : \cf1 new\cf0 ()\par ??\{\par ?? \cf1 private\cf0 \cf1 static\cf0 \cf1 bool\cf0 initilized;\par ?? \cf1 private\cf0 \cf1 static\cf0 T value;\par ??\par ?? \cf1 public\cf0 \cf1 static\cf0 T Value\par ?? \{\par ?? \cf1 get\par ??\cf0 \{\par ?? \cf1 if\cf0 (!initilized)\par ?? \{\par ?? value = \cf1 new\cf0 T();\par ?? initilized = \cf1 true\cf0 ;\par ?? \}\par ?? \cf1 return\cf0 value;\par ?? \}\par ?? \}\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">Static</span><T> <span style="color: blue">where</span> T : <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: blue">bool</span> initilized;</p> <p style="margin: 0px">    <span style="color: blue">private</span> <span style="color: blue">static</span> T value;</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">static</span> T Value</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">get</span></p> <p style="margin: 0px">        {</p> <p style="margin: 0px">            <span style="color: blue">if</span> (!initilized)</p> <p style="margin: 0px">            {</p> <p style="margin: 0px">                value = <span style="color: blue">new</span> T();</p> <p style="margin: 0px">                initilized = <span style="color: blue">true</span>;</p> <p style="margin: 0px">            }</p> <p style="margin: 0px">            <span style="color: blue">return</span> value;</p> <p style="margin: 0px">        }</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> </div> <p>to use it instead of <em>Instance</em> field.</p> <p>And now I can write Convert method like this:</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 static\cf0 Tout Convert<TConverter, Tin, Tout>(Tin value) \par ?? \cf1 where\cf0 TConverter : \cf4 IConverter\cf0 <Tin, Tout>, \cf1 new\cf0 ()\par ??\{\par ?? \cf1 return\cf0 \cf4 Static\cf0 <TConverter>.Value.Convert(value);\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> Tout Convert<TConverter, Tin, Tout>(Tin value) </p> <p style="margin: 0px">    <span style="color: blue">where</span> TConverter : <span style="color: #2b91af">IConverter</span><Tin, Tout>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">return</span> <span style="color: #2b91af">Static</span><TConverter>.Value.Convert(value);</p> <p style="margin: 0px">}</p> </div> <p>or Create method</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0 \cf1 interface\cf0 \cf4 INew\cf0 <T, T1>\par ??\{\par ?? T New(T1 param1);\par ??\}\par ??\par ??\cf1 public\cf0 \cf1 static\cf0 T Create<T, TFactory>() \cf1 where\cf0 TFactory : \cf4 INew\cf0 <T, \cf1 string\cf0 >, \cf1 new\cf0 ()\par ??\{\par ?? \cf1 return\cf0 \cf4 Static\cf0 <TFactory>.Value.New(\cf5 "somethng"\cf0 );\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">INew</span><T, T1></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    T New(T1 param1);</p> <p style="margin: 0px">}</p> <p style="margin: 0px"> </p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> T Create<T, TFactory>() <span style="color: blue">where</span> TFactory : <span style="color: #2b91af">INew</span><T, <span style="color: blue">string</span>>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">return</span> <span style="color: #2b91af">Static</span><TFactory>.Value.New(<span style="color: #a31515">"something"</span>);</p> <p style="margin: 0px">}</p> </div> <p>So my solution is to create one instance of my “virtual static” type and make sure all other classes can use it without tight coupling to some static field. Right now, all they need to know is <span style="color: #2b91af">Static</span><T> class.</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-84063402188996836022009-08-25T03:28:00.001-07:002009-08-25T03:28:55.987-07:00Why should you use generics instead of simple interfaces in method parameters in .NET<p>Answer: for performance reasons</p> <p>Consider following methods</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">void</span> TestMax()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">int</span> max = (<span style="color: blue">int</span>)Max(<span style="color: green">5</span>, <span style="color: green">10</span>);</p> <p style="margin: 0px">}</p> <p style="margin: 0px"> </p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">object</span> Max(<span style="color: #2b91af">IComparable</span> left, <span style="color: #2b91af">IComparable</span> right)</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">return</span> left.CompareTo(right) > <span style="color: green">0</span> ? left : right;</p> <p style="margin: 0px">}</p> </div> <p>Now let see how TestMax() is looking when compiled to IL</p> <pre>.method public hidebysig static <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Void">void</a> <b><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://CreateCertificateTest:1.0.0.0/CreateCertificateTest.Program/TestMax()">TestMax</a></b>() cil managed<br />{<br /> .maxstack 2<br /> .locals init ([0] <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32">int32</a> <b>max</b>)<br /> L_0000: <a>nop</a> <br /> L_0001: <a>ldc.i4.5</a> <br /> <strong>L_0002: </strong><a><strong>box</strong></a><strong> </strong><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32"><strong>int32</strong></a><br /> L_0007: <a>ldc.i4.s</a> 10<br /> <strong>L_0009: </strong><a><strong>box</strong></a><strong> </strong><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32"><strong>int32</strong></a><br /> L_000e: <a>call</a> <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Object">object</a> <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://CreateCertificateTest:1.0.0.0/CreateCertificateTest.Program">Test.Program</a>::<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://CreateCertificateTest:1.0.0.0/CreateCertificateTest.Program/Max(System.IComparable,System.IComparable):Object">Max</a>(class [<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089">mscorlib</a>]<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.IComparable">System.IComparable</a>, class [<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089">mscorlib</a>]<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.IComparable">System.IComparable</a>)<br /> <strong>L_0013: </strong><a><strong>unbox.any</strong></a><strong> </strong><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32"><strong>int32</strong></a><br /> L_0018: <a>stloc.0</a> <br /> L_0019: <a>ret</a> <br />}</pre><br /><br /><p>So as we can see for this simple call we have two <strong>box</strong> instructions. This means that we have two heap allocations (malloc() in c). <br /><br /> <br />Now lets see how generic version will behave:</p><br /><br /><div style="font-family: courier new; background: white; color: black; font-size: 10pt"><br /> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">void</span> TestMax()</p><br /><br /> <p style="margin: 0px">{</p><br /><br /> <p style="margin: 0px">    <span style="color: blue">int</span> max = Max(<span style="color: green">5</span>, <span style="color: green">10</span>);</p><br /><br /> <p style="margin: 0px">}</p><br /><br /> <p style="margin: 0px"> </p><br /><br /> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> T Max<T>(T left, T right) <span style="color: blue">where</span> T : <span style="color: #2b91af">IComparable</span></p><br /><br /> <p style="margin: 0px">{</p><br /><br /> <p style="margin: 0px">    <span style="color: blue">return</span> left.CompareTo(right) > <span style="color: green">0</span> ? left : right;</p><br /><br /> <p style="margin: 0px">}</p><br /></div><br /><br /><p>and TestMax() in IL looks like this: <br /> <br /></p><br /><br /><pre>.method public hidebysig static <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Void">void</a> <b><a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://CreateCertificateTest:1.0.0.0/CreateCertificateTest.Program/TestMax()">TestMax</a></b>() cil managed<br />{<br /> .maxstack 2<br /> .locals init (<br /> [0] <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32">int32</a> <b>max</b>)<br /> L_0000: <a>nop</a> <br /> L_0001: <a>ldc.i4.5</a> <br /> L_0002: <a>ldc.i4.s</a> 10<br /> L_0004: <a>call</a> !!0 <a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://CreateCertificateTest:1.0.0.0/CreateCertificateTest.Program">Test.Program</a>::<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://CreateCertificateTest:1.0.0.0/CreateCertificateTest.Program/Max<>(<!!0>,<!!0>):<!!0>">Max</a><<a href="http://www.aisto.com/roeder/dotnet/Default.aspx?Target=code://mscorlib:2.0.0.0:b77a5c561934e089/System.Int32">int32</a>>(!!0, !!0)<br /> L_0009: <a>stloc.0</a> <br /> L_000a: <a>ret</a> <br />}</pre><br /><br /><p>As you can see instead of <strong>box</strong> we now have <strong>ldc</strong> instructions which means that now we are allocating 2*4 bytes on the stack which is <strong>much much faster </strong>then allocation on the heap.</p><br /><br /><p>So the long answer is: Because by this simple tweak you can speed up your method for all struct parameters.</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-26276891474419013882009-08-07T02:52:00.001-07:002009-08-07T02:52:46.373-07:00How to test generic class/methods with Rhino mocks<p>Rhino mocks is my isolation framework of choice and as you my notice from <a href="http://seermindflow.blogspot.com/2009/07/c-generics-free-but-ugly-dependency.html" target="_blank">my earlier post</a> I use generics as my Inversion of Control tool. Problem is that when you use <a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino Mocks</a> you cannot mock constructor (right now to my knowledge only <a href="http://www.typemock.com/" target="_blank">TypeMock Isolator</a> can do this). The reason for this is that Rhino Mocks generates mocks at runtime, and for testing methods that use <font color="#0000ff">new</font>() constraint you need to know the mock type at compile time. <br />So the only way to solve this seems to be creation of mock classes by hand. But then shortly I realized that all of them seems to look very similar. <br />So…</p> <p>Here is how I solved this: <br />First I created <a href="http://www.visualt4.com/" target="_blank">t4 file</a> called <a href="http://sites.google.com/site/seermindflow/Mocks.tt" target="_blank">Mocks.tt</a> which I attach to my test project.</p> <p>It’s almost unreadable, so don’t be scared – I’m not t4 expert, it’s my first experiment :-)</p> <p>This file is:</p> <ul> <li>generating <font color="#008080">MockAttribute</font> class </li> <li>searching for each class in project (it belongs to) that have such attribute and are partial and then creates mock methods for each interface this class implements and for default constructor. </li> </ul> <p>To create such mock type I must first write something like this:</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px">[<span style="color: #2b91af">Mock</span>]</p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">partial</span> <span style="color: blue">class</span> <span style="color: #2b91af">MockAskEmailWindow</span> : <span style="color: #2b91af">IQuestion</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">}</p> </div> <p>Then click “Run Custom Tool”</p> <p><a href="http://lh3.ggpht.com/_fMibvjBHyKw/Snv5a27Yt9I/AAAAAAAAAB0/EnYO0mfCnVc/s1600-h/runcustomtool3.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="run custom tool" border="0" alt="run custom tool" src="http://lh6.ggpht.com/_fMibvjBHyKw/Snv5bZ8pVJI/AAAAAAAAAB4/kyt63C2mWfE/runcustomtool_thumb1.gif?imgmax=800" width="240" height="230" /></a> </p> <p>And because IQuestion is defined like this</p> <p></p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IQuestion</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">string</span> Ask(<span style="color: blue">string</span> question);</p> <p style="margin: 0px">}</p> </div> <p></p> <p>in file generated by t4 script I have following code</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">partial</span> <span style="color: blue">class</span> <span style="color: #2b91af">MockAskEmailWindow</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">MockAskEmailWindow</span> mock;</p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">bool</span> Created;</p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: #2b91af">MockAskEmailWindow</span> Object;</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">public</span> MockAskEmailWindow()</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">if</span> (<span style="color: #2b91af">Service</span><<span style="color: #2b91af">Queue</span><<span style="color: #2b91af">MockAskEmailWindow</span>>>.Value != <span style="color: blue">null</span>)</p> <p style="margin: 0px">        {</p> <p style="margin: 0px">            mock = <span style="color: #2b91af">Service</span><<span style="color: #2b91af">Queue</span><<span style="color: #2b91af">MockAskEmailWindow</span>>>.Value.Dequeue();</p> <p style="margin: 0px">            mock.Created = <span style="color: blue">true</span>;</p> <p style="margin: 0px">            mock.Object = <span style="color: blue">this</span>;</p> <p style="margin: 0px">        }</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Ask( <span style="color: blue">string</span> question)</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">return</span> mock.Ask( question);</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> </div> <p>Now if we have following method to test:</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">string</span> AskForNewUserEmail<TQuestion>() <span style="color: blue">where</span> TQuestion : <span style="color: #2b91af">IQuestion</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">NotSupportedException</span>();</p> <p style="margin: 0px">}</p> </div> <p>We write test like this:</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px">[<span style="color: #2b91af">Test</span>]</p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">void</span> ShowUsermNewUserEmailRequestAndRetrieveEmail()</p> <p style="margin: 0px">{</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">var</span> ask = <span style="color: #2b91af">MockRepository</span>.GenerateMock<<span style="color: #2b91af">MockAskEmailWindow</span>>();</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    ask.Expect(a => a.Ask(<span style="color: #a31515">"Plase type email of the user you want to create"</span>)).Return(<span style="color: #a31515">"test@test.pl"</span>);</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">using</span> (<span style="color: #2b91af">Service</span>.CreateQueue(ask))</p> <p style="margin: 0px">        <span style="color: #2b91af">Assert</span>.AreEqual(<span style="color: #a31515">"test@test.pl"</span>, AskForNewUserEmail<<span style="color: #2b91af">MockAskEmailWindow</span>>());</p> <p style="margin: 0px">    ask.VerifyAllExpectations();</p> <p style="margin: 0px">}</p> </div> <p>And to make test pass we change our method to</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">string</span> AskForNewUserEmail<TQuestion>() <span style="color: blue">where</span> TQuestion : <span style="color: #2b91af">IQuestion</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">return</span> <span style="color: blue">new</span> TQuestion().Ask(<span style="color: #a31515">"Plase type email of the user you want to create"</span>);</p> <p style="margin: 0px">}</p> </div> <p>Seems, simple :-) <br />The only unknown class that I used here is <font color="#008080">Service<></font> so here is it’s very simple code</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Service</span><T> : <span style="color: #2b91af">IDisposable</span> <span style="color: blue">where</span> T : <span style="color: blue">class</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">private</span> <span style="color: blue">readonly</span> T parent;</p> <p style="margin: 0px">    [<span style="color: #2b91af">ThreadStatic</span>] <span style="color: blue">private</span> <span style="color: blue">static</span> T current;</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">public</span> Service(T service)</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        parent = Value;</p> <p style="margin: 0px">        Value = service;</p> <p style="margin: 0px">    }</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">static</span> T Value</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">get</span> { <span style="color: blue">return</span> current;}</p> <p style="margin: 0px">        <span style="color: blue">private</span> <span style="color: blue">set</span> {current = <span style="color: blue">value</span>;}</p> <p style="margin: 0px">    }</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        Value = parent;</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> <p style="margin: 0px"> </p> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">Service</span></p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: #2b91af">Service</span><<span style="color: #2b91af">Queue</span><T>> CreateQueue<T>(T value, <span style="color: blue">params</span> T[] values)</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">var</span> queue = <span style="color: blue">new</span> <span style="color: #2b91af">Queue</span><T>(values.Length + <span style="color: green">1</span>);</p> <p style="margin: 0px">        queue.Enqueue(value);</p> <p style="margin: 0px">        <span style="color: blue">foreach</span> (<span style="color: blue">var</span> v <span style="color: blue">in</span> values)</p> <p style="margin: 0px">            queue.Enqueue(v);</p> <p style="margin: 0px">        <span style="color: blue">return</span> <span style="color: blue">new</span> <span style="color: #2b91af">Service</span><<span style="color: #2b91af">Queue</span><T>>(queue);</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> </div> <p>This class I created as my implementation of service locator earlier when I tried use this pattern to decouple the code. As you can see from code, service implementations can be nested and are specific for current thread (I failed to create services that work between multiple thread because of <a href="http://stackoverflow.com/questions/883486/endinvoke-changes-current-callcontext-why" target="_blank">strange CallContext class behaviour</a> when someone called EndInvoke()). If anyone is interested here is example of usage:</p> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: blue">new</span> <span style="color: #2b91af">Service</span><<span style="color: #2b91af">IQuestion</span>>(<span style="color: blue">new</span> <span style="color: #2b91af">MockAskEmailWindow</span>()))</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: green">//some code</span></p> <p style="margin: 0px">    <span style="color: blue">using</span> (<span style="color: blue">new</span> <span style="color: #2b91af">Service</span><<span style="color: #2b91af">IQuestion</span>>(<span style="color: blue">new</span> <span style="color: #2b91af">MockAskEmailWindow</span>()))</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: green">//some other code that uses other version of IQuestion</span></p> <p style="margin: 0px">        <span style="color: green">//by calling Service<IQuestion>.Value</span></p> <p style="margin: 0px">    }</p> <p style="margin: 0px">    <span style="color: green">//here we use again the first IQuestion</span></p> <p style="margin: 0px">}</p> </div> <p>But back to generic method testing as you can see from example above the scheme is following:</p> <ul> <li>Create mocks using Rhino Mocks </li> <li>put them in the service queue </li> <li>run tested method </li> <li>When mocked type instance is created it takes mock from service queue </li> <li>All calls to newly created object are redirected to mock created in test </li> </ul> <p>And that’s it.</p> <p>Just one more note: Because of EnvDTE unavailability to read generic constraints (and because it was failing when I called CodeMethod.StartPoint and CodeMethod.EndPoint) I was unable to mock such methods. I solved this by don’t mocking it at all. You must implement such method in your part of partial mock class.</p> <p>Hope this helps someone</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-78108298588452629932009-07-30T18:03:00.001-07:002009-07-30T18:03:07.214-07:00C# generics – free but ugly Dependency Injection<p>I must admit that: I’m obsessed with generics for some time.</p> <p> </p> <p>Some time ago my way to decouple code <a href="http://seermindflow.blogspot.com/2008/07/one-instance-of-dataset-in-application.html" target="_blank">was to use IServiceProvider</a>. It was great but required from me and my coworkers to pass it to each newly created class.</p> <p>In the mean time other developers used different IoC containers which solved this problem by using static methods to register and use specific objects. For example:</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;\red0\green0\blue255;}??\fs20 \cf1 IOC\cf0 .Register<\cf1 ISomething\cf0 >(\cf4 new\cf0 \cf1 Something\cf0 ());}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: #2b91af">IOC</span>.Register<<span style="color: #2b91af">ISomething</span>>(<span style="color: blue">new</span> <span style="color: #2b91af">Something</span>());</p> <p style="margin: 0px"> </p> <p style="margin: 0px">And later in the code it was used like this:</p> <p style="margin: 0px"> </p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 IOC\cf0 .Resolve<\cf1 ISomething\cf0 >().DoSomething();}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: #2b91af">IOC</span>.Resolve<<span style="color: #2b91af">ISomething</span>>().DoSomething();</p> </div> </div> <p>As I said it solved one problem but I had still other problems with that:</p> <ul> <li>Because of static methods I can have only one configuration for the whole application </li> <li>Even if I tried to create my version of IoC container that can be nested like this <br /><!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red0\green128\blue0;}??\fs20 \cf1 using\cf0 (\cf1 new\cf0 \cf4 Service\cf0 <\cf4 IService\cf0 >(\cf1 new\cf0 \cf4 ServiceImplementation\cf0 ()))\par ??\{\par ?? \cf5 //some code\par ??\cf0 \cf5 //and later\par ??\cf0 \cf1 using\cf0 (\cf1 new\cf0 \cf4 Service\cf0 <\cf4 IService\cf0 >(\cf1 new\cf0 \cf4 AnotherServiceImplementation\cf0 ()))\par ?? \{\par ?? \cf5 //some other code\par ??\cf0 \}\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">using</span>(<span style="color: blue">new</span> <span style="color: #2b91af">Service</span><<span style="color: #2b91af">IService</span>>(<span style="color: blue">new</span> <span style="color: #2b91af">ServiceImplementation</span>()))</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: green">//some code</span></p> <p style="margin: 0px">    <span style="color: green">//and later</span></p> <p style="margin: 0px">    <span style="color: blue">using</span>(<span style="color: blue">new</span> <span style="color: #2b91af">Service</span><<span style="color: #2b91af">IService</span>>(<span style="color: blue">new</span> <span style="color: #2b91af">AnotherServiceImplementation</span>()))</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: green">//some other code</span></p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> </div> <br />I failed to create a version that worked correctly between multiple threads, because I was forced to use static fields and <a href="http://stackoverflow.com/questions/846187/how-to-include-own-data-in-executioncontext" target="_blank">I was unable to force CallContext to not overwrite current Thread configuration when EndInvoke() was called</a>. </li> <li>If I want to write component that may be used by someone else the only way to inform him about required dependencies is documentation, or runtime errors. </li> <li>I must agree <a href="http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code" target="_blank">with Joel Spolsky</a> that code that uses IoC containers is less readable </li> </ul> <p>Aside from above I’m using static language C#. Why should my dependencies be resolved at runtime. I had never written application that required dynamic dependencies. All of them was known to me while I was writing my applications. <strong>Why not use compiler as my dependency resolver.</strong></p> <p><strong></strong></p> <p>So, <strong>I want to write decoupled and reusable methods and classes.</strong>  This can be achived partially by parameter or property Dependency Injection.</p> <p>Great, but after a while you come to the moment when you must create new object that will be passed to this method or property.</p> <p>What now, how can I create instance of class without coupling to concrete type, and not using IServiceProvider or static IoC Container (or worse: use reflection). Then it hit me: <strong>we can make new() constraint on generic type</strong>. That way I can write my method/class in a way that it will create instances without knowledge of concrete type. <strong>We can create really decoupled/reusable code using  generics</strong>.</p> <p> </p> <p>After few tests I also created short rule:</p> <p><strong>Every time you must call new() – do it on generic type.</strong> (It doesn’t matter if it’s method or class scope generic type)</p> <p> </p> <p>There is one problem with this rule – I must use default constructor - which means – I must inject all already instantiated dependencies by properties or method parameters.</p> <p>Last month I had small project to create application to manage users in database where data are encrypted. It was separate, small exe file – so I thought that I test my thoughts about generics. As example of decoupled code lets see fragment of my UserCreator class:</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 class\cf0 \cf4 UserCreator\cf0 <TRepository, TCertificateStore, TCertificate, TUserLoginQuestion, TPasswordGenerator> : \cf4 IUserCreator\cf0 <TRepository>\par ?? \cf1 where\cf0 TRepository : \cf4 IRepository\par ??\cf0 \cf1 where\cf0 TCertificateStore : \cf4 ICertificateStore\cf0 <TCertificate>, \cf1 new\cf0 ()\par ?? \cf1 where\cf0 TCertificate : \cf4 ICertificate\par ??\cf0 \cf1 where\cf0 TUserLoginQuestion : \cf4 IQuestion\cf0 , \cf1 new\cf0 ()\par ?? \cf1 where\cf0 TPasswordGenerator : \cf4 IPasswordGenerator\cf0 , \cf1 new\cf0 ()\par ??\{\par ?? \cf1 public\cf0 TRepository Repository \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\par ?? \cf1 public\cf0 \cf1 void\cf0 CreateFirstUser()\par ?? \{\par ?? \cf1 var\cf0 store = \cf1 new\cf0 TCertificateStore();\par ?? \cf1 var\cf0 adminCert = store.CreateAdministratorCertificate();\par ?? store.SaveAdministratorCertificate();\par ?? \cf1 var\cf0 login = \cf1 new\cf0 TUserLoginQuestion().Ask();\par ?? \cf1 var\cf0 userCert = store.CreateUserCertificate(login);\par ?? store.SaveUserCertificate(userCert);\par ?? \cf1 var\cf0 userCertBytes = userCert.ToBytes();\par ?? Repository.CreateNewUser(login, userCert.Encrypt(\cf4 Encoding\cf0 .ASCII.GetBytes(\cf1 new\cf0 TPasswordGenerator().Generate())), userCertBytes);\par ?? Repository.CreateNewAdministrator(userCertBytes, adminCert.Sign(userCertBytes));\par ?? \}\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UserCreator</span><TRepository, TCertificateStore, TCertificate, TUserLoginQuestion, TPasswordGenerator> : <span style="color: #2b91af">IUserCreator</span><TRepository></p> <p style="margin: 0px">    <span style="color: blue">where</span> TRepository : <span style="color: #2b91af">IRepository</span></p> <p style="margin: 0px">    <span style="color: blue">where</span> TCertificateStore : <span style="color: #2b91af">ICertificateStore</span><TCertificate>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">    <span style="color: blue">where</span> TCertificate : <span style="color: #2b91af">ICertificate</span></p> <p style="margin: 0px">    <span style="color: blue">where</span> TUserLoginQuestion : <span style="color: #2b91af">IQuestion</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">    <span style="color: blue">where</span> TPasswordGenerator : <span style="color: #2b91af">IPasswordGenerator</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">public</span> TRepository Repository { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p> <p style="margin: 0px"> </p> <p style="margin: 0px">    <span style="color: blue">public</span> <span style="color: blue">void</span> CreateFirstUser()</p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">var</span> store = <span style="color: blue">new</span> TCertificateStore();</p> <p style="margin: 0px">        <span style="color: blue">var</span> adminCert = store.CreateAdministratorCertificate();</p> <p style="margin: 0px">        store.SaveAdministratorCertificate();</p> <p style="margin: 0px">        <span style="color: blue">var</span> login = <span style="color: blue">new</span> TUserLoginQuestion().Ask();</p> <p style="margin: 0px">        <span style="color: blue">var</span> userCert = store.CreateUserCertificate(login);</p> <p style="margin: 0px">        store.SaveUserCertificate(userCert);</p> <p style="margin: 0px">        <span style="color: blue">var</span> userCertBytes = userCert.ToBytes();</p> <p style="margin: 0px">        Repository.CreateNewUser(login, userCert.Encrypt(<span style="color: #2b91af">Encoding</span>.ASCII.GetBytes(<span style="color: blue">new</span> TPasswordGenerator().Generate())), userCertBytes);</p> <p style="margin: 0px">        Repository.CreateNewAdministrator(userCertBytes, adminCert.Sign(userCertBytes));</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">}</p> </div> <p>Uhh, little ugly – but (almost) completly decoupled (<span style="color: #2b91af">Encoding</span>.ASCII.GetBytes is not important dependency in that case). To make this class more usable I created also default version</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 class\cf0 \cf4 UserCreator\cf0 : \cf4 UserCreator\cf0 <\cf4 RepositoryDataContext\cf0 , \cf4 CertificateStore\cf0 , \cf4 Certificate\cf0 , \cf4 AskUserEmailForm\cf0 , \cf4 PasswordGenerator\cf0 >\{\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UserCreator</span> : <span style="color: #2b91af">UserCreator</span><<span style="color: #2b91af">RepositoryDataContext</span>, <span style="color: #2b91af">CertificateStore</span>, <span style="color: #2b91af">Certificate</span>, <span style="color: #2b91af">AskUserEmailForm</span>, <span style="color: #2b91af">PasswordGenerator</span>>{}</p> </div> <p>As you can see I can change everything this class uses to whatever implementation I want. What blows my mind is – <strong>how such small method requires so much dependencies</strong>. Below you have example of usage:</p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 static\cf0 \cf1 void\cf0 Main<TRepository, TAdministratorTable, TAdministrator, TUserCreator, TLogin, TApplication>(TRepository repository)\par ?? \cf1 where\cf0 TRepository : \cf4 IRepository\cf0 , \cf4 IAdministratorRepositoy\cf0 <TAdministratorTable, TAdministrator>\par ?? \cf1 where\cf0 TAdministratorTable : \cf4 IQueryable\cf0 <TAdministrator>, \cf4 ITable\par ??\cf0 \cf1 where\cf0 TAdministrator : \cf4 IAdministrator\cf0 , \cf1 new\cf0 ()\par ?? \cf1 where\cf0 TUserCreator : \cf4 IUserCreator\cf0 <TRepository>, \cf1 new\cf0 ()\par ?? \cf1 where\cf0 TLogin : \cf4 ILogin\cf0 , \cf1 new\cf0 ()\par ?? \cf1 where\cf0 TApplication : \cf4 IApplication\cf0 , \cf1 new\cf0 ()\par ??\{\par ?? \cf1 try\par ??\cf0 \{\par ?? \cf1 if\cf0 (repository.Administrators.Count() == 0)\par ?? \cf1 new\cf0 TUserCreator\{Repository = repository\}.CreateFirstUser();\par ?? \cf1 var\cf0 login = \cf1 new\cf0 TLogin();\par ?? login.Login();\par ?? \cf1 if\cf0 (login.UserAuthenticated)\par ?? \cf1 new\cf0 TApplication().Start();\par ?? \}\par ?? \cf1 catch\cf0 (\cf4 CancelException\cf0 )\par ?? \{\}\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">void</span> Main<TRepository, TAdministratorTable, TAdministrator, TUserCreator, TLogin, TApplication>(TRepository repository)</p> <p style="margin: 0px">    <span style="color: blue">where</span> TRepository : <span style="color: #2b91af">IRepository</span>, <span style="color: #2b91af">IAdministratorRepository</span><TAdministratorTable, TAdministrator></p> <p style="margin: 0px">    <span style="color: blue">where</span> TAdministratorTable : <span style="color: #2b91af">IQueryable</span><TAdministrator>, <span style="color: #2b91af">ITable</span></p> <p style="margin: 0px">    <span style="color: blue">where</span> TAdministrator : <span style="color: #2b91af">IAdministrator</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">    <span style="color: blue">where</span> TUserCreator : <span style="color: #2b91af">IUserCreator</span><TRepository>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">    <span style="color: blue">where</span> TLogin : <span style="color: #2b91af">ILogin</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">    <span style="color: blue">where</span> TApplication : <span style="color: #2b91af">IApplication</span>, <span style="color: blue">new</span>()</p> <p style="margin: 0px">{</p> <p style="margin: 0px">    <span style="color: blue">try</span></p> <p style="margin: 0px">    {</p> <p style="margin: 0px">        <span style="color: blue">if</span> (repository.Administrators.Count() == 0)</p> <p style="margin: 0px">            <span style="color: blue">new</span> TUserCreator{Repository = repository}.CreateFirstUser();</p> <p style="margin: 0px">        <span style="color: blue">var</span> login = <span style="color: blue">new</span> TLogin();</p> <p style="margin: 0px">        login.Login();</p> <p style="margin: 0px">        <span style="color: blue">if</span> (login.UserAuthenticated)</p> <p style="margin: 0px">            <span style="color: blue">new</span> TApplication().Start();</p> <p style="margin: 0px">    }</p> <p style="margin: 0px">    <span style="color: blue">catch</span>(<span style="color: #2b91af">CancelException</span>)</p> <p style="margin: 0px">    {}</p> <p style="margin: 0px">}</p> </div> <p>In line</p> <p>            <span style="color: blue">new</span> TUserCreator{Repository = repository}.CreateFirstUser();</p> <p>you can see that I must pass repository as property. It will be great if I can make a constraint for constructor other than default. For example</p> <p>    <span style="color: blue">where</span> TUserCreator : <span style="color: #2b91af">IUserCreator</span><TRepository>, <span style="color: blue">new</span>(TRepository)</p> <p>but right now I must live with a tools I have (c# 3.0). I don’t have strong opinion which is better default constructor + properties or specific constructor.</p> <p> </p> <p>I was afraid that when my codebase will grow the list of dependencies will grow, especially in Main() method. What I observed instead of this was that each method require max 6-10 dependencies. Not so scary.</p> <p> </p> <p>OK time for some summary: <br />Pros:</p> <ul> <li>Completly decoupled/reusable code </li> <li>Completly testable code </li> <li>Best performance possible (no boxing for value types) </li> <li>Free – you already have all tools – I mean you already have one tool – compiler :-) </li> <li>All dependencies are resolved by compiler </li> <li>User of your code knows all dependencies at compile time (using only intellisense) </li> <li>Because dependencies are static, they will not change in other thread (until you say so) </li> </ul> <p>Cons:</p> <ul> <li>Little ugly method/class definition (I’m sure that better type inference would help here, but I’m not sure how much better is possible) </li> <li>Only constraint for default constructor is possible </li> <li>No possibility to use static methods (<a href="http://channel9.msdn.com/posts/Charles/Ian-Carmichael-The-History-and-Future-of-CLR/?CommentID=473023" target="_blank">MS please add static virtual methods</a>) </li> </ul> <p>If anyone isintrested I’ll try to write in short time how I test such generic methods/classes. Especially how I test newly created instances. All I can say right now is that I use t4 script and Rhino Mocks.</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-71709943157478570492008-10-09T14:39:00.001-07:002009-07-30T14:51:44.470-07:00Is it possible to write c# application without using cast?<p>For last few months I'm more and more fascinated with .NET generics. Especially interesting for me is a (totally academic) question: Is it possible to write application without using an cast? <br />While considering that option first 2 problematic cases I found was some kind of cache or ServiceProvider implementations. I even <a href="http://stackoverflow.com/questions/178255/serviceprovider-cache-etc-done-with-generics-without-cast" target="_blank">asked a question on stackoverflow.com</a> if it's possible, but the only answer I had was that it's not or that I should have something like WeakDictionary - which probably will use cast in its implementation.</p> <p>But I wouldn't be oneself if I will abandon this subject :-). As I <a href="http://stackoverflow.com/questions/178255/serviceprovider-cache-etc-done-with-generics-without-cast" target="_blank">showed in question</a> it's possible for only one instance using static generic fields, but I can't find the solution for non static objects. After few days I think I found the solution to this - not so elegant, but it should work.</p> <p>So here you have fully generic (but simplified) implementation of ServiceProvider: </p> <!--<br />{\rtf1\ansi\ansicpg\lang1024\noproof1250\uc1 \deff0{\fonttbl{\f0\fnil\fcharset238\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0 \cf1 class\cf0 \cf4 ServiceContainer\cf0 : \cf4 IDisposable\par ??\cf0 \{\par ?? \cf1 readonly\cf0 \cf4 IList\cf0 <\cf4 IService\cf0 > services = \cf1 new\cf0 \cf4 List\cf0 <\cf4 IService\cf0 >();\par ??\par ?? \cf1 public\cf0 \cf1 void\cf0 Add<T>(T service)\par ?? \{\par ?? Add<T,T>(service);\par ?? \}\par ??\par ?? \cf1 public\cf0 \cf1 void\cf0 Add<Key, T>(T service) \cf1 where\cf0 T : Key\par ?? \{\par ?? services.Add(\cf1 new\cf0 \cf4 Service\cf0 <Key>(\cf1 this\cf0 , service));\par ?? \}\par ??\par ?? \cf1 public\cf0 \cf1 void\cf0 Dispose()\par ?? \{\par ?? \cf1 foreach\cf0 (\cf1 var\cf0 service \cf1 in\cf0 services)\par ?? service.Remove(\cf1 this\cf0 );\par ?? \}\par ??\par ?? ~ServiceContainer()\par ?? \{\par ?? Dispose();\par ?? \}\par ??\par ?? \cf1 public\cf0 T Get<T>()\par ?? \{\par ?? \cf1 return\cf0 \cf4 Service\cf0 <T>.Get(\cf1 this\cf0 );\par ?? \}\par ??\}\par ??\par ??\cf1 public\cf0 \cf1 interface\cf0 \cf4 IService\par ??\cf0 \{\par ?? \cf1 void\cf0 Remove(\cf1 object\cf0 parent);\par ??\}\par ??\par ??\cf1 public\cf0 \cf1 class\cf0 \cf4 Service\cf0 <T> : \cf4 IService\par ??\cf0 \{\par ?? \cf1 static\cf0 \cf1 readonly\cf0 \cf4 Dictionary\cf0 <\cf1 object\cf0 , T> services = \cf1 new\cf0 \cf4 Dictionary\cf0 <\cf1 object\cf0 , T>();\par ??\par ?? \cf1 public\cf0 Service(\cf1 object\cf0 parent, T service)\par ?? \{\par ?? services.Add(parent, service);\par ?? \}\par ??\par ?? \cf1 public\cf0 \cf1 void\cf0 Remove(\cf1 object\cf0 parent)\par ?? \{\par ?? services.Remove(parent);\par ?? \}\par ??\par ?? \cf1 public\cf0 \cf1 static\cf0 T Get(\cf1 object\cf0 parent)\par ?? \{\par ?? \cf1 return\cf0 services[parent];\par ?? \}\par ??\}}<br />--> <div style="font-family: courier new; background: white; color: black; font-size: 10pt"> <p style="margin: 0px"><span style="color: #2b91af">    6</span> <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">ServiceContainer</span> : <span style="color: #2b91af">IDisposable</span></p> <p style="margin: 0px"><span style="color: #2b91af">    7</span> {</p> <p style="margin: 0px"><span style="color: #2b91af">    8</span>     <span style="color: blue">readonly</span> <span style="color: #2b91af">IList</span><<span style="color: #2b91af">IService</span>> services = <span style="color: blue">new</span> <span style="color: #2b91af">List</span><<span style="color: #2b91af">IService</span>>();</p> <p style="margin: 0px"><span style="color: #2b91af">    9</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   10</span>     <span style="color: blue">public</span> <span style="color: blue">void</span> Add<T>(T service)</p> <p style="margin: 0px"><span style="color: #2b91af">   11</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   12</span>         Add<T,T>(service);</p> <p style="margin: 0px"><span style="color: #2b91af">   13</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   14</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   15</span>     <span style="color: blue">public</span> <span style="color: blue">void</span> Add<Key, T>(T service) <span style="color: blue">where</span> T : Key</p> <p style="margin: 0px"><span style="color: #2b91af">   16</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   17</span>         services.Add(<span style="color: blue">new</span> <span style="color: #2b91af">Service</span><Key>(<span style="color: blue">this</span>, service));</p> <p style="margin: 0px"><span style="color: #2b91af">   18</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   19</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   20</span>     <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</p> <p style="margin: 0px"><span style="color: #2b91af">   21</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   22</span>         <span style="color: blue">foreach</span>(<span style="color: blue">var</span> service <span style="color: blue">in</span> services)</p> <p style="margin: 0px"><span style="color: #2b91af">   23</span>             service.Remove(<span style="color: blue">this</span>);</p> <p style="margin: 0px"><span style="color: #2b91af">   24</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   25</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   26</span>     ~ServiceContainer()</p> <p style="margin: 0px"><span style="color: #2b91af">   27</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   28</span>         Dispose();</p> <p style="margin: 0px"><span style="color: #2b91af">   29</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   30</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   31</span>     <span style="color: blue">public</span> T Get<T>()</p> <p style="margin: 0px"><span style="color: #2b91af">   32</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   33</span>         <span style="color: blue">return</span> <span style="color: #2b91af">Service</span><T>.Get(<span style="color: blue">this</span>);</p> <p style="margin: 0px"><span style="color: #2b91af">   34</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   35</span> }</p> <p style="margin: 0px"><span style="color: #2b91af">   36</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   37</span> <span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IService</span></p> <p style="margin: 0px"><span style="color: #2b91af">   38</span> {</p> <p style="margin: 0px"><span style="color: #2b91af">   39</span>     <span style="color: blue">void</span> Remove(<span style="color: blue">object</span> parent);</p> <p style="margin: 0px"><span style="color: #2b91af">   40</span> }</p> <p style="margin: 0px"><span style="color: #2b91af">   41</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   42</span> <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Service</span><T> : <span style="color: #2b91af">IService</span></p> <p style="margin: 0px"><span style="color: #2b91af">   43</span> {</p> <p style="margin: 0px"><span style="color: #2b91af">   44</span>     <span style="color: blue">static</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">Dictionary</span><<span style="color: blue">object</span>, T> services = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span><<span style="color: blue">object</span>, T>();</p> <p style="margin: 0px"><span style="color: #2b91af">   45</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   46</span>     <span style="color: blue">public</span> Service(<span style="color: blue">object</span> parent, T service)</p> <p style="margin: 0px"><span style="color: #2b91af">   47</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   48</span>         services.Add(parent, service);</p> <p style="margin: 0px"><span style="color: #2b91af">   49</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   50</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   51</span>     <span style="color: blue">public</span> <span style="color: blue">void</span> Remove(<span style="color: blue">object</span> parent)</p> <p style="margin: 0px"><span style="color: #2b91af">   52</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   53</span>         services.Remove(parent);</p> <p style="margin: 0px"><span style="color: #2b91af">   54</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   55</span> </p> <p style="margin: 0px"><span style="color: #2b91af">   56</span>     <span style="color: blue">public</span> <span style="color: blue">static</span> T Get(<span style="color: blue">object</span> parent)</p> <p style="margin: 0px"><span style="color: #2b91af">   57</span>     {</p> <p style="margin: 0px"><span style="color: #2b91af">   58</span>         <span style="color: blue">return</span> services[parent];</p> <p style="margin: 0px"><span style="color: #2b91af">   59</span>     }</p> <p style="margin: 0px"><span style="color: #2b91af">   60</span> }</p> </div> <p></p> <p>As you can see I store all services in static generic Dictionary, which also have information to which serviceProvider this service belong. Normally when ServiceProvider will be cleaned by Garbage Collector, all services also will be removed from memory. But because I have static field that holds them, to avoid memory leaks I'm cleaning those services in destructor/finalizer o ServiceProvider.</p> <p>I see two drawbacks of this solution</p> <ul> <li>Larger memory usage due to need of having two lists of references to those services </li> <li>ServiceProvider stays one generation longer in memory than normal solution with cast, because of finalizer usage. </li> </ul> <p>Now with this example Implementation of cache without cast shouldn't be so hard :-)</p> <p><strong></strong></p> <p><strong>LATE EDIT (2009-07-30): </strong>As someone may notice from <a href="http://stackoverflow.com/questions/178255/serviceprovider-cache-etc-done-with-generics-without-cast/189329#189329" target="_blank">my answer on stackoverflow.com</a>  I tried to implement such ServiceProvider but failed to do it without memory leaks. Uhh :-(</p> <p>My request to microsoft: Please implement WeakReference<T>.</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-87540782054236939432008-07-02T10:47:00.001-07:002008-07-02T10:47:47.993-07:00One instance of dataset in application and Windows Forms designer<p>Want to know one simple requirement that makes Windows Forms designer useles? <br />Here it is:</p> <p><em>Application should use one instance of Dataset (or other component) in all windows and user controls.</em></p> <p>Simple enough, right. So let's see it on some simple example: application that have two forms - list and the details of concrete record. <br />So first the list form. I've dragged the dataset table from the datasource window (in VS 2008) and it creates automagically Dataset object, datasource and gridview with apropriate databindings. Pretty amazing, huh. <br />Now lets go to the details form. The same way I've dragged the table but choosed that I want to see details. The same story: Dataset object, datasource and fields. <br />Now it seems that because we have two separate datasets in each form, the Microsoft way to fill this datasets is to fill them twice from the database (which cost bandwith),  or once from the database - on the list form - and on the details form just copy it (which costs your developement time needed for code you must write). The situation is worse if each line on the list (let say customers) have many related tables that are also needed (for example are aggregated and shown in Dataset expression columns) - you must reload/copy them all. <br />Another stupid effect of this default behaviour of designer is that you must first call InitilizeComponent() which binds all controls to the created empty dataset and only then you can fill/copy data making great cascade of unnecesary events that will refresh the controls and which could be avoided if we will have ability to provide already filled Dataset and then the code could databind.</p> <p>The simplest solution to this problem would be to force the designer in some way to use only one instance of Dataset in all windows. <br />Three years ago, when I for the first time spot this problem, the only solution that came to my mind was to abandon the designer...</p> <p>OK I'm joking</p> <p>The only solution that I've found then was to create a method that goes through all components and rebinds all components to the new Dataset (just after InitilizeComponent()). It was ugly hack that had similiar performance like copying all needed data to the new already binded Dataset, but doesn't duplicated the data in memory. <br />This way I used it for three years and it somehow works. <br />During this time I've found that InstanceDescriptor (object that defines what code to produce in InitilizeComponent() to create your component) allows to use static methods. My happines was cooled down so fast when I saw that code generates correctly, but it makes designer to crash. I cannot find the reason for two days and I droped this path. <br /></p> <p>In the beggining of this year I owned Visual Studio 2008 and tried to write one application using WPF. I saw that it allows to use DynamicResource which behave exactly like my rebinding in windows forms. I've tried also to force it to use static method to create object, but again failed and I must say that WPF for me seems less extensive than windows forms (read -  more sealed and interal, or better - even runtime control tree has Sealed flag - lol). <br />I'm not convinced to WPF. Comparing to Windows Forms you must assume that you will have no designer. Nor Expression Blend, nor VS 2008 designer works for me. It ends for me that I designed only in XAML and the only preview was runtime, because designer didn't worked. For my luck this project was skipped for some time.</p> <p>Right now I'm sitting on a new project back in Windows Forms and it's so much easier :-). But this time I had some free time and enough patience to sit down and find the reason why InstanceDescriptor generating static method blows away designer (of course this bug was not fixed in VS 2008 :-( ). <br />So in short time I've created typed Dataset called DB and my class called Data that will inherit from it to use InstanceDescriptor</p> <div style="font-size: 10pt; font-family: monospace; background-color: white">[<span style="color: #2b91af">TypeConverter</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">OneInstanceTypeConverter</span><span style="color: black"><</span><span style="color: #2b91af">Data</span><span style="color: black">>))] <br />    [</span><span style="color: #2b91af">FactoryMethod</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">Data</span><span style="color: black">), </span><span style="color: #a31515">"Instance"</span><span style="color: black">)] <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black"> : </span><span style="color: #2b91af">DB <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">readonly</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black"> instance = </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black">(); <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black"> Instance() <br />        { <br />            </span><span style="color: blue">return</span><span style="color: black"> instance; <br />        } <br />    } <br /> <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">OneInstanceTypeConverter</span><span style="color: black"><T> : </span><span style="color: #2b91af">TypeConverter <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">override</span><span style="color: black"> </span><span style="color: blue">bool</span><span style="color: black"> CanConvertTo(</span><span style="color: #2b91af">ITypeDescriptorContext</span><span style="color: black"> context, </span><span style="color: #2b91af">Type</span><span style="color: black"> destinationType) <br />        { <br />            </span><span style="color: blue">if</span><span style="color: black"> (destinationType == </span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">)) <br />                </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: blue">true</span><span style="color: black">; <br />            </span><span style="color: #2b91af">TypeConverter</span><span style="color: black"> converter = <br />                (</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">) </span><span style="color: blue">typeof</span><span style="color: black"> (T).BaseType.GetCustomAttributes(</span><span style="color: blue">typeof</span><span style="color: black"> (</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">), </span><span style="color: blue">false</span><span style="color: black">)[0]; <br />            </span><span style="color: blue">return</span><span style="color: black"> converter.CanConvertTo(context, destinationType); <br />        } <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">override</span><span style="color: black"> </span><span style="color: blue">object</span><span style="color: black"> ConvertTo(</span><span style="color: #2b91af">ITypeDescriptorContext</span><span style="color: black"> context, </span><span style="color: #2b91af">CultureInfo</span><span style="color: black"> culture, </span><span style="color: blue">object</span><span style="color: black"> value, </span><span style="color: #2b91af">Type</span><span style="color: black"> destinationType) <br />        { <br />            </span><span style="color: blue">if</span><span style="color: black"> (destinationType == </span><span style="color: blue">typeof</span><span style="color: black"> (</span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">) && value </span><span style="color: blue">is</span><span style="color: black"> T) <br />            { <br />                </span><span style="color: blue">object</span><span style="color: black">[] attributes = </span><span style="color: blue">typeof</span><span style="color: black"> (T).GetCustomAttributes(</span><span style="color: blue">typeof</span><span style="color: black"> (</span><span style="color: #2b91af">FactoryMethodAttribute</span><span style="color: black">), </span><span style="color: blue">false</span><span style="color: black">); <br />                </span><span style="color: blue">if</span><span style="color: black"> (attributes.Length == 0) <br />                    </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black"> (T).GetConstructor(</span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">Type</span><span style="color: black">[0]), </span><span style="color: blue">null</span><span style="color: black">); <br />                </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">(((</span><span style="color: #2b91af">FactoryMethodAttribute</span><span style="color: black">)attributes[0]).Method, </span><span style="color: blue">null</span><span style="color: black">, </span><span style="color: blue">true</span><span style="color: black">); <br />            } <br />            </span><span style="color: #2b91af">TypeConverter</span><span style="color: black"> converter = <br />                (</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">)</span><span style="color: blue">typeof</span><span style="color: black">(T).BaseType.GetCustomAttributes(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">), </span><span style="color: blue">false</span><span style="color: black">)[0]; <br />            </span><span style="color: blue">return</span><span style="color: black"> converter.ConvertTo(context, culture, value, destinationType); <br />        }         <br />    } <br /> <br />    [</span><span style="color: #2b91af">AttributeUsage</span><span style="color: black">(</span><span style="color: #2b91af">AttributeTargets</span><span style="color: black">.Class)] <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">FactoryMethodAttribute</span><span style="color: black"> : </span><span style="color: #2b91af">Attribute <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">readonly</span><span style="color: black"> </span><span style="color: #2b91af">MethodInfo</span><span style="color: black"> method; <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> FactoryMethodAttribute(</span><span style="color: #2b91af">Type</span><span style="color: black"> type, </span><span style="color: blue">string</span><span style="color: black"> method) <br />        { <br />            </span><span style="color: blue">this</span><span style="color: black">.method = type.GetMethod(method, </span><span style="color: #2b91af">BindingFlags</span><span style="color: black">.Public | </span><span style="color: #2b91af">BindingFlags</span><span style="color: black">.Static); <br />        } <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: #2b91af">MethodInfo</span><span style="color: black"> Method <br />        { <br />            </span><span style="color: blue">get</span><span style="color: black"> { </span><span style="color: blue">return</span><span style="color: black"> method; } <br />        } <br />    }</span> </div> <p>This code produces following line in InitilizeComponent():</p> <div style="font-size: 10pt; font-family: monospace; background-color: white"><span style="color: blue">this</span><span style="color: black">.data = </span><span style="color: #2b91af">Data</span><span style="color: black">.Instance();</span> </div> <p>Sweet, but when you close the form and try to open it again it will show you few exceptions that happens somwhere in CodeDomSerializer.Deserialize and says that field 'data' does not exists. <br />So serialization to static method works, but deserialization can't create object from it, and this is the reason I've abandoned it earlier. <br />Right now after two nights with Reflector and VS Debugger (of course for some reason VS 2008 didn't wanted to cooperate and load System.Design source code to debugger) I finally spot the place that have problem. But first... some theory. <br />When you drag some object onto form, it's created in memory and added to the designer list of objects which should be serialized to code. Later when designer is opening the file it deserializes it and calls appropriate methods to create it. usually it's a constructor, but we are trying here to call static method. What we see here is that VS can create object from constructor, but have some problem when it must call the static method. So coming this path I've checked if static method is called at all. To my lucky it was. Her is the stack trace:</p> <p><font face="Monospace" size="-1">HRDB.exe!Data.Instance() Line 23    C# <br />[Native to Managed Transition]     <br />[Managed to Native Transition]     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, string name, System.CodeDom.CodeExpression expression) + 0xc25 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.DeserializeStatementToInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.CodeDom.CodeStatement statement) + 0x6b bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, object codeObject) + 0x114 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.DeserializeName(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, string name = "data", System.CodeDom.CodeStatementCollection statements) + 0x300 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, System.CodeDom.CodeTypeDeclaration declaration = {System.CodeDom.CodeTypeDeclaration}) + 0xe00 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager) + 0x56 bytes     <br />Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager serializationManager) + 0x2c4 bytes     <br />Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(int fReload) + 0x48 bytes     <br />[Native to Managed Transition]    </font></font></p> <p>I tried to find the bug somwhere in the code near the one stack trace shows me, but without success. And as a one of my ideas, I tried to comapre it to normal constructor.</p> <p><font face="Monospace" size="-1">HRDB.exe!HRDB.Data.Data() Line 18    C# <br />[Native to Managed Transition]     <br />[Managed to Native Transition]     <br />System.dll!System.SecurityUtils.SecureConstructorInvoke(System.Type type, System.Type[] argTypes, object[] args, bool allowNonPublic, System.Reflection.BindingFlags extraFlags) Line 153 + 0xc bytes    C# <br />System.dll!System.ComponentModel.ReflectTypeDescriptionProvider.CreateInstance(System.IServiceProvider provider, System.Type objectType = {Name = "Data" FullName = "HRDB.Data"}, System.Type[] argTypes, object[] args = {object[0]}) Line 198 + 0x11 bytes    C# <br />System.dll!System.ComponentModel.TypeDescriptor.TypeDescriptionNode.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 3751 + 0x10 bytes    C# <br />System.dll!System.ComponentModel.TypeDescriptionProvider.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 70 + 0xfffffff1 bytes    C# <br />System.dll!System.ComponentModel.TypeDescriptor.TypeDescriptionNode.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 3751 + 0x10 bytes    C# <br />System.dll!System.ComponentModel.TypeDescriptor.CreateInstance(System.IServiceProvider provider, System.Type objectType, System.Type[] argTypes, object[] args) Line 600 + 0x18 bytes    C# <br />System.Design.dll!System.ComponentModel.Design.DesignSurface.CreateInstance(System.Type type = {Name = "Data" FullName = "HRDB.Data"}) + 0x60 bytes     <br />Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.VSDesignSurface.CreateInstance(System.Type type) + 0x20 bytes     <br />System.Design.dll!System.ComponentModel.Design.DesignerHost.System.ComponentModel.Design.IDesignerHost.CreateComponent(System.Type componentType = {Name = "Data" FullName = "HRDB.Data"}, string name = "data") + 0xcf bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.DesignerSerializationManager.CreateInstance(System.Type type = {Name = "Data" FullName = "HRDB.Data"}, System.Collections.ICollection arguments, string name = "data", bool addToContainer = true) + 0x1fb bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.DesignerSerializationManager.System.ComponentModel.Design.Serialization.IDesignerSerializationManager.CreateInstance(System.Type type, System.Collections.ICollection arguments, string name = "data", bool addToContainer) + 0x94 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.Type type, object[] parameters, string name, bool addToContainer) + 0x24 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer.DeserializeInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, System.Type type, object[] parameters, string name, bool addToContainer) + 0x23 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, string name, System.CodeDom.CodeExpression expression) + 0x550 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.DeserializeStatementToInstance(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager, System.CodeDom.CodeStatement statement) + 0x6b bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, object codeObject) + 0x114 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.DeserializeName(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, string name = "data", System.CodeDom.CodeStatementCollection statements) + 0x300 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager = {System.ComponentModel.Design.Serialization.DesignerSerializationManager}, System.CodeDom.CodeTypeDeclaration declaration = {System.CodeDom.CodeTypeDeclaration}) + 0xe00 bytes     <br />System.Design.dll!System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager manager) + 0x56 bytes     <br />Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(System.ComponentModel.Design.Serialization.IDesignerSerializationManager serializationManager) + 0x2c4 bytes     <br />Microsoft.VisualStudio.Design.dll!Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(int fReload) + 0x48 bytes     <br />[Native to Managed Transition]     <br /></font></font></p> <p>This one is a longer one but it shows that for normal contructor there is much more done than for static method. The paths seems to break in CodeDomSerializerBase.DeserializeExpression() method. For static method it calls the metod, but for constructor it calls ComponentCodeDomSerializer.DeserializeInstance(). <br />Another night and I knew everything.</p> <p>CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, string name, CodeExpression expression);</p> <p><strong>For static method expression parameter is CodeMethodInvokeExpression which results in just one call to System.Type.InvokeMember(). <br />For constructor, expresion parameter is CodeObjectCreateExpression which results in call to ComponentCodeDomSerializer.DeserializeInstance() which is calling IDesignerSerializationManager.CreateInstance which apart from calling constructor is also adding created object to the list of components so it can be later used when it's refrenced in other CodeStatement.</strong></p> <p>So I've found a bug, but how to overcome it. It takes me a little time to find a way to do it without using Reflection. I was forced to create my own serializer which will exchange the CodeMethodInvokeExpression to CodeObjectCreateExpression just before deserialization. Below you have the full code:</p> <div style="font-size: 10pt; font-family: monospace; background-color: white">    [<span style="color: #2b91af">DesignerSerializer</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">OneInstanceSerializer</span><span style="color: black"><</span><span style="color: #2b91af">Data</span><span style="color: black">>), </span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">CodeDomSerializer</span><span style="color: black">))] <br />    [</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">OneInstanceTypeConverter</span><span style="color: black"><</span><span style="color: #2b91af">Data</span><span style="color: black">>))] <br />    [</span><span style="color: #2b91af">FactoryMethod</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">Data</span><span style="color: black">), </span><span style="color: #a31515">"Instance"</span><span style="color: black">)] <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black"> : </span><span style="color: #2b91af">DB <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">readonly</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black"> instance = </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black">(); <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: #2b91af">Data</span><span style="color: black"> Instance() <br />        { <br />            </span><span style="color: blue">return</span><span style="color: black"> instance; <br />        } <br />    } <br /> <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">OneInstanceTypeConverter</span><span style="color: black"><T> : </span><span style="color: #2b91af">TypeConverter <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">override</span><span style="color: black"> </span><span style="color: blue">bool</span><span style="color: black"> CanConvertTo(</span><span style="color: #2b91af">ITypeDescriptorContext</span><span style="color: black"> context, </span><span style="color: #2b91af">Type</span><span style="color: black"> destinationType) <br />        { <br />            </span><span style="color: blue">if</span><span style="color: black"> (destinationType == </span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">)) <br />                </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: blue">true</span><span style="color: black">; <br />            </span><span style="color: #2b91af">TypeConverter</span><span style="color: black"> converter = <br />                (</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">) </span><span style="color: blue">typeof</span><span style="color: black"> (T).BaseType.GetCustomAttributes(</span><span style="color: blue">typeof</span><span style="color: black"> (</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">), </span><span style="color: blue">false</span><span style="color: black">)[0]; <br />            </span><span style="color: blue">return</span><span style="color: black"> converter.CanConvertTo(context, destinationType); <br />        } <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">override</span><span style="color: black"> </span><span style="color: blue">object</span><span style="color: black"> ConvertTo(</span><span style="color: #2b91af">ITypeDescriptorContext</span><span style="color: black"> context, </span><span style="color: #2b91af">CultureInfo</span><span style="color: black"> culture, </span><span style="color: blue">object</span><span style="color: black"> value, </span><span style="color: #2b91af">Type</span><span style="color: black"> destinationType) <br />        { <br />            </span><span style="color: blue">if</span><span style="color: black"> (destinationType == </span><span style="color: blue">typeof</span><span style="color: black"> (</span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">) && value </span><span style="color: blue">is</span><span style="color: black"> T) <br />            { <br />                </span><span style="color: blue">object</span><span style="color: black">[] attributes = </span><span style="color: blue">typeof</span><span style="color: black"> (T).GetCustomAttributes(</span><span style="color: blue">typeof</span><span style="color: black"> (</span><span style="color: #2b91af">FactoryMethodAttribute</span><span style="color: black">), </span><span style="color: blue">false</span><span style="color: black">); <br />                </span><span style="color: blue">if</span><span style="color: black"> (attributes.Length == 0) <br />                    </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black"> (T).GetConstructor(</span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">Type</span><span style="color: black">[0]), </span><span style="color: blue">null</span><span style="color: black">); <br />                </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">InstanceDescriptor</span><span style="color: black">(((</span><span style="color: #2b91af">FactoryMethodAttribute</span><span style="color: black">)attributes[0]).Method, </span><span style="color: blue">null</span><span style="color: black">, </span><span style="color: blue">true</span><span style="color: black">); <br />            } <br />            </span><span style="color: #2b91af">TypeConverter</span><span style="color: black"> converter = <br />                (</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">)</span><span style="color: blue">typeof</span><span style="color: black">(T).BaseType.GetCustomAttributes(</span><span style="color: blue">typeof</span><span style="color: black">(</span><span style="color: #2b91af">TypeConverter</span><span style="color: black">), </span><span style="color: blue">false</span><span style="color: black">)[0]; <br />            </span><span style="color: blue">return</span><span style="color: black"> converter.ConvertTo(context, culture, value, destinationType); <br />        }         <br />    } <br /> <br />    [</span><span style="color: #2b91af">AttributeUsage</span><span style="color: black">(</span><span style="color: #2b91af">AttributeTargets</span><span style="color: black">.Class)] <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">FactoryMethodAttribute</span><span style="color: black"> : </span><span style="color: #2b91af">Attribute <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">readonly</span><span style="color: black"> </span><span style="color: #2b91af">MethodInfo</span><span style="color: black"> method; <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> FactoryMethodAttribute(</span><span style="color: #2b91af">Type</span><span style="color: black"> type, </span><span style="color: blue">string</span><span style="color: black"> method) <br />        { <br />            </span><span style="color: blue">this</span><span style="color: black">.method = type.GetMethod(method, </span><span style="color: #2b91af">BindingFlags</span><span style="color: black">.Public | </span><span style="color: #2b91af">BindingFlags</span><span style="color: black">.Static); <br />        } <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: #2b91af">MethodInfo</span><span style="color: black"> Method <br />        { <br />            </span><span style="color: blue">get</span><span style="color: black"> { </span><span style="color: blue">return</span><span style="color: black"> method; } <br />        } <br />    } <br /> <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">OneInstanceSerializer</span><span style="color: black"><T> : </span><span style="color: #2b91af">CodeDomSerializer <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">override</span><span style="color: black"> </span><span style="color: blue">object</span><span style="color: black"> Deserialize(</span><span style="color: #2b91af">IDesignerSerializationManager</span><span style="color: black"> manager, </span><span style="color: blue">object</span><span style="color: black"> codeObject) <br />        {             <br />            </span><span style="color: #2b91af">CodeDomSerializer</span><span style="color: black"> serializer = GetSerializer(manager, </span><span style="color: blue">typeof</span><span style="color: black"> (T).BaseType); <br />            </span><span style="color: #2b91af">CodeStatementCollection</span><span style="color: black"> statements = codeObject </span><span style="color: blue">as</span><span style="color: black"> </span><span style="color: #2b91af">CodeStatementCollection</span><span style="color: black">; <br />            </span><span style="color: blue">if</span><span style="color: black"> (statements != </span><span style="color: blue">null</span><span style="color: black">) <br />            { <br />                </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = 0; i < statements.Count; i++) <br />                { <br />                    </span><span style="color: blue">object</span><span style="color: black"> value = DeserializeStatementToInstance(manager, statements[i]); <br /> <br />                    </span><span style="color: blue">if</span><span style="color: black"> (value != </span><span style="color: blue">null</span><span style="color: black">) <br />                    { <br />                        </span><span style="color: #2b91af">CodeAssignStatement</span><span style="color: black"> statement = statements[i] </span><span style="color: blue">as</span><span style="color: black"> </span><span style="color: #2b91af">CodeAssignStatement</span><span style="color: black">; <br />                        </span><span style="color: blue">if</span><span style="color: black">(statement != </span><span style="color: blue">null</span><span style="color: black">) <br />                            statement.Right = </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">CodeObjectCreateExpression</span><span style="color: black">(</span><span style="color: blue">typeof</span><span style="color: black"> (T)); <br />                        </span><span style="color: blue">break</span><span style="color: black">; <br />                    } <br />                } <br />                </span><span style="color: blue">return</span><span style="color: black"> serializer.Deserialize(manager, statements); <br />            } <br /> <br />            </span><span style="color: blue">return</span><span style="color: black"> serializer.Deserialize(manager, codeObject); <br />        } <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">override</span><span style="color: black"> </span><span style="color: blue">object</span><span style="color: black"> Serialize(</span><span style="color: #2b91af">IDesignerSerializationManager</span><span style="color: black"> manager, </span><span style="color: blue">object</span><span style="color: black"> value) <br />        { <br />            </span><span style="color: blue">return</span><span style="color: black"> GetSerializer(manager, </span><span style="color: blue">typeof</span><span style="color: black">(T).BaseType).Serialize(manager, value); <br />        } <br />    }</span> </div> <p>It's written in a way that you can just copy it and use in your project to any component you want. Just remember that you must use all 3 attributes. <br />I hope that it will help someone to write more performant code and still use designer to design the window in an elegant way.</p> <p>I must say that - in my opinion - it's sad that windows forms style of designing will be abandon in favour of WPF and XAML. Just try to do such thing in WPF. <br />Wait I have better one, try to inherit from BaseForm class in WPF. <br />And my favourite - try to write equivalent of following generated code in WPF:</p> <div style="font-size: 10pt; font-family: monospace; background-color: white"><span style="color: blue">this</span><span style="color: black">.components = </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">MyContainer</span><span style="color: black">(</span><span style="color: blue">this</span><span style="color: black">);</span> </div> <p>The key here is keyword <span style="color: blue">this.</span> I don't know how to pass Form reference in XAML. In Windows Forms it was not easy to do it, but it's possible (I'll show you later how). BTW I needed it to inject my IServiceProvider into each Form and its controls/components.</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-64067358694956319062008-05-19T16:27:00.001-07:002008-05-19T16:49:06.494-07:00How to test static method call - Benchmarks<p>This is a continuation of <a href="http://seermindflow.blogspot.com/2008/05/how-to-test-static-method-call-in-c.html">my last post</a>.</p> <p>For a long time I rejected to even test Delegates as a method to make static method calls "virtual" because of performance. My mind doesn't allow me to accept the fact that they can be viable alternative.</p> <p>But real numbers was a little strange.</p> <p>First, test console program</p> <p></p> <div style="font-size: 10pt; font-family: monospace; background-color: white"><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">Program</span><span style="color: black"> : </span><span style="color: #2b91af">IProgram <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: #2b91af">Action</span><span style="color: black"> TestStaticDelegate = TestStatic; <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: #2b91af">Action</span><span style="color: black"> TestStaticNoInlineDelegate = TestStaticNoInline; <br /> <br />        </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">void</span><span style="color: black"> Main(</span><span style="color: blue">string</span><span style="color: black">[] args) <br />        { <br />            TestStatic(); <br />            TestStaticNoInline(); <br />            </span><span style="color: #2b91af">IProgram</span><span style="color: black"> p = </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">Program</span><span style="color: black">(); <br />            </span><span style="color: #2b91af">Action</span><span style="color: black"> TestInterfaceDelegate = p.TestInterface; <br />            p.TestInterface(); <br /> <br />            </span><span style="color: blue">int</span><span style="color: black"> number = </span><span style="color: red">1000000000</span><span style="color: black">; <br />             <br />            </span><span style="color: #2b91af">DateTime</span><span style="color: black"> start = </span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now; <br />            </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = </span><span style="color: red">0</span><span style="color: black">; i < number; i++ ) <br />                TestStatic(); <br />            </span><span style="color: #2b91af">Console</span><span style="color: black">.WriteLine(</span><span style="color: red">"TestStatic: "</span><span style="color: black"> + (</span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now - start).Ticks); <br /> <br />            start = </span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now; <br />            </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = </span><span style="color: red">0</span><span style="color: black">; i < number; i++) <br />                TestStaticNoInline(); <br />            </span><span style="color: #2b91af">Console</span><span style="color: black">.WriteLine(</span><span style="color: red">"TestStaticNoInline: "</span><span style="color: black"> + (</span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now - start).Ticks); <br /> <br />            start = </span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now; <br />            </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = </span><span style="color: red">0</span><span style="color: black">; i < number; i++) <br />                p.TestInterface(); <br />            </span><span style="color: #2b91af">Console</span><span style="color: black">.WriteLine(</span><span style="color: red">"TestInterface: "</span><span style="color: black"> + (</span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now - start).Ticks); <br /> <br />            start = </span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now; <br />            </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = </span><span style="color: red">0</span><span style="color: black">; i < number; i++) <br />                TestStaticDelegate(); <br />            </span><span style="color: #2b91af">Console</span><span style="color: black">.WriteLine(</span><span style="color: red">"TestStaticDelegate: "</span><span style="color: black"> + (</span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now - start).Ticks); <br /> <br />            start = </span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now; <br />            </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = </span><span style="color: red">0</span><span style="color: black">; i < number; i++) <br />                TestStaticNoInlineDelegate(); <br />            </span><span style="color: #2b91af">Console</span><span style="color: black">.WriteLine(</span><span style="color: red">"TestStaticNoInlineDelegate: "</span><span style="color: black"> + (</span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now - start).Ticks); <br /> <br />            start = </span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now; <br />            </span><span style="color: blue">for</span><span style="color: black"> (</span><span style="color: blue">int</span><span style="color: black"> i = </span><span style="color: red">0</span><span style="color: black">; i < number; i++) <br />                TestInterfaceDelegate(); <br />            </span><span style="color: #2b91af">Console</span><span style="color: black">.WriteLine(</span><span style="color: red">"TestInterfaceDelegate: "</span><span style="color: black"> + (</span><span style="color: #2b91af">DateTime</span><span style="color: black">.Now - start).Ticks); <br />        } <br /> <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">int</span><span style="color: black"> x = </span><span style="color: red">0</span><span style="color: black">; <br /> <br />        </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">void</span><span style="color: black"> TestStatic() <br />        { <br />            x++; <br />        } <br /> <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">int</span><span style="color: black"> y = </span><span style="color: red">0</span><span style="color: black">; <br />        [</span><span style="color: #2b91af">MethodImpl</span><span style="color: black">(</span><span style="color: #2b91af">MethodImplOptions</span><span style="color: black">.NoInlining)] <br />        </span><span style="color: blue">static</span><span style="color: black"> </span><span style="color: blue">void</span><span style="color: black"> TestStaticNoInline() <br />        { <br />            y++; <br />        } <br /> <br />        </span><span style="color: blue">private</span><span style="color: black"> </span><span style="color: blue">int</span><span style="color: black"> z = </span><span style="color: red">0</span><span style="color: black">; <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">void</span><span style="color: black"> TestInterface() <br />        { <br />            z++; <br />        }         <br />    } <br /> <br />    </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">interface</span><span style="color: black"> </span><span style="color: #2b91af">IProgram <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">void</span><span style="color: black"> TestInterface(); <br />    }</span> </div> <p>As you can see I want to compare static method calls with delegates and (the most important) with virtual call. <br />I've run this program on my AMD Athlon XP 2400+ 2GHz machine (it was Release version of course :-). The results were following:</p> <p></p> <pre>TestStatic: 18326352<br />TestStaticNoInline: 39556880<br />TestInterface: 56280928<br />TestStaticDelegate: 67697344<br />TestStaticNoInlineDelegate: 61989136<br />TestInterfaceDelegate: 56180784</pre><br /><br /><p>For me the most intresting numbers are TestInterface and TestStaticDelegate, because it compares Dependency Injection using interface with DI using Delegates. As you can see delegates are around 17% slower then interface method call. That was predictable but I've suspected much higher difference. I've run this test few times and the results was always similiar.</p><br /><br /><p>According to the power this method gives me, it's acceptable performance penalty, but for some strange reason I've thought that it will be interesting to test it on Intel platform also, so I've run it on my work machine with Intel Pentium 4 3 Ghz. The results were little strange:</p><br /><br /><p></p><br /><br /><pre>TestStatic: 17031359<br />TestStaticNoInline: 61250392<br />TestInterface: 55000352<br />TestStaticDelegate: 51250328<br />TestStaticNoInlineDelegate: 49844069<br />TestInterfaceDelegate: 34218969</pre><br /><br /><p>Woow, it seems that on Intel, Delegates are something around 7% faster then interface call. What's more, delegate instance call is 40% faster then interface one. <br /> <br />I've tried to find some bug in this code, but everything looks, fine for me. Event tried to change (DateTime.Now - start).Ticks to (DateTime.Now - start).ToString() but results were similiar:</p><br /><br /><p></p><br /><br /><pre>TestStatic: 00:00:01.6875108<br />TestStaticNoInline: 00:00:06.0625388<br />TestInterface: 00:00:05.5312854<br />TestStaticDelegate: 00:00:05.0625324<br />TestStaticNoInlineDelegate: 00:00:05.2187834<br />TestInterfaceDelegate: 00:00:03.4687722</pre><br /><br /><p>Seeing this, I saw also that even on AMD, delegate instance call (TestInterfaceDelegate) is faster then normal interface call (TestInterface).</p><br /><br /><p> </p><br /><br /><p><strong>My Conclusions</strong></p><br /><br /><ul><br /> <li>If you need performance use static methods and TypeMock for testing </li><br /><br /> <li>If you need to inject some code at runtime you can freely use Delegates without any significant performance loose. Even better - it looks like .NET 3.5 JIT promotes functional programing (static methods and delegates) by making it more performant than object oriented (interface calls) one - at least on Intel platform. </li><br /><br /> <li>If you don't wan't to use TypeMock you can safely use <strong>Delegates based Dependency Injection</strong>. </li><br /></ul> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com1tag:blogger.com,1999:blog-6986769256944213284.post-50926281717003039972008-05-09T14:59:00.001-07:002008-05-19T16:35:49.678-07:00How to test static method call in c# without TypeMock<p>If you think - like me - that TDD is not only testing, but also design process, you probably are using <a href="http://www.ayende.com/projects/rhino-mocks/downloads.aspx" target="_blank">Rhino Mocks</a> or any other mocking tool that is based on interface/virtual methods implementation. But how can one mock a call to static method like </p> <div style="font-size: 10pt; font-family: monospace; background-color: white"><span style="color: #2b91af">File</span><span style="color: black">.Open(</span><span style="color: red">"..."</span><span style="color: black">, </span><span style="color: #2b91af">FileMode</span><span style="color: black">.Open);</span> </div> <p>The only method until now (for me) was to use <a href="http://www.typemock.com/" target="_blank">Typemock</a>. But until you buy a paid version, you cannot use it without typing method names as string - which I don't like.</p> <p>After long long long searching I think I found an alternative - Delegates.</p> <p>Lets see an example (in c# 3.5):</p> <div style="font-size: 10pt; font-family: monospace; background-color: white">    <span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">class</span><span style="color: black"> </span><span style="color: #2b91af">SomeClass <br /></span><span style="color: black">    { <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: #2b91af">Func</span><span style="color: black"><</span><span style="color: blue">string</span><span style="color: black">, </span><span style="color: #2b91af">FileMode</span><span style="color: black">, </span><span style="color: #2b91af">Stream</span><span style="color: black">> FileOpen = </span><span style="color: #2b91af">File</span><span style="color: black">.Open; <br /> <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">void</span><span style="color: black"> DoSomethingWithFile(</span><span style="color: blue">string</span><span style="color: black"> path) <br />        { <br />            </span><span style="color: blue">using</span><span style="color: black"> (</span><span style="color: #2b91af">Stream</span><span style="color: black"> s = FileOpen(path, </span><span style="color: #2b91af">FileMode</span><span style="color: black">.Open)) <br />            { <br />                </span><span style="color: green">//... <br /></span><span style="color: black">                </span><span style="color: green">//... <br /></span><span style="color: black">            } <br />        } <br />    }</span> </div> <p>As you see, I placed a public delegate to File.Open which I can change later in my test</p> <div style="font-size: 10pt; font-family: monospace; background-color: white">        [<span style="color: #2b91af">Test</span><span style="color: black">] <br />        </span><span style="color: blue">public</span><span style="color: black"> </span><span style="color: blue">void</span><span style="color: black"> TestDoSomethingWithFile() <br />        { <br />            </span><span style="color: #2b91af">SomeClass</span><span style="color: black"> sc = </span><span style="color: blue">new</span><span style="color: black"> </span><span style="color: #2b91af">SomeClass</span><span style="color: black">(); <br />            </span><span style="color: blue">string</span><span style="color: black"> testFile = </span><span style="color: #2b91af">Path</span><span style="color: black">.GetTempFileName(); <br />            </span><span style="color: green">//...fill this testFile <br /> <br /></span><span style="color: black">            sc.FileOpen = </span><span style="color: blue">delegate</span><span style="color: black"> { </span><span style="color: blue">return</span><span style="color: black"> </span><span style="color: #2b91af">File</span><span style="color: black">.OpenRead(testFile); }; <br />            sc.DoSomethingWithFile(testFile); <br />             <br />            </span><span style="color: green">//Asserts here <br /></span><span style="color: black">        }</span> </div> <p>What is great about such pattern is that you can treat those delegates in class as references in dll file. <br />Another great thing is that you can use Dependency Injection to inject static(or not) methods to the class.</p> <p> </p> <p>And thats it. So simple right? <br />Ummm, but what about performance, delegates can't work as fast as static calls. <br />Well, I'll show you some benchmarks <a href="http://seermindflow.blogspot.com/2008/05/how-to-test-static-method-call.html">later</a>.</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0tag:blogger.com,1999:blog-6986769256944213284.post-19156200437810029792008-05-09T14:03:00.001-07:002008-05-09T14:03:55.651-07:00Welcome<p>So the time has come for me also :-)</p> <p>It's time to try to archive some of my thougths about programming and whatever comes to my mind.</p> <p>So let's start and see what will come from this :-)</p> <p> </p> <p>First of all (and this is the only time I will do it) I want to apologize for my English. I'm not a native English speaker so be ready for mistakes :-)</p> seerhttp://www.blogger.com/profile/05782283170327563523noreply@blogger.com0