<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>Real Coders Coding</title>
	<atom:link href="http://blog.realcoderscoding.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.realcoderscoding.com</link>
	<description></description>
	<pubDate>Mon, 01 Mar 2010 21:05:27 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6</generator>
	<language>en</language>
			<item>
		<title>Lambdas, Extension Methods, and Asynchronous Execution Example</title>
		<link>http://blog.realcoderscoding.com/index.php/2009/09/lambdas-extension-methods-async/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2009/09/lambdas-extension-methods-async/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 17:18:26 +0000</pubDate>
		<dc:creator>Bogdan Varlamov (a.k.a. Phantom Stranger)</dc:creator>
		
		<category><![CDATA[.NET 3.5]]></category>

		<category><![CDATA[.NET Framework]]></category>

		<category><![CDATA[Tricks]]></category>

		<category><![CDATA[Utilities]]></category>

		<category><![CDATA[asynchronous]]></category>

		<category><![CDATA[csharp]]></category>

		<category><![CDATA[extensions]]></category>

		<category><![CDATA[lambda]]></category>

		<category><![CDATA[multithreading]]></category>

		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=265</guid>
		<description><![CDATA[I've often found myself working on a class in some legacy application using objects hidden away in third-party libraries and thinking, "Wow... it would be really great if I could call this current existing method but have it process asynchronously (without blocking) and then notify me when it is complete."
The only way to do this [...]]]></description>
			<content:encoded><![CDATA[<p>I've often found myself working on a class in some legacy application using objects hidden away in third-party libraries and thinking, "Wow... it would be really great if I could call this current existing method but have it process asynchronously (without blocking) and then notify me when it is complete."</p>
<p>The only way to do this would be to inherit the legacy object and add a new "Async" version of the method, right? And what about those pesky sealed classes? Not to mention the problems with having to refactor your whole application (and perhaps any dependent components used by other applications).</p>
<p>It can be quite a mess! But, luckily there is a simpler way...<br />
<span id="more-265"></span><br />
What I've done is create an extension library that allows any object to do asynchronous processing.</p>
<p>Here is an example of how to use this:</p>
<pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Linq</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Text</span>;
&nbsp;
<span style="color: #0600FF;">using</span> _5DSolutions.<span style="color: #0000FF;">Extensions</span>.<span style="color: #0000FF;">AsyncHandler</span>; <span style="color: #008080; font-style: italic;">//here are the extensions</span>
&nbsp;
<span style="color: #0600FF;">namespace</span> Example
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Program
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">long</span> _asyncComplesCounter = <span style="color: #FF0000;">0</span>;
        <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">long</span> _disposedCounter = <span style="color: #FF0000;">0</span>;
&nbsp;
        <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Main<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> args<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            GoCrazy<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> GoCrazy<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//here we have some &quot;legacy&quot; object that we cant update/add new methods to</span>
            TestObject tmp = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> TestObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #FF0000;">int</span> counter;
&nbsp;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;How many times would you like to asynchronously print?&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span>!<span style="color: #FF0000;">int</span>.<span style="color: #0000FF;">TryParse</span><span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">out</span> counter<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Enter an integer number only, less than {0}&quot;</span>, <span style="color: #FF0000;">int</span>.<span style="color: #0000FF;">MaxValue</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">while</span> <span style="color: #000000;">&#40;</span>counter &gt; <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//here we are using the extension method on some &quot;TestObject&quot; class that we can't modify</span>
                tmp.<span style="color: #0000FF;">HandleAsynchronously</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span>sender, e<span style="color: #000000;">&#41;</span> =&gt;
                    <span style="color: #000000;">&#123;</span>
                        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Asynchronously calling a synchronous method&quot;</span><span style="color: #000000;">&#41;</span>;
                        tmp.<span style="color: #0000FF;">DoSomething</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;<span style="color: #008080; font-style: italic;">//this blocks</span>
                        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Woohoo! We are done blocking the synchronous method call, notifying through the completed event handler...&quot;</span><span style="color: #000000;">&#41;</span>;
                    <span style="color: #000000;">&#125;</span>,
                    <span style="color: #000000;">&#40;</span>sender, e<span style="color: #000000;">&#41;</span> =&gt;
                    <span style="color: #000000;">&#123;</span>
&nbsp;
                        <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Threading</span>.<span style="color: #0000FF;">Interlocked</span>.<span style="color: #0000FF;">Increment</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _asyncComplesCounter<span style="color: #000000;">&#41;</span>;
                        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;---An Asynch write has finished! -- {0}&quot;</span>, <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Threading</span>.<span style="color: #0000FF;">Interlocked</span>.<span style="color: #0000FF;">Read</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _asyncComplesCounter<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
                    <span style="color: #000000;">&#125;</span>,
                    <span style="color: #0600FF;">null</span>,
                    <span style="color: #000000;">&#40;</span>sender, e<span style="color: #000000;">&#41;</span> =&gt;
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Threading</span>.<span style="color: #0000FF;">Interlocked</span>.<span style="color: #0000FF;">Increment</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">ref</span> _disposedCounter<span style="color: #000000;">&#41;</span>;
                        Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; disposed&quot;</span><span style="color: #000000;">&#41;</span>;
                    <span style="color: #000000;">&#125;</span>,
                    <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>;
                counter--;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            tmp = <span style="color: #0600FF;">null</span>;
            GC.<span style="color: #0000FF;">Collect</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Total completed events: {0}&quot;</span>, _asyncComplesCounter<span style="color: #000000;">&#41;</span>;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Total disposed bg-workers: {0}&quot;</span>, _disposedCounter<span style="color: #000000;">&#41;</span>;
&nbsp;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Go again?&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>Console.<span style="color: #0000FF;">ReadLine</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Equals</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Yes&quot;</span>, StringComparison.<span style="color: #0000FF;">InvariantCultureIgnoreCase</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                GoCrazy<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">else</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//just exit</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre>
<p>There is nothing tricky going on with the TestObject class. In fact, you should be able to use your own class. Or you can use this test object:</p>
<pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Linq</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Text</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Example
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> TestObject
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> TestObject<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> DoSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;Synchronously writing this then waiting for 0.5 seconds...&quot;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Threading</span>.<span style="color: #0000FF;">Thread</span>.<span style="color: #0000FF;">Sleep</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">500</span><span style="color: #000000;">&#41;</span>;
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;--Synchronous write Done.&quot;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre>
<p>The real magic actually lives in the Extensions project:</p>
<pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Linq</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Text</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">ComponentModel</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> _5DSolutions.<span style="color: #0000FF;">Extensions</span>.<span style="color: #0000FF;">AsyncHandler</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> ObjectAsyncExtension
    <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> HandleAsynchronously<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> <span style="color: #FF0000;">Object</span> caller, DoWorkEventHandler onDoWork, RunWorkerCompletedEventHandler onCompleted<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            HandleAsynchronously<span style="color: #000000;">&#40;</span>caller, onDoWork, onCompleted, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span>, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> HandleAsynchronously<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span> <span style="color: #FF0000;">Object</span> caller, DoWorkEventHandler onDoWork, RunWorkerCompletedEventHandler onCompleted, ProgressChangedEventHandler onProgressChanged, EventHandler onDisposed, <span style="color: #FF0000;">object</span> argument<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//check required params</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span> == onDoWork<span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ArgumentNullException<span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;onDoWork&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span> == onCompleted<span style="color: #000000;">&#41;</span>
                <span style="color: #0600FF;">throw</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ArgumentNullException<span style="color: #000000;">&#40;</span><span style="color: #808080;">&quot;onCompleted&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            BackgroundWorker tmp = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> BackgroundWorker<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            tmp.<span style="color: #0000FF;">DoWork</span> += onDoWork;
            tmp.<span style="color: #0000FF;">RunWorkerCompleted</span> += onCompleted;
            tmp.<span style="color: #0000FF;">RunWorkerCompleted</span> += <span style="color: #000000;">&#40;</span>sender, e<span style="color: #000000;">&#41;</span> =&gt;
            <span style="color: #000000;">&#123;</span><span style="color: #008080; font-style: italic;">//note, we subscribe twice to &quot;dispose&quot; of the object</span>
                <span style="color: #008080; font-style: italic;">//and raise the Disposed event</span>
                tmp.<span style="color: #0000FF;">DoWork</span> -= onDoWork;
                tmp.<span style="color: #0000FF;">RunWorkerCompleted</span> -= onCompleted;
                tmp.<span style="color: #0000FF;">ProgressChanged</span> -= onProgressChanged;
                tmp.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                tmp = <span style="color: #0600FF;">null</span>;
            <span style="color: #000000;">&#125;</span>;
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span> != onProgressChanged<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                tmp.<span style="color: #0000FF;">WorkerReportsProgress</span> = <span style="color: #0600FF;">true</span>;
                tmp.<span style="color: #0000FF;">ProgressChanged</span> += onProgressChanged;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span> != onDisposed<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                tmp.<span style="color: #0000FF;">Disposed</span> += onDisposed;
                tmp.<span style="color: #0000FF;">Disposed</span> += <span style="color: #000000;">&#40;</span>sender, e<span style="color: #000000;">&#41;</span> =&gt;
                    <span style="color: #000000;">&#123;</span><span style="color: #008080; font-style: italic;">//i dont think this is really necessary...</span>
                        <span style="color: #008080; font-style: italic;">//but leaving it in for reference</span>
                        tmp.<span style="color: #0000FF;">Disposed</span> -= onDisposed;
                    <span style="color: #000000;">&#125;</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span> != argument<span style="color: #000000;">&#41;</span>
                tmp.<span style="color: #0000FF;">RunWorkerAsync</span><span style="color: #000000;">&#40;</span>argument<span style="color: #000000;">&#41;</span>;
            <span style="color: #0600FF;">else</span>
                tmp.<span style="color: #0000FF;">RunWorkerAsync</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre>
<p>Of course you can substitute your own named delegates for the lambdas in the Program class in this example, or your own lambdas to do actual work.</p>
<p>The main concern I had with this implementation was whether or not this code would be subject to thread leaks.</p>
<p>I tested this code with 30k calls to HandleAsynchronously and watched the threads/memory/handles fluctuate, but always drop back down as garbage collection was performed. (I am explicitly calling it in the code samples above to better observe potential issues, but it should happen naturally without the need for an explicit call).</p>
<p>--</p>
<p>The above source code is © 2009 by Bogdan Varlamov and may only be used if you agree to the <a href="http://blog.realcoderscoding.com/?page_id=138">BSD License Terms</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2009/09/lambdas-extension-methods-async/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Filter Logs by Changing log4net Configuration</title>
		<link>http://blog.realcoderscoding.com/index.php/2009/05/filter-logs-by-changing-log4net-configuration/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2009/05/filter-logs-by-changing-log4net-configuration/#comments</comments>
		<pubDate>Wed, 20 May 2009 17:37:09 +0000</pubDate>
		<dc:creator>Bogdan Varlamov (a.k.a. Phantom Stranger)</dc:creator>
		
		<category><![CDATA[General Technology]]></category>

		<category><![CDATA[Tricks]]></category>

		<category><![CDATA[XML]]></category>

		<category><![CDATA[configuration file]]></category>

		<category><![CDATA[log4net]]></category>

		<category><![CDATA[logging]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=242</guid>
		<description><![CDATA[We've all been there before--trying to track down some insipid bug which is impossible to reproduce on a developer's machine. What is the response? To add more logging of course!
That's all well and good, but eventually your log files are going to start getting huge. Don't get me wrong, I LOVE applications with good logging. [...]]]></description>
			<content:encoded><![CDATA[<p>We've all been there before--trying to track down some insipid bug which is impossible to reproduce on a developer's machine. What is the response? To add more logging of course!</p>
<p>That's all well and good, but eventually your log files are going to start getting huge. Don't get me wrong, I LOVE applications with good logging. (In my opinion it's much better to "overlog" than "underlog" [or not log at all!]). But, sometimes it makes sense to cut back on the amount of logging to save disk space, or to make the log files easier to digest...</p>
<p>How can this be done? Certainly not by <strong>removing logging from code</strong>!<br />
<span id="more-242"></span><br />
As you may or may not know, <a href="http://logging.apache.org/log4net/index.html">log4net</a> provides various "logging levels" which range from "INFO" to "FATAL" with several in between. However, in some cases I've found that these levels are not enough.</p>
<p>For instance, there are some applications where it makes sense to log every single method entry and exit (yes, I DO realize this is usually discouraged as it gives an architectural layout of your application to competitors, etc.). But, there is no appropriate logging level to correspond to this. Ideally, one might have something that looked like this:</p>
<pre class="csharp">&nbsp;
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> DoSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
        log.<span style="color: #0000FF;">Enter</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Reflection</span>.<span style="color: #0000FF;">MethodBase</span>.<span style="color: #0000FF;">GetCurrentMethod</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
<span style="color: #008080; font-style: italic;">//do more code here</span>
&nbsp;
        log.<span style="color: #0000FF;">Exit</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Reflection</span>.<span style="color: #0000FF;">MethodBase</span>.<span style="color: #0000FF;">GetCurrentMethod</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
&nbsp;</pre>
<p>But alas, there is no such thing. We have to use the "Debug" logging level if we are to log enters/exits, like so:</p>
<pre class="csharp">&nbsp;
&nbsp;
constant <span style="color: #FF0000;">string</span> LOG_ENTER = <span style="color: #808080;">&quot;Enter - &quot;</span>;
constant <span style="color: #FF0000;">string</span> LOG_EXIT = <span style="color: #808080;">&quot;Exit - &quot;</span>;
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> DoSomething<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
      <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>log.<span style="color: #0000FF;">IsDebugEnabled</span><span style="color: #000000;">&#41;</span>
      <span style="color: #000000;">&#123;</span>
           log.<span style="color: #0000FF;">Debug</span><span style="color: #000000;">&#40;</span>LOG_ENTER + <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Reflection</span>.<span style="color: #0000FF;">MethodBase</span>.<span style="color: #0000FF;">GetCurrentMethod</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
      <span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #008080; font-style: italic;">//do more code here</span>
&nbsp;
      <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>log.<span style="color: #0000FF;">IsDebugEnabled</span><span style="color: #000000;">&#41;</span>
      <span style="color: #000000;">&#123;</span>
           log.<span style="color: #0000FF;">Debug</span><span style="color: #000000;">&#40;</span>LOG_EXIT + <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Reflection</span>.<span style="color: #0000FF;">MethodBase</span>.<span style="color: #0000FF;">GetCurrentMethod</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
      <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;</pre>
<p>This works (although it's not the prettiest code in the world). We can keep track of when a method is entered, when it is exited, calculate how long it takes, look for inefficiencies, troubleshoot much easier, etc.</p>
<p>But when all of that is done, we don't want to ALWAYS log the method entries and exits. We <strong>could</strong> change our logging level, but since we are using "DEBUG" all of our other debug log statements will also disappear. What can we do?</p>
<p>Luckily there is an easy way to filter out all of our method enters/exits just by updating the <a href="http://logging.apache.org/log4net/release/manual/configuration.html">configuration file</a> with a string filter setup to filter out "Enter" and another one for "Exit" like so:</p>
<pre class="xml">&nbsp;
&nbsp;
      <span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- NOTE: this filters out Enter statements in methods, uncomment to NOT print method enters
      &lt;filter type=&quot;log4net.Filter.StringMatchFilter&quot;&gt;</span>
</span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;stringtomatch</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Enter&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;acceptonmatch</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
      --&gt;
&nbsp;
      <span style="color: #009900;"><span style="color: #808080; font-style: italic;">&lt;!-- NOTE: this filters out Exit statements in methods, uncomment to NOT print method exits
      &lt;filter type=&quot;log4net.Filter.StringMatchFilter&quot;&gt;</span>
</span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;stringtomatch</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;Exit&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
        <span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;acceptonmatch</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span>
       --&gt;
&nbsp;</pre>
<p>Just add this to the "appender" element in the log4net section in your configuration file and uncomment/comment out as necessary.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2009/05/filter-logs-by-changing-log4net-configuration/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Not So RESTful Days</title>
		<link>http://blog.realcoderscoding.com/index.php/2009/05/not-so-restful-days/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2009/05/not-so-restful-days/#comments</comments>
		<pubDate>Tue, 19 May 2009 18:13:44 +0000</pubDate>
		<dc:creator>Flash</dc:creator>
		
		<category><![CDATA[.NET 3.5]]></category>

		<category><![CDATA[ASP.NET]]></category>

		<category><![CDATA[ADO.NET Data Services]]></category>

		<category><![CDATA[ASP.NET MVC]]></category>

		<category><![CDATA[PHP]]></category>

		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=223</guid>
		<description><![CDATA[One of my clients asked me to write a very simple RESTful web service to retrieve user data (name, email, address, etc.) based on login credentials.  Having recently finished working on a PHP-driven RESTful interface for another client (based on the Zend Framework), I thought this would be a simple and straightforward task.  As comedian Bill [...]]]></description>
			<content:encoded><![CDATA[<p>One of my clients asked me to write a very simple RESTful web service to retrieve user data (name, email, address, etc.) based on login credentials.  Having recently finished working on a PHP-driven RESTful interface for another client (based on the <a href="http://framework.zend.com/">Zend Framework</a>), I thought this would be a simple and straightforward task.  As comedian Bill Engvall says: "Here's your sign!".  I should have known better.<span id="more-223"></span></p>
<p>My first effort was to simply refactor my previous work.  It took me a few hours but it worked great... on my development machine.  However, once I ported it to the host for testing, it crapped out because they host their site on a Windows server under IIS7.  So, having very little control, there goes the possibility for url rewrites (on the server level).</p>
<p>Next, I thought back to an recent <a href="http://www.wncdotnet.com/">WNC .NET Developer's Guild</a> presentation given by Joel Reyes (of Microsoft) entitled ADO.NET Data Services.  His code examples demonstrated a simple RESTful service in action.  So, another few hours and I had a great working example.  A few hours?!?  Well, I had to download a few things to get my Windows XP up to snuff (such as .NET 3.5 SP1 among other things).  There was my next sign... it didn't occur to me then that the host (Web.com) wasn't up to date either.  Too late!  After I deployed a quick test app I realized they were behind the times when I got this error:</p>
<h2><em>Configuration Error</em></h2>
<p><span style="font-family: Arial, Helvetica, Geneva, SunSans-Regular, sans-serif;"><strong>Description: </strong>An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </span></p>
<p><strong>Parser Error Message: </strong>Could not load file or assembly 'System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.</p>
<p><strong>Source Error:</strong> </p>
<pre><span style="color: red;"><span style="color: #ff0000;">Line 33: &lt;add assembly="System.Data.Entity, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089" /&gt;</span></span></pre>
<p><strong>Source File: </strong>\\HOSTING\DFS\20\3\3\4\2030628433\user\sites\dampp-chaserdb.com\www\test\web.config<strong>    Line: </strong>33 </p>
<p><em>As a sidebar... I tried to ask their front-line technical support staff for some information on their current version of the .NET framework and if they had a workaround for URL rewrites on the box the site was hosted on.  Yeah right!.  That was another wasted 30 minutes.</em></p>
<p>Alack!  And Alas!  I decided it was time to force feed myself some ASP.NET MVC and quick.  ASP.NET MVC has the ability to return XML and JSON via a RESTful interface.  So, to keep this note short, I'm heading back to tuck into some tutorials.  I purchased <a href="http://www.amazon.com/Effective-REST-Services-via-NET/dp/0321613252">Effective REST Services via .NET</a> by Kenn Scribner and Scott Seely so I've got to read through it quick.  I'm also using blog posts from Piers Lawson as a guide.  Here's a link to <a href="http://www.shouldersofgiants.co.uk/Blog/post/2008/09/27/Creating-a-RESTful-Web-Service-Using-ASPNet-MVC-Part-1-Introduction.aspx">Part 1</a>.  Just filter by the REST tag to get a list of the other posts in the series.  There's a bunch there.</p>
<p>One helpful note:  If you find yourself using Piers' posts like I did, I had to fix an error that was preventing me from getting the same results as he did.  In Part 1 in the Guid.aspx file use this code snippet instead of his example:</p>
<pre>&lt;asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server"&gt;
    &lt;ul class="guids"&gt;
        &lt;% foreach (var guid in (IEnumerable)ViewData.Model)
              {
         %&gt;
              &lt;li&gt;&lt;%= guid.ToString().ToUpper()%&gt;&lt;/li&gt;
        &lt;% } %&gt;
    &lt;/ul&gt;
&lt;/asp:Content&gt;</pre>
<p> </p>
<p>This may be because of the version of ASP.NET he used as compared to the latest bits.</p>
<p>I really dig MVC having been first exposed to it when writing custom components in Joomla.  I'm psyched now that I have the chance to mix some MVC peanut butter with some ASP.NET chocolate.  Now I'm off to get some REST.</p>
<p>(That was lame, sorry)</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2009/05/not-so-restful-days/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Reinstalling SQL Server 2005 (or 8 Hours of My Life Wasted)</title>
		<link>http://blog.realcoderscoding.com/index.php/2009/01/reinstalling-sql-server-2005-or-8-hours-of-my-life-wasted/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2009/01/reinstalling-sql-server-2005-or-8-hours-of-my-life-wasted/#comments</comments>
		<pubDate>Thu, 15 Jan 2009 15:03:41 +0000</pubDate>
		<dc:creator>Flash</dc:creator>
		
		<category><![CDATA[Installers]]></category>

		<category><![CDATA[Lessons Learned the Hard Way]]></category>

		<category><![CDATA[SQL Server 2005]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=211</guid>
		<description><![CDATA[The main purpose of RealCodersCoding is to post about problems we, the authors, have overcome in our daily coding adventures.  Sometimes, the problems we are faced with are complex and require some interesting coding yoga to to work out.  Other times the solutions are drop-dead simple, but we refuse to recognize them.  Here's a little [...]]]></description>
			<content:encoded><![CDATA[<p>The main purpose of <a href="http://blog.realcoderscoding.com">RealCodersCoding</a> is to post about problems we, the authors, have overcome in our daily coding adventures.  Sometimes, the problems we are faced with are complex and require some interesting coding yoga to to work out.  Other times the solutions are drop-dead <em>simple</em>, but we refuse to recognize them.  Here's a little post about how I wasted an entire freakin' day to one of the latter.</p>
<p><span id="more-211"></span></p>
<p>I've been coding in the PHP/Joomla/MySQL space for the last 6 months and haven't cracked open my local MS SQL Server 2005 instance lately.  When I tried to do so yesterday I was met with this gem--the app wouldn't connect to my local instance.  Instead I got some bizarre error message about remote connections.  Diving into my Event Viewer to see if there's any clues there, I'm told that the master database is corrupt.  The error message helpfully guides me to the <a href="http://msdn.microsoft.com/en-us/library/aa197950(SQL.80).aspx">Books Online</a> for information on how to rebuild the master database.  The easiest solution would be to use a valid backup and just restore it.  Ahem!  Backup?!?  This is my dev machine and I don't do much backing up of anything.  I guess I'm stupid that way.</p>
<p>So, I do some research and tried all of the various methods the blog posts and KB articles tell me to try, as in:</p>
<ul>
<li><a href="http://www.mshelpzone.com/Forum/viewtopic.php?f=13&amp;t=6&amp;sid=a8dc794c4e85f5271b3ccfd1b5f6f9b8">SQL 2005 Rebuild Master And Other System Databases</a></li>
<li><a href="http://geekswithblogs.net/mskoolaid/archive/2005/12/17/63413.aspx">Rebuild Master Database in SQL 2005</a></li>
<li><a href="http://blogs.techrepublic.com.com/window-on-windows/?p=390">Recover the Master Database in SQL Server</a></li>
</ul>
<p>All to no avail!  So, I'm in a time crunch here.  This maintenance work I'm doing should only take a few hours (that's all I'm getting paid for, at least).  I decided, screw it, I'll do a reinstall.  That'll fix it.  That always works, right?</p>
<p>Right off the bat, I know I'm in trouble.  I can't completely uninstall SQL Server 2005 via the traditional Add/Remove Programs (ARP).  Artifacts are left over including all of the hot fixes and patches that have been applied over time.  I follow other blog posts and msdn articles on how to manually uninstall SQL Server 2005, as in:</p>
<ul>
<li><a href="http://www.google.com/search?q=manually+uninstall+sql+server+2005&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">How to Uninstall an Instance of SQL Server 2005 Manually</a></li>
<li><a href="http://www.crucialp.com/blog/2008/02/26/how-to-uninstall-ms-sql-server-2005-manually/">How to Uninstall MS SQL Server 2005 Manually</a></li>
</ul>
<p>There's a ton out there, but they all pretty much say the same thing.  The MSDN article did reference a <a href="http://support.microsoft.com/kb/290301">Windows Install Clean Up utility</a> which eventually helped me get rid of the hangers on in ARP.  Finally, and we are talking about 2 hours into it, I start installing the new instance.  I'm doing this from one of my MSDN DVD's.  I navigate the DVD menu and manually run setup.exe from the proper directory (I'm installing the Developer version).  The initial install was a snap!</p>
<p>However, I realize (a little later when nothing worked) that I only installed the client tools.  No server!  No services!  No management tools!  Arrg!  So, I uninstall (again).  Clean up after myself and start again.  Now, I go a little slower to make sure I make the correct selections in the installer.  However, now I'm not given any options for the server components.  I go right from the registration screen to the feature selections.  I skip the component selections completely.  WTF?</p>
<p>My assumption is that there must be some latent artifacts from the previous installation (registry settings, installed services, files, etc.) that make the installer think I still have an instance set up.  More blog posts and articles (and hours) and I still can't get the server components installed!</p>
<p>I finally give up and install SQL Server 2000.  But that doesn't solve my problem since the DB I need for my maintenance work has been SQL Server 2005-ied and won't open in 2000 any more.  :(  I swear, cry, go eat dinner and resolve to fight this to the death (of one of us).</p>
<p>Later, I uninstall Visual Studio 2008 (thinking that maybe it's got to be installed after SQL Server 2005).  That didn't work (and now I'm faced with the long reinstall [and I'm doing that as I type]).  I'm about to tear my hair out (except I don't have any) when I start poking around the DVD directories and stumble across something very interesting:  There's a setup.exe in both the Tools directory:</p>
<p>H:\ENGLISH\SQL2005\DEVELOPER\SQL Server x86\Tools\setup.exe</p>
<p>and the Servers directory:</p>
<p>H:\ENGLISH\SQL2005\DEVELOPER\SQL Server x86\Servers\setup.exe</p>
<p>I never once looked in the Servers directory.  I just assumed (yeah, yeah, I know) that there's only one setup.exe that I need to deal with.</p>
<p>So the moral to this blog post, if moral there needs to be, is to make sure you know that you are installing the right thing.  Otherwise, you'll end up like me - 8 hours into a 3 hour job.  And I still have to finish installing VS.NET 2008.  If all goes well, I should be done with this work sometime tomorrow.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2009/01/reinstalling-sql-server-2005-or-8-hours-of-my-life-wasted/feed/</wfw:commentRss>
		</item>
		<item>
		<title>System.ExecutionEngineException when opening a WPF Window from Windows Form</title>
		<link>http://blog.realcoderscoding.com/index.php/2008/12/how-to-avoid-a-systemexecutionengineexception-when-opening-a-wpf-window-from-windows-form/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2008/12/how-to-avoid-a-systemexecutionengineexception-when-opening-a-wpf-window-from-windows-form/#comments</comments>
		<pubDate>Mon, 22 Dec 2008 14:50:06 +0000</pubDate>
		<dc:creator>Bogdan Varlamov (a.k.a. Phantom Stranger)</dc:creator>
		
		<category><![CDATA[.NET 2.0]]></category>

		<category><![CDATA[.NET 3.5]]></category>

		<category><![CDATA[.NET Framework]]></category>

		<category><![CDATA[Lessons Learned the Hard Way]]></category>

		<category><![CDATA[c sharp]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[WinForms]]></category>

		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=174</guid>
		<description><![CDATA[One of the great things about .NET 3.5 is that it is fully inter-operable with .NET 2.0. You just have to reference the right assemblies and you can use WPF and Windows Forms from the same application! This is great for slowly migrating a .NET 2.0 application over to .NET 3.5; all you have to [...]]]></description>
			<content:encoded><![CDATA[<p>One of the great things about .NET 3.5 is that it is fully inter-operable with .NET 2.0. You just have to reference the right assemblies and you can use WPF and Windows Forms from the same application! This is great for slowly migrating a .NET 2.0 application over to .NET 3.5; all you have to do is add the new functionality while keeping your old .NET 2.0 logic. Once you are ready, you can slowly migrate your old code over into .NET 3.5 as needed.</p>
<p>Well...at least it's all that easy in theory; there's just one pesky little hiccup--a System.ExecutionEngineException...</p>
<p><span id="more-174"></span><br />
What I was trying to accomplish was to create a .NET 3.0 WPF application and run a Windows Form with all of my old .NET 2.0 logic. This was easy and worked great. Then, I tried adding a WPF window which would open when a button was clicked in the Windows Form.</p>
<p>I compiled my application, ran it, clicked the button and the WPF window opened up just as I was hoping. Excellent! I continued working in debug mode and made some code changes. I clicked the button again to see the code changes in action and...System.ExecutionEngineException.</p>
<p>It took me forever to figure out what the problem was. I undid all of my code changes, I even created a blank testing application and still got the same exception.</p>
<p>Apparently the problem is that a .NET 3.5 WPF application has a <a href="http://msdn.microsoft.com/en-us/library/system.windows.application.shutdownmode.aspx">ShutdownMode property</a> which by default is set to "OnLastWindowClose." This means that when the last WPF Window in the application is closed, the application itself shuts down.</p>
<p>Oddly enough the application doesn't close the Windows Form when it "shuts down"--it just disposes of internal objects.</p>
<p>So this is what was happening:</p>
<ol>
<li>The application starts and shows a Windows Form.</li>
<li>Then the Windows Form shows a WPF Window.</li>
<li>Then the WPF Window closes and the application "shuts down" while leaving the Windows Form window open.</li>
<li>When I try opening another WPF Window I get the exception because the application I'm trying to open a window for has already been shut down.</li>
</ol>
<p>There are two ways to get around this problem. The first is the "right way" to do it as described in the <a href="http://msdn.microsoft.com/en-us/library/system.windows.application.shutdownmode.aspx">MSDN article</a>; it is by setting the ShutdownMode property to OnExplicitShutdown. Then to shutdown the application you could create an event handler method to be called when the Windows Form's "FormClosed" event fires. This event handler would call the applications "Shutdown()" method.</p>
<p>Here is an example:</p>
<p><strong>App.xaml.cs</strong></p>
<pre class="csharp"><span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Collections</span>.<span style="color: #0000FF;">Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Configuration</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Data</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Linq</span>;
<span style="color: #0600FF;">using</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> MultiWindowTest
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #008080; font-style: italic;">/// Interaction logic for App.xaml</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #0600FF;">public</span> partial <span style="color: #FF0000;">class</span> App : Application
    <span style="color: #000000;">&#123;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Application_Startup<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, StartupEventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Form1 f1 = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> Form1<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            f1.<span style="color: #0000FF;">FormClosed</span> += <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Forms</span>.<span style="color: #0000FF;">FormClosedEventHandler</span><span style="color: #000000;">&#40;</span>f1_FormClosed<span style="color: #000000;">&#41;</span>;
            f1.<span style="color: #0000FF;">ShowDialog</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">void</span> f1_FormClosed<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Forms</span>.<span style="color: #0000FF;">FormClosedEventArgs</span> e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Shutdown</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre>
<p>An alternative way to avoid this exception is a bit of a hack; but still works. You can leave the ShutdownMode property alone and instead create a WPF window that is hidden. If you had an application that shows a splash-screen or a logon window it would make more sense to do this. The application loads, you show the logon window--once they logon this window is hidden and the Windows Form is shown. Once that form is closed you would once again show the logon WPF Window. Hiding a WPF Window does not trigger the Shutdown of the application, so you will be able to open and close as many WPF Windows as you like without worrying about getting the exception.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2008/12/how-to-avoid-a-systemexecutionengineexception-when-opening-a-wpf-window-from-windows-form/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Detecting a physical network disconnection with .NET Sockets</title>
		<link>http://blog.realcoderscoding.com/index.php/2008/10/detecting-a-physical-network-disconnection-with-net-sockets/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2008/10/detecting-a-physical-network-disconnection-with-net-sockets/#comments</comments>
		<pubDate>Fri, 31 Oct 2008 13:56:46 +0000</pubDate>
		<dc:creator>Bogdan Varlamov (a.k.a. Phantom Stranger)</dc:creator>
		
		<category><![CDATA[.NET Framework]]></category>

		<category><![CDATA[Lessons Learned the Hard Way]]></category>

		<category><![CDATA[Tricks]]></category>

		<category><![CDATA[c sharp]]></category>

		<category><![CDATA[Sockets]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=61</guid>
		<description><![CDATA[I recently ran into an issue with an application that was not detecting a physical network problem and was consequently losing data while attempting to write it to the socket.
I know what you are thinking. Sounds like poor programming; surely the .NET Socket class has a clean and Object Oriented way of handling network failures.
That [...]]]></description>
			<content:encoded><![CDATA[<p>I recently ran into an issue with an application that was not detecting a physical network problem and was consequently losing data while attempting to write it to the socket.</p>
<p>I know what you are thinking. Sounds like poor programming; surely the .NET Socket class has a clean and Object Oriented way of handling network failures.</p>
<p>That is what I thought at first. The .NET Framework is filled with tons of goodies--namespaces with classes that make coding life easier. I am usually fairly satisfied with what is available in .NET (especially in .NET 3.5), but when it comes to the System.Net.Sockets namespace, there is just more to be desired.</p>
<p><span id="more-61"></span>At first glance, it seems like the Socket class provides exactly what you need to get the job done. There is even a "Connected" property that is exposed, which seems like a natural thing to check before trying to send data over a connection.</p>
<p>The way that <em>this</em> application was designed, however, makes it a moot point as to what the Connected property returns (If you <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx">check the MSDN</a>, you will see that the Connected property actually returns whether or not the last IO operation on the socket was successful--not whether or not there is a connection currently).</p>
<p>This application was coded to handle failures to write to the Socket. The logic flow for this process looked something like this:</p>
<ol>
<li>Add all outgoing messages into an outgoing Queue for storage in case of problems</li>
<li>Peek at the Queue to get the next message (not Dequeueing/Requeueing since the order of the messages matters in this application)</li>
<li>Attempt to write the bytes of the message to the socket</li>
<li>If all bytes were written successfully, Dequeue the message as we no longer need to store it for sending</li>
<li>If the entire message was not transmitted, reset the connection and retry sending upon reconnection</li>
</ol>
<p>I looked at the code, and could not tell where the failure was occurring. This application was logging successful socket writes and the application on the other side never got the bytes! How was this nightmare possible?</p>
<p>Well... it was all thanks to the magic of TCP/IP. The "magic of TCP/IP" is a topic for another article (or book even) so I won't go into great detail here. Basically, once a TCP/IP Socket connection is "established" it is considered valid even if the physical connection is broken. In fact, if you unplug the OTHER computer, your computer won't know the connection is gone until you try sending data and the TCP/IP stack fails to deliver it after a certain timeout. TCP/IP was meant to be a robust protocol, being able to recover from intermittent physical connectivity failures. And it does a great job at what it was designed to do...</p>
<p>However, in my scenario I needed to know <strong>instantly</strong> (or almost instantly) whether or not the message was delivered to the other machine--not 30 seconds, 2 minutes, or 2 hours after we tried sending another message.</p>
<p>How could I know BEFORE a TCP/IP retry timeout whether or not the connection was still there? The answer: TCP keep-alives!</p>
<p>These are short messages that are basically just empty packets that need to be ACKed. When this message is sent from one computer to another, the TCP/IP stack replies to it with an ACK. The best thing about keep-alives is that any system that implements TCP/IP automatically supports keep-alives. Once they are turned on if the connection between the two TCP/IP stacks is physically aborted and a keep-alive is not ACKed within a certain time the sending stack knows that the connection is broken.</p>
<p>I searched how to set TCP Keep Alives from the managed .NET sockets and finally came across <a href="http://blogs.msdn.com/lcleeton/archive/2006/09/15/754932.aspx">Larry Cleeton's blog entry</a> which shares this method:<br />
<code>
<pre class="csharp">&nbsp;
<span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> SetKeepAlive<span style="color: #000000;">&#40;</span>Socket s, <span style="color: #FF0000;">bool</span> on, <span style="color: #FF0000;">uint</span> time, <span style="color: #FF0000;">uint</span> interval<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
<span style="color: #008080; font-style: italic;">/* the native structure
struct tcp_keepalive {
ULONG onoff;
ULONG keepalivetime;
&nbsp;
ULONG keepaliveinterval;
};
*/</span> 
&nbsp;
<span style="color: #008080; font-style: italic;">// marshal the equivalent of the native structure into a byte array</span>
<span style="color: #FF0000;">uint</span> dummy = <span style="color: #FF0000;">0</span>;
<span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> inOptionValues = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span>Marshal.<a href="http://www.google.com/search?q=sizeof+msdn.microsoft.com"><span style="color: #008000;">SizeOf</span></a><span style="color: #000000;">&#40;</span>dummy<span style="color: #000000;">&#41;</span> * <span style="color: #FF0000;">3</span><span style="color: #000000;">&#93;</span>;
BitConverter.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">uint</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#40;</span>on ? <span style="color: #FF0000;">1</span> : <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">CopyTo</span><span style="color: #000000;">&#40;</span>inOptionValues, <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span>;
BitConverter.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">uint</span><span style="color: #000000;">&#41;</span>time<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">CopyTo</span><span style="color: #000000;">&#40;</span>inOptionValues, Marshal.<a href="http://www.google.com/search?q=sizeof+msdn.microsoft.com"><span style="color: #008000;">SizeOf</span></a><span style="color: #000000;">&#40;</span>dummy<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
BitConverter.<span style="color: #0000FF;">GetBytes</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">uint</span><span style="color: #000000;">&#41;</span>interval<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">CopyTo</span><span style="color: #000000;">&#40;</span>inOptionValues, Marshal.<a href="http://www.google.com/search?q=sizeof+msdn.microsoft.com"><span style="color: #008000;">SizeOf</span></a><span style="color: #000000;">&#40;</span>dummy<span style="color: #000000;">&#41;</span> * <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span>;
<span style="color: #008080; font-style: italic;">// of course there are other ways to marshal up this byte array, this is just one way</span>
&nbsp;
<span style="color: #008080; font-style: italic;">// call WSAIoctl via IOControl</span>
<span style="color: #FF0000;">int</span> ignore = s.<span style="color: #0000FF;">IOControl</span><span style="color: #000000;">&#40;</span>IOControlCode.<span style="color: #0000FF;">KeepAliveValues</span>, inOptionValues, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>; 
&nbsp;
<span style="color: #000000;">&#125;</span>
&nbsp;</pre>
<p></code></p>
<p>The "time" variable represents the time to wait between each TCP Keep Alive that is sent out. The "interval" variable represents the amount of time that the TCP/IP stack should wait to receive a response from the other machine.</p>
<p>By turning on the keep alives you will be able to know when the physical network connectivity is broken.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2008/10/detecting-a-physical-network-disconnection-with-net-sockets/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Minimize Asynchronous Socket Callbacks With Dynamic Buffer Sizes</title>
		<link>http://blog.realcoderscoding.com/index.php/2008/10/minimize-asynchronous-socket-callbacks-with-dynamic-buffer-sizes/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2008/10/minimize-asynchronous-socket-callbacks-with-dynamic-buffer-sizes/#comments</comments>
		<pubDate>Wed, 08 Oct 2008 14:06:30 +0000</pubDate>
		<dc:creator>Bogdan Varlamov (a.k.a. Phantom Stranger)</dc:creator>
		
		<category><![CDATA[.NET Framework]]></category>

		<category><![CDATA[Tricks]]></category>

		<category><![CDATA[c sharp]]></category>

		<category><![CDATA[code]]></category>

		<category><![CDATA[networking]]></category>

		<category><![CDATA[Sockets]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=105</guid>
		<description><![CDATA[I've been doing a lot of work with .NET Sockets lately, and I will be posting more articles discussing what I've been working on in greater detail. In this article, I want to talk about the concept of reading a Socket asynchronously, raising events to notify your application when bytes are received, and minimizing the [...]]]></description>
			<content:encoded><![CDATA[<p>I've been doing a lot of work with .NET Sockets lately, and I will be posting more articles discussing what I've been working on in greater detail. In this article, I want to talk about the concept of reading a Socket asynchronously, raising events to notify your application when bytes are received, and minimizing the number of times the callback method is processed.</p>
<p>If you are familiar with .NET Sockets you might already know that there are asynchronous methods to receive bytes from Sockets (Microsoft has an <a href="http://msdn.microsoft.com/en-us/library/fx6588te.aspx">Asynchronous Server Socket Example</a> available if you are interested in seeing  code for doing this).</p>
<p>In the above code sample, a StateObject class that contains a byte buffer with a static size is passed around. When the asynchronous socket read happens, incoming bytes are stored into this buffer and then passed back to the receive callback method. This example works fine, but I think there are some optimizations that can be applied.</p>
<p><span id="more-105"></span><br />
To see where these optimizations can be applied let's think about what happens in the typical Socket reading application, but with real world examples. Let's pretend that our task is to pick up items that arrive at a train station and take them to our home.</p>
<p>In the Microsoft example this would look something like this:</p>
<blockquote><p>You wait at the train station with a bag that can hold 1024 items. 3 items arrive, you stick them into your bag, then run home to drop them off. Then, you come back to the train station and wait for more items.</p>
<p>If 8000 items arrive, you put 1024 into your bag and take them home, then come back and put the next 1024 into the bag, take them home, and repeat until all of the items are home.</p></blockquote>
<p>An alternative to this would be to just grab all of the items that arrive, stick them into a bag that holds exactly that amount of items, and bring them back once.</p>
<p>I haven't found a way to do exactly that in .NET Sockets, so the next best thing I have come up with would look like this:</p>
<blockquote><p>You wait at the train station with a bag that can hold 0 items. 3 items arrive, you run home, get a bag that can hold 3 items, run back to the train station and fill your bag. Then, you bring the items home, get a bag that can hold 0 items and return to the train station to wait again.</p></blockquote>
<p>At first this sounds inefficient...you have to switch out bags and run back and forth twice! Seems wasteful, but when you think about it you will notice that no matter how many items arrive you can always grab <strong>all items</strong> in just two trips.</p>
<p><em>So, what? It costs more to allocate memory for the new buffers every time than to keep reading into the same one!</em></p>
<p>While that may be true, when buffering into a fixed size buffer you will inevitably have some "left over space" in the buffer. So, you may be receiving into a 1024 byte buffer, but you only receive 1000 bytes. Now you have 24 empty bytes that are being wasted...And you will undoubtedly have to "trim up" your buffer before using the received bytes in the application.</p>
<p>In most cases you will probably do an Array.Copy to move over the bytes with real data into a separate byte[] of the appropriate size--allocating space for the new array, and using twice the memory during the copy operation!</p>
<p>In theory it might be less costly to reuse the same buffer, but in practice it might actually be <em><strong>more efficient</strong></em> to create the properly sized array in the beginning. Your application is going to <em>do something</em> with the received data, so in most cases the bytes need to be in a usable state...</p>
<p>I'm not advocating that you use my model for all of your socket communications logic, but there are some places where it might especially make sense to do so...</p>
<p>When your application:</p>
<ul>
<li>receives greatly varying amounts of data (e.g. an app that receives a periodic and small keep-alive message, while also receiving large image files)</li>
<li>performs intensive processing each time data is received (e.g. received bytes are being buffered and scanned for application specific protocols)</li>
<li>receives large chunks of data intermittently</li>
</ul>
<p>I've got some sample code to illustrate what my train station example would look like translated into C#:</p>
<pre class="csharp"><span style="color: #008080; font-style: italic;">//will be used to listen for incoming channel connections</span>
TcpListener _tcpListener;
&nbsp;
<span style="color: #008080; font-style: italic;">//socket will be used to determine connectivity/etc.</span>
Socket _incomingSocket; 
&nbsp;
<span style="color: #008080; font-style: italic;">//will control the socket buffer</span>
<span style="color: #008080; font-style: italic;">//NOTE: if you implement some real-time network traffic analysis</span>
<span style="color: #008080; font-style: italic;">//         or are using an application level protocol and know the min.</span>
<span style="color: #008080; font-style: italic;">//         size of a message, adjust this value as appropriate!</span>
<span style="color: #FF0000;">int</span> _incomingSocketByteBufferSize = <span style="color: #FF0000;">0</span>;
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">bool</span> StartIncomingCommunications<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
     <span style="color: #FF0000;">bool</span> returnValue = <span style="color: #0600FF;">false</span>;<span style="color: #008080; font-style: italic;">//assume problems</span>
&nbsp;
    <span style="color: #0600FF;">try</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//start listening</span>
        _tcpListener.<span style="color: #0000FF;">Start</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
         <span style="color: #008080; font-style: italic;">//let us accept the connection when we get it</span>
         _tcpListener.<span style="color: #0000FF;">BeginAcceptSocket</span><span style="color: #000000;">&#40;</span>
          <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> AsyncCallback<span style="color: #000000;">&#40;</span>DoAcceptIncomingSocketConnection<span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception caught<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
          HandleLogging<span style="color: #000000;">&#40;</span>caught<span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> returnValue;
<span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//the callback to handle the incoming socket connection</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> DoAcceptIncomingSocketConnection<span style="color: #000000;">&#40;</span>IAsyncResult iaResult<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">try</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//this application only allows one socket connection at a time</span>
               <span style="color: #008080; font-style: italic;">//so we need to check that our socket variable isn't already being used</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_incomingSocket != <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #0600FF;">try</span>
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #008080; font-style: italic;">//we already connected by some socket</span>
                        <span style="color: #008080; font-style: italic;">//we will close the current connection and establish a new one</span>
                        <span style="color: #008080; font-style: italic;">//an alternative would be to reject the incoming socket</span>
                        _incomingSocket.<span style="color: #0000FF;">Close</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                        _incomingSocket = <span style="color: #0600FF;">null</span>;
                    <span style="color: #000000;">&#125;</span>
                    <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception caught<span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        HandleLogging<span style="color: #000000;">&#40;</span>caught<span style="color: #000000;">&#41;</span>;
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
&nbsp;
                    <span style="color: #008080; font-style: italic;">// End the operation and get the socket</span>
                    _incomingSocket = _tcpListener.<span style="color: #0000FF;">EndAcceptSocket</span><span style="color: #000000;">&#40;</span>iaResult<span style="color: #000000;">&#41;</span>;
&nbsp;
                    <span style="color: #008080; font-style: italic;">//create a byte buffer to store received information</span>
                    <span style="color: #008080; font-style: italic;">//this buffer is of size 0 by default and serves as a way to notify when bytes are received</span>
                    <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> readingBuffer = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span>_incomingSocketByteBufferSize<span style="color: #000000;">&#93;</span>;
&nbsp;
                     <span style="color: #008080; font-style: italic;">//the last parameter in this method should be a custom object</span>
                     <span style="color: #008080; font-style: italic;">//i'm just passing along my readingBuffer since i only have one socket</span>
                     <span style="color: #008080; font-style: italic;">//and don't care about anything other than the buffer</span>
                    _incomingSocket.<span style="color: #0000FF;">BeginReceive</span><span style="color: #000000;">&#40;</span>readingBuffer, <span style="color: #FF0000;">0</span>, readingBuffer.<span style="color: #0000FF;">Length</span>, SocketFlags.<span style="color: #0000FF;">None</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> AsyncCallback<span style="color: #000000;">&#40;</span>DoReceiveCallback<span style="color: #000000;">&#41;</span>, readingBuffer<span style="color: #000000;">&#41;</span>;
&nbsp;
                    NotifyOfConnectivityStatus<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
                    <span style="color: #008080; font-style: italic;">//start accepting again</span>
                    <span style="color: #008080; font-style: italic;">//this will allow us to process new connections</span>
                    <span style="color: #008080; font-style: italic;">//an alternative would be to only do this once the current connection is closed</span>
                    _tcpListener.<span style="color: #0000FF;">BeginAcceptSocket</span><span style="color: #000000;">&#40;</span>
                        <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> AsyncCallback<span style="color: #000000;">&#40;</span>DoAcceptIncomingSocketConnection<span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception caught<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                HandleLogging<span style="color: #000000;">&#40;</span>caught<span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// this method processes the receive callback</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> DoReceiveCallback<span style="color: #000000;">&#40;</span>IAsyncResult iaResult<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">try</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> buffer = <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span>iaResult.<span style="color: #0000FF;">AsyncState</span>;<span style="color: #008080; font-style: italic;">//extract our original buffer</span>
&nbsp;
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>buffer.<span style="color: #0000FF;">Length</span> == <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008080; font-style: italic;">//this buffer was used as a notification of bytes received</span>
                <span style="color: #000000;">&#123;</span> <span style="color: #008080; font-style: italic;">//we will replace our &quot;zero bag&quot; with the appropriately sized one</span>
                    buffer = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span>_incomingSocket.<span style="color: #0000FF;">Available</span><span style="color: #000000;">&#93;</span>;
                <span style="color: #000000;">&#125;</span>
                <span style="color: #0600FF;">else</span><span style="color: #008080; font-style: italic;">//read real data (got our appropriately sized bag)</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">//some method that does something with the bytes we just got...</span>
                    OnBytesReceivedOverIncomingChannel<span style="color: #000000;">&#40;</span>buffer<span style="color: #000000;">&#41;</span>;
&nbsp;
                    <span style="color: #008080; font-style: italic;">//maybe more bytes arrived while we've been sitting here?</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_incomingSocket.<span style="color: #0000FF;">Available</span> &gt; <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008080; font-style: italic;">//still bytes available for reading</span>
                    <span style="color: #000000;">&#123;</span>
                        buffer = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span>_incomingSocket.<span style="color: #0000FF;">Available</span><span style="color: #000000;">&#93;</span>;<span style="color: #008080; font-style: italic;">//get the bag for the bytes just arrived</span>
                    <span style="color: #000000;">&#125;</span>
                    <span style="color: #0600FF;">else</span><span style="color: #008080; font-style: italic;">//done, go to notification cycle (get the zero-sized bag)</span>
                    <span style="color: #000000;">&#123;</span>
                        buffer = <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span>_incomingSocketByteBufferSize<span style="color: #000000;">&#93;</span>;
                    <span style="color: #000000;">&#125;</span>
&nbsp;
                <span style="color: #000000;">&#125;</span>
&nbsp;
                <span style="color: #0600FF;">try</span> <span style="color: #008080; font-style: italic;">//MSDN recomends trying to read from a socket and handling exceptions as a way</span>
                <span style="color: #000000;">&#123;</span>   <span style="color: #008080; font-style: italic;">//of detecting when the connection is broken..</span>
                     <span style="color: #008080; font-style: italic;">//go back and wait for more data (go back to the train station)</span>
                    _incomingSocket.<span style="color: #0000FF;">BeginReceive</span><span style="color: #000000;">&#40;</span>buffer, <span style="color: #FF0000;">0</span>, buffer.<span style="color: #0000FF;">Length</span>, SocketFlags.<span style="color: #0000FF;">None</span>, <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> AsyncCallback<span style="color: #000000;">&#40;</span>DoReceiveCallback<span style="color: #000000;">&#41;</span>, buffer<span style="color: #000000;">&#41;</span>;
                <span style="color: #000000;">&#125;</span>
                <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>SocketException sckEx<span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>sckEx.<span style="color: #0000FF;">SocketErrorCode</span> == SocketError.<span style="color: #0000FF;">ConnectionReset</span><span style="color: #000000;">&#41;</span><span style="color: #008080; font-style: italic;">//socket conn got closed...</span>
                    <span style="color: #000000;">&#123;</span>
                        NotifyOfConnectivityStatus<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                    <span style="color: #000000;">&#125;</span>
                    <span style="color: #0600FF;">else</span> <span style="color: #008080; font-style: italic;">//some other weird error</span>
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #0600FF;">throw</span> sckEx; <span style="color: #008080; font-style: italic;">//pass it up to the higher try/catch</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">catch</span> <span style="color: #000000;">&#40;</span>Exception caught<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                HandleLogging<span style="color: #000000;">&#40;</span>caught<span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span></pre>
<p>To see that code work you have to paste it into your own class, and add your own methods for HandleLogging, and NotifyOfConnectionStatus, etc. I'm working on something for which I will post the complete code later, so keep checking RealCodersCoding.com! Hopefully you get the general idea from the code in this article...if not, just leave me a comment : )</p>
<p>The above source code is © 2008 by Bogdan Varlamov and may only be used if you agree to the <a href="http://blog.realcoderscoding.com/?page_id=138">BSD License Terms</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2008/10/minimize-asynchronous-socket-callbacks-with-dynamic-buffer-sizes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Tips on Creating Excel Spreadsheets via PHP</title>
		<link>http://blog.realcoderscoding.com/index.php/2008/10/tips-on-creating-excel-spreadsheets-via-php/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2008/10/tips-on-creating-excel-spreadsheets-via-php/#comments</comments>
		<pubDate>Mon, 06 Oct 2008 16:16:52 +0000</pubDate>
		<dc:creator>Flash</dc:creator>
		
		<category><![CDATA[PHP]]></category>

		<category><![CDATA[XML]]></category>

		<category><![CDATA[DBF]]></category>

		<category><![CDATA[FoxPro]]></category>

		<category><![CDATA[Microsoft Excel]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=108</guid>
		<description><![CDATA[One of my current clients has an old FoxPro (old as in created in '97 and upgraded in '99) database application that the users can't stand.  It frequently crashes and it's all too easy to lose valuable data after a lengthy data entry session (just by clicking the sadly misnamed Save button).  We are porting [...]]]></description>
			<content:encoded><![CDATA[<p>One of my current clients has an old FoxPro (old as in created in '97 and upgraded in '99) database application that the users can't stand.  It frequently crashes and it's all too easy to lose valuable data after a lengthy data entry session (just by clicking the sadly misnamed Save button).  We are porting them over to a LAMP-based web application.  One of the early tasks in this project is to analyze their existing database structure.  This application involves hundreds of FoxPro DBF files which are tables (data and schema) that reside in various child directories.  </p>
<p>My initial approach (following the KISS principle) was to inspect some of these files and see what's in 'em and how to get the schema out of 'em.  I downloaded a trial version of <a href="http://www.dbf2002.com/">DBF Viewer 2000</a> and it's a fine tool.  I was able to view the data and the schema and, using <a href="http://www.techsmith.com/screen-capture.asp">SnagIt</a>, I captured the text and pasted the values to an Excel spreadsheet.  But purely manual approach would take way too long for me.  Time to whip out a quick script.  The problem: .NET or PHP or other?  I'm a recovering .NET dev working on PHP apps.  I surprised myself by deciding to go for the PHP option.  And I'm glad I did.  Here's how I was able to create an Excel spreadsheet with hundreds of worksheets in PHP.</p>
<p><span id="more-108"></span><br />
I assumed I'd be able to plug into some existing PHP-based Excel spreadsheet API and knock this out.  Boy was I surprised.  There's a few <a href="http://www.google.com/custom?domains=www.phpclasses.org&amp;q=Excel&amp;sa=Search&amp;sitesearch=www.phpclasses.org&amp;client=pub-2951707118576741&amp;forid=1&amp;channel=5742870948&amp;ie=ISO-8859-1&amp;oe=ISO-8859-1&amp;cof=GALT%3A%23663399%3BGL%3A1%3BDIV%3A%23222222%3BVLC%3A663399%3BAH%3Acenter%3BBGC%3AA3C5CC%3BLBGC%3AA3C5CC%3BALC%3A0000FF%3BLC%3A0000FF%3BT%3A000000%3BGFNT%3A0000FF%3BGIMP%3A0000FF%3BLH%3A50%3BLW%3A256%3BL%3Ahttp%3A%2F%2Ffiles.phpclasses.org%2Fgraphics%2Fgooglesearch.jpg%3BS%3Ahttp%3A%2F%2Fwww.phpclasses.org%2Fsearch.html%3BFORID%3A1%3B&amp;hl=en">classes related to Excel over at PHPClasses.org</a> but they were either too simple (not enough features I needed) or unsupported or just plain useless.  The <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer">Spreadsheet Excel Writer PEAR package</a> has way too many bugs in it and I couldn't get it to work on my setup (probably my fault).  It then hit me that moden versions of Excel (since 2003?) can read and write XML (given a proper schema).  After some quick testing (involving creating a simple spreadsheet and <a href="http://office.microsoft.com/en-us/excel/HP010425731033.aspx">exporting to XML</a> and viewing the output in a text editor) I decided the best solution would be to create an Excel-flavored XML file.  </p>
<p>Here's the source data in Excel:</p>
<p><a href="http://blog.realcoderscoding.com/wp-content/uploads/2008/10/php2excel1.png"><img class="aligncenter size-full wp-image-112" title="php2excel1" src="http://blog.realcoderscoding.com/wp-content/uploads/2008/10/php2excel1.png" alt="" width="156" height="67" /></a></p>
<p>And here's the 92 line XML output for this data:</p>
<pre>&lt;?xml version="1.0"?&gt;
&lt;?mso-application progid="Excel.Sheet"?&gt;
&lt;Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40"&gt;
 &lt;DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"&gt;
  &lt;Author&gt;Brian&lt;/Author&gt;
  &lt;LastAuthor&gt;Brian&lt;/LastAuthor&gt;
  &lt;Created&gt;2008-10-06T15:14:58Z&lt;/Created&gt;
  &lt;LastSaved&gt;2008-10-06T15:17:02Z&lt;/LastSaved&gt;
  &lt;Company&gt;One Who Serves&lt;/Company&gt;
  &lt;Version&gt;12.00&lt;/Version&gt;
 &lt;/DocumentProperties&gt;
 &lt;ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"&gt;
  &lt;WindowHeight&gt;10170&lt;/WindowHeight&gt;
  &lt;WindowWidth&gt;20655&lt;/WindowWidth&gt;
  &lt;WindowTopX&gt;600&lt;/WindowTopX&gt;
  &lt;WindowTopY&gt;360&lt;/WindowTopY&gt;
  &lt;ProtectStructure&gt;False&lt;/ProtectStructure&gt;
  &lt;ProtectWindows&gt;False&lt;/ProtectWindows&gt;
 &lt;/ExcelWorkbook&gt;
 &lt;Styles&gt;
  &lt;Style ss:ID="Default" ss:Name="Normal"&gt;
   &lt;Alignment ss:Vertical="Bottom"/&gt;
   &lt;Borders/&gt;
   &lt;Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/&gt;
   &lt;Interior/&gt;
   &lt;NumberFormat/&gt;
   &lt;Protection/&gt;
  &lt;/Style&gt;
 &lt;/Styles&gt;
 &lt;Worksheet ss:Name="Sheet1"&gt;
  &lt;Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="2" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15"&gt;
   &lt;Row&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is A1&lt;/Data&gt;&lt;/Cell&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is B1&lt;/Data&gt;&lt;/Cell&gt;
   &lt;/Row&gt;
   &lt;Row&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is A2&lt;/Data&gt;&lt;/Cell&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is B2&lt;/Data&gt;&lt;/Cell&gt;
   &lt;/Row&gt;
  &lt;/Table&gt;
  &lt;WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"&gt;
   &lt;PageSetup&gt;
    &lt;Header x:Margin="0.3"/&gt;
    &lt;Footer x:Margin="0.3"/&gt;
    &lt;PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/&gt;
   &lt;/PageSetup&gt;
   &lt;Selected/&gt;
   &lt;Panes&gt;
    &lt;Pane&gt;
     &lt;Number&gt;3&lt;/Number&gt;
     &lt;ActiveRow&gt;17&lt;/ActiveRow&gt;
     &lt;ActiveCol&gt;11&lt;/ActiveCol&gt;
    &lt;/Pane&gt;
   &lt;/Panes&gt;
   &lt;ProtectObjects&gt;False&lt;/ProtectObjects&gt;
   &lt;ProtectScenarios&gt;False&lt;/ProtectScenarios&gt;
  &lt;/WorksheetOptions&gt;
 &lt;/Worksheet&gt;
 &lt;Worksheet ss:Name="Sheet2"&gt;
  &lt;Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15"&gt;
  &lt;/Table&gt;
  &lt;WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"&gt;
   &lt;PageSetup&gt;
    &lt;Header x:Margin="0.3"/&gt;
    &lt;Footer x:Margin="0.3"/&gt;
    &lt;PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/&gt;
   &lt;/PageSetup&gt;
   &lt;ProtectObjects&gt;False&lt;/ProtectObjects&gt;
   &lt;ProtectScenarios&gt;False&lt;/ProtectScenarios&gt;
  &lt;/WorksheetOptions&gt;
 &lt;/Worksheet&gt;
 &lt;Worksheet ss:Name="Sheet3"&gt;
  &lt;Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15"&gt;
  &lt;/Table&gt;
  &lt;WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"&gt;
   &lt;PageSetup&gt;
    &lt;Header x:Margin="0.3"/&gt;
    &lt;Footer x:Margin="0.3"/&gt;
    &lt;PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/&gt;
   &lt;/PageSetup&gt;
   &lt;ProtectObjects&gt;False&lt;/ProtectObjects&gt;
   &lt;ProtectScenarios&gt;False&lt;/ProtectScenarios&gt;
  &lt;/WorksheetOptions&gt;
 &lt;/Worksheet&gt;
&lt;/Workbook&gt;</pre>
<p>However, most of the elements are either static or unimportant (for my simple needs).  So, here's the part that's most important:</p>
<pre> &lt;Worksheet ss:Name="Sheet1"&gt;
  &lt;Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="2" x:FullColumns="1"
   x:FullRows="1" ss:DefaultRowHeight="15"&gt;
   &lt;Row&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is A1&lt;/Data&gt;&lt;/Cell&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is B1&lt;/Data&gt;&lt;/Cell&gt;
   &lt;/Row&gt;
   &lt;Row&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is A2&lt;/Data&gt;&lt;/Cell&gt;
    &lt;Cell&gt;&lt;Data ss:Type="String"&gt;This is B2&lt;/Data&gt;&lt;/Cell&gt;
   &lt;/Row&gt;
  &lt;/Table&gt;
 &lt;/Worksheet&gt;</pre>
<p>Everything before the first Worksheet tag became a static heredoc header and the footer is simply the closing &lt;/Workbook&gt; tag.  I didn't require setting any &lt;WorksheetOptions&gt; so I removed that element completely. </p>
<p>Now that I figured out how to layout an XML fragment that represents a worksheet, all I needed to next was the following:</p>
<ul>
<li>loop through the directories where I stored the DBF files in question (using PHP's <a href="http://us.php.net/manual/en/class.recursivedirectoryiterator.php">RecursiveDirectoryIterator</a> class)</li>
<li>parse each DBF file for the data schema (<a href="http://www.easywms.com/easywms/?q=en/node/83">here's how I learned how to do this</a>)</li>
<li>loop through the parsed data (using foreach loops on arrays)</li>
<li>generate the appropriate &lt;Cell&gt; and &lt;Data&gt; tags</li>
</ul>
<p>After much trial and error, I finally succeeded in creating an well-formed XML document.  I probably should have used some <a href="http://us.php.net/manual/en/refs.xml.php">existing PHP XML API </a>but, for the sake of time, I went with the brute force method of hacking my way to a well-formed XML document (via heredoc strings and concatenating variables and new line characters, etc.).  However, this XML file did not open in Excel for many reasons and Excel was not being reasonable with me and giving me information I can use for debugging my text.  I kept getting (nearly) useless errors like this:</p>
<p><a href="http://blog.realcoderscoding.com/wp-content/uploads/2008/10/php2excel2.png"><img class="aligncenter size-medium wp-image-120" title="php2excel2" src="http://blog.realcoderscoding.com/wp-content/uploads/2008/10/php2excel2-300x161.png" alt="" width="300" height="161" /></a></p>
<p>I couldn't find the log mentioned either.  After much more experimenting, I finally learned the following lessons:</p>
<ul>
<li>Worksheet names need to be unique (duh but not so obvious in the heat of the moment).
<ul>
<li>Set the ss:Name attribute for the &lt;Worksheet&gt; tag.</li>
</ul>
</li>
<li>Worksheet names are limited to 31 characters.
<ul>
<li>This sucked since I was using a version of the file path to create unique worksheet names.  </li>
<li>I solved this one by using sequential numbers for the worksheet names and creating a sort of table of content worksheet that maps the files to their matching worksheet (cumbersome but effective).</li>
</ul>
</li>
<li>The ss:ExpandedRowCount attribute for the &lt;Table&gt; tag needs to match the number of actual rows to be displayed in each worksheet.
<ul>
<li>This one took me a long time to debug because of the aforementioned useless Exel error message.</li>
</ul>
</li>
</ul>
<p>In the end, I have my Excel spreadsheet with 183 worksheets in it (one for every DBF file and the master TOC).  I can regenerate it at will.  And, most importantly, I can refactor it later and use it again to extract the data from the DBF files (probably to export the data to MySQL for later use).  While I was fighting the ExpandedRowCount issue, I did find another method of creating Excel Spreadsheets in PHP that I may use in the future - <a href="http://www.codeplex.com/PHPExcel">PHPExcel</a>.  Once I got it up and running on my dev machine, I was amazed at what I could do with it.  My script would be much cleaner without all of those heredoc strings in it.  Plus, <a href="http://www.codeplex.com/PHPExcel">PHPExcel</a> is well-documented and has a growing base of users which can only bode well for the future of this set of classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2008/10/tips-on-creating-excel-spreadsheets-via-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>System.Threading.Timer Stops Firing in Windows Server 2003 SP1</title>
		<link>http://blog.realcoderscoding.com/index.php/2008/09/systemthreadingtimer-stops-firing-in-windows-server-2003-sp1/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2008/09/systemthreadingtimer-stops-firing-in-windows-server-2003-sp1/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 13:16:35 +0000</pubDate>
		<dc:creator>Bogdan Varlamov (a.k.a. Phantom Stranger)</dc:creator>
		
		<category><![CDATA[.NET 2.0]]></category>

		<category><![CDATA[.NET Framework]]></category>

		<category><![CDATA[Lessons Learned the Hard Way]]></category>

		<category><![CDATA[Bug]]></category>

		<category><![CDATA[Server 2003 SP1]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=92</guid>
		<description><![CDATA[Do you have an application that starts misbehaving randomly? You aren't quite sure what is going on, but it seems like for some reason your Timer just stops firing it's event handler--and once it stops it never starts back up.
This drove me nuts! But, it is definitely a problem in the Windows Server 2003 SP1. [...]]]></description>
			<content:encoded><![CDATA[<p>Do you have an application that starts misbehaving randomly? You aren't quite sure what is going on, but it seems like for some reason your Timer just stops firing it's event handler--and once it stops it never starts back up.</p>
<p>This drove me nuts! But, it is definitely a problem in the Windows Server 2003 SP1. This bug is particularly devious since even if your application uses extensive logging it maybe be nearly impossible to find proof of a timer <em>not</em> firing in your logs.</p>
<p>Short of implementing a <a href="http://www.simpsons-crazy.co.uk/homer.html">Homer Simpson</a> type of "everything is okay alarm" is there anything you can do to determine whether or not your application might be suffering from dying timers?</p>
<p><span id="more-92"></span><br />
When I realized that my application had timers that randomly stopped firing, I set out on an Internet quest to figure out if anyone has ever had this problem before. And, yes, I found many many forum threads and blog posts already discussing this issue (just do a quick Google Search if you don't believe me). The problem was that everything I found was from over a year ago and only mentioned .NET 1.1. Well... I was having what seemed like the same issue, but with .NET 2.0.</p>
<p>It was nearly impossible to find anything from Microsoft about the issue. The only thing I came across was <a href="http://support.microsoft.com/kb/900822">this article</a> which had a misleading title, but contained the following (plausible) explanation:</p>
<blockquote><p>The Timer classes are implemented as a linked list of timer objects. When the first System.Threading.Timer object is created, the thread pool manager starts a thread to process the linked list. Every timer object is added to the linked list. The thread that process the linked list cycles through the linked list and determines when the timer event is expected to be signaled against the current clock count.</p>
<p>If the timer object has expired, the thread asynchronously queues a callback function before the thread updates the time that the timer event is expected to be signaled. After the thread has processed all timer objects in the linked list, the thread updates the time that the linked list was last processed. Then, the thread calculates the shortest time that the thread should sleep before the thread reprocesses the linked list for the next elapsed timer object.</p>
<p>Sometimes, when the system is under stress or when the linked list includes many timer objects, the processing thread may be pre-empted by a higher priority thread before the whole linked list has been processed. When this behavior occurs, the time that a timer event is next expected to be signaled is calculated to be earlier than the timestamp when the linked list was last processed. Therefore, the time that the timer event is expected to be signaled is in the past and never expires.</p>
<p>Because the time that the timer event is expected to be signaled has already passed, the thread may calculate a negative period to wait before the timer event must be signaled. When the thread has a negative period to wait, the thread enters a sleep state for a long time.</p></blockquote>
<p>I decided that the only way to be sure that this bug is caused by the Server 2003 SP1 (and not the .NET 1.1 Framework SP1 as the Microsoft article claims) would be to test using the .NET 2.0 Framework.</p>
<p>After some more grueling searching I came across a Google Groups Topic that contained <a href="http://groups.google.com/group/microsoft.public.dotnet.framework.performance/browse_thread/thread/8f4430b6f6efe829/5224d5666844a215?hl=en">source code to test System.Threading.Timer bug</a>.  Basically, all it does is create 30,000 Timers and tells them all to go off in 5 seconds. Then it prints out the updated count each time one fires--so if all of them fire the application will count up to 30000.</p>
<p>I built the testing application from the source, and ran it on the 2003 SP1 machine. The first time I ran the process all 30k timers fired (this got me worried), but after running it a few more times I was able to see that sometimes hardly ANY fired at all (the lowest I saw was around 11,000).</p>
<p>This proved that this System.Threading.Timer problem is well alive in .NET 2.0 Framework and that it is in fact caused by Server 2003 SP1 (not only the .NET 1.1 Framework SP1). I have tested the same process on SP2 and SP3 and each time all 30000 timers fire.</p>
<p>I have not tried to install the hotfix which Microsoft says will also fix the problem, but there is one available here: <a href="http://code.msdn.microsoft.com/KB900822">KB900822</a>. Please feel free to respond to this post if the hotfix has worked for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2008/09/systemthreadingtimer-stops-firing-in-windows-server-2003-sp1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Spreading the Word w/ Information Radiators</title>
		<link>http://blog.realcoderscoding.com/index.php/2008/09/spreading-the-word-w-information-radiators/</link>
		<comments>http://blog.realcoderscoding.com/index.php/2008/09/spreading-the-word-w-information-radiators/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 20:55:28 +0000</pubDate>
		<dc:creator>Flash</dc:creator>
		
		<category><![CDATA[Agile Software Development]]></category>

		<category><![CDATA[Scrum]]></category>

		<category><![CDATA[task board]]></category>

		<guid isPermaLink="false">http://blog.realcoderscoding.com/?p=74</guid>
		<description><![CDATA[I was introduced to the world of agile software methodologies and, in particular, Scrum at my last company.  In fact, on my first day new whiteboards were delivered to almost every office and a book called Agile and Iterative Development: A Manager's Guide by Craig Larman was handed out to at least one member of each [...]]]></description>
			<content:encoded><![CDATA[<p>I was introduced to the world of <a href="http://en.wikipedia.org/wiki/Agile_software_development">agile software methodologies</a> and, in particular, <a href="http://en.wikipedia.org/wiki/Scrum_(development)">Scrum</a> at my <a href="http://www.interact911.com">last company</a>.  In fact, on my first day new whiteboards were delivered to almost every office and a book called <a href="http://www.amazon.com/Agile-Iterative-Development-Managers-Software/dp/0131111558/ref=pd_bxgy_b_img_b">Agile and Iterative Development: A Manager's Guide</a> by Craig Larman was handed out to at least one member of each dev team.  We were told to choose an agile approach that works best for our team and go for it.  However, I later learned that we were to choose any approach we wanted as long as it was called Scrum.  In that effort, I helped to wrangle our usual cat herding approach to software development into something closely resembling Scrum processes.  It was fun and challenging and a very eye-opening experience.</p>
<p><span id="more-74"></span></p>
<p>Along the way, we struggled with various ways to maintain transparency so that we could satisfy our higher-ups (or <a href="http://www.implementingscrum.com/2006/09/11/the-classic-story-of-the-pig-and-chicken/">the chickens</a> in Scrum parlance) desire to know the status of our sprints and when we would be ready to deploy, deploy, deploy.  Mostly I'm talking about burndown charts and product/sprint backlogs.  If you have no clue as to what a <a href="http://www.controlchaos.com/about/burndown.php">burndown chart</a> or <a href="http://www.mountaingoatsoftware.com/sprint_backlog">backlog</a> is... I implore you to follow the links and come back for the rest of the story.  The chickens wanted an easy way to know where we were and the dev teams wanted an easy way to keep them up to date (and out of their hair).  We started w/ Excel backlogs and burndowns, toyed with 3rd party commercial software and ended up with a custom wiki/issue tracker implementation that works but is not very lightweight.  It really involves our internal TWiki, our custom bug tracker and several tools to integrate the two so they communicate properly (involving java, groovy, .NET, XML, etc.).  What we really needed and should have started with was some sort of task board (otherwise known as an <a href="http://c2.com/cgi-bin/wiki?InformationRadiator">information radiator</a>) to make sure we were following Scrum principles as opposed to just displaying data for the sake of technology.</p>
<p style="text-align: left;">Now, at <a href="http://www.onewhoserves.com">my current job</a>, we are implementing Scrum but only in spurts (one project at a time) and keeping technology out of the mix as much as possible (at first).  I really wanted to stay away from Excel and wikis and what not and use a task board.  The model I followed came from Henrik Kniberg's excellent paper called <a href="http://www.crisp.se/henrik.kniberg/ScrumAndXpFromTheTrenches.pdf">Scrum and XP from the Trenches</a>:</p>
<p style="text-align: left;"><a href="http://blog.realcoderscoding.com/wp-content/uploads/2008/09/hk.png"><img class="aligncenter size-medium wp-image-76" title="Task board from \&quot;Scrum and XP from the Trenches" src="http://blog.realcoderscoding.com/wp-content/uploads/2008/09/hk-300x197.png" alt="" width="300" height="197" /></a></p>
<p style="text-align: left;">My information radiator consists of two big, sticky pieces of <a href="http://www.3m.com/intl/ca/english/centres/office/postit/images/products/easel/subprod_wall.jpg">wall size Post-It paper</a>, index cards (w/ tape) to indicate major tasks and tons of yellow Post-It notes representing individual tasks.  I <a href="http://incompetech.com/graphpaper/plain/">generate the grid</a> for the burndown chart online (set to a grid spacing of 2 lines per inch), print it out and tape it the task board.</p>
<p style="text-align: left;">This works for us so far.  The chickens can walk by and find out how we are doing in the current iteration and the dev team can easily see what specific tasks are left to do and who's doing what.  Eventually, we'll move to a more permanent surface (although the sticky paper and tape is working fine and hasn't failed me yet).  I doubt we'll go so far as actually using electrons to do the representin'.  I mean, c'mon, I'm only a software developer.  Geez, who's got time to write internal tools these days?</p>
<p style="text-align: left;">I came across a few other examples from various developers across the 'net and thought you'd be interested to see what your peers are working on:</p>
<div class="wp-caption aligncenter" style="width: 442px"><a href="http://www.lostechies.com/blogs/joe_ocampo/archive/2007/12/08/information-radiators-make-life-visible.aspx"><img src="http://www.lostechies.com/blogs/joe_ocampo/WindowsLiveWriter/InformationRadiatorsMakelifevisible_E7BD/Cheerleading%20006_thumb.jpg" alt="AgileJoe at LostTechies.com" width="432" height="325" /></a><p class="wp-caption-text">AgileJoe at LostTechies.com</p></div>
<div class="wp-caption aligncenter" style="width: 401px"><a href="http://www.mountaingoatsoftware.com/taskboard.php"><img title="Many examples at mountaingoatsoftware.com" src="http://www.mountaingoatsoftware.com/system/hidden_asset/file/32/LabelledTaskBoard_small.jpg" alt="" width="391" height="292" /></a><p class="wp-caption-text">Many examples at mountaingoatsoftware.com</p></div>
<div class="wp-caption aligncenter" style="width: 650px"><a href="http://blog.xebia.com/2007/10/18/sharing-your-task-board-across-the-globe/"><img title="No so low tech version from Serge Beaumont" src="http://blog.xebia.com/wp-content/uploads/2007/10/Desktop%20Task%20Board%20640x400.png" alt="No so low tech version from Serge Beaumont" width="640" height="400" /></a><p class="wp-caption-text">Not so low tech version from Serge Beaumont</p></div>
<div class="wp-caption aligncenter" style="width: 586px"><a href="http://www.agilecoaching.dk/images/ScrumTaskBoard.jpg"><img title="From AgileCoaching.dk" src="http://www.agilecoaching.dk/images/ScrumTaskBoard.jpg" alt="From AgileCoaching.dk" width="576" height="432" /></a><p class="wp-caption-text">From AgileCoaching.dk</p></div>
<div class="wp-caption aligncenter" style="width: 488px"><a href="http://agiletools.wordpress.com/2007/11/24/task-boards-telling-a-compelling-agile-story/"><img title="Who says you need a wall when a window works fine" src="http://agiletools.files.wordpress.com/2007/11/brentsmind.jpg" alt="Who says you need a wall when a window works fine" width="478" height="355" /></a><p class="wp-caption-text">Who says you need a wall when a window works fine</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.realcoderscoding.com/index.php/2008/09/spreading-the-word-w-information-radiators/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
