<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://msmvps.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><title type="html">the blog =&amp;gt; anything goes</title><subtitle type="html">Senthil Kumar&amp;#39;s tech blog</subtitle><id>http://msmvps.com/blogs/senthil/atom.aspx</id><link rel="alternate" type="text/html" href="http://msmvps.com/blogs/senthil/default.aspx" /><link rel="self" type="application/atom+xml" href="http://msmvps.com/blogs/senthil/atom.aspx" /><generator uri="http://communityserver.org" version="4.0.30619.63">Community Server</generator><updated>2007-05-12T01:23:00Z</updated><entry><title>Wami 0.1 released</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/07/02/wami-0-1-released.aspx" /><id>/blogs/senthil/archive/2008/07/02/wami-0-1-released.aspx</id><published>2008-07-02T16:25:28Z</published><updated>2008-07-02T16:25:28Z</updated><content type="html">&lt;p&gt;&lt;a title="Where Am I" href="http://msmvps.com/blogs/senthil/archive/2008/05/05/where-am-i.aspx"&gt;Where Am I&lt;/a&gt;, a Windows Mobile app that I was working on, is now available for download. You can get the binaries from &lt;a title="http://www.codeplex.com/wami" href="http://www.codeplex.com/wami"&gt;http://www.codeplex.com/wami&lt;/a&gt;. There is still a lot of fit and finish work to be done, but with the core functionality working fine, I decided to let it out in the wild and get some feedback.&lt;/p&gt; &lt;p&gt;There is RouteLogger.exe, which runs on the mobile phone and records cell broadcast information to a log file, along with the time interval between successive broadcasts. RouteEditor.exe, which runs on the PC, allows you to group the logged location information into names of places that you can recognize readily. RouteEditor saves the information into route files, which can then be loaded by wami.exe, running on the mobile phone. Wami gets the current cell broadcast location, indexes into the route information, and estimates the time needed to reach the final destination and intermediate points along the way.&lt;/p&gt; &lt;p&gt;Oh, and Wami is open source, so you can take a peek at the source code if you&amp;#39;re interested. This being my first Windows Mobile app, your comments about the application, its usability and the source code are most welcome.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1639132" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="Windows mobile C# software Where Am I" scheme="http://msmvps.com/blogs/senthil/archive/tags/Windows+mobile+C_2300_+software+Where+Am+I/default.aspx" /></entry><entry><title>String.Empty versus "" - The real deal</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/06/27/string-empty-versus-quot-quot.aspx" /><id>/blogs/senthil/archive/2008/06/27/string-empty-versus-quot-quot.aspx</id><published>2008-06-27T13:36:00Z</published><updated>2008-06-27T13:36:00Z</updated><content type="html">&lt;p&gt;This is one topic that keeps popping up every now and then. A lot of people seem to be curious about the performance implications of using one versus the other, and not unexpectedly, a lot of different answers come up.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;To settle it once for all, here&amp;#39;s a small program that uses both of them. &lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;namespace ConsoleApplication&lt;br /&gt;{  &lt;br /&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        static void Main()&lt;br /&gt;        {&lt;br /&gt;            Method1();&lt;br /&gt;            Method2();&lt;br /&gt;            Console.ReadLine();&lt;br /&gt;            Method1();&lt;br /&gt;            Method2();&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;        static void Method1()&lt;br /&gt;        {&lt;br /&gt;            string s = &amp;quot;&amp;quot;;&lt;br /&gt;            DoNothing(s); &lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;        static void Method2()&lt;br /&gt;        {&lt;br /&gt;            string s = string.Empty;&lt;br /&gt;            DoNothing(s);&lt;br /&gt;        }&lt;br /&gt;&lt;br /&gt;        [MethodImpl(MethodImplOptions.NoInlining)]&lt;br /&gt;        static void DoNothing(string s)&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(s);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;As you can see above, Method1 and Method2 call DoNothing, passing &amp;quot;&amp;quot; and string.Empty respectively. Now how do we compare these two? Easy, just look at the jitted code - after all, that&amp;#39;s what is going to run on the machine.&lt;/p&gt;&lt;p&gt;We&amp;#39;ll use Windbg to disassemble the code after the JITter did its job. And if you&amp;#39;re wondering why Method1 and Method2 have been called twice, now you know why - the second time around, we can look at the JITted code that was generated as part of the first time execution of each of those methods. &lt;/p&gt;&lt;p&gt;So breaking into the debugger at Console.ReadLine() and dumping the method descriptors for Program &lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;0:003&amp;gt; !Name2EE Sample.exe!ConsoleApplication.Program&lt;br /&gt;...&lt;br /&gt;MethodTable: 002a3048&lt;br /&gt;&lt;br /&gt;0:003&amp;gt; !DumpMT -MD 002a3048&lt;br /&gt;...&lt;br /&gt;--------------------------------------&lt;br /&gt;   Entry MethodDesc      JIT Name&lt;br /&gt;...&lt;br /&gt;00860070   002a3020      JIT ConsoleApplication.Program.Main()&lt;br /&gt;008600a8   002a3028      JIT ConsoleApplication.Program.Method1()&lt;br /&gt;00860100   002a3030      JIT ConsoleApplication.Program.Method2()&lt;br /&gt;008600c8   002a3038      JIT ConsoleApplication.Program.DoNothing(System.String)&lt;br /&gt;002ac021   002a3040     NONE ConsoleApplication.Program..ctor()&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;shows the method descriptors for all the methods in that class. Now, using !u to disassemble code for Method1&lt;/p&gt;
&lt;pre&gt;0:003&amp;gt; !u 002a3028&lt;br /&gt;Normal JIT generated code&lt;br /&gt;ConsoleApplication.Program.Method1()&lt;br /&gt;Begin 008600a8, size d&lt;br /&gt;008600a8 8b0d3c30e402    mov     ecx,dword ptr ds:[2E4303Ch] (&amp;quot;&amp;quot;)&lt;br /&gt;008600ae ff158c302a00    call    dword ptr ds:[2A308Ch] (ConsoleApplication.Program.DoNothing(System.String), mdToken: 06000004)&lt;br /&gt;008600b4 c3              ret&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt; and then for Method2&lt;/p&gt;
&lt;pre&gt;0:003&amp;gt; !u 002a3030&lt;br /&gt;Normal JIT generated code&lt;br /&gt;ConsoleApplication.Program.Method2()&lt;br /&gt;Begin 00860100, size c&lt;br /&gt;00860100 8b0d2c10e402    mov     ecx,dword ptr ds:[2E4102Ch] (&amp;quot;&amp;quot;)&lt;br /&gt;00860106 e8bdffffff      call    008600c8 (ConsoleApplication.Program.DoNothing(System.String), mdToken: 06000004)&lt;br /&gt;0086010b c3              ret&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;shows that, surprise surprise,&lt;b&gt; the generated assembly code is identical&lt;/b&gt;.&lt;b&gt; &lt;/b&gt;The only difference is the address referenced in the mov instruction.&lt;/p&gt;&lt;p&gt;So there you have it - the JITter generates the same code whether you use String.Empty or &amp;quot;&amp;quot;, and there should no difference in performance.&lt;/p&gt;&lt;p&gt;PS : It&amp;#39;s interesting to note that the two addresses are different, even though the string contents are the same. Address 2E4303Ch in the disassembly for Method1 is the address referring to an interned string object with the content &amp;quot;&amp;quot;. You can verify that by creating another string variable initialized to &amp;quot;&amp;quot; and disassembling that code - the same address (2E4303Ch) will be referenced there as well. What&amp;#39;s surprising is that the address referenced in Method2 is different - which means the string object referenced by string.Empty is not the interned object. Wonder why - maybe because it&amp;#39;s ngen&amp;#39;ned code? &lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1638404" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /><category term="software debugging Windbg leaks" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+debugging+Windbg+leaks/default.aspx" /></entry><entry><title>The case of the leaking thread handles</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/05/29/the-case-of-the-leaking-thread-handles.aspx" /><id>/blogs/senthil/archive/2008/05/29/the-case-of-the-leaking-thread-handles.aspx</id><published>2008-05-29T18:15:00Z</published><updated>2008-05-29T18:15:00Z</updated><content type="html">&lt;p&gt;This was one of the more challenging and interesting problems to debug in a while. When testing out code for an unrelated fix, I noticed that the application&amp;#39;s handle count, as seen in the Handles column in Task Manager, kept rising steadily.&lt;/p&gt;&lt;p&gt;WinDbg, showed that the app was leaking thread handles.&lt;/p&gt;&lt;pre&gt;0:003&amp;gt; !handle&lt;p&gt;1417 Handles&lt;br /&gt;Type&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;Count&lt;br /&gt;Event&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;452&lt;br /&gt;Section&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;8&lt;br /&gt;File&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;12&lt;br /&gt;Port&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;2&lt;br /&gt;Directory&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;3&lt;br /&gt;&lt;b&gt;Thread&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;916&lt;/b&gt;&lt;br /&gt;Desktop&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;1&lt;br /&gt;KeyedEvent&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;1 &lt;/p&gt;&lt;/pre&gt;&lt;p&gt;Half expecting the code to hold references to dead threads, I dumped Thread objects in the GC heap.&lt;/p&gt;&lt;pre&gt;0:003&amp;gt; !dumpheap -stat -type System.Threading.Thread&lt;p&gt;total 353 objects&lt;br /&gt;Statistics:&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; MT&amp;nbsp;&amp;nbsp;&amp;nbsp; Count&amp;nbsp;&amp;nbsp;&amp;nbsp; TotalSize Class Name&lt;br /&gt;790fe284&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 2&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 144 System.Threading.ThreadAbortException&lt;br /&gt;79124b74&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 32&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 640 System.Threading.ThreadHelper&lt;br /&gt;791249e8&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 33&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1056 System.Threading.ThreadStart&lt;br /&gt;&lt;b&gt;790fe704&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 286&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 16016 System.Threading.Thread&lt;/b&gt;&lt;br /&gt;Total 353 objects&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;No luck there. This was perplexing - I knew the app created a lot of threads that do some work and die, but the Thread class is the only way the app deals with them, so if it&amp;#39;s not Thread instances, who else was holding the handles open? &lt;/p&gt;&lt;p&gt;Realizing that barring a CLR bug, there must be some .NET object behind each handle, I dumped the entire GC heap, looking for types with the number of instances close to the number of handles. &lt;/p&gt;&lt;pre&gt;&amp;nbsp;0:003&amp;gt; !dumpheap -stat&lt;p&gt;...&lt;/p&gt;&lt;p&gt;7912d9bc&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 25&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 54264 System.Collections.Hashtable+bucket[]&lt;br /&gt;7b483294&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1098&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 57096 System.Windows.Forms.CreateParams&lt;br /&gt;&lt;b&gt;7b48193c&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 1098&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 61488 System.Windows.Forms.Control+ControlNativeWindow&lt;/b&gt;&lt;br /&gt;7912d8f8&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 544&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 72264 System.Object[]&lt;br /&gt;&lt;b&gt;7b48398c&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 819&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 85176 System.Windows.Forms.Application+MarshalingControl&lt;/b&gt;&lt;br /&gt;&lt;b&gt;7b4835ec&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 819&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 108108 System.Windows.Forms.Application+ThreadContext&lt;/b&gt;&lt;br /&gt;0014c740&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 40&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 137064&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Free&lt;br /&gt;790fd8c4&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 7016&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 421636 System.String&lt;br /&gt;Total 22730 objects&lt;b&gt;&lt;br /&gt;&lt;/b&gt;&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;That number (819) of ThreadContext instances was pretty close to the number of open thread handles (916). Repeating the above exercise after letting the application run some more time confirmed the theory - the number of ThreadContext instances increased by almost the same extent as the number of open thread handles.&lt;/p&gt;&lt;p&gt;It should have been simple from now on - all that was left was to find the roots holding the ThreadContext instances and problem solved.&amp;nbsp; &lt;/p&gt;&lt;pre&gt;0:003&amp;gt; !dumpheap -mt 7b4835ec&lt;p&gt;...&amp;nbsp;&lt;/p&gt;&lt;p&gt;0145b550 7b4835ec&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 132&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;total 819 objects&lt;br /&gt;Statistics:&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; MT&amp;nbsp;&amp;nbsp;&amp;nbsp; Count&amp;nbsp;&amp;nbsp;&amp;nbsp; TotalSize Class Name&lt;br /&gt;7b4835ec&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 819&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 108108 System.Windows.Forms.Application+ThreadContext&lt;br /&gt;Total 819 objects&lt;br /&gt;&lt;br /&gt;&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;and then&lt;/p&gt;&lt;pre&gt;&amp;nbsp;0:003&amp;gt; !gcroot 0145b550&lt;p&gt;&amp;nbsp;Note: Roots found on stacks may be false positives. Run &amp;quot;!help gcroot&amp;quot; for&lt;br /&gt;more info.&lt;br /&gt;Scan Thread 0 OSTHread 34c0&lt;br /&gt;Scan Thread 2 OSTHread 34c8&lt;br /&gt;DOMAIN(001546E8):HANDLE(Pinned):9f13f0:Root:02373030(System.Object[])-&amp;gt;&lt;br /&gt;013720f4(System.Collections.Hashtable)-&amp;gt;&lt;br /&gt;0142486c(System.Collections.Hashtable+bucket[])&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;Here&amp;#39;s where the fun started. The main root was (System.Object[]), which indicated that the next object in the object graph (Hashtable) was a static member of some class. A search for static Hashtables in the application&amp;#39;s source code turned up nothing. The only possibility then was the BCL - some class there must be holding a static Hashtable of ThreadContexts.&lt;/p&gt;&lt;p&gt;I got a lucky break there - Reflector showed that ThreadContext class had a static Hashtable and that it&amp;#39;s constructor adds itself (this), to the hashtable. But who instantiates ThreadContexts? Reflector&amp;#39;s &amp;quot;Analyze&amp;quot; command turned up too many method flows to go through one by one, so I decided to do it the other way - set up a breakpoint on ThreadContext&amp;#39;s constructor and let the application run.&lt;/p&gt;&lt;pre&gt;0:003&amp;gt; DumpMT -MD 7b4835ec&lt;p&gt;&amp;nbsp;EEClass: 7b483400&lt;br /&gt;Module: 7b454000&lt;br /&gt;Name: System.Windows.Forms.Application+ThreadContext&lt;br /&gt;mdToken: 020001e4&amp;nbsp; (C:\WINDOWS\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll)&lt;br /&gt;BaseSize: 0x84&lt;br /&gt;ComponentSize: 0x0&lt;br /&gt;Number of IFaces in IFaceMap: 1&lt;br /&gt;Slots in VTable: 64&lt;br /&gt;--------------------------------------&lt;br /&gt;MethodDesc Table&lt;br /&gt;&amp;nbsp;&amp;nbsp; Entry MethodDesc&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; JIT Name&lt;/p&gt;&lt;p&gt;...&lt;/p&gt;&lt;p&gt;7b664ad4&amp;nbsp;&amp;nbsp; 7b4a76b0&amp;nbsp;&amp;nbsp; PreJIT System.Windows.Forms.Application+ThreadContext..ctor()&lt;/p&gt;&lt;p&gt;&amp;nbsp;and then&lt;/p&gt;&lt;p&gt;0:003&amp;gt; !bpmd -md 7b4a76b0&amp;nbsp;&amp;nbsp; &lt;/p&gt;&lt;p&gt;&lt;br /&gt;MethodDesc = 7b4a76b0&lt;br /&gt;Setting breakpoint: bp 7B06B934 [System.Windows.Forms.Application+ThreadContext..ctor()]&lt;br /&gt;&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;When the breakpoint was hit, the stack looked like this&lt;/p&gt;&lt;pre&gt;&amp;nbsp;!CLRStack&amp;nbsp;&lt;p&gt;OS Thread Id: 0x2c90 (3)&lt;br /&gt;ESP&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; EIP&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br /&gt;0106ea74 7b06b934 System.Windows.Forms.Application+ThreadContext..ctor()&lt;br /&gt;0106ea78 7b06b8cc System.Windows.Forms.Application+ThreadContext.FromCurrent()&lt;br /&gt;0106ea80 7b06b885 System.Windows.Forms.WindowsFormsSynchronizationContext..ctor()&lt;br /&gt;0106ea90 7b06b7b2 System.Windows.Forms.WindowsFormsSynchronizationContext.InstallIfNeeded()&lt;br /&gt;0106eabc 7b06a09b System.Windows.Forms.Control..ctor(Boolean)&lt;br /&gt;&lt;b&gt;0106eb30 7b068f75 System.Windows.Forms.Label..ctor()&lt;/b&gt;&lt;br /&gt;0106eb3c 00d5012b LanguageFeatures.Program.&amp;lt;Main&amp;gt;b__0()&lt;br /&gt;0106eb44 793b0d1f System.Threading.ThreadHelper.ThreadStart_Context(System.Object)&lt;br /&gt;0106eb4c 79373ecd System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)&lt;br /&gt;0106eb64 793b0c68 System.Threading.ThreadHelper.ThreadStart()&lt;br /&gt;0106ed8c 79e7c74b [GCFrame: 0106ed8c]&amp;nbsp; &lt;/p&gt;&lt;/pre&gt;&lt;p&gt;As the stack dump shows, the ThreadContext was created as part of System.Windows.Forms.Control&amp;#39;s constructor to set the synchronization context of the thread to WindowsForms. The problem was that created context didn&amp;#39;t die when the thread died. Some more poking around with Reflector showed that the instance is removed from static Hashtable when the thread receives a quit message (via Application.ExitThread, for example). The threads in the app were not pumping messages, so the ThreadContexts kept accumulating in the Hashtable, keeping the associated Thread handle open. Here&amp;#39;s some code that demonstrates the problem. &lt;/p&gt;
&lt;pre&gt;class Program
{
   static void Main(string[] args)
   {
      while (true)
      {
         new Thread(delegate() { new System.Windows.Forms.Label(); }).Start();
         Thread.Sleep(100);
      }
   }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;Bottomline - don&amp;#39;t create controls from non-message pumping threads, especially if you create lots of threads over the lifetime of the application. &lt;/p&gt;&lt;p&gt;It seems obvious in retrospect, but in the application&amp;#39;s case, it was not using the control visually, so it didn&amp;#39;t really need WM_PAINT or the hundred other messages that a control needs to work. The fix was to move control creation to a GUI (message pumping) thread and then Invoke/BeginInvoke from the other threads. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1628861" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software debugging Windbg leaks" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+debugging+Windbg+leaks/default.aspx" /></entry><entry><title>Where Am I </title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/05/05/where-am-i.aspx" /><id>/blogs/senthil/archive/2008/05/05/where-am-i.aspx</id><published>2008-05-05T19:19:00Z</published><updated>2008-05-05T19:19:00Z</updated><content type="html">&lt;p&gt;That&amp;#39;s my first Windows mobile application you&amp;#39;re seeing below.&lt;br /&gt;&lt;img src="http://msmvps.com/blogs/senthil/whereami.png" border="0" alt="" /&gt;&lt;/p&gt;&lt;p&gt;Most cellular service providers in India broadcast the location of the communicating cell tower to the phone. Where Am I (Wami) is a managed Windows Mobile application that uses the broadcast information to let you know where you are and when you will reach your destination. The screenshot above shows that I&amp;#39;m at INDIRA NAGAR, somewhere close to TIDEL PARK and that I&amp;#39;ll reach home at 12:59 AM.&lt;/p&gt;&lt;p&gt;How does Wami do this? There&amp;#39;s a sister application, RouteLogger, that automatically logs cell tower locations (INDIRA NAGAR, for e.g) along with the time taken to reach the current location from the previous location. You take the route log generated by RouteLogger, group the locations into broad categories that you can readily identify (TIDEL PARK, for e.g.) and then give those route details to Wami. Wami then uses that information, and the current cell tower location, to tell you where you are and when you will reach the final destination as well as intermediate locations.&lt;/p&gt;&lt;p&gt;I wrote this application to solve a specific problem - knowing my whereabouts when taking an overnight train. I travel to my hometown once a month and I usually choose to take an overnight train. When I wake up, I have no idea where I am or when the train will reach my hometown. Wami tells me both.&lt;/p&gt;&lt;p&gt;I figured that it will be useful to a lot of other people as well. The code is not ready for primetime yet, but I&amp;#39;ll be releasing a beta version shortly. I&amp;#39;m also planning to set up a website that&amp;#39;ll allow people to share route logs. If you are interested in Wami, please post a comment so I know and keep watching this space! &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1614321" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="Windows mobile C# software Where Am I" scheme="http://msmvps.com/blogs/senthil/archive/tags/Windows+mobile+C_2300_+software+Where+Am+I/default.aspx" /></entry><entry><title>Itertools for C# - Tee</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/05/05/itertools-for-c-tee.aspx" /><id>/blogs/senthil/archive/2008/05/05/itertools-for-c-tee.aspx</id><published>2008-05-05T17:03:00Z</published><updated>2008-05-05T17:03:00Z</updated><content type="html">&lt;p&gt;Tee is a cool function that &amp;quot;clones&amp;quot; enumerators whatever their current state is - it basically allows you to branch off an enumerator into as many enumerators as you want, all independent of each other.&lt;/p&gt;&lt;p&gt;&amp;nbsp;You can do something like&lt;/p&gt;
&lt;pre&gt;List&amp;lt;int&amp;gt; list = new List&amp;lt;int&amp;gt; { 1, 2, 3, 4, 5 };&lt;br /&gt;&lt;br /&gt;IEnumerator&amp;lt;int&amp;gt; iterable1 = list.GetEnumerator();&lt;br /&gt;&lt;br /&gt;IEnumerator&amp;lt;int&amp;gt; []teedIterables = Itertools.Tee(iterable1, 2);&lt;br /&gt;&lt;br /&gt;foreach(int val in teedIterables[0])&lt;br /&gt;{&lt;br /&gt;   Console.WriteLine(val);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;foreach(int val in teedIterables[1])&lt;br /&gt;{&lt;br /&gt;   Console.WriteLine(val);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;// prints 1 2 3 4 5 1 2 3 4 5&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;
If there was a iterable1.MoveNext() before the call to Tee, then the output would have been 2 3 4 5 2 3 4 5.

The implementation proved to be pretty interesting - and complicated, partly because the C# compiler does not allow the yield statement inside anonymous methods. Here&amp;#39;s the implementation.
&lt;/p&gt;
&lt;pre&gt;public static IEnumerator&amp;lt;T&amp;gt;[] Tee&amp;lt;T&amp;gt;(IEnumerator&amp;lt;T&amp;gt; source, int count)&lt;br /&gt;{&lt;br /&gt;    List&amp;lt;T&amp;gt; tValues = new List&amp;lt;T&amp;gt;();&lt;br /&gt;    IEnumerator&amp;lt;T&amp;gt;[] results = new IEnumerator&amp;lt;T&amp;gt;[count];&lt;br /&gt;&lt;br /&gt;    for (int i = 0; i &amp;lt; count; ++i)&lt;br /&gt;    {&lt;br /&gt;       int currentLocation = 0;&lt;br /&gt;       results [ i ] = CreateEnumerator(source, new EnumeratorState&amp;lt;T&amp;gt;() { CurrentLocation = currentLocation, TValues = tValues });&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    return results;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;private static IEnumerator&amp;lt;T&amp;gt; CreateEnumerator&amp;lt;T&amp;gt;(IEnumerator&amp;lt;T&amp;gt; source, EnumeratorState&amp;lt;T&amp;gt; state)&lt;br /&gt;{&lt;br /&gt;   while (true)&lt;br /&gt;   {&lt;br /&gt;      if (state.CurrentLocation &amp;lt; state.TValues.Count)&lt;br /&gt;      {&lt;br /&gt;          yield return state.TValues[state.CurrentLocation++];&lt;br /&gt;      }&lt;br /&gt;      else&lt;br /&gt;      {&lt;br /&gt;         if (source.MoveNext())&lt;br /&gt;         {&lt;br /&gt;            state.TValues.Add(source.Current);&lt;br /&gt;            state.CurrentLocation = state.TValues.Count;&lt;br /&gt;            yield return source.Current;&lt;br /&gt;         }&lt;br /&gt;         else&lt;br /&gt;         {&lt;br /&gt;             break;&lt;br /&gt;         }&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;class EnumeratorState&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;   internal int CurrentLocation { get; set; }&lt;br /&gt;   internal List&amp;lt;T&amp;gt; TValues { get; set; }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;There&amp;#39;s a fair bit of code involved, as you can see. The basic idea behind the implementation is to maintain a list as a backing store. Each teed off enumerator attempts to read from the list - if it hits the end of the list, it advances the original enumerator&amp;nbsp; and gets the current value, updates the list and returns that value. The rest of the code is plumbing to work around the inability to use yield inside an anonymous method. The code basically does what the compiler would have done - there&amp;#39;s the EnumeratorState class to hold captured variables and a new instance of the class is created and passed to CreateEnumerator, which is in the place of the anonymous method.&lt;/p&gt;&lt;p&gt;Tee is that kind of function that is incredibly useful once you know you can do such a thing. Let&amp;#39;s say you have an application that needs to process lines in a file, but the processing can happen in different contexts, independent of each other. Take for example, a log parser, that goes through each line in a file, looking for the start of an operation. The log parser notifies another component once it finds the start of the operation and proceeds through the file looking for the next operation. Normally, you&amp;#39;ll solve the problem by adding the component to a list that gets notified after the parser reads each line. With Tee, you can simply tee off an enumerator and pass it to the other component - both the log parser and the component now have independent enumerators and can actually run in parallel. And you can tee off as many enumerators as there are components. &lt;/p&gt;&lt;p&gt;With that, we come to the end of this series of blog posts on implementing itertools in C#. The source code for all the functions implemented in the series is available at &lt;a href="http://code.msdn.microsoft.com/itertools"&gt;http://code.msdn.microsoft.com/itertools&lt;/a&gt;.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1614250" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /><category term="C# 3.0" scheme="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx" /></entry><entry><title>Itertools for C# - Cycle and Zip</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/04/26/itertools-for-c-cycle-and-zip.aspx" /><id>/blogs/senthil/archive/2008/04/26/itertools-for-c-cycle-and-zip.aspx</id><published>2008-04-26T05:21:00Z</published><updated>2008-04-26T05:21:00Z</updated><content type="html">Continuing our implementation of Python iterator functions in C#, we&amp;#39;ll implement Cycle and Zip this time.
&lt;p&gt;&lt;b&gt;Cycle&lt;/b&gt;&lt;br /&gt;
&lt;/p&gt;&lt;pre&gt;IEnumerable Cycle(IEnumerable iterable)&lt;/pre&gt;
&lt;p&gt;Cycle keeps cycling through the enumerator, that is, it cycles back to the first element when the enumerator is exhausted. You can use it like
&lt;/p&gt;&lt;pre&gt;IEnumerable&amp;lt;int&amp;gt; source = new List&amp;lt;int&amp;gt;() { 1, 2, 3};
foreach(int element in Itertools.Cycle(source))
{
   Console.WriteLine(element); // prints 1 2 3 1 2 3..
}&lt;/pre&gt;
&lt;p&gt;The implementation is again very straightforward - all we have to do is wrap the foreach over the iterable in an infinite loop. The outer loop while loop creates a new enumerator for every iteration, as foreach calls GetEnumerator() before looping over the returned enumerator.

&lt;/p&gt;
&lt;pre&gt;public static IEnumerable&amp;lt;T&amp;gt; Cycle&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; iterable)
{
   while (true)
   {
      foreach (T t in iterable)
      {
          yield return t;
      }
   }
}
&lt;/pre&gt;

The Python cycle function has a slightly different behavior - it caches elements in the iterable the first time around and then iterates over the cache after that. This means that changes to the collection will not be visible to the users of the cycle function, but only if the changes happen after cycle starts returning elements from its cache.&lt;br /&gt;
&lt;p&gt;&lt;b&gt;Zip&lt;/b&gt;
&lt;/p&gt;&lt;pre&gt;IEnumerable&amp;lt;T[]&amp;gt; Zip&amp;lt;T&amp;gt;(params IEnumerable&amp;lt;T&amp;gt;[] iterables)&lt;/pre&gt;
&lt;p&gt;Zip returns an enumerable array of elements, with each array containing one element per input iterator. The first array contains the first element of every iterator, the second array has every second element and so on.
&lt;/p&gt;&lt;pre&gt;IEnumerable&amp;lt;int&amp;gt; e1 = new List&amp;lt;int&amp;gt;() { 1, 2, 3};
IEnumerable&amp;lt;int&amp;gt; e2 = new List&amp;lt;int&amp;gt;() { 4, 5, 6};
IEnumerable&amp;lt;int[]&amp;gt; zippedValues = Itertools.Zip(e1, e2);
foreach(int[] arr in zippedValues)
{
   Console.WriteLine(&amp;quot;{&amp;quot;);
   foreach(int val in arr)
       Console.WriteLine(val);
   Console.WriteLine(&amp;quot;}&amp;quot;);
}
&lt;/pre&gt;&lt;p&gt;
This prints {1,4}, {2,5}, {3,6}&lt;/p&gt;&lt;p&gt;The implementation is slightly more complex.&lt;/p&gt;
&lt;pre&gt;public static IEnumerable&amp;lt;T[]&amp;gt; Zip&amp;lt;T&amp;gt;(params IEnumerable&amp;lt;T&amp;gt;[] iterables)
{
   IEnumerator&amp;lt;T&amp;gt;[] enumerators = Array.ConvertAll(iterables, (iterable) =&amp;gt; iterable.GetEnumerator());

    while (true)
    {
       int index = 0;
       T[] values = new T[enumerators.Length];

       foreach (IEnumerator&amp;lt;T&amp;gt; enumerator in enumerators)
       {
           if (!enumerator.MoveNext())
              yield break;

            values[index++] = enumerator.Current;
       }

       yield return values;
    }
}
&lt;/pre&gt;
&lt;p&gt;The code gets enumerators for all the iterables, moves all enumerators forward, accumulates their current values into an array and yields the array. It does this until any one of the enumerators runs out of elements.

&lt;/p&gt;&lt;p&gt;Next time, we&amp;#39;ll look at Tee - an interesting function that also proved to be a little tricky to implement.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1605010" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author></entry><entry><title>Itertools for C#</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/04/13/itertools-for-c.aspx" /><id>/blogs/senthil/archive/2008/04/13/itertools-for-c.aspx</id><published>2008-04-13T18:47:00Z</published><updated>2008-04-13T18:47:00Z</updated><content type="html">&lt;p&gt;If you are a C# developer and haven&amp;#39;t taken a look at the &lt;a href="http://docs.python.org/lib/itertools-functions.html"&gt;itertools&lt;/a&gt; python module so far, you owe it to yourself to learn about it. It&amp;#39;s a module with functions that operate on what Python calls &amp;quot;iterables&amp;quot; (IEnumerable in C#). Go ahead, take a look at it before reading on.&lt;/p&gt;&lt;p&gt;This got me interested about implementing similar functions in C#, using IEnumerable&amp;lt;T&amp;gt;. I fired up VS 2008 and started cranking out the code, only to find that most of the itertools functions are already implemented as extension methods on IEnumerable&amp;lt;T&amp;gt; in .NET 3.5. Some of the functions even have the same name, like Repeat and TakeWhile. I found four functions that weren&amp;#39;t directly available as IEnumerable&amp;lt;T&amp;gt; methods and decided to implement them. Let&amp;#39;s take a look at them, one by one.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;&lt;b&gt;Chain&lt;/b&gt;&lt;/p&gt;&lt;pre&gt;IEnumerable&amp;lt;T&amp;gt; Chain&amp;lt;T&amp;gt;(params IEnumerable&amp;lt;T&amp;gt;[] iterables)&lt;/pre&gt;&lt;p&gt;Chain returns one flat view of all the enumerators chained together. IEnumerable&amp;lt;T&amp;gt;.Concat does the same thing, but you&amp;#39;ll have to call it multiple times to chain more than one iterator. Chain can be used to do things like&lt;/p&gt;
&lt;pre&gt;IEnumerable&amp;lt;int&amp;gt; e1 = new List&amp;lt;int&amp;gt;() { 1, 2, 3};&lt;br /&gt;IEnumerable&amp;lt;int&amp;gt; e2 = new List&amp;lt;int&amp;gt;() { 4, 5, 6};&lt;br /&gt;IEnumerable&amp;lt;int&amp;gt; e3 = new List&amp;lt;int&amp;gt;() { 7, 8, 9};&lt;br /&gt;&lt;br /&gt;IEnumerable&amp;lt;int&amp;gt; chained = Itertools.Chain(e1, e2, e3);&lt;br /&gt;&lt;br /&gt;foreach(int element in chained)&lt;br /&gt;{&lt;br /&gt;   Console.WriteLine(element); // prints 1 2 3 4 5 6 7 8 9&lt;br /&gt;}&lt;/pre&gt;
&lt;p&gt;The implementation is fairly straightforward, thanks to the incredibly useful yield statement.
&lt;/p&gt;&lt;pre&gt;public static IEnumerable&amp;lt;T&amp;gt; Chain&amp;lt;T&amp;gt;(params IEnumerable&amp;lt;T&amp;gt;[] iterables)
{
   foreach(IEnumerable&amp;lt;T&amp;gt; iterable in iterables)
   {
      foreach (T t in iterable)
      {
         yield return t;
      }
   }
}
&lt;/pre&gt;

Next up is the Cycle method. We&amp;#39;ll see how it works in the next blog post.&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1585605" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author></entry><entry><title>The Observer Effect</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/03/30/the-observer-effect-bug.aspx" /><id>/blogs/senthil/archive/2008/03/30/the-observer-effect-bug.aspx</id><published>2008-03-30T21:48:00Z</published><updated>2008-03-30T21:48:00Z</updated><content type="html">&lt;p&gt;The observer effect &amp;quot;refers to changes that the act of observing will make on the phenomenon being observed.&amp;quot;. How infuriating would be a bug that demonstrates that effect - things work when you see them, don&amp;#39;t when you don&amp;#39;t?&lt;/p&gt;&lt;p&gt;There&amp;#39;s this third party Winforms control I use that does a lot of custom painting. Think of it as a chart control that displays live stock data one stock at a time, with the stock changing every few minutes. Everything was ok, until I happened to see the chart all mixed up on a colleague&amp;#39;s machine. On taking a closer look, I figured out that the images for the previous stock were not cleared by the control, before it drew them for the current stock.&lt;/p&gt;&lt;p&gt;Easy fix - it must be either incorrect data or the control failing to refresh, I thought. I checked the data, that was fine. Explicitly calling Refresh - nope, that didn&amp;#39;t work either.&lt;/p&gt;&lt;p&gt;Hmm, I figured if I could reproduce this on my machine, I could attach a debugger and fix this. And that&amp;#39;s where the fun started. It simply would not happen on my machine - no matter what I tried. Finally, out of desperation, I moved to a different screen that would hide the control as it was painting and sure enough, the painting was messed up when the control was visible again.&lt;/p&gt;&lt;p&gt;It was time to look at the source code for the control. The reason for the garbled painting was easy to find - the control caches the bitmap used for drawing. As newer data comes in, it draws them on top of the cached bitmap. For some reason, the cached bitmap was not getting invalidated when the stock changed. The invalidation of the cached bitmap is controlled by a flag. The flag is set when new data is coming in and is reset when the code hosting the control calls Reset.&lt;/p&gt;&lt;p&gt;My code is missing the Reset, I thought, but that should lead to garbled displays always, not just when the control is invisible. And then it struck me - the code doing the actual invalidation of the cached bitmap was inside the OnPaint method. &lt;/p&gt;&lt;p&gt;If the control happens to be visible when Reset is called, the painting code gets triggered, the flag is false and the bitmap is disposed. If it is invisible during Reset AND becomes visible only after new data starts flowing in, the flag would have been reset to true and the control would continue drawing on top of the cached bitmap, messing up the display.&lt;/p&gt;&lt;p&gt;The fix was to invalidate the cache inside Reset as well.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1562741" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /></entry><entry><title>Not just a function : Generating functions</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2008/02/12/more-than-just-functions-generating-functions.aspx" /><id>/blogs/senthil/archive/2008/02/12/more-than-just-functions-generating-functions.aspx</id><published>2008-02-12T15:29:00Z</published><updated>2008-02-12T15:29:00Z</updated><content type="html">&lt;p&gt;Every now and then, you hit some problem that a programming language helps solve very cleanly. Here&amp;#39;s the problem.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;You are writing a series of functions that return a bool depending on some condition (predicates). Something like&lt;br /&gt;&lt;/p&gt;&lt;pre&gt;bool Foo(State t);&lt;/pre&gt;&lt;p&gt;Let&amp;#39;s also assume that State is defined as&lt;/p&gt;&lt;pre&gt;class State&amp;nbsp; { Color c; ... }&lt;/pre&gt;&lt;p&gt;You have a set of colors, known at compile time, for which Foo should return true. How would you go about doing it?&lt;/p&gt;&lt;p&gt;You could pack the set of colors into an array and write Foo so that at runtime, it searches the color array and returns true if the color passed is in the array. Something like&lt;/p&gt;&lt;pre&gt;bool Foo(State t) { return colors.IndexOf(t.Color) != -1; }&lt;/pre&gt;&lt;p&gt;Assume that, for design reasons, it isn&amp;#39;t really possible to allow access to colors from within Foo. Then what?&lt;/p&gt;&lt;p&gt;Anonymous methods and closures, of course. How about writing a function, that returns a Foo that returns true only if the color matches. Whew, that sounds confusing, but the code looks pretty simple. &lt;/p&gt;&lt;pre&gt;Foo GenerateFoo(Color color) { return delegate(Color passedColor) { return color == passedColor; } }&lt;/pre&gt;&lt;p&gt;You can then call GenerateFoo(Color.Red) to get a Foo that will return true only if it is called with Color.Red, call GenerateFoo(Color.Orange) to get one that returns true only if called with Color.Orange and so on.&lt;/p&gt;&lt;pre&gt;Foo redFoo = GenerateFoo(Color.Red);
Foo orangeFoo = GenerateFoo(Color.Orange);
Console.WriteLine(redFoo(Color.Red)); // prints true
Console.WriteLine(redFoo(Color.Yellow)); // prints false&lt;/pre&gt;&lt;p&gt;Nifty, eh? &lt;br /&gt;&lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1510302" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /></entry><entry><title>C# 3.0 compiler bug - Using object initializers, generics and value types</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/12/26/c-3-0-compiler-bug-using-object-initializers-generics-and-value-types.aspx" /><id>/blogs/senthil/archive/2007/12/26/c-3-0-compiler-bug-using-object-initializers-generics-and-value-types.aspx</id><published>2007-12-26T17:44:00Z</published><updated>2007-12-26T17:44:00Z</updated><content type="html">&lt;p&gt;There is a description of the bug &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319430"&gt;here&lt;/a&gt;. The following piece of code demonstrates the bug.&lt;/p&gt;
&lt;pre&gt;    class Program
    {
        interface I
        {
            int X { get; set; }
        }

        struct S : I
        {
            public int X { get; set; }
        }

        static void Main(string[] args)
        {
            Func&amp;lt;S&amp;gt;();
        }

        static void Func&amp;lt;T&amp;gt;() where T : I, new()
        {
            var c = new T() { X = 1 };
            Console.WriteLine(c.X);
        }
    }
&lt;/pre&gt;&lt;p&gt;The code prints 0 instead of 1. The bug goes away if object initializers are not used - changing var c = new T() { X = 1 }; to var c = new T(); c.X = 1; will print 1.&lt;/p&gt;&lt;p&gt;I had assumed all along that object initializers were transformed into property setters at the source code level (or somewhere above IL). This bug doesn&amp;#39;t help much to confirm that :)&lt;/p&gt;&lt;p&gt;Anyway, let&amp;#39;s see what&amp;#39;s causing the problem. Peeking into the generated IL,&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;   .locals init (
        [0] !!T c,
        [1] !!T &amp;lt;&amp;gt;g__initLocal0,
        [2] !!T CS$0$0000)
        ... // Store zeroed out instance of S in locals[1]
    L_0022: ldloc.1 
    L_0023: box !!T
    L_0028: ldc.i4.1 
    L_0029: callvirt instance void CSharp3Test.Program/I::set_X(int32)
    L_002e: nop 
    L_002f: ldloc.1 
    L_0030: stloc.0 
    L_0031: ldloca.s c
    L_0033: constrained !!T
    L_0039: callvirt instance int32 CSharp3Test.Program/I::get_X()
    L_003e: call void [mscorlib]System.Console::WriteLine(int32)
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;Can you spot the problem now?&lt;/p&gt;&lt;p&gt;You can see that at L_0023, S is boxed and the boxed instance is used to make the virtual call to set X. You can also see that the boxed instance is not stored in any of the local variables, the &lt;b&gt;callvirt&lt;/b&gt; instruction pops it off the stack and then it&amp;#39;s gone. To load the value of X, the &lt;b&gt;callvirt&lt;/b&gt; instruction is given a reference to c (locals[0]), which contains the unboxed instance of the struct. Which is why we are getting a 0 (the default value), instead of 1. Essentially, the compiler is generating the equivalent IL for something like&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;   S s = new S();
   I i = s;
   i.X = 10;
   Console.WriteLine(s.X);
&lt;/pre&gt;&lt;p&gt;This again prints 0 instead of 10, because i is assigned a different (boxed) instance of S and therefore changing i.X doesn&amp;#39;t change s.X.&lt;br /&gt;&lt;/p&gt;But then how does doing the initialization in two steps (var c = new T(); c.X = 1) work. The answer - Two step initialization does not use boxing when setting the value of X. Here&amp;#39;s how the generated IL looks.&lt;br /&gt;
&lt;pre&gt;   .locals init (
        [0] !!T c,
        [1] !!T CS$0$0000)
    L_0021: stloc.0 
    L_0022: ldloca.s c
    L_0024: ldc.i4.1 
    L_0025: constrained !!T
    L_002b: callvirt instance void CSharp3Test.Program/I::set_X(int32)
    L_0030: nop 
    L_0031: ldloca.s c
    L_0033: constrained !!T
    L_0039: callvirt instance int32 CSharp3Test.Program/I::get_X()
    L_003e: call void [mscorlib]System.Console::WriteLine(int32)
&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;The box instruction is gone, instead, the compiler has generated a constrained prefix for the &lt;b&gt;callvirt&lt;/b&gt; instruction. MSDN says that&lt;/p&gt;&lt;p&gt;&amp;quot;When a &lt;span class="keyword"&gt;callvirt&lt;/span&gt; &lt;span class="parameter"&gt;method&lt;/span&gt; instruction has been prefixed by &lt;span class="keyword"&gt;constrained&lt;/span&gt; &amp;nbsp;&lt;span class="parameter"&gt;thisType&lt;/span&gt;, the instruction is executed as follows: &lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;p&gt;If &lt;span class="parameter"&gt;thisType&lt;/span&gt; is a reference type (as opposed to a value type) then &lt;span class="parameter"&gt;ptr&lt;/span&gt; is dereferenced and passed as the &amp;#39;this&amp;#39; pointer to the &lt;span class="keyword"&gt;callvirt&lt;/span&gt; of &lt;span class="parameter"&gt;method&lt;/span&gt;.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;p&gt;If &lt;span class="parameter"&gt;thisType&lt;/span&gt; is a value type and &lt;span class="parameter"&gt;thisType&lt;/span&gt; implements &lt;span class="parameter"&gt;method&lt;/span&gt; then &lt;span class="parameter"&gt;ptr&lt;/span&gt; is passed unmodified as the &amp;#39;this&amp;#39; pointer to a &lt;span class="keyword"&gt;call&lt;/span&gt; &amp;nbsp;&lt;span class="parameter"&gt;method&lt;/span&gt; instruction, for the implementation of &lt;span class="parameter"&gt;method&lt;/span&gt; by &lt;span class="parameter"&gt;thisType&lt;/span&gt;.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;...&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;&amp;nbsp;&amp;quot;&lt;/p&gt;&lt;p&gt;In other words, the address of the instance is passed as the this parameter to the &lt;b&gt;call &lt;/b&gt;method - no boxing at all. If you&amp;#39;d looked carefully enough, the getter for X uses the constrained prefix, even in our buggy IL (the first listing). &lt;br /&gt;&lt;/p&gt;&lt;p&gt;That explains the bug then, but opens up another question. If virtual dispatch can be done for a value type without boxing, then why not do it that way for&lt;/p&gt;&lt;pre&gt;   S s = new S();&lt;br /&gt;   I i = s;&lt;br /&gt;   i.X = 10;&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;as well? Mind you, virtual dispatch doesn&amp;#39;t mean anything for value types, as they cannot derive from or derived by anything else, so any &lt;b&gt;callvirt&lt;/b&gt; instruction on value types can be treated as a straight &lt;b&gt;call&lt;/b&gt; instruction. The constrained prefix does exactly this, after making sure that &lt;b&gt;this &lt;/b&gt;is a value type. So why not use it for all virtual calls? Performance (not many value types implementing interfaces)? &lt;/p&gt;&lt;p&gt;What do you think?&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1420645" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /><category term="C# 3.0" scheme="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx" /></entry><entry><title>More greasemonkeying with IRCTC</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/12/26/more-greasemonkeying-with-irctc.aspx" /><id>/blogs/senthil/archive/2007/12/26/more-greasemonkeying-with-irctc.aspx</id><published>2007-12-26T08:09:00Z</published><updated>2007-12-26T08:09:00Z</updated><content type="html">&lt;p&gt;I&amp;#39;m glad that a lot of people found &lt;a href="http://msmvps.com/blogs/senthil/archive/2007/11/10/greasemonkeying-around-with-irctc.aspx" target="_blank"&gt;AJAXAvailability&lt;/a&gt; useful. For people who haven&amp;#39;t heard about it, AJAXAvailability is a Greasemonkey script for IRCTC&amp;#39;s website that loads availability information asynchronously and shows it in the availability table, right alongside the list of trains (more information &lt;a href="http://msmvps.com/blogs/senthil/archive/2007/11/10/greasemonkeying-around-with-irctc.aspx"&gt;here&lt;/a&gt;).&lt;br /&gt;&lt;/p&gt;&lt;p&gt;&lt;a href="http://msmvps.com/blogs/senthil/archive/2007/11/10/greasemonkeying-around-with-irctc.aspx#1417733" target="_blank"&gt;Mani&lt;/a&gt; suggested that the ability to sort the availability table based on departure time would be useful. That seemed like a nice idea, so here it is - &lt;a href="http://senthil.thecoder.googlepages.com/sortitout.user.js"&gt;SortItOut&lt;/a&gt;, a Greasemonkey script
that modifies the availability table and makes the header texts clickable.
Clicking on one of the headers, say &amp;quot;Departure time&amp;quot;, sorts the table by the
values in that column, in ascending order.Greasemonkey script to do that.&lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;img src="http://msmvps.com/blogs/senthil/ascendingsort.png" alt="Ascending sort screenshot" align="absmiddle" border="0" height="342" hspace="" width="518" /&gt;&lt;/p&gt;&lt;p&gt;Clicking on the same header again will sort the table in descending order.&amp;nbsp;&lt;/p&gt;&lt;p&gt;&lt;img src="http://msmvps.com/blogs/senthil/descendingsort.png" alt="" align="absmiddle" border="" height="344" hspace="" width="518" /&gt; &lt;br /&gt;&lt;/p&gt;&lt;p&gt;You can sort by any column, except the one with radio buttons (&amp;quot;Select&amp;quot;). This script also works nicely with AJAXAvailability, in that it allows you to sort the table even when availability information is loading (unless you are sorting the table by availability information, of course).&amp;nbsp;&lt;/p&gt;&lt;p&gt;To install the script, &lt;a href="http://www.google.co.in/url?sa=t&amp;amp;ct=res&amp;amp;cd=1&amp;amp;url=https%3A%2F%2Faddons.mozilla.org%2Fen-US%2Ffirefox%2Faddon%2F748&amp;amp;ei=OL41R4LENaa6swLDtrijCw&amp;amp;usg=AFQjCNGwTfL-iNiyO_EdM51X1x7LgP1rEg&amp;amp;sig2=ks4n6Am8DHeoJTVzTfEFFQ" title="Install Greasemonkey"&gt;install Greasemonkey&lt;/a&gt; first (if you haven&amp;#39;t already), navigate to &lt;a href="http://senthil.thecoder.googlepages.com/sortitout.user.js"&gt;SortItOut&lt;/a&gt;&lt;a href="http://senthil.thecoder.googlepages.com/ajaxavailability.user.js" title="AJAXAvailability.user.js" target="_blank"&gt;&lt;/a&gt;
and click Install. The next time you visit IRCTC&amp;#39;s website and go to
the &amp;quot;Plan My Travel&amp;quot; page, the script gets loaded and runs
automatically. &lt;br /&gt;&lt;/p&gt;&lt;p&gt;That&amp;#39;s all, folks - the rest of the post is about the technical details of how the script works, feel free to skip it if you&amp;#39;re not interested.&lt;br /&gt;
&lt;/p&gt;&lt;hr /&gt;
&lt;p&gt;The script works by getting the availability table&amp;#39;s DOM object through an XPath expression and replacing the cells of the first row with dynamically created anchor elements. The click event of those elements are hooked up to a function that then sorts the table, based on the column&amp;#39;s values. The sort function is pretty simple - it creates an array of objects, one object per row. Each object holds a reference to it&amp;#39;s row and a reference to the value of the column in that row, on which the sort must be done.&lt;/p&gt;&lt;p&gt;The script then uses the Array.sort library function to do the sorting and then rearranges the rows in the table based on the sorted result. There are quite a few ways of rearranging the table -&lt;/p&gt;&lt;p&gt;1. Replace the existing HTML in each row with the HTML of the row to-be&lt;/p&gt;&lt;p&gt;2. Remove all rows in the table and create new rows and cells, based on the sorted output.&lt;/p&gt;&lt;p&gt;3. Use Greasemonkey&amp;#39;s insertBefore to switch around &amp;quot;TR&amp;quot; DOM objects.&lt;/p&gt;&lt;p&gt;The first approach wouldn&amp;#39;t work with AJAXAvailability. That script stores references to &amp;quot;TD&amp;quot; DOM elements, for updating availability information in the AJAX callback. Replacing the innerHTML of the table&amp;#39;s rows would create new TD objects, breaking that script. There was another subtle problem when I tried doing this - my sorted array and the actual table hold references to the same TR DOM objects, so replacing the HTML in the table would also affect the sorted output. &lt;/p&gt;&lt;p&gt;The second approach will not work for the same reason - new TD elements will be created, and the AJAXAvailability script will update the now obsolete TD elements.&lt;br /&gt;&lt;/p&gt;&lt;p&gt;The third approach works because no new objects are created, existing TR objects are shunted around, based on the sorted output. This was also the simplest to code as well. Doesn&amp;#39;t it feel great, when the best solution is the simplest and cleanest one as well?&lt;br /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1420043" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="IRCTC AJAX Javascript" scheme="http://msmvps.com/blogs/senthil/archive/tags/IRCTC+AJAX+Javascript/default.aspx" /></entry><entry><title>Mucking around with instance field initializers - Part 2</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/12/23/mucking-around-with-instance-field-initializers-part-2.aspx" /><id>/blogs/senthil/archive/2007/12/23/mucking-around-with-instance-field-initializers-part-2.aspx</id><published>2007-12-23T18:20:00Z</published><updated>2007-12-23T18:20:00Z</updated><content type="html">&lt;p&gt;We saw in &lt;a href="http://msmvps.com/blogs/senthil/archive/2007/12/06/mucking-around-with-instance-field-initializers-part-1.aspx" target="_blank"&gt;Part 1&lt;/a&gt; that C# doesn&amp;#39;t allow an instance field initializer to refer another field in the class. Before trying to figure out why, let&amp;#39;s first see if this is a restriction imposed by C#, rather than by the CLR.&amp;nbsp;&lt;/p&gt;&lt;p&gt;Some disassembling and reassembling later, this is what the new IL code looks like.&lt;br /&gt;
&lt;/p&gt;&lt;pre&gt;    IL_0000:  ldarg.0&lt;br /&gt;    IL_0001:  ldc.i4.1&lt;br /&gt;    IL_0002:  stfld      int32 ConsoleApplication1.Program::x&lt;br /&gt;    IL_0007:  ldarg.0&lt;br /&gt;    IL_0008:  ldarg.0&lt;br /&gt;    IL_000b:  ldfld      int32 ConsoleApplication1.Program::x&lt;br /&gt;    IL_0009:  ldc.i4.1&lt;br /&gt;    IL_000a:  add&lt;br /&gt;    IL_000c:  stfld      int32 ConsoleApplication1.Program::y&lt;br /&gt;    IL_000d:  ldarg.0&lt;br /&gt;    IL_000e:  ldfld      int32 ConsoleApplication1.Program::y&lt;br /&gt;    IL_000f:  call       void [mscorlib]System.Console::WriteLine(int32)&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;It&amp;#39;s basically the same code in Part 1, except for the initialization of y. Instead of initializing y to 2, the code tries to load this.x, add 1 to it, store the result in y (y = x + 1) and then print out the result. The call to the constructor of System.Object comes next, but I&amp;#39;ve left that out for clarity.&amp;nbsp; &lt;/p&gt;&lt;p&gt;Guess what, it works! The code assembles, checks out with peverify and runs fine, printing the value 2. &lt;/p&gt;&lt;p&gt;So, it looks like the CLR does not have any problems accessing other instance fields when initializing them. Then why doesn&amp;#39;t the C# compiler like them?&lt;/p&gt;&lt;p&gt;How about fields inherited from a base class? If C# doesn&amp;#39;t have the instance field initializer restriction, then the following piece of code should compile . What do you expect the value of y to be?&lt;/p&gt;&lt;pre&gt;    class A&lt;br /&gt;    {&lt;br /&gt;        protected int x = 1;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    class B : A&lt;br /&gt;    {&lt;br /&gt;        int y = x + 1;&lt;br /&gt;        B() { Console.WriteLine(y); }&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;1? 2? It depends on where the C# compiler puts the instance field initialization code. According to the current spec, it&amp;#39;s placed before the call to the base class constructor, which means that y will be initialized to 1. Suddenly, the derived class now gets to access uninitialized base class state. Not good at all. &lt;/p&gt;&lt;p&gt;You could argue that the compiler knows about inherited fields and therefore can apply the restriction only to those fields - but that would add a nasty special case to the &amp;quot;you-cannot-reference-during-instance-field-initialization&amp;quot; list. I don&amp;#39;t think it will be intuitive either - a typical programmer will be surprised if a &amp;quot;Move to base class&amp;quot; refactor suddenly breaks working code.&lt;/p&gt;&lt;p&gt;Static fields don&amp;#39;t have this problem - they aren&amp;#39;t really &amp;quot;inherited&amp;quot;. Which could be why the compiler allows static field initializers to reference other fields.&lt;/p&gt;&lt;p&gt;What do you think?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1414545" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /></entry><entry><title>Mucking around with instance field initializers - Part 1</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/12/06/mucking-around-with-instance-field-initializers-part-1.aspx" /><id>/blogs/senthil/archive/2007/12/06/mucking-around-with-instance-field-initializers-part-1.aspx</id><published>2007-12-06T13:02:00Z</published><updated>2007-12-06T13:02:00Z</updated><content type="html">&lt;p&gt;What do you think of the following piece of code?&lt;/p&gt;
&lt;pre&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        int x = 1;&lt;br /&gt;        int y = x + 1;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;Looks simple, except that it doesn&amp;#39;t compile (error CS0236: A field initializer cannot reference the non-static field, method, or property &amp;#39;Program.x&amp;#39;)&lt;br /&gt;&lt;br /&gt;Try making x and y static - the code will compile fine now. I have been trying to find out why - so far, I haven&amp;#39;t got a clue. Just in case it&amp;#39;s not obvious, I do know that moving y = x + 1 into the body of Program&amp;#39;s constructor will get me what I want, but I was (and am) curious to know why field initializers, and only instance field initializers, aren&amp;#39;t allowed to access non-static fields. &lt;/p&gt;&lt;p&gt;The C# spec says that &lt;span class="paragraph"&gt;&lt;span class="sentence"&gt;field initializers &amp;quot;correspond to a sequence of assignments that are executed immediately upon entry to any one of the instance constructors&amp;quot;&lt;/span&gt;&lt;/span&gt;, just before the call to the base class constructor. When I generated IL for Program&amp;#39;s constructor after replacing y = x + 1 with y = 2, it looked like this&lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;    L_0000: ldarg.0 &lt;br /&gt;    L_0001: ldc.i4.1 &lt;br /&gt;    L_0002: stfld int32 ConsoleApplication1.Program::x&lt;br /&gt;    L_0007: ldarg.0 &lt;br /&gt;    L_0008: ldc.i4.2 &lt;br /&gt;    L_0009: stfld int32 ConsoleApplication1.Program::y&lt;br /&gt;    L_000e: ldarg.0 &lt;br /&gt;    L_000f: call instance void [mscorlib]System.Object::.ctor()&lt;br /&gt;    L_0014: nop &lt;br /&gt;    L_0015: ret &lt;br /&gt;&lt;/pre&gt;&lt;p&gt;
The generated IL matches with the spec - 1 and 2 are stfld&amp;#39;ed into x and y before calling the base class constructor (System.Object::.ctor()).&lt;/p&gt;&lt;p&gt;The C# spec also says that a field initializer is not allowed to reference the &lt;b&gt;this&lt;/b&gt; pointer - &amp;quot;&lt;span class="paragraph"&gt;&lt;span class="sentence"&gt; variable initializer for an instance field cannot reference the instance being created.&amp;quot; It doesn&amp;#39;t say why though.&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;&lt;p&gt;The IL shown above clearly indicates that &lt;b&gt;this&lt;/b&gt; (ldarg.0) is valid when storing 1 and 2 into x and y. So why doesn&amp;#39;t C# allow y = x + 1?&lt;/p&gt;&lt;p&gt;I initially wondered if that rule is to prevent code like this&amp;nbsp;&lt;/p&gt;
&lt;pre&gt;    class Program&lt;br /&gt;    {&lt;br /&gt;        int x = y + 1;&lt;br /&gt;        int y = x + 1;&lt;br /&gt;    }&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;but then, the C# spec clearly says that the variable initializers will be run in &amp;quot;textual&amp;quot; order. If you combine that with the fact that x and y will be assigned their default values even before their variable initializers run, you&amp;#39;ll see that the above code should run fine, resulting in x = 1 (because y is zero) and y = 2. You can make x and y static and run the code, you will see the same result. &lt;/p&gt;&lt;p&gt;So again, why? Can you figure out why? We&amp;#39;ll do some more digging into this in the next post.&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1382869" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /></entry><entry><title>Type inference != Dynamic typing</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/11/19/type-inference-dynamic-typing.aspx" /><id>/blogs/senthil/archive/2007/11/19/type-inference-dynamic-typing.aspx</id><published>2007-11-19T16:27:00Z</published><updated>2007-11-19T16:27:00Z</updated><content type="html">&lt;p&gt;Local variable type inferencing is a new feature in C# 3.5 - a very &amp;quot;handy&amp;quot; one, in that it saves a lot of typing. Basically, it lets you do&amp;nbsp;&lt;/p&gt;&lt;pre&gt;var dict = new Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;p&gt;instead of&amp;nbsp;&lt;/p&gt;&lt;pre&gt;Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt; dict = Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;p&gt;That&amp;#39;s pretty cool, but remember, C# is still a statically typed language. dict is statically bound to the type Dictionary&amp;lt;string, List&amp;lt;int, Dictionary&amp;lt;int, string&amp;gt;&amp;gt;&amp;gt; and you cannot change it. You cannot do&lt;/p&gt;&lt;pre&gt;dict = Dictionary&amp;lt;int, string&amp;gt;();&lt;/pre&gt;&lt;p&gt;in the same method. The compiler will complain that the type on the RHS is not convertible to the statically bound type of dict. &lt;/p&gt;&lt;p&gt;Contrast this to a dynamically typed language like Javascript, which also uses the var keyword to declare variables.&amp;nbsp;&lt;/p&gt;&lt;pre&gt;var x = 1;&lt;p&gt;x = new Array();&lt;/p&gt;&lt;p&gt;x = &amp;quot;23&amp;quot;;&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;Or to Python&amp;nbsp;&lt;/p&gt;&lt;pre&gt;x = 42&lt;p&gt;x = def fn(z) : return z + 1&lt;/p&gt;&lt;/pre&gt;&lt;p&gt;In such languages, variables (x, in our example) simply act as placeholders and get bound to the type of the value they are holding at the moment. In the first example, x is holding an integer after executing the first line. After executing the second line, it&amp;#39;s holding an array. If the same two lines of code were to be written in a statically typed language, the second line would be correct only if an array is somehow convertible to an int.&lt;/p&gt;&lt;p&gt;The point of the post - don&amp;#39;t be misled by the var keyword. The variable it declares is still a good old statically typed variable. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1335878" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /><category term="C# 3.0" scheme="http://msmvps.com/blogs/senthil/archive/tags/C_2300_+3.0/default.aspx" /></entry><entry><title>Greasemonkeying around with IRCTC</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/11/10/greasemonkeying-around-with-irctc.aspx" /><id>/blogs/senthil/archive/2007/11/10/greasemonkeying-around-with-irctc.aspx</id><published>2007-11-10T13:26:00Z</published><updated>2007-11-10T13:26:00Z</updated><content type="html">&lt;p&gt;[&lt;b&gt;Update&lt;/b&gt; 1/21/2008: Updated the script to handle availability URL change by IRCTC developers. If you&amp;#39;ve already installed the script, uninstall it (Tools-&amp;gt;Greasemonkey-&amp;gt;ManageUserScripts, select AJAXAvailability and click Uninstall), and install the updated script from the same location (&lt;a href="http://senthil.thecoder.googlepages.com/ajaxavailability.user.js" title="AJAXAvailability.user.js" target="_blank"&gt;http://senthil.thecoder.googlepages.com/ajaxavailability.user.js&lt;/a&gt;)] &lt;/p&gt;&lt;p&gt;For those of you who have not heard about Greasemonkey, it is a Firefox extension that &amp;quot;allows you to customize the way a webpage displays using small bits of JavaScript.&amp;quot;.&amp;nbsp; IRCTC (http://www.irctc.co.in/) is Indian Railways&amp;#39;s website for booking tickets. While a huge improvement over standing in queue at railway stations, I would not consider it to be a well designed site - it doesn&amp;#39;t stand up to heavy user load, and the interface is not very user friendly. For one, the HTML is absolutely nasty, with multiple &amp;lt;html&amp;gt; tags, multiple elements with the same id, etc.. For what I think is a bandwidth strapped site, the HTML has lots and lots of unnecessary whitespace and commented out HTML and it doesn&amp;#39;t even use gzip encoding. &lt;/p&gt;&lt;p&gt;Enough ranting about that - Greasemonkey can&amp;#39;t help there. What it can do is help manipulate the UI. My first target was the &amp;quot;Plan My Travel&amp;quot; page. After entering the source and destination stations, date of travel etc. and hitting &amp;quot;Find Trains&amp;quot;, the page shows the list of trains that run between the stations on that day. So far, so good. Now, to book tickets on a train, the user selects a train and hits &amp;quot;Book Ticket&amp;quot;. However, the user would typically have to check availability of tickets before proceeding to book them. The page makes it frustratingly difficult to do that - checking availability for &lt;b&gt;a&lt;/b&gt; train takes two clicks, and worse, the availability information shows up on a new window, forcing the user to switch back and forth between the windows. &lt;/p&gt;&lt;p&gt;I decided to write a Greasemonkey script to show availability information right alongside the list of trains. I did not want to slow down loading of the page though, so I decided to do AJAX style dynamic loading of availability information. Here&amp;#39;s how the page looks after enabling the script.&lt;/p&gt;&lt;p&gt;&lt;img src="http://msmvps.com/blogs/senthil/AJAXAvailability.PNG" alt="Screenshot after AJAXAvailability" align="middle" border="" height="329" hspace="" width="520" /&gt; &lt;/p&gt;&lt;p&gt;Notice how the new column blends in seamlessly with the rest of the page. &lt;br /&gt;&lt;/p&gt;&lt;p&gt;For the technically inclined, the script works by first adding a column to the train details table. It uses a XPath expression to get the list of train numbers from the HTML content and then queries availability information from the server by generating the same query string that a click on the &amp;quot;Show Availability&amp;quot; button generates. The difference is that it does it automatically for all trains in the page and that it uses GM_xmlhttpRequest to do the query asynchronously - which means that the script queries availability for trains (almost) simultaneously. &lt;/p&gt;&lt;p&gt;From here, it&amp;#39;s fairly simple - another XPath expression &amp;quot;screen scrapes&amp;quot; the availability string from the HTML content returned by the server and there is some code to update the cell&amp;#39;s contents with the string. The script handles failures also - for HTTP failures, it retries the request and for other kind of failures, it shows a &amp;quot;Query Failed&amp;quot; link, which, when clicked, shows the actual error in a messagebox (another XPath expression takes care of scraping the error text). &lt;/p&gt;&lt;p&gt;To install the script, &lt;a href="http://www.google.co.in/url?sa=t&amp;amp;ct=res&amp;amp;cd=1&amp;amp;url=https%3A%2F%2Faddons.mozilla.org%2Fen-US%2Ffirefox%2Faddon%2F748&amp;amp;ei=OL41R4LENaa6swLDtrijCw&amp;amp;usg=AFQjCNGwTfL-iNiyO_EdM51X1x7LgP1rEg&amp;amp;sig2=ks4n6Am8DHeoJTVzTfEFFQ" title="Install Greasemonkey"&gt;install Greasemonkey&lt;/a&gt; first (if you haven&amp;#39;t already), navigate to &lt;a href="http://senthil.thecoder.googlepages.com/ajaxavailability.user.js" title="AJAXAvailability.user.js" target="_blank"&gt;http://senthil.thecoder.googlepages.com/ajaxavailability.user.js&lt;/a&gt; and click Install. The next time you visit IRCTC&amp;#39;s website and go to the &amp;quot;Plan My Travel&amp;quot; page, the script gets loaded and runs automatically.&lt;/p&gt;&lt;p&gt;While you&amp;#39;re at it, you might also find &lt;a href="http://msmvps.com/blogs/senthil/archive/2007/12/26/more-greasemonkeying-with-irctc.aspx" target="_blank"&gt;SortItOut&lt;/a&gt;, a script for sorting the availability table (shown above), useful.  &lt;/p&gt;&lt;p&gt;Hope you guys find the scripts useful.&amp;nbsp;&lt;/p&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1293793" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="IRCTC AJAX Javascript" scheme="http://msmvps.com/blogs/senthil/archive/tags/IRCTC+AJAX+Javascript/default.aspx" /></entry><entry><title>Mixing generics and polymorphism</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/10/14/mixing-generics-and-polymorphism.aspx" /><id>/blogs/senthil/archive/2007/10/14/mixing-generics-and-polymorphism.aspx</id><published>2007-10-14T16:29:00Z</published><updated>2007-10-14T16:29:00Z</updated><content type="html">&lt;p&gt;Polymorphism, which attempts to hide differences in implementation, and generics, which attemtps to highlight them by providing exact information about types, don&amp;#39;t seem to mix very well. Consider the following fairly common pattern.&lt;/p&gt;&lt;pre&gt;        class Base
        {
        }

        class Derived : Base
        {
        }

        abstract class Manipulator
        {
            List&amp;lt;Base&amp;gt; list;

            public Manipulator(List&amp;lt;Base&amp;gt; list)
            {
                this.list = list;
            }
         }

        class BaseManipulator : Manipulator
        {
            public BaseManipulator(List&amp;lt;Base&amp;gt; list)
                : base(list)
            { }
        }

        class DerivedManipulator : Manipulator
        {
            public DerivedManipulator(List&amp;lt;Derived&amp;gt; list)
                : base(list)
            { }
        }

        public static void Main()
        {
            List&amp;lt;Derived&amp;gt; list = new List&amp;lt;Derived&amp;gt;();
            list.Add(new Derived());
            DerivedManipulator d = new DerivedManipulator(list);
        }
&lt;/pre&gt;
&lt;p&gt;The code above will not compile - the compiler complains that List&amp;lt;Derived&amp;gt;&amp;nbsp;cannot be converted to List&amp;lt;Base&amp;gt; in DerivedManipulator&amp;#39;s constructor. Which seems kindof strange, given that Derived[] is implicitly convertible to Base[]. But what would happen if implicit conversion occurred with generics?&lt;/p&gt;&lt;pre&gt;List&amp;lt;Derived&amp;gt; derivedList = new List&amp;lt;Derived&amp;gt;();
List&amp;lt;Base&amp;gt; baseList = derivedList;
baseList.Add(new Base());
Derived d = derivedList[0]; // BOOM&lt;/pre&gt;
&lt;p&gt;All hell&amp;nbsp;will break loose. The type safety&amp;nbsp;that generics offer will disappear, obviating the very need for generics.&lt;/p&gt;
&lt;p&gt;What can be done then? We could make Manipulator a generic class, taking the type of the List as a generic parameter and make DerivedManipulator derive from Manipulator&amp;lt;Derived&amp;gt;. But then we are only shifting the problem - treating Manipulators polymorphically becomes impossible then. &lt;/p&gt;
&lt;p&gt;There seems to be a basic impedance mismatch between polymorphism and generics. Does anyone know of a better way to solve the problem?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1247436" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /><category term="generics" scheme="http://msmvps.com/blogs/senthil/archive/tags/generics/default.aspx" /><category term="polymorphism" scheme="http://msmvps.com/blogs/senthil/archive/tags/polymorphism/default.aspx" /></entry><entry><title>GC::PleaseRunWhenProcessRunningOutOfMemory()</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/07/04/gc-pleaserunwhenyouarerunningoutofmemory.aspx" /><id>/blogs/senthil/archive/2007/07/04/gc-pleaserunwhenyouarerunningoutofmemory.aspx</id><published>2007-07-05T02:01:00Z</published><updated>2007-07-05T02:01:00Z</updated><content type="html">&lt;p&gt;I don&amp;#39;t think anybody except the guys who coded the GC knows the list of triggers for garbage collection. I believe it&amp;#39;s not part of the CLR spec and I guess&amp;nbsp;that was a deliberate decision to allow&amp;nbsp;implementors flexibility in their GC algorithms. That said, there are some situations which leave one confounded as to why the heck the GC doesn&amp;#39;t run. Take a look at the following program.&lt;/p&gt;&lt;pre&gt;#include &amp;quot;stdafx.h&amp;quot;
#include &amp;quot;windows.h&amp;quot;

using namespace System;

ref class Allocator
{
	LPVOID ptr;
public:
	Allocator()
	{
		ptr = VirtualAlloc(NULL, 1024 * 1024 * 1024, MEM_RESERVE, PAGE_EXECUTE_READWRITE);
		
		if (ptr == NULL)
			Console::WriteLine(&amp;quot;Virtual Alloc failed&amp;quot;);
		else
			Console::WriteLine(&amp;quot;Allocated unmanaged memory&amp;quot;);
	}

	!Allocator()
	{
		VirtualFree(ptr, 0, MEM_RELEASE);
	}
};

int main(array&amp;lt;System::String ^&amp;gt; ^args)
{
	array&amp;lt;byte&amp;gt; ^bigArray = gcnew array&amp;lt;byte&amp;gt;(1024 * 1024 * 1024);
	Allocator ^allocator = gcnew Allocator();
}
&lt;/pre&gt;
&lt;p&gt;Allocator reservers 1 GB of virtual memory in its constructor and releases it in its finalizer. The main method instantiates a big managed byte array with 1 GB elements and then instantiates an instance of Allocator.&lt;/p&gt;
&lt;p&gt;Without the notion of GC, this is obviously going to fail as Windows limits user address space in a process to around 1.5 GB. With GC, however, I would expect this to run, because bigArray can be GC&amp;#39;ed before executing VirtualAlloc (on Release builds).&lt;/p&gt;
&lt;p&gt;Unfortunately it doesn&amp;#39;t. The GC doesn&amp;#39;t seem to care about unmanaged memory allocations and therefore sits idle when VirtualAlloc runs - this causes VirtualAlloc to fail. Insert a GC::Collect between the two lines in main and it all runs fine.&lt;/p&gt;
&lt;p&gt;I ran into a variant of this issue the other day and was left with no option but to force GC explicitly using GC::Collect. I later read about GC::AddMemoryPressure and GC::RemoveMemoryPressure and those work perfect for these scenarios. Just put a AddMemoryPressure call before allocating a big chunk of unmanaged memory (with the corresponding RemoveMemoryPressure) and the GC kicks in.&lt;/p&gt;&lt;pre&gt;	Allocator()
	{
                  GC::AddMemoryPressure(1024 * 1024 * 1024);
		ptr = VirtualAlloc(NULL, 1024 * 1024 * 1024, MEM_RESERVE, PAGE_EXECUTE_READWRITE);
		
		if (ptr == NULL)
		   Console::WriteLine(&amp;quot;Virtual Alloc failed&amp;quot;);
		else
		   Console::WriteLine(&amp;quot;Allocated unmanaged memory&amp;quot;);
	}

	!Allocator()
	{
		VirtualFree(ptr, 0, MEM_RELEASE);
                  GC::AddRemovePressure(1024 * 1024 * 1024);
	}

&lt;/pre&gt;
&lt;p&gt;It didn&amp;#39;t help in my case though, as the unmanaged allocations were occuring in a third party component we had no control over.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=1001302" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author></entry><entry><title>The quirky ?:</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/05/19/the-quirky.aspx" /><id>/blogs/senthil/archive/2007/05/19/the-quirky.aspx</id><published>2007-05-19T18:03:00Z</published><updated>2007-05-19T18:03:00Z</updated><content type="html">
&lt;p&gt;If there was ever a poll conducted for the most favorite C# operator, I&amp;#39;d guess the conditional operator ?:, also known as the ternary operator, will win hands down. I find it to be one of those tools that make things shorter and clearer at the same time. But how well do you know the operator?&lt;/p&gt;

&lt;p&gt;What do you think is wrong with the following piece of code?&lt;/p&gt;

&lt;pre&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; interface IDoer {}&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class ADoer : IDoer { }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class BDoer : IDoer { }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; class Program&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; static void Main(string[] args)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; bool flag = bool.Parse(args[0]);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; IDoer doer = flag ? new ADoer() : new BDoer();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; } &lt;/pre&gt;
&lt;p&gt;Looks straightforward, doesn&amp;#39;t it? Yet, this does not compile; the error being&lt;/p&gt;

&lt;pre&gt;error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between &amp;#39;ADoer&amp;#39; and &amp;#39;BDoer&amp;#39;&lt;br /&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href="http://www.jaggersoft.com/csharp_standard/14.12.htm" target="_blank"&gt;C# spec&lt;/a&gt; says that the two expressions that appear on either side of the : must be one of the following
&lt;/p&gt;&lt;ul&gt;
&lt;li&gt;Both of them should be of the same type&lt;/li&gt;

&lt;li&gt;The first one should be convertible to the second&lt;/li&gt;

&lt;li&gt;The second one should be convertible to the first&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the above case, ADoer and BDoer are both convertible to IDoer (because they implement IDoer), but  because neither of them is implicitly convertible to the other, compilation fails. It doesn&amp;#39;t matter to the compiler that the result of the expression is always convertible to IDoer, all it cares about is the deduction of the type of the ternary expression.&lt;/p&gt;

&lt;p&gt;I guess this is one of those places where static typing gets in the way of the developer, instead of helping him. You win some, you lose some :)&lt;/p&gt;

&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=913957" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software C# language" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+C_2300_+language/default.aspx" /></entry><entry><title>Playing with IronPython</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/05/12/playing-with-ironpython.aspx" /><id>/blogs/senthil/archive/2007/05/12/playing-with-ironpython.aspx</id><published>2007-05-12T06:25:00Z</published><updated>2007-05-12T06:25:00Z</updated><content type="html">&lt;p&gt;I&amp;#39;ve been dabbling with IronPython for the last few days, trying to
host it and use it as a scripting engine. I have to say that I&amp;#39;m
impressed. The hosting API is incredibly simple to use and Mike Stall&amp;#39;s
&lt;a href="http://blogs.msdn.com/jmstall/archive/2005/09/01/Howto_embed_ironpython.aspx"&gt;blog&lt;/a&gt; served as a handy reference.&lt;br /&gt;
&lt;br /&gt;
One thing I wanted my scripts to do was to access private and internal
members of types in the hosting application. I found that the command
line python interpreter (ipy.exe) had a -X:PrivateBinding switch to
allow access to private and internal members using the
&amp;lt;type&amp;gt;_&amp;lt;type&amp;gt;__memberName convention (which seems to be the
standard python name mangling for private members).&lt;br /&gt;
&lt;br /&gt;
However, I couldn&amp;#39;t find an easy way to do that from the hosting
application. It was time to download the source code and figure out how
the command line option got translated in code. It turned out to be
pretty simple, there is a static class Options, which has properties
for most of the command line options. From the hosting application, all
you have to do is set the corresponding property before initializing
the PythonEngine.&lt;br /&gt;
&lt;/p&gt;&lt;pre&gt;void Initialize()&lt;br /&gt;{&lt;br /&gt;   Options.PrivateBinding = true;&lt;br /&gt;   pythonEngine = new PythonEngine();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=899643" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software" scheme="http://msmvps.com/blogs/senthil/archive/tags/software/default.aspx" /></entry><entry><title>Add logs to the start and end of methods</title><link rel="alternate" type="text/html" href="/blogs/senthil/archive/2007/05/12/add-logs-to-the-start-and-end-of-methods.aspx" /><id>/blogs/senthil/archive/2007/05/12/add-logs-to-the-start-and-end-of-methods.aspx</id><published>2007-05-12T06:23:00Z</published><updated>2007-05-12T06:23:00Z</updated><content type="html">&lt;p&gt;&amp;nbsp;&lt;a href="http://senthil.thecoder.googlepages.com/MethodLogger.zip"&gt;MethodLogger&lt;/a&gt;
is a macro I wrote that adds log statements at the beginning and ending
of all methods in the current document in Visual Studio. Unzip the
file, load it in Visual Studio using Tools-&amp;gt;Macros-&amp;gt;Load Macro
Project, open the appropriate C# file and then run the
LogMethodStartAndEnd macro. It transforms
&lt;/p&gt;&lt;pre&gt;class SomeClass&lt;br /&gt;{&lt;br /&gt;    public void SomeMethod()&lt;br /&gt;    {&lt;br /&gt;        MessageBox.Show(&amp;quot;Doodly doodly Doo&amp;quot;);&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;
to
&lt;pre&gt;class SomeClass&lt;br /&gt;{&lt;br /&gt;    public void SomeMethod()&lt;br /&gt;    {&lt;br /&gt;        Console.WriteLine(&amp;quot;Start of SomeClass.SomeMethod()&amp;quot;);&lt;br /&gt;        try&lt;br /&gt;        {&lt;br /&gt;            MessageBox.Show(&amp;quot;Doodly doodly Doo&amp;quot;);&lt;br /&gt;        }&lt;br /&gt;        finally&lt;br /&gt;        {&lt;br /&gt;            Console.WriteLine(&amp;quot;End of SomeClass.SomeMethod()&amp;quot;);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;The
code, written in VB .NET (which seems to be the only supported language
for writing macros?) uses Visual Studio&amp;#39;s automation interface to get
the code model for the currently open file. It then walks through all
the methods, figures out the starting and ending points of each method
and inserts the appropriate statements, with the most significant part
being the method signature. It does a very basic check (finds the first
non-empty, non comment line and checks if it&amp;#39;s the same as the text to
be logged) to make sure it doesn&amp;#39;t modify methods it has already added
logs to - when the user runs the macro twice, for example.
&lt;br /&gt;
&lt;p&gt;It should be fairly simple to change Console.WriteLine to something
else - right clicking on LogMethodStartAndEnd and selecting Edit should
take you to the Macro Editor IDE and lines 92, 93 contain the text to
be inserted at the start and end of each method.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://msmvps.com/aggbug.aspx?PostID=899639" width="1" height="1"&gt;</content><author><name>Senthil</name><uri>http://msmvps.com/members/Senthil/default.aspx</uri></author><category term="software tools" scheme="http://msmvps.com/blogs/senthil/archive/tags/software+tools/default.aspx" /></entry></feed>