<?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>CodeToast</title>
	<atom:link href="http://codetoast.com/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://codetoast.com/blog</link>
	<description>Free software, programming revelations, musings, and caffeine powered rants.</description>
	<pubDate>Tue, 09 Dec 2008 02:51:02 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>OpenVideoPlayer for Silverlight and Flash</title>
		<link>http://codetoast.com/blog/archives/58</link>
		<comments>http://codetoast.com/blog/archives/58#comments</comments>
		<pubDate>Tue, 09 Dec 2008 02:51:02 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Applications]]></category>

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

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

		<guid isPermaLink="false">http://codetoast.com/blog/?p=58</guid>
		<description><![CDATA[

code {
-border: solid 1px blue;
-font-size:1.2em;    margin: 0px;
font-weight: normal;    padding:0px;
b-ackground-color: #dddddd;
 color: #000000}.style1 {color: #009933;}.style2 {}.style5 {	color: #009933;	font-size: small;}
.style6 {font-size: small;}.style7 {font-size: small;}
.style8 {color: #009933;font-size: medium;}.style9 {color: #009933;}
.style10 {background-color: #EBEBE0;}


  I&#8217;ve been working full-time with a new open source project, OpenVideoPlayer, available at http://sourceforge.com/projects/openvideoplayer  OVP is a cross-platform/technology [...]]]></description>
			<content:encoded><![CDATA[<p><head></p>
<style type="text/css">
code {
-border: solid 1px blue;
-font-size:1.2em;    margin: 0px;
font-weight: normal;    padding:0px;
b-ackground-color: #dddddd;
 color: #000000}.style1 {color: #009933;}.style2 {}.style5 {	color: #009933;	font-size: small;}
.style6 {font-size: small;}.style7 {font-size: small;}
.style8 {color: #009933;font-size: medium;}.style9 {color: #009933;}
.style10 {background-color: #EBEBE0;}
</style>
<p></head></p>
<p><span class="style6"><!-- google_ad_section_start --> <a target=_blank href='http://openvideoplayer.sourceforge.net/ovpsl/preview.html?tag=%3Cobject%20data%3D%22data%3Aapplication/x-silverlight-2%2C%22%20type%3D%22application/x-silverlight-2%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20id%3D%22slp%22%20%3E%0A%3Cparam%20name%3D%22source%22%20value%3D%22OVP.xap%22/%3E%3Cparam%20name%3D%22minRuntimeVersion%22%20value%3D%222.0.30923.0%22%20/%3E%3Cparam%20name%3D%22onerror%22%20value%3D%22onSilverlightError%22%20/%3E%3Cparam%20name%3D%22MaxFrameRate%22%20value%3D%2230%22%20/%3E%0A%3Cparam%20name%3D%22initparams%22%20value%3D%27showstats%3Dfalse%2C%20autoplay%3Dtrue%2C%20muted%3Dfalse%2C%20playlistoverlay%3Dtrue%2C%20stretchmode%3DFit%2C%20playlistsource%3Dadaptive-playlist.xml%27%20/%3E%0A%3Ca%20href%3D%22http%3A//go.microsoft.com/fwlink/%3FLinkID%3D124807%22%20style%3D%22text-decoration%3A%20none%3B%22%3E%3Cimg%20src%3D%22http%3A//go.microsoft.com/fwlink/%3FLinkId%3D108181%22%20alt%3D%22Get%20Microsoft%20Silverlight%22%20style%3D%22border-style%3A%20none%22/%3E%3C/a%3E%3C/object%3E'><img style="float:right; padding:10px 10px 20px 10px; " border=0 src='http://sourceforge.net/dbimage.php?id=194833' title='OpenVideoPlayer in Action' width=220 height=210 class='alignnone' /></a> I&#8217;ve been working full-time with a new open source project, OpenVideoPlayer, available at <a href='http://sourceforge.com/projects/openvideoplayer' >http://sourceforge.com/projects/openvideoplayer</a>  OVP is a cross-platform/technology web video player, with versions in both Flash and Silverlight.  The project is sponsored by Akamai, Microsoft, Adobe, and others.  The aim is to provide a good starting point for websites that need built-in players.  We just released version 2.0 of the Silverlight player last Friday and it&#8217;s turned out to be quite a capable solution.  The OVP started life as a media framework that Akamai provided to customers to make for an easier integration with their network.  It was licensed as OSS for the 2.0 release in order to expand the community and involve other media companies and consumers.<span id="more-58"></span></p>
<p>&nbsp;</p>
<p>It currently supports direct media links and standard playlist types, as well as MediaRSS feeds for consuming content from Content Delivery Networks like Akamai.  We also created the technology behind SmoothHD.com, an adaptive streaming method that adapts Hi-Def content dynamically to play smoothly on nearly any system without buffering, regardless of bandwidth and hardware (within reason).  The technology is currently a Microsoft and Akamai exclusive, and works with plug-ins for our player and on the server side with IIS 7.0.  OpenVideoPlayer has a configuration page that generates the object tag for you, including parameters for the input source and visual settings. <a target=_blank href='http://openvideoplayer.sourceforge.net/ovpsl/' ><img style="float:left; padding: 22px 14px 10px 0px; " border=0 src='http://sourceforge.net/dbimage.php?id=194857' title='OVP Configuration Tool' width=250 height=220 /></a></p>
<p>&nbsp;</p>
<p>If anyone has a need for a solid player in Flash or Silverlight versions, I encourage you to check it out and provide feedback on features you would like to see in the future.  Upcoming features will include theming and easy re-styling, plug-ins for ad networks, and support for closed captioning.  Theming is important to us, so OVP can be adapted to various sites and situations without significant changes to the core player classes.  This way future revisions are much easier to roll out to customized installations.  The next task at hand is updating SmoothHD.com to the latest player, and developing the theming system as I go.  At that point I&#8217;ll some more in-depth posts about the guts of OVP.  Cheers!</p>
<p> <!-- google_ad_section_end --><br />
<img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/58/feed</wfw:commentRss>
		</item>
		<item>
		<title>Towards cleaner code, a C# Async. Helper for GUI (Pt 3 of 3)</title>
		<link>http://codetoast.com/blog/archives/51</link>
		<comments>http://codetoast.com/blog/archives/51#comments</comments>
		<pubDate>Sat, 27 Sep 2008 19:22:01 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Samples]]></category>

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

		<guid isPermaLink="false">http://codetoast.com/blog/?p=51</guid>
		<description><![CDATA[

code {
-border: solid 1px blue;
-font-size:1.2em;
     margin: 0px;
font-weight: normal;
     padding:0px;
b-ackground-color: #dddddd;
     color: #000000}
.style1 {
	color: #009933;
}
.style2 {
}
.style5 {
	color: #009933;
	font-size: small;
}
.style6 {
	font-size: small;
}
.style7 {
	font-size: small;
}
.style8 {
	color: #009933;
	font-size: medium;
}
.style9 {
	color: #009933;
}
.style10 {
	background-color: #EBEBE0;
}


// Threading and User Interfaces

When doing GUI development on Windows you must very careful what [...]]]></description>
			<content:encoded><![CDATA[<p><head></p>
<style type="text/css">
code {
-border: solid 1px blue;
-font-size:1.2em;
     margin: 0px;
font-weight: normal;
     padding:0px;
b-ackground-color: #dddddd;
     color: #000000}
.style1 {
	color: #009933;
}
.style2 {
}
.style5 {
	color: #009933;
	font-size: small;
}
.style6 {
	font-size: small;
}
.style7 {
	font-size: small;
}
.style8 {
	color: #009933;
	font-size: medium;
}
.style9 {
	color: #009933;
}
.style10 {
	background-color: #EBEBE0;
}
</style>
<p></head></p>
<p><span class="style8"><strong>// Threading and User Interfaces</strong></span><br />
<span class="style6"><!-- google_ad_section_start --><br />
When doing GUI development on Windows you must very careful what thread you access a form or control from.  Hopefully most Windows Forms developers know this by now, but in the early versions of the framework it could be a sneaky issue.  As of .NET 2.0 they were kind enough to immediately cause an exception when a control was accessed from the wrong thread - forcing you to deal with it now instead of trying to figure out why you randomly get exceptions like this 6 weeks after deploying your application: <img src="http://codetoast.com/blog/wp-content/uploads/c-error.png" alt="" title="This error still gives me nightmares." border=0 class="alignnone size-medium wp-image-44" style="float:left; margin: 25px 12px 8px 0px;"/><br />
<br />
I wont delve much in to why this is necessary, there are plenty of explanations on the subject.  The short story is that in .NET there is still a message loop that is running on the thread your form was run from, access from any other thread just isn&#8217;t thread-safe - you can&#8217;t use locking because it would block the user interface.<br />   So let&#8217;s append the Async helper static class that we worked on in parts <a href="/blog/archives/45">1</a> and <a href="/blog/archives/46">2</a>, giving it the ability to schedule tasks on the UI thread.  This will go even further towards making an app cleaner and more maintainable.<br />
<br />
UPDATE: This post is now an article on <a href="http://www.codeproject.com/KB/threads/CSharpAsynchronousHelper2.aspx" target=_blank>CodeProject</a>.<br />
<span id="more-51"></span><br />
</span></p>
<p>&nbsp;</p>
<p><span class="style8"><strong>// The old way of doing things.</strong></span><br />
<br />
<span class="style6">Let&#8217;s say we want to update a <code>TextBox </code>in our application.  Following with tradition I&#8217;ll show a few conventional ways to accomplish this, and then how we can do better.  Here is what we are trying to do:</p>
<p>&nbsp;</p>
<p></span></p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
private void UpdateText(string myString){
    textBox1.Text = myString;
}
</code></pre>
</div>
<p>&nbsp;</p>
<p>Simple as can be.  Problem is when we want to run it from anywhere in our code.  One way is to check if an invoke is required each time we run it.  In this case I&#8217;m again using anonymous methods to keep things as clean as possible.</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
<span style="color:green">// ... //</span>

<span style="color:green">// ask the control if we are on its UI thread</span>
if(textBox1.InvokeRequired){
   <span style="color:green">//we are not, so an invoke is required.</span>
   textBox1.Invoke(delegate{UpdateText("This is text");});
}else{
   <span style="color:green">//we are on the UI thread, we can directly modify the control</span>
   UpdateText("This is text");
}

<span style="color:green">// ... //</span></code></pre>
</div>
<p>&nbsp;</p>
<p>A safer way is to build the invoke into the method itself.  Note that this time I am using <code>BeginInvoke</code>, same concept but it does not block - it runs the task asynchronously.</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
private void SafeUpdateText(string myString){
    if(textBox1.InvokeRequired){
       <span style="color:green">//Invoke into this same method, but this time on the correct thread.</span>
       textBox1.BeginInvoke(delegate{UpdateText(myString);});
	 return; <span style="color:green">//important, so we don't fall through</span>
    }
    <span style="color:green">//this only runs if the above check says an invoke is not required.</span>
    textBox1.Text = myString;
}
</code></pre>
</div>
<p>&nbsp;</p>
<p>Hopefully that isn&#8217;t too confusing.  If the <code>Invoke </code>is required we invoke our own method recursively, knowing that it will be on the right thread on the next time through.  This isn&#8217;t too bad, but it can be a serious pain to make a method for every operation you need to do - once again its more things to remember and maintain, and more bloat for larger applications.<br />
</span><br />
<span class="style8"><strong>// The new method: Async.UI(&#8230;);</strong></span><br />
<span class="style6"><br />So know let&#8217;s fix up our <code>Async </code>class to make this whole process easier.  I decided to make a separate method for this, &#8216;<code>Do()</code>&#8216; had enough overloads as it was and I wanted it to be very clear at a glance whether the task was UI related.<br />
<br />
I&#8217;ll start with usage.  Instead of all of the above, we can now do this:</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
<span style="color:green">//Method prototype: public static AsyncRes UI(Dlg d, Control c, bool asynchronous);</span>
Async.UI(delegate { textBox1.Text = "This is way easier!"; }, textBox1, true);</code></pre>
</div>
<p>&nbsp;</p>
<p>Once again, something that might have needed a separate method and 5 to 10 lines of code, can know be distilled into a quick single method that takes care of the details for us.  Let&#8217;s check see what those arguments are.</p>
<p>&nbsp;</p>
<p>Our first argument is a <code>delegate</code>, same as we&#8217;ve done before - it can be an actual delegate instance, an anonymous method as above, or even a method without a parameter which .NET will silently wrap into a delegate.<br />
<br />
The second parameter is the <code>Control </code>we&#8217;d like to invoke with.  It can be the control you are accessing, our any of it&#8217;s parent controls/forms.  Of course in the method you pass, you can modify as many controls as you like, provided they are all from the same form / UI thread.<br />
<br />
Third is a <code>bool </code>that if true, tells the method to use <code>BeginInvoke </code>to make the call non-blocking.  Otherwise the caller will block while the UI thread finds time to run your task.<br />
</span><br />
<span class="style8"><strong>// I, for one, welcome our new UI method overloads.</strong></span><br />
<span class="style6"><br />
We have three more overloads with more and more options, first here are the prototypes:</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
<span style="color:green">// This re-introduces our ReentraceMode option, for thread safety and more control.</span>
public static AsyncRes UI(Dlg d, Control c, bool async, ReenteranceMode rMode) 

<span style="color:green">// Now with the ability to grab a return value for you</span>
public static AsyncRes UI(DlgR d, bool getRetVal, Control c, bool async);

<span style="color:green">// Pass a state object that is returned on an EndInvoke</span>
public static AsyncRes UI(Dlg d, Control c, object state, bool async, ReenteranceMode rMode);

<span style="color:green">// And the last one, with all of the above.</span>
public static AsyncRes UI(DlgR d, bool getRetVal, Control c, object state,
   bool async, ReenteranceMode rMode);</code></pre>
</div>
<p>&nbsp;</p>
<p>Got all that?  It should all be pretty straight-forward.  Now I&#8217;ll demonstrate using the last one with a return value.</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
<span style="color:green">// ... //</span>

AsyncRes result = Async.UI(
	<span style="color:green">//make sure the delegate/method returns a value:</span>
	delegate { return textBox1.Text; },
	true, <span style="color:green">//yes, we want to get the return value</span>
	myForm, <span style="color:green">//the control to invoke on</span>
	null, <span style="color:green">//the state object, we don't need to track anything.</span>
	true, <span style="color:green">//invoke asynchronously?</span>
	ReenteranceMode.Allow); //don't worry about thread safety in this case.</span>

<span style="color:green">// .... do other things ... //</span>

<span style="color:green">// now make sure the task above has completed.. </span>
result.AsyncWaitHandle.WaitOne();

<span style="color:green">//and use the value</span>
Console.WriteLine("The textbox says: " + result.ReturnValue);

<span style="color:green">// ... //</span></code></pre>
</div>
<p>&nbsp;</p>
<p>That&#8217;s about as complicated as it gets now; even the most advanced usage of the new class is simpler than invoking the most basic UI tasks without it.  The call to <code>WaitOne </code>is only needed because we chose to invoke asynchronously - we need to make sure it has completed or our value might be null.  If we had passed a false to the <code>async </code>parameter the call would have blocked and the value would immediately be guaranteed to be there.  </p>
<p>&nbsp;</p>
<p></span><br />
<span class="style8"><strong>// The code that makes it happen.</strong></span><br />
<br />
This functionality has been added to the same <code>Async </code>class we&#8217;ve already been working with, and it makes use of much of the same code: all of our <code>UI </code>methods simply call the <code>Do </code>method internally, which has been expanded slightly.  Here is the new signature of the <code>Do </code>method, along with a new blurb for handling UI:</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
<span style="color:green">// The private master Do method now also takes a control.</span>
private static AsyncRes Do(DlgR dr, Dlg d, bool getRetVal, object state,
   bool tryThreadPool, ReenteranceMode rMode, Control control, bool async) {

<span style="color:green">// .. In the first part we still set up our delegate the same way as before //</span>

if(control!=null) {
	res.control = control;
	res.result = AsyncAction.ControlInvoked;
	if (!async) {
		if (!control.InvokeRequired) {
			res.completedSynchronously = true;
			dlg();
		} else {
			control.Invoke(dlg);
		}
	}else {
		control.BeginInvoke(dlg);
	}
	return res;
} <span style="color:green">
// don't catch any errors; if this fails
// we don't want it to continue below and get invoked in some other way

// .. the rest of the method, where we use thread or the threadpool
// .. only happens if the control was null, meaningth ecall was not UI related.</span></code></pre>
</div>
<p>&nbsp;</p>
<p>We were able to add quite a bit of functionality to this handy class, with only a few lines of code!  The only other change is adding all of the <code>UI </code>overloads, each one simply calls <code>Do </code>with various parameters:</p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
public static AsyncRes UI(Dlg d, Control c, bool async) {
	return Do(null, d, false, null, false, ReenteranceMode.Allow, c, async);
}

public static AsyncRes UI(DlgR d, bool getRetVal, Control c, object state,
  bool async, ReenteranceMode rMode) {
	return Do(d, null, getRetVal, state, false, rMode, c, async);
}

<span style="color:green">// .. and so on .. //</span></code></pre>
</div>
<p>&nbsp;</p>
<p>That&#8217;s all there is to it.  Of course now we have some updated source code to share with you.  <a href="/blog/wp-content/uploads/async-with-gui.zip">The new zip file</a> is the source in a VS2005 project, and <a href="/blog/wp-content/uploads/async2.cs">the Async2.cs file</a> has the entire source code for the previous posts, along with these new updates; now up to a 400 lines.<br />
<br />
Again, let me know if you have any problems, comments, suggestions, questions, compliments, or threats of bodily harm - I&#8217;ll take them in stride.<br />
<br />
<em><span class="style6"><font size=small>*Coming in future posts of this series: Expanding this async concept into timers for recurring tasks, a handy stop watch, a throttling utility, and configuration file handling.</font></span></em><br />
<!-- google_ad_section_end --><br />
<img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/51/feed</wfw:commentRss>
		</item>
		<item>
		<title>Towards cleaner code, a C# Asynchronous Helper (Pt 2 of 3)</title>
		<link>http://codetoast.com/blog/archives/46</link>
		<comments>http://codetoast.com/blog/archives/46#comments</comments>
		<pubDate>Wed, 24 Sep 2008 20:43:49 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Samples]]></category>

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

		<guid isPermaLink="false">http://codetoast.com/blog/?p=46</guid>
		<description><![CDATA[

code {
-border: solid 1px blue;
-font-size:1.2em;
     margin: 10px;
font-weight: normal;
     padding:10px;
b-ackground-color: #dddddd;
     color: #000000}
.style1 {
	color: #009933;
}
.style2 {
}
.style5 {
	color: #009933;
	font-size: small;
}
.style6 {
	font-size: small;
}
.style7 {
	font-size: small;
}
.style8 {
	color: #009933;
	font-size: medium;
}
.style9 {
	color: #009933;
}
.style10 {
	background-color: #EBEBE0;
}


// The Code.

When we last were together, I spent entirely too long explaining the wrong [...]]]></description>
			<content:encoded><![CDATA[<p><head></p>
<style type="text/css">
code {
-border: solid 1px blue;
-font-size:1.2em;
     margin: 10px;
font-weight: normal;
     padding:10px;
b-ackground-color: #dddddd;
     color: #000000}
.style1 {
	color: #009933;
}
.style2 {
}
.style5 {
	color: #009933;
	font-size: small;
}
.style6 {
	font-size: small;
}
.style7 {
	font-size: small;
}
.style8 {
	color: #009933;
	font-size: medium;
}
.style9 {
	color: #009933;
}
.style10 {
	background-color: #EBEBE0;
}
</style>
<p></head></p>
<p><span class="style8"><strong>// The Code.</strong></span><br />
<span class="style6"><!-- google_ad_section_start --><br />
When we <a href="/blog/archives/45">last were together</a>, I spent entirely too long explaining the wrong and/or hard ways to start a quick asynchronous task in C#, and only gave a quick taste of what was to come with the Async helper class.  This time I&#8217;ve got the source to back me up.<br />
<br />
UPDATE: The first part of this series is now an article on <a href="http://www.codeproject.com/KB/threads/CSharpAsynchronousHelper.aspx" target=_blank>CodeProject</a>.  Check it out and give it a vote for me.<br />
</span></p>
<p>&nbsp;</p>
<p><span class="style8"><strong>// The main method: Async.Do(&#8230;);</strong></span><br />
<span class="style6"><br />Our Do() method is where most of the magic happens, although it is only 60 lines with generous comments.  Sharp observers will notice a couple odd things: it is private, and it takes two different delegate parameters.  There are several overloads, these in turn call this method passing one or the other delegate, depending on whether we need a return value. This cleans the caller&#8217;s code greatly.
<p>&nbsp;</p>
<p> Making one method that does the work keeps the important logic (and troubleshooting) in one place, but it is private as to not confuse the caller as to which delegate to use.<span id="more-46"></span>
<p>&nbsp;</p>
<p></span>
<div style="width:640px;border-style:solid; border: black 1px solid; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
<span style="color:black">private static AsyncRes Do(DlgR dr, Dlg d, bool getRetVal, object state,
bool tryThreadPool, ReenteranceMode rMode) {</span>
	<span style="color:green">//get a generic MethodInfo for checks..</span>
	MethodInfo mi = ((dr != null) ? dr.Method : d.Method);
	<span style="color:green">//make a unique key for output usage</span>
	string key = string.Format("{0}{1}{2}{3}", ((getRetVal) ? "&lt;-" : ""),
		mi.DeclaringType, ((mi.IsStatic) ? ":" : "."), mi.Name);
	<span style="color:green">//our custom return value, holds our delegate, state, key, etc.</span>
	AsyncRes res = new AsyncRes(state, ((dr != null) ?
		(Delegate)dr : (Delegate)d), key, rMode);

	<span style="color:green">//Create a delegate wrapper for what we will actually invoke..</span>
	Dlg dlg = (Dlg)delegate {
		<span style="color:green">//checks for reentrance issues and sets us up</span>
		if (!BeforeInvoke(res)) return;
		try {
			if (res.IsCompleted) return;
			if (dr != null) {
				res.retVal = dr();<span style="color:green">//use this one with a return</span>
			} else {
				d();<span style="color:green">//otherwise the simpler dlg</span>
			}&lt;br /&gt;
		<span style="color:green">//we never want a rogue exception, it can't bubble up anywhere</span>
		} catch (Exception ex) {
			Console.WriteLine("Async Exception:" + ex);
		} finally {
			<span style="color:green">//this will fire their callback and clean up</span>
			FinishInvoke(res);
		}
	};

	<span style="color:green">//...//</span>

		</code></pre>
</div>
<p><!--EndFragment--><br />
		<span class="style6">So far we have obtained a MethodInfo object that gives more detail about the delegate we will be executing, created an instance of the AsyncResult custom class that will be returned to the caller for tracking, and then wrapped their delegate into another anonymous method/delegate that can be bandied about as needed.  This wrapper also injects method calls for before and after the invoke, these help with locking for our reentrance as well as setting some properties on the result object.
<p>&nbsp;</p>
<p>Don&#8217;t worry, the overhead of this extra indirection of this wrapper method is remarkable small (I benchmarked it) unless you are talking thousands of tasks executing per second.  If that is the case then you need to rethink your architecture.  Now for the rest of our Do() method:<br />
		</span>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid ;background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre>	<code> 

	if (tryThreadPool) { <span style="color:green">//we are going to use the .NET threadpool</span>
		try {
			<span style="color:green">//get some stats - much better than silently failing </span>
			<span style="color:green">//or throwing an expensive exception</span>
			int minThr, minIO, threads, ioThr, totalThr, totalIO;
			ThreadPool.GetMinThreads(out minThr, out minIO);
			ThreadPool.GetAvailableThreads(out threads, out ioThr);
			ThreadPool.GetMaxThreads(out totalThreads, out totalIO);

			<span style="color:green">//check for at least our thread + one more in ThreadPool</span>
			if (threads &gt; minThreads) {
				<span style="color:green">//this is what actually fires this task off..</span>
				bool result = ThreadPool.QueueUserWorkItem(
					(WaitCallback)delegate { dlg(); });
				if (result) {
					res.result = AsyncAction.ThreadPool;
					<span style="color:green">//this means success in queueing the item</span>
					return res;
				} else {
					<span style="color:green">//according to docs, this "won't ever happen" </span>
					<span style="color:green">// but an exception instead.. who knows.</span>
					Console.WriteLine( "Failed to queue in threadpool." +
						"Method: " + key);
				}
			} else {
				Console.WriteLine(String.Format(
					"Insufficient idle threadpool threads: {0}of{1}-min {2},
					Method: {3}", threads, totalThreads, minThreads, key));
			}
		} catch (Exception ex) {
			Console.WriteLine("Failed to queue in threadpool: " + ex.Message +
				"- Method: " + key);
		}
	}

	<span style="color:green">//if we got this far, then something failed, or they wanted a dedicated thread</span>
	Thread t = new Thread((ThreadStart)delegate { dlg(); });
	t.IsBackground = true; <span style="color:green">//this &amp; priority are candidates for additional settings</span>
	t.Name = "Async_" + key;
	res.result = AsyncAction.Thread;
	t.Start();

	return res;
}
		</code></pre>
</div>
<p><!--EndFragment--></p>
<p class="style2"><span class="style6"><br />
In the latter part of our method we check some threadpool stats to see if it is worth even trying to use it.  If all is good, we queue up the delegate and we&#8217;re done.  If it is out of threads or the user chose a dedicated thread, then we skip that hullabaloo and just make our own thread to run.</p>
<p>&nbsp;</p>
<p><span class="style8"><strong>// Before and After methods</strong></span><br />
<span class="style6"><br />Injected into our wrapper delegate we have a BeforeInvoke and FinishInvoke.  There are a few important concepts there so let&#8217;s check them out quickly.</span></p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid ; background-color: #dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
private static bool BeforeInvoke(AsyncRes res) {
	<span style="color:green">//if marked as completed then we abort.</span>
	if (res.IsCompleted) return false;
	<span style="color:green">//if mode is 'allow' there is nothing to check.  Otherwise...</span>
	if (res.RMode != ReenteranceMode.Allow) {
		<span style="color:green">//be threadsafe with our one and only member field</span>
		lock (methodLocks) {
			if (!methodLocks.ContainsKey(res.Method)) {
				<span style="color:green">// make sure we have a generic locking object in the coll. </span>
				<span style="color:green">// it will already be there if we are reentering</span>
				methodLocks.Add(res.Method, new object());
			}
			<span style="color:green">//if bypass mode and we can't get or lock, we dump out.</span>
			if (res.RMode == ReenteranceMode.Bypass) {
				if (!Monitor.TryEnter(methodLocks[res.Method])) {
					res.result = AsyncAction.Reenterant;
					return false;
				}
			} else {
				<span style="color:green">//Otherwise in 'stack' mode, </span>
				<span style="color:green">//we just wait until someone else releases it...</span>
				Monitor.Enter(methodLocks[res.Method]);
			}
			<span style="color:green">//if we are here, all is good.  </span>
			<span style="color:green">//Set some properties on the result class to show when </span>
			<span style="color:green">//and what thread we are on</span>
			res.isStarted = true;
			res.startTime = DateTime.Now;
			res.thread = Thread.CurrentThread;
		}
	}

	return true;
}</code></pre>
</div>
<p><span class="style6"><br />
Here we look for &#8217;stack&#8217; or &#8216;bypass&#8217; modes which require locking, allow mode can just play on though.  We first look for a locking object in our methodLocks collection, keyed by our delegate&#8217;s fully qualified method name.  The lock object is unimportant, just something that can be synchronized against - I chose not to use any existing objects because the caller might have access to them - which could cause problems if they also decided to lock on them.
<p>&nbsp;</p>
<p>Once we have our lock we Monitor.TryEnter (and fail otherwise) in &#8216;bypass&#8217; mode, or just Monitor.Enter the lock and wait forever for it to free in &#8217;stack&#8217; mode.
<p>&nbsp;</p>
<p> That collection is the only thing we keep track of at a class level - everything else cleans up itself.  Now for our FinishInvoke:<br />
</span></p>
<p>&nbsp;</p>
<div style="width:640px;border-style:solid; border: black 1px solid ; background-color: #dddddd; padding: 10px 10px 10px 10px;">
<pre><code>
private static void FinishInvoke(AsyncRes res) {
	if (res == null) return;
	try {
		<span style="color:green">//finish a few more properties</span>
		res.isCompleted = true;
		res.completeTime = DateTime.Now;
		<span style="color:green">// set the resetevent, in case someone is using the handle to </span>
		<span style="color:green">// know when we've completed.</span>
		res.mre.Set();
	} catch (Exception ex) {
		Console.WriteLine("Error setting wait handle on " +
			(res.Method ?? "NULL") + ex);
	}

	if (res.RMode != ReenteranceMode.Allow) {
		<span style="color:green">//if mode is bypass or stack, then a lock that needs releasing</span>
		try {
			if (methodLocks.ContainsKey(res.Method)) {
				Monitor.Exit(methodLocks[res.Method]);
			}
		} catch (Exception ex) {
			Console.WriteLine("Error releasing lock on " +
				(res.Method ?? "NULL")+ ex);
		}
	}
}</code></pre>
</div>
<p><span class="style6"><br />
In FinishInvoke we set a few more properties, including a ManualResetEvent that can be used by the caller to wait on this task&#8217;s completion.  Then we release our lock to allow other instances of this task to proceed.
<p>&nbsp;</p>
<p>The overloads and AsyncResult class are about all that is left in the code, and they aren&#8217;t especially groundbreaking, so I&#8217;ll leave it to you to check them out.  <a href="/blog/wp-content/uploads/async.zip">This zip file</a> has a VS2005 project that I used to make sure this compiled by itself, and <a href="/blog/wp-content/uploads/async.cs">this Async.cs file</a> has the entire source code, a little over 300 lines with lots of comments.
<p>&nbsp;</p>
<p><b>UPDATE:</b> <a href="/blog/archives/51">Part three</a> of the series expands on this class, before downloading the code you may want to read the next part and get the source there with added UI functionality.
<p>&nbsp;</p>
<p>Later on I may post some interesting uses for this, as well as some expanded functionality that I&#8217;ve already been using.  I hope this can be as useful to you as it has for me - use it in good health, and don&#8217;t hesitate to post questions, comments, or suggestions.<br />
</span></p>
<p>&nbsp;</p>
<p><em><span class="style6"><font size=small>*Coming in future posts of this series: Async tasks in a Windows Forms GUI environment (<a href="/blog/archive/47">Part 3</a>), expanding this async concept into timers for recurring tasks, a handy stop watch, and configuration file handling.</font></span></em><br />
<!-- google_ad_section_end --><br />
<br/><img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/46/feed</wfw:commentRss>
		</item>
		<item>
		<title>Towards cleaner code, a C# Asynchronous Helper (Pt 1 of 3)</title>
		<link>http://codetoast.com/blog/archives/45</link>
		<comments>http://codetoast.com/blog/archives/45#comments</comments>
		<pubDate>Wed, 17 Sep 2008 21:35:50 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Samples]]></category>

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

		<guid isPermaLink="false">http://codetoast.com/blog/?p=45</guid>
		<description><![CDATA[

code {
-border: solid 1px blue;
-font-size:1.2em;
     margin: 10px;
font-weight: bold;
     padding:10px;
b-ackground-color: #dddddd;
     -color: #086060}
.style1 {
	color: #009933;
}
.style2 {
}
.style5 {
	color: #009933;
	font-size: small;
}
.style6 {
	font-size: small;
}
.style7 {
	font-size: small;
}
.style8 {
	color: #009933;
	font-size: medium;
}
.style9 {
	color: #009933;
}
.style10 {
	background-color: #EBEBE0;
}


// Series Introduction
I&#8217;m a sucker for clean and beautifully groomed code. In my experience maintaining [...]]]></description>
			<content:encoded><![CDATA[<p><head></p>
<style type="text/css">
code {
-border: solid 1px blue;
-font-size:1.2em;
     margin: 10px;
font-weight: bold;
     padding:10px;
b-ackground-color: #dddddd;
     -color: #086060}
.style1 {
	color: #009933;
}
.style2 {
}
.style5 {
	color: #009933;
	font-size: small;
}
.style6 {
	font-size: small;
}
.style7 {
	font-size: small;
}
.style8 {
	color: #009933;
	font-size: medium;
}
.style9 {
	color: #009933;
}
.style10 {
	background-color: #EBEBE0;
}
</style>
<p></head></p>
<p><span class="style8"><strong>// Series Introduction</strong></span><span class="style2"><br />
<span class="style6"><br /><!-- google_ad_section_start -->I&#8217;m a sucker for clean and beautifully groomed code. In my experience maintaining a large code base with few resources, it is in fact the only way to keep sanity and keep from sliding into a pit of spaghetti.  I&#8217;ve been on a push to find areas of necessarily messy or repeated code and find ways to make them more elegant and maintainable - this is the first in a series* of small classes and helpers that I kick myself for not doing sooner.<br />
<br />
UPDATE: This post is now an article on <a href="http://www.codeproject.com/KB/threads/CSharpAsynchronousHelper.aspx" target=_blank>CodeProject</a>.<br />
</span></p>
<p>&nbsp;</p>
<p></span><span class="style8"><strong>// The Problem at Hand</strong></span><span class="style2"><br />
<span class="style6"><br />
In any reasonably large application there are a lot of times when you need to perform a quick task asynchronously. One use off-hand is application that saves a log or status report to file on start-up. The operation is slow in relative terms since it involves file I/O, and we don&#8217;t have to worry much about other code paths depending on it. Making it asynchronous will speed up our start time with no risk of side effects.<span id="more-45"></span><br />
</span></p>
<p>&nbsp;</p>
<p></span><span class="style8"><strong>// The Obvious and Ubiquitous Solutions</strong></span><span class="style2">
<p>&nbsp;</p>
<p><span class="style6">The .NET Framework makes this quite easy, we&#8217;ll show a few ways to accomplish it. However there are gotchas and keeping track of everything can lead to messier code, so I&#8217;ll introduce a helper class to make our lives easier.  Of course exception handling and such is excluded from these examples for brevity.
<p>&nbsp;</p>
<p></span><span class="style6"><strong>Example Method. </strong> Lets say we have a method as such that we need to run async:</span>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 private void SaveReport() {
      statusReport.Save(); <span class="style9">//This takes a bit of time</span>
      Console.WriteLine("Status report saved!");
 } </code></pre>
</div>
<p>&nbsp;</p>
<p> <!--EndFragment-->
<p class="style2"><span class="style6"><strong>1. Brute Force - </strong>create a new thread:</span></p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 ThreadStart ts = new ThreadStart(SaveReport);
 Thread t = new Thread(ts); &lt;br /&gt;
 t.IsBackground = true; &lt;br /&gt;
 t.Start();</code></pre>
</div>
<p>&nbsp;</p>
<p class="style2"><span class="style6">Besides the chattiness here, this is not the most efficient way to get this done, unless you have a pretty long running task.  For every action, a new thread with context and stack space will be created, just to be used for a short period.  More effective is to utilize the .NET ThreadPool, and let it reuse a few preallocated threads on your behalf. </p>
<p>&nbsp;</p>
<p></span><span class="style6"><strong>2. BeginInvoke.</strong> One way to use the ThreadPool in a round-about way is to make a delegate and begin invocation on it directly:</span></p>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 MethodInvoker dlg = new MethodInvoker(SaveReport);
 dlg.BeginInvoke(null, null); </code></pre>
</div>
<p>&nbsp;</p>
<p><!--EndFragment-->
<p class="style2"><span class="style6"><strong>3. Anonymous Method.</strong>  I&#8217;ll also note that in .NET 2.0 we can use an anonymous method, saving us from defining the method separately.  functionally this operates the same way as the previous.</span></p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 delegate {
	statusReport.Save();
	Console.WriteLine("Status report saved!");
 }.BeginInvoke(null, null);.</code></pre>
</div>
<p>&nbsp;</p>
<p class="style2"><span class="style6">There is a problem with both of these examples as well, besides their messiness. The BeginInvoke method takes two parameters, a AsyncCallback for notifying when the operation completes, and an object that is passed through to that callback for the callers purposes, typically the original delegate. Now creating a callback just adds more trouble to this whole exercise, particularly if you do not need to know exactly when the operation completes. However, although not documented well, I&#8217;ve seen issues if the callback is not used to call EndInvoke, as such:
<p>&nbsp;</p>
<p> </span><span class="style6"><strong>4. BeginInvoke with Callback.</strong>  Here we will use a BeginInvoke on the delegate with a callback to inform completion:</span></p>
<p>&nbsp;</p>
<div style="border-style:solid;  background-color:#dddddd;border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 private void ReportCompleted(IAsyncResult result) {
	if (!result.IsCompleted) return;
	MethodInvoker dlg = result.AsyncState as MethodInvoker;
	dlg.EndInvoke(result);
 }
<span class="style9"> //...//</span>
 AsyncCallback asc = new AsyncCallback(ReportCompleted);
 MethodInvoker dlg = new MethodInvoker(SaveReport);
 dlg.BeginInvoke(asc, dlg);</code></pre>
</div>
<p>&nbsp;</p>
<p class="style2"><span class="style6">No major issues now, but again - this gets very messy, especialy once you start creating a couple 5 line methods everywhere for each task.
<p>&nbsp;</p>
<p></span><span class="style6"><strong>5. ThreadPool.</strong>  Another way is to go straight after the ThreadPool:</span></p>
<p>&nbsp;</p>
<div style="border-style:solid; border: black 1px solid ; background-color:#dddddd;padding: 10px 10px 10px 10px;">
<pre><code>
 WaitCallback wc = new WaitCallback(SaveReport);
 ThreadPool.QueueUserWorkItem(wc);</code></pre>
</div>
<p>&nbsp;</p>
<p class="style2"><span class="style6">This is much more concise, but without the control over the process that we have in the above examples. A larger problem that I haven&#8217;t discussed is that any of these examples can fail spectacularly, or sometimes silently - any exceptions from your invoked methods will vanish into the ether. Once error handling (and logging, right?) is applied to both the action being performed, and the action of invoking it, and possibly to ending the invoke, we have a lot of code to just make a one-liner action happen safely asynchronous.
<p>&nbsp;</p>
<p>If this does fail, you may want to then attempt the action with a dedicated thread to make sure it works if the ThreadPool is not cooperating, that&#8217;s more code to bandy about.
<p>&nbsp;</p>
<p>A more subtle limitation I started to run into is the matter of reentrance. In the above example we are periodically saving a status report. What happens if it gets delayed? Its quite possible that the next time you invoke it the prior attempt is still in process, all kinds of mayhem could ensue. Now we need to add even more code for blocking and thread safety.
<p>&nbsp;</p>
<p>
</span><span class="style6"><strong>6. Thread-Safety: Blocking.</strong>  This time we will use a lock to make our method blocking, it could then be invoked in any of the above ways.</span></p>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 private readonly object reportLock = new object();

 private void SaveReport(){
	lock(reportLock){ <span class="style9">
		/* extra credit for why we didn't just lock our status report object! */</span>
		statusReport.Save();
		Console.WriteLine("Status report saved!"span&amp;gt;);
	}
 }</code></pre>
</div>
<p>&nbsp;</p>
<p class="style2"><span class="style6">Wait a second though - if one status report is a few minutes behind, we don&#8217;t need one to follow right on it&#8217;s tail.  We also want to avoid getting multiple ThreadPool threads stacked up on each other, preventing other tasks.  Let&#8217;s instead make this blocking into a bypass, and skip the next action if we get backed up:</p>
<p>&nbsp;</p>
<p></span><strong><span class="style6">7. Thread-Safety: Bypass.</span></strong><span class="style6"><br />
</span></p>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 private readonly object reportLock = new object(); 

 private void SaveReport() {
	if (!Monitor.TryEnter(reportLock)) return;<span class="style9">
	//if it is locked, just dump outta here..</span>
	try {
		statusReport.Save();
		Console.WriteLine("Status report saved!");
	} finally {
        	Monitor.Exit(reportLock);
	}
 }</code></pre>
</div>
<p class="style2"><span class="style6">If you aren&#8217;t familiar with this syntax, the C# lock statement is just a shortcut for using the Monitor.Enter and Monitor.Exit calls appropriately.  In this case we used the monitor class directly, with TryEnter so that it didn&#8217;t block forever.
<p>&nbsp;</p>
<p> So now we have at least seven different ways of skinning this cat, all with pros and cons. Every time you need to run a task asynchronously you must evaluate multiple options, worry about exceptions, copy and paste (ack!) more chunks of similar code around, and then maintain that code that clutters up the flow of your logic.
<p>&nbsp;</p>
<p></span><span class="style8"><strong>// A Better Way - The Async helper class.</strong></span><span class="style6">
<p>&nbsp;</p>
<p>What if we had some kind of magical helper class that had the power of any of the examples above, but was also incredibly concise? It would put all of this power in one place, so troubleshooting and changes and error handling and tweaks could be concentrated in one place. Come to think of it, such a class might even heal sick puppies! Here&#8217;s how we would use it:</span></p>
<p>&nbsp;</p>
<div style="background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 Async.Do(SaveReport);</code></pre>
</div>
<p>&nbsp;</p>
<p class="style7">What? How could it be that easy? Is this possible? Yes, all this can be yours, and more. .NET automatically takes any void method with no parameters and invisibly makes a delegate for it, which is how the above works by passing a method name, we can also pass delegates or anonymous methods. </p>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 Async.Do(delegate {
	Console.WriteLine("I'm in an anonymous delegate!");
	statusReport.Save();
 });</code></pre>
</div>
<p class="style7"><strong><span class="style8"><br />
// More advanced Async class examples</span><span class="style5"><br />
</span></strong><br />
With some overloading and fancy footwork, we can also do any of the following:</p>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
<span class="style9">/* this takes care of any of our locking and blocking and thread-safety woes. The ReentranceMode enumeration also has options for 'Stack' and 'Allow' */
</span>
 Async.Do(SaveReport, ReentranceMode.Bypass); </code></pre>
</div>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code> <span class="style9">
 /* The bool parameter 'useReturnValue' instructs the helper to track the return value of your delegate/method if you ask for it later from the IAsyncResult that is returned : */ </span>
 IAsyncResult result = Async.Do(SaveReport, true);
 <span class="style9">//do other stuff in meantime...
 // ...and if the action is not completed, wait for it to finish</span>
 if (!result.IsCompleted) result.AsyncWaitHandle.WaitOne();
 Console.WriteLine("My result was: " + result.ReturnValue);</code></pre>
</div>
<p>&nbsp;</p>
<div style="background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
 <span class="style9">/* Methods that take parameters can be wrapped in an anonymous method, the parameter will be psuedo-curryed for us by the framework. If the return value is important, we can also use a return inside the anonymous method! */
</span>
 Async.Do(delegate { return GetAnObject("A string parameter"); }); </code></pre>
</div>
<p>&nbsp;</p>
<div style=" background-color:#dddddd;border-style:solid; border: black 1px solid ;padding: 10px 10px 10px 10px;">
<pre><code>
<span class="style9"> /* our most advanced method signature has all of the options, as seen below */
</span>
 Async.Do(
	SaveReport, <span class="style9">//our delegate or method</span>
	false, <span class="style9">//track return value?</span>
	this, <span class="style9">// a state object to be tracked with the IAsyncResult</span>
	true,<span class="style9"> /* Use ThreadPool? true will attempt to use the threadpool, then fall back to a thread.
		False always uses a thread, for use with long-running tasks.*/</span>
	ReenteranceMode.Stack); <span class="style9">//our enum controlling how we handle multiple calls to the same action.</span> </code></pre>
</div>
<p class="style2"><span class="style6"><br />
So there it is, the best .NET Asynchronous helper class a geek could ask for.  All the power of any other methodology with none of the bloat and maintainability issues.  This class has greatly simplified code flow and literally cut thousands of lines of code from an large application.  I&#8217;ve taken long enough just explaining the need and usage of the class, I&#8217;m going to save the implementation (and source code) for <a href="/blog/archives/46">the next post</a>.
<p>&nbsp;</p>
<p>Check back soon for the thrilling conclusion, and let me know what you think!
<p>&nbsp;</p>
<p></span><em><span class="style6">*Coming in future posts of this series: The code that makes this example work (<a href="/blog/archives/46">Part 2</a>), Async tasks in a Windows Forms GUI environment(<a href="/blog/archives/51">Part 3</a>), expanding this async concept into timers for recurring tasks, a handy stop watch, and configuration file handling.</span></em></p>
<p><!-- google_ad_section_end --><br />
<br/><img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/45/feed</wfw:commentRss>
		</item>
		<item>
		<title>Malware sucks, Anti-Malware sucks nearly as bad.</title>
		<link>http://codetoast.com/blog/archives/40</link>
		<comments>http://codetoast.com/blog/archives/40#comments</comments>
		<pubDate>Tue, 12 Aug 2008 12:16:16 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[General]]></category>

		<category><![CDATA[Operating Systems]]></category>

		<guid isPermaLink="false">http://codetoast.com/blog/?p=40</guid>
		<description><![CDATA[As for what it sucks, that would be system performance.    It had been a long time since I&#8217;ve used Anti-Virus software on my Windows system, I hadn&#8217;t realized how bad the performance issue had gotten until I saw the benchmarks.  I&#8217;d had more trouble with the Anti-Virus software itself than it [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://codetoast.com/blog/wp-content/uploads/fluvirus-220x205.gif" alt="" title="I think this is a close-up of the Slammer worm.." width="220" height="205" class="alignnone size-medium wp-image-54" style="float:right;"/>As for what it sucks, that would be system performance.  <!-- google_ad_section_start -->  It had been a long time since I&#8217;ve used Anti-Virus software on my Windows system, I hadn&#8217;t realized how bad the performance issue had gotten until I saw the benchmarks.  I&#8217;d had more trouble with the Anti-Virus software itself than it could have possibly saved me, since well, it never found anything.<br />
<br />
Part of the problem is that for quite a while now Spyware has been much more of a problem than conventional viruses, but the big boys like Norton and MacAfee have been slow to adjust and pick this up.  Things are starting to change in that regard, but that leaves the issue of speed.  <span id="more-40"></span><br />
<br />As Jeff Atwood dramatically pointed out in <a href="http://www.codinghorror.com/blog/archives/000803.html" target="_blank" >Choosing Anti Anti-Virus Software</a>, AV is one of the most drastic speed reductions you possibly perform on your system.  If it were <em>only</em> CPU utilization then I really wouldn&#8217;t worry - I sprang for a quad-core and rarely get too much over 50% unless I have a lot of VM action going on - but unfortunately most of the hit is with Disk performance and  I/O latency.  This means my full build goes from 4 minutes to about 12 minutes.  Ouch.<br />
<br />
Now I&#8217;m quite aware that I&#8217;m not the typical end-user in this arena, so I&#8217;m certainly not advocating that everyone dumps their trusty AV / Anti-Spyware.  Unless it&#8217;s Norton - I hate to disparage, but wow that&#8217;s some awful stuff.  If you are one of us careful downloaders though and speed is of the essence, then I do have a recommendation.  <br/><br />
<strong>1. Install one of the free or inexpensive AV solutions.</strong>  <a href="http://lifehacker.com/395046/five-best-antivirus-applications" target="_blank"><br />
Lifehacker has a good list</a> to start with.  I&#8217;ve been using Avira for a while with good results, many people like AVG as well.  Of course this post is targeted towards Windows - ClamAV is the only choice for Linux.<br />
<br />
<strong>2. Ok, now disable it.</strong><br />
<a href='http://codetoast.com/blog/wp-content/uploads/sshot-44.png'><img src="http://codetoast.com/blog/wp-content/uploads/sshot-44-220x165.png" alt="" title="Scanning from Context Menu" width="220" height="165" class="alignnone size-medium wp-image-55" style="float:left; padding: 8px 10px 0px 0px" border=0 /></a><br />
Keep the updates scheduled, but turn off real-time protection.  Now you have a super easy way to spot check files that may be under suspicion.  Right-click any file you aren&#8217;t sure of, and choose &#8220;Scan for viruses&#8221; before trusting it.  You can also schedule a full scan to run at night a couple times a week - SETI will barely notice your decreased contribution.   There are free online scans, but I&#8217;ve found them to be cumbersome and slow for spot checking individual files - which means you&#8217;ll end up not using it reliably.<br />
<br />
Some AV apps allow filters on real-time protection - if that&#8217;s the case, make sure you have a folder only for downloads and set your browser to use it automatically.  Then add your temp folders and download folder to be scanned in real-time.  The temp folder is important so that opened email attachments and the like get scanned.<br />
<br />
I don&#8217;t personally worry as much about spyware, a high percentage of infections are caused by careless clicking or browsers that aren&#8217;t up to date.  If you don&#8217;t trust yourself in that regard, or your system is shared with others, then you may want to consider something there.  I also have the luxury of firewall and e-mail malware scanning at the server-level, while not perfect it is an extra layer.  Jeff also mentions using a Virtual Machine for sand-boxing untrusted apps.  I&#8217;ve thought of doing all my development in a VM, more on that to follow, but for now it isn&#8217;t feasible.  In the meantime this works well for scanning all those little utilities or driver updates or test apps that you shouldn&#8217;t implicitly trust.<br />
<br />
This isn&#8217;t exactly a ground-breaking revelation, but the bottom-line is if speed is a major factor, particularly for disk I/O, then this can make an enormous, noticeable difference - if you have the discipline to remember to scan potentially dangerous files.  You could have three 15k SAS drives in a crazy-fast RAID 0 and get worse performance than a single run-of-the-mill SATA drive at 5,400 RPM - just by installing a speed-sucking Anti-Malware package.<br />
<!-- google_ad_section_end --><br />
<img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/40/feed</wfw:commentRss>
		</item>
		<item>
		<title>Source Control for the unwashed masses</title>
		<link>http://codetoast.com/blog/archives/39</link>
		<comments>http://codetoast.com/blog/archives/39#comments</comments>
		<pubDate>Tue, 08 Jul 2008 12:09:34 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<category><![CDATA[Tools and Strategy]]></category>

		<guid isPermaLink="false">http://codetoast.com/blog/?p=39</guid>
		<description><![CDATA[Visual SourceSafe (VSS).  Those words make me shudder, and it&#8217;s been years since I have touched it.  I was snapped back to the reality so many Microsoft-centric developers deal with when my friend Dave sent this:

Do you really see any advantage to rolling bug tracking, source control, and a development IDE into the same gigantic [...]]]></description>
			<content:encoded><![CDATA[<p>Visual SourceSafe (VSS).  Those words make me shudder, and it&#8217;s been years since I have touched it.  I was snapped back to the reality so many Microsoft-centric developers deal with when my friend Dave sent this:<span id="more-39"></span><!-- google_ad_section_start --><br/><br/></p>
<div style="margin-left: 30px;">
<blockquote><p><span style="color: #000080;">Do you really see any advantage to rolling bug tracking, source control, and a development IDE into the same gigantic tower of Babel product?  I don&#8217;t see the advantage.  It seems similar to writing software and saying &#8220;Look!  It&#8217;s a text editor AND a screen saver!&#8221;  They&#8217;re different functions.  In the same field, yes, but different functions nonetheless. Maybe I&#8217;m just irritated at TFS this morning.  We rent rack space so our TFS server is remote.  You know how well VSS (which is really all that TFS source control is) handles remote connections.  The end result is when I want to refresh my local source repository, it ran all of last night and is still running this morning.  So we&#8217;re working on about 18 hours now.  I could get the entire code base in a couple of hours using SVN and my cable connection.</span><br/><br />
<span style="color: #000080;">I probably shouldn&#8217;t feel so strongly about source control, but poor source control structure and/or technology feels like a lot of needless man hours lost sometimes.</span></p></blockquote>
</div>
<p><br/></p>
<div class="ArwC7c ckChnd">I haven&#8217;t personally used Team Foundation System (TFS), so my comments are mostly regarding the fact that it shares any lineage with VSS.  in short, yes you should care that much about it, yes Subversion (SVN) is that much better, and no - I don&#8217;t see an enormous advantage in combing bug tracking and Source Control Management (SCM) into the same product.  For one thing, Fogbugz is a great bug tracking application, it is inexpensive, and it integrates with several SCM systems.  At SAM Systems we&#8217;ve been using Fogbugz and SVN both for several years, but we&#8217;ve never bothered to look into integrating them.  It just doesn&#8217;t add anything for us.</div>
<p><br/></p>
<div class="ArwC7c ckChnd"><a href='http://codetoast.com/blog/wp-content/uploads/sshot-3.png'><img src="http://codetoast.com/blog/wp-content/uploads/sshot-3-219x192.png" alt="" title="VisualSVN Integration" width="219" height="192" border=0 class="alignnone size-medium wp-image-44" style="float:left; margin: 0px 8px 0px 0px;"/></a>The biggest thing for me is integration with Visual Studio.  There is a great SVN client called TortoiseSVN that is a shell extension to Explorer.  It works extremely well - and since it isn&#8217;t IDE-centric, it allows for easy use of SVN for your documents or just about any file resource.  The only problem is that if you move files in Visual Studio - say dragging a cs file into a sub folder of your project, or even adding a new class, SVN doesn&#8217;t pick up on the change.  Later you&#8217;ll realize your files didn&#8217;t get checked in and it can be a pain to find all of them.  VisualSVN to the rescue.  It is a Visual Studio plug-in that lets SVN know about the actions you make, keeping everything in sync.  you can also update or commit changes from the IDE.  It is a commercial project, but very inexpensive and very worth it.</div>
<p><br/></p>
<div class="ArwC7c ckChnd">SVN is literally over 100 times faster than VSS.  It doesn&#8217;t require crazy bindings that always get broken.  It doesn&#8217;t have an asinine database design that is always getting corrupt, and has to be taken offline for integrity checks, that with our modest code base could take more than half a day.</div>
<p><br/></p>
<div class="ArwC7c ckChnd">
<div class="ArwC7c ckChnd"><a href="http://www.sourcegear.com/TEM/TEMads.html" target="_blank"><img src='http://codetoast.com/blog/wp-content/uploads/tem250.jpg'  alt="" border=0 style="float:right; margin: 0px 4px 0px 8px;" title='SourceGear, makers of Vault' class='alignnone' /></a>There are tons of alternatives to Visual SourceSafe.  Some are expensive (Perforce, Clearcase) and designed for larger teams, while others are free/open source (CVS, SVN, etc..).  Some even have neat-o comic advertisements in programming magazines.</div>
<p><br/>
</div>
<div class="ArwC7c ckChnd"><strong>ALL OF THEM ARE BETTER THAN VSS.</strong></div>
<p><br/></p>
<div class="ArwC7c ckChnd">Well, there are hundreds out there - maybe one is worse, but unlikely.</div>
<p><br/></p>
<div class="ArwC7c ckChnd">I can&#8217;t be too hard on the VSS users though.  In general if you work in a Microsoft-centric world and there is an MS product to server your needs, it&#8217;s probably the right choice*.  Also, just the fact that you are using source control is commendable - a shocking number of teams, even reasonably big teams, use nothing -and email source files or fight over source on a network share.  Ack!</div>
<p><br/></p>
<div class="ArwC7c ckChnd">
<div class="ArwC7c ckChnd">Do youself a favor.  If you have more than zero developers and either do not have source control, or are using Visual Source Safe, try Subversion.  It will be a lot easier than you think, and you&#8217;ll kick yourself for not trying it sooner.</div>
<p><br/>
</div>
<p>* More to follow in a future post - experiences from building a new clustered datacenter.<br />
<!-- google_ad_section_end --><br />
<br/><img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/39/feed</wfw:commentRss>
		</item>
		<item>
		<title>I&#8217;m bored of all this Smorgas.</title>
		<link>http://codetoast.com/blog/archives/28</link>
		<comments>http://codetoast.com/blog/archives/28#comments</comments>
		<pubDate>Thu, 03 Jul 2008 18:26:14 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[General]]></category>

		<category><![CDATA[Operating Systems]]></category>

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

		<category><![CDATA[Tools and Strategy]]></category>

		<guid isPermaLink="false">http://codetoast.com/blog/?p=28</guid>
		<description><![CDATA[It&#8217;s common in software that often the absolute basics get trumped by candy-coated interfaces and lists of features that mostly go unused (hmm.. MS office 2001-present?).  In fact it used to be that the Operating System&#8217;s central role was actually memory and I/O management, can you imagine?  It is an easy mistake to make. [...]]]></description>
			<content:encoded><![CDATA[<p><!-- google_ad_section_start -->It&#8217;s common in software that often the absolute basics get trumped by candy-coated interfaces and lists of features that mostly go unused (hmm.. MS office 2001-present?).  In fact it used to be that the Operating System&#8217;s central role was actually memory and I/O management, can you imagine?  It is an easy mistake to make.  It is fun making new features; tail-wagging dogs that help you search or desktop gadgets that crash in new and interesting ways.  The saying that <a href="http://en.wikipedia.org/wiki/Jamie_Zawinski#Quotes" target="_blank">&#8220;every program will eventually expand until it can read mail&#8221;</a>, is pretty insightful.   I swore off using Winamp on the dark day that it took over my video associations, but still couldn&#8217;t seem to handle &#8217;shuffle&#8217; correctly - it seemed at the time that every application was expanding until it could play movies.<br />
<br/></p>
<p style="text-align: center;"><em><img src="http://www.mpex.net/img/news/00428_sc_wa29a_g.gif" border="0" alt="" width="300" height="240" /><br />
There is way too much going on here.</em></p>
<p><span id="more-28"></span><br />
I&#8217;ve been on both sides of this as a developer, and I understand the compulsion.  It&#8217;s easy to dream of better applications that integrate everything you need into one place, until you realize the end result is one ginormical application for all tasks, doing all things but none particularly well, with more bloat than Uncle Ralph after Thanksgiving.   Instead of the Super-Deluxe All-You-Can Eat Fortune Buffet* method of designing software, let&#8217;s go for the specialist role.  I want a music player that does one thing very well - play music.   I also want an Operating System that manages my files, memory, and processes - and stays out of my way for most of everything else.<br/><br />
The music player part is easy these days.  For GNU/Linux <a href="http://amarok.kde.org/" target="_blank">Amarok</a> is excellent, and for Windows I highly recommend <a href="http://www.foobar2000.org/" target="_blank">Foobar</a>.  On the Operating System front, things aren&#8217;t as easy.  Windows XP (or Server 2003) can be beaten into submission fairly well, and that&#8217;s what I&#8217;ve been using on my Windows development workstation for quite a while, well since it was in beta.  It is certainly showing it&#8217;s age 8 years later though.  Vista is not as bad as some of the rap it has gotten, but it is bad enough that I don&#8217;t want to use it every day.  I love Linux and there are several distros I&#8217;d rather have in front of me all day, so I&#8217;ve given though to doing all development in a Windows Virtual Machine.  Lately I&#8217;ve also been using Server 2008 more and more, and have to say it&#8217;s an excellent O/S, so I&#8217;ve also thought of trying it as a workstation for a while.  I tell myself it is not much different than Vista, at least at a kernel level - but the speed difference and UI constancy improvements are drastic.<br/><br />
The key thing is that the development I do, regardless of where and how, will be kept overly simple.  How often do you complain an application is too simple, and can&#8217;t accomplish a task?  How often do you complain that an application is bloated, and slow, and controlling?  For me it is clear that the latter is much more common.  Create a program that serves a basic need.  Use it.  Then add features once you know you (or others) can&#8217;t live without them.<br/><center><br />
<a href="http://www.mandolux.com/archive/index.html"><img class="aligncenter size-full wp-image-42" title="mandolux-mintg-l-1024" src="http://codetoast.com/blog/wp-content/uploads/mandolux-mintg-l-1024.jpg" alt="" width="300" height="228" /></a></center><br/>I like a buffet now and again, but most of the time I&#8217;d rather have one dish made to perfection.<br/><br />
  I hereby solemnly affirm my commitment to developing simple and useful programs.  They will do a few things very well.  The things they do not do well or are not appropriate for, they will not do.  This will take discipline - it is harder to write a great small program than it is to write a big terrible one.  I&#8217;m up for the task, are you?<br/><br />
* A real place, somewhere in Indiana near the Michigan border.<br />
<!-- google_ad_section_end --><br />
<br/><img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/28/feed</wfw:commentRss>
		</item>
		<item>
		<title>Other People&#8217;s Code</title>
		<link>http://codetoast.com/blog/archives/32</link>
		<comments>http://codetoast.com/blog/archives/32#comments</comments>
		<pubDate>Mon, 09 Jun 2008 21:42:11 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<category><![CDATA[Tools and Strategy]]></category>

		<guid isPermaLink="false">http://codetoast.com/blog/?p=32</guid>
		<description><![CDATA[As I mentioned in a previous installment, I had started the dreaded task of analyzing the source of the rdesktop project,   to see how I might best integrate it into ToastControl.  For non-programmers, &#8216;having the source&#8217; often seems to be 99% of the solution, when in fact it can be closer to [...]]]></description>
			<content:encoded><![CDATA[<p><!-- google_ad_section_start -->As I mentioned <a href="http://codetoast.com/blog/archives/33" target="_blank">in a previous installment</a>, I had started the dreaded task of analyzing the source of the <a href="http://www.rdesktop.org/" target="_blank">rdesktop project</a>,   <a href='http://www.mcescher.com' target="_blank"><img src="http://codetoast.com/blog/wp-content/uploads/escher200.jpg" alt="" border=0 style="float:left; margin: 8px 8px 0px 0px;" title="M.C. Escher's 'Print Gallery'" class="alignnone size-medium wp-image-36" /></a>to see how I might best integrate it into ToastControl.  For non-programmers, &#8216;having the source&#8217; often seems to be 99% of the solution, when in fact it can be closer to 10%, or I could argue even a liability sometimes.  While it may seem like having the plans to a building - I don&#8217;t know of many architects that use their own system of measurement for dimensions (variable names), re-define the standard types of rooms and what they do (functions / methods), or hopefully none that use recursion (Frank Lloyd Wright meets M.C. Escher?).<br/><br />
The possible issues are many.  First of all, rdesktop is a great piece of software and I have great respect for it, and owe thanks to the author, Matt Chapman.  That could be part of the problem - <em>what if this guy is a genius</em>, and I&#8217;m not able to even comprehend his masterpiece?<sup>1</sup>  I risk not being able to figure it out, damaging my fragile binary ego.  Even worse would be that he <em>thinks he&#8217;s a genius</em>, but falls somewhat short of the mark - creating an obtuse and abstruse monstrosity that seeks to reinvent software development at it&#8217;s core (you know, I&#8217;ll bet I can do better than this silly Boolean stuff&#8230;).  For examples of this, look no further than <a target="_blank" href="http://thedailywtf.com">the Daily WTF.</a><span id="more-32"></span><br/><br />
Very fortunately for me, it was none of the above.  The code was well written, compact but clear.  Even better is that I didn&#8217;t have to look far - after familiarizing myself with the project&#8217;s guts, I stumbled across a command-line argument that solved my problem outright.  It did get me thinking however to all the times it wasn&#8217;t so easy, and how tempting it is to &#8216;just rewrite it&#8217;.<br/><br />
<em>Guiding proper code reuse has been one of the more difficult aspects of managing a development team. </em>I can think of many times that two teams or individuals concurrently solved the same problem on different tasks - overlap that could have been easily abstracted out and used by all.  In other cases I have worked long and hard to design functionality in an application, just to find later that another has rewritten half of it to make a minuscule change - because they didn&#8217;t understand the rest and it was the path of least resistance - if not the most efficient by any means.  Now I&#8217;ll take some of the blame - my code was probably not commented quite enough, I probably didn&#8217;t make the architectural intentions clear enough, and my variables were all Simpsons characters - each used multiple times in the same scope with differing prefixes and types of capitalization<sup>2</sup>.<br/><br />
<center><img title="'The Plug' at the D.I.A."  src="http://codetoast.com/blog/wp-content/uploads/dia-plug.jpg" alt="" title="dia-plug" width="432" height="290" class="alignnone size-full wp-image-38" /></center><br />
Assuming reasonably well-written code, what can be done to make sure it gets used?  It is tempting to do it yourself.  We all know that <a href="http://www.jwz.org/doc/cadt.html" target="_blank">writing new code</a> is a lot more fun that figuring out someone else&#8217;s.  In the commercial environment a lot of it comes down to communication and culture.  This should be a major goal of leadership, not an afterthought.  I think an internal wiki of sorts might work well to communicate what small modules are in the code.  I&#8217;m not even talking about major segments - a lot of time could be saved just with the little 10 line methods here and there that maybe should have been added to static utility classes, etc.  No one can be expected to keep the entire code-base for a medium-to-large application<sup>3</sup> in their head, so an easy search for small snippets would be helpful.  I recently took on the task of maintaining an application with one other developer, that previously had as many as 8 people working on it.  I&#8217;d say were able to trim 30% of the code just by taking a second look through and enforcing better modularity.  I&#8217;m sure many projects are much more cluttered.<br/><br />
Notes:<br />
&nbsp;&nbsp;1.  Arguably a true genius would make the code for an open-source project easy to understand, at the expense of verbosity or diminished geek-points.<br />
&nbsp;&nbsp;2.  Well not really, but I won&#8217;t rule it out for the future.<br />
&nbsp;&nbsp;3.  Except Steve Yegge and maybe Linus Torvalds.<br />
<!-- google_ad_section_end --><br />
<br/><img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/32/feed</wfw:commentRss>
		</item>
		<item>
		<title>ToastControl starts to crawl&#8230;</title>
		<link>http://codetoast.com/blog/archives/33</link>
		<comments>http://codetoast.com/blog/archives/33#comments</comments>
		<pubDate>Wed, 04 Jun 2008 21:55:50 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[Applications]]></category>

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

		<category><![CDATA[Tools and Strategy]]></category>

		<guid isPermaLink="false">http://codetoast.com/blog/?p=33</guid>
		<description><![CDATA[I&#8217;ve managed to plug away at ToastControl a bit over the last couple weeks, and have some items to report.
Decisions decided

- I&#8217;m going to use Python.  I wanted to use a dynamic language that would be flexible.  The heavy lifting is done by the plug-ins like Rdesktop / mstsc and VNC anyway, written [...]]]></description>
			<content:encoded><![CDATA[<p><!-- google_ad_section_start -->I&#8217;ve managed to plug away at <a href="http://codetoast.com/blog/ToastControl" >ToastControl</a> a bit over the last couple weeks, and have some items to report.<br />
<br/><b>Decisions decided</b><br/><a href='http://codetoast.com/blog/wp-content/uploads/toast-run.png' target="_blank"><img src="http://codetoast.com/blog/wp-content/uploads/toast-run-220x167.png" title="ToastControl - It's Alive...!" width="220" height="167" border=0 style="float:right; margin-left:10px;margin-top:10px;" class="alignnone size-medium wp-image-34" /></a></p>
<ul STYLE="list-style-type: none;">
<li><span style="color:black;">- I&#8217;m going to use <a href="http://www.python.org/" target="_blank">Python</a>.</span>  I wanted to use a dynamic language that would be flexible.  The heavy lifting is done by the plug-ins like Rdesktop / mstsc and VNC anyway, written in C - the surrounding application doesn&#8217;t need tons of speed.  Ruby was a contender, but Python seems much more suited to cross-platform thick-client apps like this, at least at the moment. </li>
<p><span id="more-33"></span></p>
<li><span style="color:black;">- I&#8217;m using the <a href="http://www.wxwidgets.org/" target="_blank">wxWidget</a> library for a cross platform GUI.</span>  It is simple to use with Python, has a better look and feel than <a href="http://wiki.python.org/moin/TkInter" target="_blank">TkInter</a>, and with less weight and licensing baggage than <a href="http://en.wikipedia.org/wiki/Qt_(toolkit)" target="_blank">Qt</a>.</li>
<li><span style="color:black;">- I&#8217;ve decided to work on / test with Linux first.</span>  I do plenty of Windows Development at work, so this will give me a challenge to keep my interest. Once Linux is complete, porting a Windows version will be a breeze.</li>
</ul>
<p><br/><b>State of the application</b><br/><br />
Most importantly, it&#8217;s a running app - a big part of getting excited about building something!  Now it may not be as complete as the screenshot would lead you to believe - the connections are hard-coded (only RDP is working so far), and it doesn&#8217;t actually know &#8216;new&#8217; or &#8216;open&#8217; or &#8217;save&#8217; like the toolbar would indicate, but it is making fast progress.  Python has been surprisingly easy to work in after long stints in C# and C++ - if there&#8217;s interest I may just write a <em>&#8216;Getting started in Python for .NET programmers&#8217; </em> tutorial.<br/><br />
I&#8217;m using <a href="http://www.wingware.com" target="_blank">WingIDE</a> for editing - it is commercial,  but I haven&#8217;t found anything as stable, elegant, and lightweight <a  target="_blank" href='http://codetoast.com/blog/wp-content/uploads/wingide.png'><img src="http://codetoast.com/blog/wp-content/uploads/wingide-219x180.png" title="ToastControl in WingIDE on Mint Linux with my color scheme." width="219" height="180" border=0 style="float:left; margin: 10px 10px 10px 0px;" class="size-medium wp-image-35" /></a>that was free (but not too lightweight like the included IDLE).  If I don&#8217;t come with anything better in the eval period I&#8217;ll license or steal it.  I mean license it.  I originally tried also using wxGlade, a GUI designer for wxWidgets that can export to Python, but after getting accustomed to how it all fit together I decided to write the UI by hand: more control and more concise code. I just sometimes have to sketch layouts on paper to get started, since I can&#8217;t just drag things around until they fit - which wxGlade wasn&#8217;t great for anyway.<br/><br />
One big part I was dreading, going through the <a href="http://www.rdesktop.org" target="_blank">rdesktop</a> code to integrate it with my UI, turned out to be a non-issue. Since I had last spent much time with it, rdesktop has added a parameter (&#8221;-X&#8221;) that takes a window id to embed itself into.  All I have to do is launch it in another thread and pass it the id of my panel.  Insanely easy, my integration with RDP is now about 20 lines of code.  In fact, I should send the rdesktop contributor chocolates.  It turned out to be a well written and easy to read program, but I was still pretty relieved - lets hope VNC is as easy.<br/><br />
<b>What comes next?</b><br/><br />
So here are the biggest items on the radar -</p>
<ul  STYLE="list-style-type: none;">
<li><span style="color:black;">- Public source control.</span>  I like Subversion and could host it myself, although SourceForge or the like might get more publicity.  Anyone have experience there?  I&#8217;d love to get some collaboration going on this.</li>
<li><span style="color:black;">- More information here on how I&#8217;m building it.</span>  I just need to get it broken down into article sized chunks and get to writin&#8217;.</li>
<li><span style="color:black;">- I need a plug-in system.</span> Python lends itself to pretty <a href="http://pytute.blogspot.com/2007/04/python-plugin-system.html" target="_blank">easy plug-in implementations</a>, and there are a few <a href="http://cheeseshop.python.org/pypi/setuptools" target="_blank">complete libraries</a> - although I&#8217;d like to keep dependencies to a minimum.  Plug-ins will have to not only provide the ability for a new type of connection, they will also need to somehow provide a panel with config options.  I haven&#8217;t quite yet wrapped my head around how interfaces work in a dynamically typed system </li>
<li><span style="color:black;">- A configuration / settings-persistence system.</span>  I&#8217;m fond of serialization for this type of thing - making the actual usage as easy as possible.  I haven&#8217;t spent many brain cycles on it yet, but it seems that Python would work well in a JSON-like format: just spit out Python code that will build the classes to a config file, and when loading it, evaluate the contents.</li>
</ul>
<p><!-- google_ad_section_end --><br />
Expect fast progress from this point, I&#8217;m itching to get a usable app that I can start to dogfood&#8230;<br/><img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/33/feed</wfw:commentRss>
		</item>
		<item>
		<title>Ask not what your Operating System can do for you.</title>
		<link>http://codetoast.com/blog/archives/26</link>
		<comments>http://codetoast.com/blog/archives/26#comments</comments>
		<pubDate>Mon, 02 Jun 2008 16:38:24 +0000</pubDate>
		<dc:creator>Nicholas Brookins</dc:creator>
		
		<category><![CDATA[General]]></category>

		<category><![CDATA[Operating Systems]]></category>

		<guid isPermaLink="false">http://codetoast.com/blog/?p=26</guid>
		<description><![CDATA[I recall first using Windows 3.1 and thinking it was pretty cool - but man they needed to do somthing about the file manager.  I was a DOS user, accustomed to xcopy and the superb XTree  and XTreeGold applications.  I&#8217;m not asking for too much - just the basic abilities xcopy offers, [...]]]></description>
			<content:encoded><![CDATA[<p><!-- google_ad_section_start -->I recall first using Windows 3.1 and thinking it was pretty cool - but man they needed to do somthing about the file manager.  I was a DOS user, accustomed to xcopy and the superb XTree  <a title="XTreeGold - The best of the best for DOS File Management." href="http://en.wikipedia.org/wiki/XTree" target="_blank" ><img style="float: right; margin:10px;" src='http://upload.wikimedia.org/wikipedia/en/thumb/4/4c/Xtreegold-3.0.png/275px-Xtreegold-3.0.png' alt='XTreeGold - The best of the best for DOS File Management.' class='alignnone' /></a>and XTreeGold applications.  I&#8217;m not asking for too much - just the basic abilities xcopy offers, like continuation after an error, copying files after a newer date, and the like.  You know though, Windows 95 was just a few years around the corner - I was sure they would fix the basics by then.<br/><br />
Windows 95 didn&#8217;t do much for file management, other than eliminate the MDI interface we were just getting used to.  In fact, the notoriously bad progress message during file operations just made things worse - it wouldn&#8217;t even tell us how fast the bytes were moving.  I set to work on a shell extension to add some of the xcopy goodness to Windows Explorer. <span id="more-26"></span> <br/><br />
Alas, a shell extension of that sort was a bit beyond my Pascal and BASIC skills so I set to learning C++.  I also promptly forgot the reason I started down that path.  There always seemed like something more important at the time, but every once in a while I&#8217;d be copying a group of files only to be shot down by a silly error like &#8220;Cannot copy - The file exists&#8221; and my old dreams of a better copy mechanism would surface.<br/><br />
Fast forward 11 years to the release of Windows Vista.  Sure, it somehow manages to be sluggish with just basic UI operations on a 3GHz system, a full 45 times the clock speed of my first Windows 95 machine.  Without the Aero interface.<a title="Copying some files in Server 2008" href='http://codetoast.com/blog/wp-content/uploads/filecopy.png'><img src="http://codetoast.com/blog/wp-content/uploads/filecopy.png" alt="" title="Copying some files in Server 2008" style="float:left; margin: 10px 10px 10px 0px;" width="300" height="165" " /></a>  With no programs running.  But finally - yes Microsoft has heard my plea!  Vista has a file management interface that rivals any on the market.  It asks intelligent questions when a file can&#8217;t be moved or copied.  It even shows the current transfer speed.  I guess it&#8217;s a shame that it turns out many file operations are <a href="http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=1358057&#038;SiteID=17" target="_blank">considerably slower in Vista</a><br/><br />
Server 2008 seems to have all the good from Vista, with significantly less of the bad.  I recently upgraded a 2GHz machine, slow by Vista standards, to Server 2008 and it has been running remarkably well.  The dialogs and consoles seem more intelligently laid out, and the O/S was refreshingly bare until I used the new server manager console to add roles.  Microsoft seems to be continuing with this focus on the details for Windows 7, without any of the over-ambitious change-everything type of features that plagued Vista&#8217;s development and launch.  Will it be enough to change perceptions?  I know a lot of people who have started making moves towards Linux or Mac in the last couple of years, where incidentally, we also do a pretty good job with copying files.<br/><center><img src="http://codetoast.com/blog/wp-content/uploads/screenshot-file-operations2.png" alt="" style="margin:10px;" title="Several files copying in Gnome/Ubuntu 8.04" class="alignnone size-medium wp-image-30" /></center><!-- google_ad_section_end --><br />
<img style="margin: 5px 5px 5px 5px; float:right;" src="http://codetoast.com/favicon.png" border=0 alt="" /><br/><br />
<script type="text/javascript"><!--
google_ad_client = "pub-8950600405184160";
/* 468x60 banner, created 5/21/08 */
google_ad_slot = "9626759536";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://codetoast.com/blog/archives/26/feed</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.894 seconds -->
