<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/rss2full.xsl" type="text/xsl" media="screen"?><?xml-stylesheet href="http://feeds.feedburner.com/~d/styles/itemcontent.css" type="text/css" media="screen"?><rss 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" version="2.0">

<channel>
	<title>Qurbit Blog</title>
	
	<link>http://blog.qurbit.com</link>
	<description>Slaying My Laplacean Demon</description>
	<pubDate>Fri, 12 Sep 2008 22:09:57 +0000</pubDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/QurbitBlog" type="application/rss+xml" /><item>
		<title>Building Grammars in .NET</title>
		<link>http://blog.qurbit.com/2008/09/building-grammars-in-net/</link>
		<comments>http://blog.qurbit.com/2008/09/building-grammars-in-net/#comments</comments>
		<pubDate>Fri, 12 Sep 2008 22:09:57 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[.net]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[grammar]]></category>

		<category><![CDATA[speech recognition]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=27</guid>
		<description><![CDATA[As I&#8217;ve shown before (here, here, and here), the Microsoft .NET Speech API allows you  to quickly and easily build applications that take advantage of the good folks at Microsoft Research&#8217;s work on speech recognition.  The general process is that you can construct a grammar that the engine will recognize for you, and [...]]]></description>
			<content:encoded><![CDATA[<p>As I&#8217;ve shown before (<a href="http://blog.qurbit.com/2008/06/microsoft-speech-i-getting-your-computer-to-talk/" title="Microsoft Speech I: Getting your computer to talk">here</a>, <a href="http://blog.qurbit.com/2008/06/microsoft-speech-ii-getting-your-computer-to-listen/" title="Microsoft Speech II: Getting your computer to listen">here</a>, and <a href="http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/" title="Microsoft Speech III: Setting up a pluggable infrastructure">here</a>), the <a href="http://msdn.microsoft.com/en-us/library/ms723627(VS.85).aspx">Microsoft .NET Speech API</a> allows you  to quickly and easily build applications that take advantage of the good folks at <a href="http://research.microsoft.com/">Microsoft Research</a>&#8217;s work on speech recognition.  The general process is that you can construct a grammar that the engine will recognize for you, and then event handlers for those recognized events will be triggered.  This process then, will only be as effective as the grammars that you can construct for the the <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognitionengine.aspx">SpeechRecognitionEngine</a>.  In this post I&#8217;ll show you some of the things that you can do to construct Grammars in C#.</p>
<p>The SpeechRecognitionEngine class can load one or many Grammar objects.  The MSDN page describes these Grammar objects in the following way:</p>
<blockquote><p>
The System.Speech.Recognition..::.Grammar class provides run time objects that allow an application to specify a specific combination of words, choices of words, and other speech elements that the Speech platform uses to identify meaningful phrases.</p>
<p>The Grammar object fully supports the W3C Speech Recognition Grammar Specification (SRGS) and Context Free Grammar (CFG) specifications. For more information, see SpeechRecognitionGrammar <a href="http://www.w3.org/TR/speech-grammar/">Specification</a>.</p>
<p>Grammars may be precise word phrases, such as &#8220;Turn the computer off,&#8221; or provide choices, semantic lookup tables or wildcards, such as &#8220;Change color to&#8221; and a look up table of acceptable values.</p>
<p>An application&#8217;s recognition engine, as managed by instances of SpeechRecognizer or [T:System.Speech.Recognition.SpeechRecognitionEngine,] may create and load one or more instances Grammar, independently enabling or disabling particular grammars instance, and set Grammar properties such as priorities (Priority and weight (Weight)
</p></blockquote>
<p>So you can see that we can construct Grammars that will recognize certain types of input and then load these into the SpeechRecognitionEngine.  These can be <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.grammar.priority.aspx">prioritized</a> to help with conflict resolution as well as toggled on and off if you know that only certain grammars are appropriate for a certain context.</p>
<p>So how do we construct these grammars?  Grammars can be constructed in a variety of ways, but we are going to examine the <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.grammarbuilder.aspx">GrammarBuilder </a>Class as this is the easiest way to programmatically construct a Grammar.</p>
<p>The simplest example is simple string matching.  If you have a discrete atomic command (e.g. shutdown) that takes no parameters, you can <a href="http://msdn.microsoft.com/en-us/library/ms554229.aspx">initialize a GrammarBuilder with a string</a> and it will fire its recognize event when that string is heard.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">GrammarBuilder stringGb <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GrammarBuilder<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;shutdown&quot;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>If this was added to a Grammar and loaded in the Recognizer it would fire a recognized event for this Grammar whenever the word &#8220;shutdown&#8221; was heard.  This is easy enough, but somewhat limited, because what if you wanted to also allow them to say &#8220;turn off&#8221; or &#8220;quit&#8221;?  At this point you would have to add 3 Grammars, one with each of those strings.  Enter the <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.choices.aspx">Choices</a> class.</p>
<p>The Choices class allows us to create a phrase where one part of the phrase may have many different acceptable values.  In our above example, we want the verbs &#8220;shutdown&#8221;, &#8220;turn off&#8221; and &#8220;quit&#8221; to be interchangeable.  To show how this can be used with a phrase, lets make the user ask nicely by preceding either of those with &#8220;please&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">GrammarBuilder choicesGB <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GrammarBuilder<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;please&quot;</span><span style="color: #000000;">&#41;</span>;
Choices verbChoices <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;shutdown&quot;</span>, <span style="color: #666666;">&quot;turn off&quot;</span>, <span style="color: #666666;">&quot;quit&quot;</span><span style="color: #000000;">&#41;</span>;
choicesGB.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>verbChoices<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Now our grammar will trigger an event for all of the following phrases:</p>
<ul>
<li>please shutdown</li>
<li>please turn off</li>
<li>please quit</li>
</ul>
<p>You can probably now imagine how you could combine strings and choices to come up with a variety of different recognizable phrases.  However, there is a lot more that this engine can handle, but before we get into that lets review what happens when a phrase is recognized by the SpeechRecognitionEngine.</p>
<p>Remember that when a phrase is recognized, all that the engine will trigger is a <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.speechrecognizedeventargs.aspx">SpeechRecognizedEvent</a> to which you can assign a handler.  This same event is fired for all phrases in all grammars that are loaded, so the problem becomes figuring out which phrase triggered the event.  There are numerous strategies for dealing with this so I won&#8217;t go into detail here, but note that the <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.recognitioneventargs.result.aspx">SpeechRecognizedEventArgs </a>object has a <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.recognitionresult.aspx">RecognitionResult</a> that contains a pointer to the Grammar as well as the Text of the phrase in addition to any Semantic Values that you have assigned (more on that later).  For an example see <a href="http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/" title="Microsoft Speech III: Setting up a pluggable infrastructure">here</a>.</p>
<p>Why take that little detour?  Because once you&#8217;ve tried to actually do something with the result of a recognition event you&#8217;ll realize the utility of <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.semanticvalue.aspx">SemanticValues</a>.  Semantic Values allows you to assign values to certain responses so that you do not have to do annoying string parsing in the event handler.</p>
<p>Our first basic example will show how we can simply get the appropriate text in the event handler without having to do string parsing.  Lets say that we know that the user is either going to say &#8216;yes&#8217; or &#8216;no&#8217; to a request, but we want to recognize synonyms of those phrases.  We can do something like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">GrammarBuilder yesChoices <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;yes&quot;</span>, <span style="color: #666666;">&quot;yeah&quot;</span>, <span style="color: #666666;">&quot;ok&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToGrammarBuilder</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
yesChoices.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> SemanticResultValue<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
GrammarBuilder noChoices <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;no&quot;</span>, <span style="color: #666666;">&quot;nope&quot;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToGrammarBuilder</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
noChoices.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> SemanticResultValue<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
Choices allChoices <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span>yesChoices, noChoices<span style="color: #000000;">&#41;</span>;
SemanticResultKey choiceKey <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SemanticResultKey<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;YesNoBool&quot;</span>, allChoices<span style="color: #000000;">&#41;</span>;
&nbsp;
GrammarBuilder choiceGB <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GrammarBuilder<span style="color: #000000;">&#40;</span>choiceKey<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>What does this do for us?  It creates a GrammarBuilder that has 2 choices.  Each of these Choices has a SemanticValue that can be obtained in the recognition handler.  Semantically there is a Yes choice (which is actually itself a choice of &#8220;yes&#8221;, &#8220;yeah&#8221; and &#8220;ok&#8221;) and a No choice (&#8221;no&#8221; and &#8220;nope&#8221;).  The Recognition engine, since we have assigned semantic values to these, will set the &#8220;YesNoBool&#8221; variable to either true or false depending on which Semantic choice the user makes.  This is great for us.  No string parsing, and thus we can easily build up grammars with many synonyms and never worry about adding more complexity in the event handler.</p>
<p>So far we have looked at inputs that are just combinations of predefined words.  This is great for many scenarios, but what if we want to allow more free form input?  Lets say that our grammar is built to allow users to get a current stock price.  You would probably want to match on any of the following phrases:</p>
<ul>
<li>Show me the stock price of foo</li>
<li>Let me see the stock price of foo</li>
<li>What is the price of foo</li>
</ul>
<p>Here foo may be any stock ticker and lets say we&#8217;re lazy so we don&#8217;t want to hard code all of them.  The solution lies in the <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.dictationgrammar.aspx">DictationGrammar </a>class.  This class is exactly what it sounds like&#8211;a class for dealing with understand user dictation.  Now, extracting the &#8216;foo&#8217; from any of those in the event handler could be error prone, especially as you add more and more recognized ways of asking for a stock price.  This is where semantic values come into play again.  So lets see how this might work:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">GrammarBuilder stockGB <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GrammarBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
GrammarBuilder dictation <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> GrammarBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
dictation.<span style="color: #0000FF;">AppendDictation</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;spelling&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
stockGB.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show me the stock price of&quot;</span>, <span style="color: #666666;">&quot;Let me see the stock price of&quot;</span>, <span style="color: #666666;">&quot;What is the stock price of&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
stockGB.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> SemanticResultKey<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;DictationInput&quot;</span>, dictation<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>This code creates a choice of antecendents and then appends a SemanticResultKey whose name is DictationInput.  Note that since we assigned no semantic value, the value that is assigned to DictationInput will be the actual text of the dictation.  Finally, note that when we <a href="http://msdn.microsoft.com/en-us/library/ms576566.aspx">created the Dictation we passed the parameter &#8220;spelling&#8221;</a>.  This was to let the Recognizer know that we wanted the user to spell out the ticker name and that it should not interpret the input as words.  If we had not passed that parameter it would have tried to match the input to words.  That type of dictation might be useful if you were trying to build a voice IM client for example.</p>
<p>That&#8217;s all for now.  Good luck and let me know if you build anything cool <img src='http://blog.qurbit.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/09/building-grammars-in-net/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Getting your C# app to run in the System Tray</title>
		<link>http://blog.qurbit.com/2008/07/getting-your-c-app-to-run-in-the-system-tray/</link>
		<comments>http://blog.qurbit.com/2008/07/getting-your-c-app-to-run-in-the-system-tray/#comments</comments>
		<pubDate>Sun, 06 Jul 2008 09:07:31 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[system tray]]></category>

		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=28</guid>
		<description><![CDATA[While making some additions to the Speech Framework, I needed to figure out how to get my WPF application to run in the system tray.  For the speech framework, the sys-tray is a natural place for the application to run, as we ideally don&#8217;t want to see any UI and the application should be [...]]]></description>
			<content:encoded><![CDATA[<p>While making some additions to the <a href="http://blog.qurbit.com/2008/06/microsoft-speech-i-getting-your-computer-to-talk/" title="Microsoft Speech I: Getting your computer to talk">Speech Framework</a>, I needed to figure out how to get my WPF application to run in the system tray.  For the speech framework, the sys-tray is a natural place for the application to run, as we ideally don&#8217;t want to see any UI and the application should be always on.  I opted out of a service, because I did want the rich UI of an application and for it to show up in task manager, etc. It was very straightforward, but I thought I&#8217;d write up the steps for future reference.</p>
<p>We will start by creating a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx">NotifyIcon</a> object in our Window&#8217;s Constructor.  Note that it is in the System.Windows.Forms namespace, and you may need to add a reference to your project in order to access it (it is not there by default in a new WPF project).  You may also need to add a System.Drawing reference to your project as well.  Once your references are in order, lets write some code to create the icon for us in the Window Constructor:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//Set up the system tray icon</span>
_ni <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> NotifyIcon<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
_ni.<span style="color: #0000FF;">BalloonTipTitle</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Qurbit Home Automation Engine&quot;</span>;
_ni.<span style="color: #0000FF;">BalloonTipText</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;The engine is still running, it has just been minimized.  Double click to restore to normal size&quot;</span>;
_ni.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Qurbit Home Automation Engine&quot;</span>;
<span style="color: #008080; font-style: italic;">//Add a double click handler</span>
_ni.<span style="color: #0000FF;">MouseDoubleClick</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Forms</span>.<span style="color: #0000FF;">MouseEventHandler</span><span style="color: #000000;">&#40;</span>_ni_MouseDoubleClick<span style="color: #000000;">&#41;</span>;
<span style="color: #0600FF;">try</span>
<span style="color: #000000;">&#123;</span>
    _ni.<span style="color: #0000FF;">Icon</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Drawing</span></span>.<span style="color: #0000FF;">Icon</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Images<span style="color: #008080; font-weight: bold;">\\</span>flag.ico&quot;</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 e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Debug.<span style="color: #0000FF;">Print</span><span style="color: #000000;">&#40;</span>e.<span style="color: #0000FF;">StackTrace</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The above code will create the necessary NotifyIcon object and give it an icon, text, etc.  Customize it as is appropriate.</p>
<p>Next we want to make sure that when a user minimizes the window we show the icon and do not show our application on the task bar.  To do so, we need to trap the Window&#8217;s OnStateChangedEvent.  For more info on how window events work <a href="http://msdn.microsoft.com/en-us/library/ms748948.aspx">start here</a>.  In our xaml we need to add this attribute to the window element: </p>
<p>StateChanged=&#8221;Window_StateChanged&#8221;</p>
<p>Then in C#, we can add a handler for this.  First however, let&#8217;s write a helper function for toggling the visibility of our window.  It will take a boolean that indicates whether the window should live in the system tray or not.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> windowInSysTray<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">bool</span> inTray<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>inTray<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Hide the window</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ShowInTaskbar</span> <span style="color: #008000;">=</span> false;
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">WindowState</span> <span style="color: #008000;">=</span> WindowState.<span style="color: #0000FF;">Minimized</span>;
&nbsp;
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_ni <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//Show the icon</span>
            _ni.<span style="color: #0000FF;">Visible</span> <span style="color: #008000;">=</span> true;
            <span style="color: #008080; font-style: italic;">//Show the balloon tip</span>
            <span style="color: #008080; font-style: italic;">//_ni.ShowBalloonTip(2000);</span>
        <span style="color: #000000;">&#125;</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;">//Show the window</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">ShowInTaskbar</span> <span style="color: #008000;">=</span> true;
        <span style="color: #008080; font-style: italic;">//Restore it</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">WindowState</span> <span style="color: #008000;">=</span> WindowState.<span style="color: #0000FF;">Normal</span>;
        <span style="color: #008080; font-style: italic;">//Bring it to the front</span>
        <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">Activate</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #008080; font-style: italic;">//Remove the sys tray icon</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_ni <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _ni.<span style="color: #0000FF;">Visible</span> <span style="color: #008000;">=</span> false;
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Finally, the event handler looks like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Window_StateChanged<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">//If the state is minimized then change its display type</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">WindowState</span> <span style="color: #008000;">==</span> WindowState.<span style="color: #0000FF;">Minimized</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        windowInSysTray<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</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>
        windowInSysTray<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Next we need to implement the double click handler for the notify icon to restore the application:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> _ni_MouseDoubleClick<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;">MouseEventArgs</span> e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    windowInSysTray<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>At this point you should be able to minimize and restore your application as you would expect.  There is on final bit of cleanup that we are going to want to include, and that is to handle what happens when the window is closed.  If we allow the user to close the window with the close button, then we need to explicitly remove the notify icon or it will stay down there until the area is redrawn (the user mouses over it).  For my app however I am going to make the close button also minimize the app to the sys tray and then you really close via a sys tray menu.  So lets grab onto the OnClosing Method by adding the following attribute to our window object in the xaml code: </p>
<p>Closing=&#8221;Window_Closing&#8221;</p>
<p>Then lets write an event handler:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> Window_Closing<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, <span style="color: #000000;">System.<span style="color: #0000FF;">ComponentModel</span></span>.<span style="color: #0000FF;">CancelEventArgs</span> e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">//Trap the event</span>
    e.<span style="color: #0000FF;">Cancel</span> <span style="color: #008000;">=</span> true;
    <span style="color: #008080; font-style: italic;">//Put it in the system tray</span>
    windowInSysTray<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now, when we close the application, it minimizes itself to the system tray as well.  Unfortunately, if you run it at this point there is no way to close the application smoothly, so lets add a context menu to the system tray icon that has a close option.</p>
<p>In order to get started, lets add a click handler to the NotifyIcon in the window constructor:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">_ni.<span style="color: #0000FF;">MouseClick</span> <span style="color: #008000;">+=</span> <span style="color: #008000;">new</span> <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Forms</span>.<span style="color: #0000FF;">MouseEventHandler</span><span style="color: #000000;">&#40;</span>_ni_MouseClick<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Then we need to implement the click handler.  It will be very simple, and just check for a right mouse click.  If it detects one, then it will show the context menu:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">void</span> _ni_MouseClick<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;">MouseEventArgs</span> e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>e.<span style="color: #0000FF;">Button</span> <span style="color: #008000;">==</span> MouseButtons.<span style="color: #0000FF;">Right</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Show the context menu</span>
        <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Controls</span>.<span style="color: #0000FF;">ContextMenu</span> menu <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Controls</span>.<span style="color: #0000FF;">ContextMenu</span><span style="color: #000000;">&#41;</span><span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">FindResource</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;SysTrayContextMenu&quot;</span><span style="color: #000000;">&#41;</span>;
        menu.<span style="color: #0000FF;">IsOpen</span> <span style="color: #008000;">=</span> true;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>In order for that to work we now need to add a context menu.  There a couple of ways we could do this, but lets build ours in XAML so that down the road we can have some fun with it.  To do this, lets add a context menu to our XAML file, as the first element within the window:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Window</span>.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ContextMenu</span> <span style="color: #000066;">x:Key</span>=<span style="color: #ff0000;">&quot;SysTrayContextMenu&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;MenuItem</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Open&quot;</span> <span style="color: #000066;">Click</span>=<span style="color: #ff0000;">&quot;MenuOpen_Click&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/MenuItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;MenuItem</span> <span style="color: #000066;">Header</span>=<span style="color: #ff0000;">&quot;Exit&quot;</span> <span style="color: #000066;">Click</span>=<span style="color: #ff0000;">&quot;MenuExit_Click&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span><span style="color: #000000; font-weight: bold;">&lt;/MenuItem<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ContextMenu<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Window</span>.Resources<span style="color: #000000; font-weight: bold;">&gt;</span></span></pre></div></div>

<p>Now we have a context menu, with two options.  All that remains is to implement their click handlers.  The open option is will just open up the window by calling our windowInSysTray method, and the exit one will remove our NotifyIcon (cleanup so that it doesn&#8217;t linger around) and then shutdown the application.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> MenuOpen_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, RoutedEventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    windowInSysTray<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span>;
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> MenuExit_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, RoutedEventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">//Remove the system tray icon</span>
    _ni.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #008080; font-style: italic;">//Shut it down</span>
    <span style="color: #000000;">System</span>.<span style="color: #0000FF;">Windows</span>.<span style="color: #0000FF;">Application</span>.<span style="color: #0000FF;">Current</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></pre></div></div>

<p>There you have it.  Pretty simple stuff, and if you want to add more options or add fancier effects just edit the xaml file.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/07/getting-your-c-app-to-run-in-the-system-tray/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Javascript, Flash and cross-browser clipboard fun</title>
		<link>http://blog.qurbit.com/2008/06/javascript-web-browsers-and-the-clipboard/</link>
		<comments>http://blog.qurbit.com/2008/06/javascript-web-browsers-and-the-clipboard/#comments</comments>
		<pubDate>Sat, 21 Jun 2008 00:43:29 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[clipboard]]></category>

		<category><![CDATA[cross browser]]></category>

		<category><![CDATA[flash]]></category>

		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=24</guid>
		<description><![CDATA[Recently I have been wrestling with writing some code that will manipulate text on a user&#8217;s clipboard in a web browser.  I thought I would share my findings here for others who might be interested in the same topic.
First lets start by looking at the Windows Clipboard in general.  The clipboard, as we [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I have been wrestling with writing some code that will manipulate text on a user&#8217;s clipboard in a web browser.  I thought I would share my findings here for others who might be interested in the same topic.</p>
<p>First lets start by looking at the Windows <a href="http://msdn.microsoft.com/en-us/library/ms649012.aspx">Clipboard</a> in general.  The clipboard, as we all know, stores blobs that the user has copied or cut from windows applications for future use.  It stores this data in a variety of formats (if writing a windows application you can use the formats specified by the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.dataformats_fields.aspx">DataFormats </a> class.)  It is a convenient way to transport data between applications in windows.  A simple example of writing to the clipboard in c# would then look like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">// For this example, the data to be placed on the clipboard is a simple</span>
<span style="color: #008080; font-style: italic;">// string.</span>
<span style="color: #FF0000;">string</span> textData <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;I want to put this string on the clipboard.&quot;</span>;
&nbsp;
<span style="color: #008080; font-style: italic;">// After this call, the data (string) is placed on the clipboard and tagged</span>
<span style="color: #008080; font-style: italic;">// with a data format of &quot;Text&quot;.</span>
Clipboard.<span style="color: #0000FF;">SetData</span><span style="color: #000000;">&#40;</span>DataFormats.<span style="color: #0000FF;">Text</span>, <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">Object</span><span style="color: #000000;">&#41;</span>textData<span style="color: #000000;">&#41;</span>;</pre></div></div>

<p>Doing this on in a windows app is great, and easy, because that is really what the api&#8217;s were designed for&#8230; but what if we want to do this in a web app?  Why would we do this you ask, well one argument is that as web apps and client apps converge, users are starting to expect more and more of the familiar windows UI concepts to be available to them on the web.  Yeah, we&#8217;ll say that is the reason.</p>
<p>In a web app, there are primarily 3 ways that we are going to run code that will interact with our user: javascript, flash, and silverlight.  We&#8217;ll take a look at each of these and see what is possible.</p>
<h2>Javascript</h2>
<p>So what can we do with javascript and the clipboard?  It depends on the browser and on the interaction that you want.  Lets start with the simplest, and potentially cross browser action: <a href="http://msdn.microsoft.com/en-us/library/ms536419(VS.85).aspx">execCommand</a>.  The execCommand method can perform a <a href="http://www.devguru.com/features/tutorials/wysiwyg/wysiwyg3.html">variety of operations</a>, but the ones we care about are &#8216;copy&#8217;, &#8216;cut&#8217;, and &#8216;paste&#8217;.  Because execCommand was built with enabling javascript based wysiwyg editors in mind, it operates on the selected areas of a web page.  That is, text that has been highlighted or where there is an active cursor (e.g. in a text box).  So how can we use execCommand?  If you want to simply copy the selection to the clipboard, then it is trivial and you can just:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;">document.<span style="color: #660066;">execCommand</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Copy&quot;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p>This copies the user&#8217;s selection to the clipboard.</p>
<p>What is good about the execCommand copy approach?  It is potentially cross browser (not with default security settings in FF) and simple to implement.  So long as they have javascript enabled you can use it.  What is bad?  In modern browsers the user will be prompted the first time that you attempt to do this and warned that you are trying to access their clipboard, which is a bad UX but necessary for security reasons.  </p>
<p><a href='http://blog.qurbit.com/wp-content/uploads/2008/06/clipboardaccesswarning.jpg'><img src="http://blog.qurbit.com/wp-content/uploads/2008/06/clipboardaccesswarning.jpg" alt="" title="clipboardaccesswarning" width="387" height="176" class="aligncenter size-full wp-image-25" /></a></p>
<p>Furthermore, you may only copy text that the user has selected in the browser.</p>
<p>For more examples of execCommand clipboard stuff, see <a href="http://www.geekpedia.com/tutorial126_Clipboard-cut-copy-and-paste-with-JavaScript.html">this Geekpedia tutorial</a> or this excellent <a href="http://msconline.maconstate.edu/tutorials/JSDHTML/JSDHTML12/jsdhtml12-02.htm">JS WYSIWYG Editor tutorial</a>.</p>
<h3>The IE only alternative</h3>
<p>An option, if for some strange reason you would like to build an application that only works in IE, is to take advantage of the <a href="http://msdn.microsoft.com/en-us/library/ms535220(VS.85).aspx">clipboardData</a> object.  Using this, you can write and read directly from the clipboard and the user prompt is ignored when using the default security settings.  Using this you can only take advantage of two &#8216;types&#8217; on the clipboard: &#8216;text&#8217; and &#8216;url&#8217;</p>
<p>To write text to the clipboard, you could then do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> textToCopy <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;This is some text for the clipboard&quot;</span>;
window.<span style="color: #660066;">clipboardData</span>.<span style="color: #660066;">setData</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Text&quot;</span><span style="color: #339933;">,</span> textToCopy<span style="color: #009900;">&#41;</span>;</pre></div></div>

<p>One nice thing about this, is that you can write arbitrary text to the clipboard (no user selection needed).  But remember, this is Internet Explorer only.  Mozilla does <a href="http://developer.mozilla.org/en/docs/Using_the_Clipboard">have a solution</a>, but it is FF only.  So if you want to use the clipboard in all browsers and not change security settings what can we do?</p>
<h2>Flash</h2>
<p>The best answer so far is flash.  The idea (originally credited to <a href="http://markosullivan.ca/">Mark O’Sullivan</a>) is to use the Flash <a href="http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&#038;file=00002187.html">setClipboard</a> method to write to the clipboard.  Why is this better than the javascript solutions?  Because, the good people at Adobe did all the cross browser work for us.  Now the only requirement is that the browser has a flash plugin, which given the penetration of flash is a fair bet.  What we can then do is, when we want to copy something to the clipboard, we pass (via javascript) the the text to our flash object and let it do the clipboard dirty work.</p>
<p><a href="http://www.jeffothy.com/weblog/">Jeffothy Keyings</a> has a <a href="http://www.jeffothy.com/weblog/clipboard-copy/">good example</a> of how to do this, and links to the open source flash object (_clipboard.swf) by O&#8217;Sullivan.</p>
<h2>Silverlight</h2>
<p>I looked and looked, and to the best of my knowledge Silverlight does not yet expose a method for accessing the clipboard.  Alas.</p>
<h2>Conclusions</h2>
<p>So where does that leave us?  </p>
<ol>
<li>If you want cross browser clipboard access you will need to use flash.</li>
<li>If you do not want a dependency on flash, then you only have a good solution for IE</li>
</ol>
<h3>One last thing&#8230;</h3>
<p>One more thing that is worth noting is that you can only write to and read from the clipboard from within the browser using the TEXT format.  Why is that important?  Because if you want to put images, or rich text on the clipboard you can&#8217;t.  If you go into your browser and highlight some text with styles and then paste it into Microsoft Word, you see that the styles are preserved.  That is because this is written to the Clipboard and read from it as RTF.  Not only that, but if you paste it into Microsoft OneNote, you&#8217;ll find that you can see the original source of the clip.  That is because as rich client apps, IE (or FF), Word and OneNote are not sandboxed in the same way that flash and javascript are.  To see this more clearly try downloading <a href="http://www.softpedia.com/get/Office-tools/Clipboard/Clipboard-Inspector.shtml">Clipboard Inspector</a> and looking at the format of items that you copy to the clipboard.</p>
<p>When clipping from a web browser you get the HTML option and there is header information showing source, etc:<br />
<a href='http://blog.qurbit.com/wp-content/uploads/2008/06/clipboardinspector.jpg'><img src="http://blog.qurbit.com/wp-content/uploads/2008/06/clipboardinspector-300x207.jpg" alt="" title="clipboardinspector" width="300" height="207" class="aligncenter size-medium wp-image-26" /></a></p>
<p>When you write via javascript or flash you are forced to write out text, so when applications access the clipboard, even if you have valid HTML on there they will html encode the characters thinking they they are text, and thus not render them correctly.  There are numerous reasons why this makes sense from a security perspective, but it is a pain and something that web developers need to be aware of nonetheless.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/javascript-web-browsers-and-the-clipboard/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Miles per Gallon vs. Gallons per Mile</title>
		<link>http://blog.qurbit.com/2008/06/miles-per-gallon-vs-gallons-per-mile/</link>
		<comments>http://blog.qurbit.com/2008/06/miles-per-gallon-vs-gallons-per-mile/#comments</comments>
		<pubDate>Fri, 20 Jun 2008 02:34:50 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[behavioral decision theory]]></category>

		<category><![CDATA[behavioral]]></category>

		<category><![CDATA[gas]]></category>

		<category><![CDATA[statistics]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=23</guid>
		<description><![CDATA[A new study by Richard Larrick of Duke&#8217;s Fuqua School of Business, recently published in Science magazine shows that most people have the wrong intuition about how to save gas.  This is because they misunderstand what the &#8220;miles per gallon&#8221; statistic actually represents.  As a result of this they may not be doing [...]]]></description>
			<content:encoded><![CDATA[<p>A <a href="http://faculty.fuqua.duke.edu/~larrick/bio/Reshighlights.htm">new study</a> by <a href="http://faculty.fuqua.duke.edu/~larrick/bio/index.htm">Richard Larrick</a> of Duke&#8217;s Fuqua School of Business, recently published in Science magazine shows that most people have the wrong intuition about how to save gas.  This is because they misunderstand what the &#8220;miles per gallon&#8221; statistic actually represents.  As a result of this they may not be doing the optimal things to decrease their gas consumption.</p>
<p>Lets look at a simple example. </p>
<p>Say you have 2 cars, a Honda Sedan which gets 30mpg and a Ford SUV which gets 15mpg.  You put an equal number of miles on both cars and can&#8217;t get rid of the SUV because you need it for hauling SUV sized things.</p>
<p>Now you are proud of your eco-friendliness, you recycle your cans and buy only organic, free-range, local food, so you want to figure out what you can do to use less gas.  You realize that you have enough money to upgrade one of your cars.  You can replace the Sedan with a Hybrid that gets 55mpg or you can replace the SUV with a Hybrid that gets 22mpg.  Which would you choose?</p>
<p>According to Larrick most people would replace the Sedan.  Why?  Because 50mpg sounds like a great thing!  A gain of 25 mpg sounds far more Green Peacey than a gain of 7mpg.</p>
<p>Now, lets look at the math.</p>
<p>Lets say that you drive 1000 miles a month, evenly split between the two vehicles.  That means that pre-upgrade we are burning:</p>
<blockquote><p>
500/30 + 500/15 = ~50.0 gallons of gas (16.6 for the Sedan, 33.3 for the SUV)
</p></blockquote>
<p>If we upgrade the Sedan, we get:</p>
<blockquote><p>
500/55 + 500/15 = ~42.4 gallons of gas (9.1 for the Sedan, 33.3 for the SUV)
</p></blockquote>
<p>If we upgrade the SUV, we get:</p>
<blockquote><p>
500/30 + 500/22 = ~39.3 gallons of gas (16.6 for the Sedan, 22.7 for the SUV)
</p></blockquote>
<p>So by upgrading the SUV, even though you only boost it by 7mpg you are actually burning less gas overall!  Why is this?  Because we are holding the number of miles driven fixed, thus the more important statistic is how many gallons per mile your car gets.  Miles per gallon is useful when figuring out how far you can go on a tank of gas but less so, when you have a fixed distance to travel and are looking to figure out how much gas you&#8217;ll need.</p>
<p>Larrick&#8217;s paper concludes that people looking to save gas (or trees) should figure out the gallons per mile for their vehicles when considering upgrades.  For our above examples we can see that the cars got (in units of gallons per 10 miles):</p>
<blockquote><p>
Sedan + SUV = 0.333 + 0.666 = 1 gallons/10 miles<br />
Hybrid Sedan + SUV = 0.182 + 0.666 = 0.848 gallons/10 miles<br />
Sedan + Hybrid SUV = 0.333 + 0.456 = 0.789 gallons/10 miles
</p></blockquote>
<p>Something to consider next time you get a car, and yet another feather in the behavioral decision theorists&#8217; caps.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/miles-per-gallon-vs-gallons-per-mile/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Trynt Web Services</title>
		<link>http://blog.qurbit.com/2008/06/trynt-web-services/</link>
		<comments>http://blog.qurbit.com/2008/06/trynt-web-services/#comments</comments>
		<pubDate>Thu, 19 Jun 2008 17:50:16 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[web]]></category>

		<category><![CDATA[web service]]></category>

		<category><![CDATA[web technology]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=21</guid>
		<description><![CDATA[Looking around for cool services to make use of in ISpeechPlugins I stumbled upon Trynt Heavy Technologies.  I&#8217;m not sure what their business plan is but they have a seemingly useful list of APIs for people to take advantage of.  Worth a look if you want some services to play with.
]]></description>
			<content:encoded><![CDATA[<p>Looking around for cool services to make use of in ISpeechPlugins I stumbled upon <a href="http://www.trynt.com/">Trynt Heavy Technologies</a>.  I&#8217;m not sure what their business plan is but they have a seemingly <a href="http://www.trynt.com/apis/">useful list of APIs</a> for people to take advantage of.  Worth a look if you want some services to play with.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/trynt-web-services/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Speech Plugins: Weather</title>
		<link>http://blog.qurbit.com/2008/06/speech-plugins-weather/</link>
		<comments>http://blog.qurbit.com/2008/06/speech-plugins-weather/#comments</comments>
		<pubDate>Mon, 16 Jun 2008 04:59:11 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[speech]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=20</guid>
		<description><![CDATA[In this entry we&#8217;ll look at building a basic plugin for a speech engine (Microsoft Speech III: Setting up a pluggable infrastructure), that will respond to simple queries about the weather.  For this tutorial we will be using the Yahoo Weather API.  Note that if you are just interested in how to use [...]]]></description>
			<content:encoded><![CDATA[<p>In this entry we&#8217;ll look at building a basic plugin for a speech engine (<a href="http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/" title="Microsoft Speech III: Setting up a pluggable infrastructure">Microsoft Speech III: Setting up a pluggable infrastructure</a>), that will respond to simple queries about the weather.  For this tutorial we will be using the <a href="http://developer.yahoo.com/weather/">Yahoo Weather API</a>.  Note that if you are just interested in how to use their API, it should be easy enough to extract what you&#8217;re interested without doing the previous tutorials.</p>
<p>We begin by creating a new project in our Speech Engine solution, and setting it up as described in <a href="http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/" title="Microsoft Speech III: Setting up a pluggable infrastructure">the previous tutorial</a>.  One this is setup, we can begin by creating a WeatherPlugin class that implements the ISpeechPlugin interface:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">Speech_Project.Core</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Speech.Recognition</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Xml.XPath</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Xml</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Speech_Project.<span style="color: #0000FF;">Plugins</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>SpeechPluginAttribute<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Weather&quot;</span>,
        <span style="color: #666666;">&quot;This retrieves weather data from the Yahoo weather services API&quot;</span>,
        <span style="color: #666666;">&quot;1.0&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> WeatherPlugin <span style="color: #008000;">:</span> ISpeechPlugin
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _grammarName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Weather Plugin&quot;</span>;
&nbsp;
        <span style="color: #008080;">#region ISpeechPlugin Members</span>
        <span style="color: #0600FF;">public</span> Grammar getGrammar<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
           ...
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> handleSpeechInput<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> input<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            ...
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> getGrammarName<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> _grammarName;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now we just need to build our grammar and implement the handlers.  In order to make it easier to standardize the language that we&#8217;ll be using, lets create a helper class called WeatherSpeechChoices that will contain the strings that we recognize in our grammar.  We will give it two commands to start; one will get today&#8217;s forecast and the other, tomorrow&#8217;s.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">class</span> WeatherSpeechChoices
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">//Inputs</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> forecastTomorrow <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;What is tomorrow's forecast&quot;</span>;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> forecastToday <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;What is today's forecast&quot;</span>;
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now that we have this defined we can implement the grammar building method, as before we just need to add these choices to the grammar and the engine will compile all of the various plugin grammars.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> Grammar getGrammar<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;">//Create a set of choices</span>
            Choices thisChoices <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span>
                WeatherSpeechChoices.<span style="color: #0000FF;">forecastTomorrow</span>,
                WeatherSpeechChoices.<span style="color: #0000FF;">forecastToday</span>
                <span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Create a grammar based on these choices</span>
            Grammar thisGrammar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Grammar<span style="color: #000000;">&#40;</span>thisChoices.<span style="color: #0000FF;">ToGrammarBuilder</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">// Set the Grammar name</span>
            thisGrammar.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">=</span> _grammarName;
&nbsp;
            <span style="color: #0600FF;">return</span> thisGrammar;
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Halfway there, now we just need to implement the event handler.  This is the fun part, where we call the Weather service.  Lets implement this by having the event handler call a getForecastString method that takes the number of days out as an integer parameter.  Once we know we will build that we can write our event handler:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> handleSpeechInput<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> input<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>input<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> WeatherSpeechChoices.<span style="color: #0000FF;">forecastToday</span><span style="color: #008000;">:</span>
                    <span style="color: #FF0000;">string</span> forecast <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">getForecastString</span><span style="color: #000000;">&#40;</span>0<span style="color: #000000;">&#41;</span>;
                    Talker.<span style="color: #0000FF;">Say</span><span style="color: #000000;">&#40;</span>forecast<span style="color: #000000;">&#41;</span>;
                    break;
&nbsp;
                <span style="color: #0600FF;">case</span> WeatherSpeechChoices.<span style="color: #0000FF;">forecastTomorrow</span><span style="color: #008000;">:</span>
                    <span style="color: #FF0000;">string</span> forecast1 <span style="color: #008000;">=</span> <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">getForecastString</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>;
                    Talker.<span style="color: #0000FF;">Say</span><span style="color: #000000;">&#40;</span>forecast1<span style="color: #000000;">&#41;</span>;
                    break;
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now to implement the getForecastString method.  Take a look at the <a href="http://developer.yahoo.com/weather/">API</a> and you will see that we need to be issuing requests to http://weather.yahooapis.com/forecastrss.  This URL takes two types of parameters, US zipcodes OR Yahoo location IDs.  In order to get the Yahoo location ID, their page states that:</p>
<blockquote><p>
The location parameter can be a US Zip code or a location ID. To find your location ID, browse or search for your city from the Yahoo! Weather home page. The weather ID is in the URL for the forecast page for that city. You can also get the location ID by entering your zip code on the home page. For example, if you search for Los Angeles on the Yahoo! Weather home page, the forecast page for that city is http://weather.yahoo.com/forecast/USCA0638.html. The location ID is USCA0638.
</p></blockquote>
<p>However in this tutorial we will be using a zipcode (I live in the US).  You may additionally change the units (celsius or farenheit) by appending a &#8220;u=c&#8221; or &#8220;u=f&#8221; to the URL.  For this example lets, add two private members to our WeatherPlugin class that will help us create the URL:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _zipCode <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;55407&quot;</span>;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">const</span> <span style="color: #FF0000;">string</span> _serviceURL <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;http://xml.weather.yahoo.com/forecastrss?p=&quot;</span>;</pre></div></div>

<p>Now that we know what the URL is, we need to know how to parse the response.  This service will respond with an XML document that is <a href="http://cyber.law.harvard.edu/rss/rss.html">RSS 2.0</a> compliant.  We will make use the XPathNavigator .NET class to parse the response.  So lets see what our method looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> getForecastString<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> daysFromNow<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
             <span style="color: #008080; font-style: italic;">// Create a new XmlDocument  </span>
            XPathDocument doc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XPathDocument<span style="color: #000000;">&#40;</span>_serviceURL <span style="color: #008000;">+</span> _zipCode<span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">// Create navigator  </span>
            XPathNavigator navigator <span style="color: #008000;">=</span> doc.<span style="color: #0000FF;">CreateNavigator</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">// Set up namespace manager for XPath  </span>
            XmlNamespaceManager ns <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlNamespaceManager<span style="color: #000000;">&#40;</span>navigator.<span style="color: #0000FF;">NameTable</span><span style="color: #000000;">&#41;</span>;
            ns.<span style="color: #0000FF;">AddNamespace</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;yweather&quot;</span>, <span style="color: #666666;">&quot;http://xml.weather.yahoo.com/ns/rss/1.0&quot;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Get the forecast with XPath</span>
            XPathNodeIterator nodes <span style="color: #008000;">=</span> navigator.<span style="color: #0000FF;">Select</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;//rss/channel/item/yweather:forecast&quot;</span>, ns<span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #FF0000;">string</span> day <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span>;
            <span style="color: #FF0000;">string</span> text <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span>;
            <span style="color: #FF0000;">string</span> low <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span>;
            <span style="color: #FF0000;">string</span> high <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span>;
&nbsp;
            nodes.<span style="color: #0000FF;">MoveNext</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            XPathNavigator node <span style="color: #008000;">=</span> nodes.<span style="color: #0000FF;">Current</span>;
&nbsp;
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>daysFromNow <span style="color: #008000;">==</span> <span style="color: #FF0000;">1</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                nodes.<span style="color: #0000FF;">MoveNext</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
                node <span style="color: #008000;">=</span> nodes.<span style="color: #0000FF;">Current</span>;
            <span style="color: #000000;">&#125;</span>
&nbsp;
            day <span style="color: #008000;">=</span> node.<span style="color: #0000FF;">GetAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;day&quot;</span>, ns.<span style="color: #0000FF;">DefaultNamespace</span><span style="color: #000000;">&#41;</span>;
            text <span style="color: #008000;">=</span> node.<span style="color: #0000FF;">GetAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;text&quot;</span>, ns.<span style="color: #0000FF;">DefaultNamespace</span><span style="color: #000000;">&#41;</span>;
            low <span style="color: #008000;">=</span> node.<span style="color: #0000FF;">GetAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;low&quot;</span>, ns.<span style="color: #0000FF;">DefaultNamespace</span><span style="color: #000000;">&#41;</span>;
            high <span style="color: #008000;">=</span> node.<span style="color: #0000FF;">GetAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;high&quot;</span>, ns.<span style="color: #0000FF;">DefaultNamespace</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #FF0000;">string</span> forecast <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;It will be &quot;</span> <span style="color: #008000;">+</span> text <span style="color: #008000;">+</span> <span style="color: #666666;">&quot; with a high of &quot;</span> <span style="color: #008000;">+</span> high <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;, and a low of &quot;</span> <span style="color: #008000;">+</span> low;
            <span style="color: #0600FF;">return</span> forecast;
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now lets break this method down a little further.  In order to parse the document correctly we need to load the yweather namespace (http://xml.weather.yahoo.com/ns/rss/1.0).  We select our first node for parsing by jumping to the first yweather:forecast item.  This particular service only returns a 1 day forecast, so we know that if the daysFromNow variable is either 1 or 0 (you should implement something to enforce this).  Once we have retrieved the correct node we get the attributes as described by the API, construct an English sounding sentence out of them, and return that to our Engine class.  Note that if we are worried about lag or connection overhead we could cache the navigator object and use that for subsequent calls.  In this example though, we hit the webpage every time you ask for the weather.</p>
<p>This service returns much more than the temperature in its response including windchill, speed and direction, atmospheric conditions, sunrise, sunset and others.  It also returns the current conditions in the yweather:condition node.  For an example rss feed, here is a l<a href="http://weather.yahooapis.com/forecastrss?p=55407">ink to the output</a> for Minneapolis.  As you can see its pretty easy to extend the plugin and get it to tell you this other information if you want.  Until next time, have at it and let me know what you come up with.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/speech-plugins-weather/feed/</wfw:commentRss>
		</item>
		<item>
		<title>I hope they take themselves seriously</title>
		<link>http://blog.qurbit.com/2008/06/i-hope-they-take-themselves-seriously/</link>
		<comments>http://blog.qurbit.com/2008/06/i-hope-they-take-themselves-seriously/#comments</comments>
		<pubDate>Fri, 13 Jun 2008 08:57:35 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[Things that make NNT cry]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=18</guid>
		<description><![CDATA[While watching Game 4 of the NBA Finals this evening I accidentally saw a commercial for thee local news here in Seattle.  I generally try and avoid local news like the plague&#8211;its like cable news but with a lower budget.  Anyhow, the commercial warned any and all that were listening that we had [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.qurbit.com/wp-content/uploads/2008/06/sadnnt.jpg"><img class="size-medium wp-image-19 alignright" style="float: right;" title="sadnnt" src="http://blog.qurbit.com/wp-content/uploads/2008/06/sadnnt.jpg" alt="Things that make NNT sad" width="114" height="155" /></a>While watching Game 4 of the NBA Finals this evening I accidentally saw a commercial for thee local news here in Seattle.  I generally try and avoid local news like the plague&#8211;its like cable news but with a lower budget.  Anyhow, the commercial warned any and all that were listening that we had to stay tuned in order to learn about how an &#8220;everyday item that millions of people have may be killing you.&#8221;  This everyday item was&#8230; wait for it&#8230; your vinyl shower curtain.  Now I generally discount all scare stories that the news offers up, but the warning was so grandiose and the object to be feared so ridiculous, that I had to look it up.  <a href="http://abcnews.go.com/Health/story?id=5057141&amp;page=1">Heres what I found</a> (emphasis mine)</p>
<blockquote><p>Could your shower curtain be harming your health?</p>
<p>An environmental group claims in a new study of vinyl shower curtains that some of them may release into the air toxic chemicals which could cause asthma, eye irritation or even cancer.</p>
<p>&#8220;We have a clear-cut case that these products release elevated levels of harmful chemicals,&#8221; said report co-author Mike Schade, PVC campaign coordinator for the Center for Health, Environment and Justice. &#8220;Our research builds on a growing body of evidence that shows that the government fails to protect us from the growing number of toxic chemicals in products.&#8221;</p>
<p>But some health experts are paying scant attention to those behind the curtain study. And perhaps with good reason.</p>
<p>Skeptics pointed out what they call a glaring error in the study&#8217;s methodology. <em>The group tested a total of five shower curtains, of which only one shower curtain — not one brand; one curtain — was subjected to complete testing for chemicals in its composition, as well as those it released into the air — a phenomenon known as &#8220;off-gassing.&#8221;</em></p>
<p><em>Further testing was not performed &#8220;to avoid potential instrument damage,&#8221; according to the report.</em></p>
<p><em>The study found the one curtain which was tested for off-gassing may have released, over the course of the first few hours after it was opened, chemicals that could be toxic if swallowed or inhaled only in quantities thousands of times greater than those found.</em></p>
<p><em>Critics said that the testing was not verified by an independent lab and didn&#8217;t account for real-world conditions such as temperature or humidity in a shower stall.</em></p>
<p><em>The study also included estimated results for some of the chemical amounts it reported, and most of the off-gassed chemicals found initially were not detectable after a few days.</em></p>
<p>In short, it is a piece of shower curtain research that some experts said just doesn&#8217;t hold water.</p></blockquote>
<p>They tested FIVE CURTAINS?  Thats it?!  Not only that but only one was fully tested and it emmitted for a short times toxic gasses that are 1/1000 of the toxic dose?  While the rest of the article continues to backtrack and talk slightly more rationally, if you acknowledge these facts in your article, then how in the world can you lead with &#8220;Could your shower curtain be harming your health?&#8221;?!  Furthermore, lets not understate the case, the last line should read &#8220;it is a piece of shower curtain research that <em>any and all scientists that have the right to use the title</em> said just doesn&#8217;t hold water.&#8221;</p>
<p>Jesus, I need to just watch the news for 30 seconds to remind myself why I don&#8217;t make a habit of it.  I take solace in hoping that everyone involved in this scare mongering really believes what they said and is trying to figure out how to get by without a plastic shower curtain.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/i-hope-they-take-themselves-seriously/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Microsoft Speech III: Setting up a pluggable infrastructure</title>
		<link>http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/</link>
		<comments>http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/#comments</comments>
		<pubDate>Fri, 13 Jun 2008 07:35:32 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[c#]]></category>

		<category><![CDATA[plugins]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=16</guid>
		<description><![CDATA[This post will build on the work done in Microsoft Speech II: Getting your computer to listen, where we saw how to interact with our computer via voice.  In this tutorial we will build a plugin infrastructure which we will use to add functionality to our Speech Project in the future.  While we [...]]]></description>
			<content:encoded><![CDATA[<p>This post will build on the work done in <a href="http://blog.qurbit.com/2008/06/microsoft-speech-ii-getting-your-computer-to-listen/" title="Microsoft Speech II: Getting your computer to listen">Microsoft Speech II: Getting your computer to listen</a>, where we saw how to interact with our computer via voice.  In this tutorial we will build a plugin infrastructure which we will use to add functionality to our Speech Project in the future.  While we won&#8217;t be adding any new functionality in this tutorial, we will be refactoring what we had into a &#8220;Personality&#8221; plugin.  Please note that these ideas aren&#8217;t uniquely mine and I borrow heavily from <a href="http://www.c-sharpcorner.com/UploadFile/rmcochran/plug_in_architecture09092007111353AM/plug_in_architecture.aspx">Matthew Cochran&#8217;s excellent tutorial</a> on the subject of plugins&#8211;I just adapted them for the speech project&#8217;s purposes.</p>
<p>Lets start by opening the project as we left it in <a href="http://blog.qurbit.com/2008/06/microsoft-speech-ii-getting-your-computer-to-listen/" title="Microsoft Speech II: Getting your computer to listen">Microsoft Speech II: Getting your computer to listen</a>.  At this point we should refactor our namespace to be something more useful than &#8220;Tutorial1&#8243;, so lets change that to &#8220;Speech_Project&#8221; for now (make sure to update the XAML as well).</p>
<p>Next we need to add some folders for building out our framework.  Add two folders named &#8220;Core&#8221; and &#8220;Plugins&#8221; to your project:<br />
<a href="http://blog.qurbit.com/wp-content/uploads/2008/06/tutorial3_pic1.jpg"></a></p>
<p style="text-align: center;"><img class="alignnone size-full wp-image-17 aligncenter" title="tutorial3_pic1" src="http://blog.qurbit.com/wp-content/uploads/2008/06/tutorial3_pic1.jpg" alt="" width="292" height="255" /></p>
<p>Now lets move the Say method out of the Window1 class and into its own class called Talker.  We can use this later when we add more options to the output (SMS, IM, Email, etc.).  So create a Talker class in the Speech_Project.Core namespace and move the say method into it:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Speech.Synthesis</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Speech_Project.<span style="color: #0000FF;">Core</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Talker
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Say<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> input<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            var synth <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SpeechSynthesizer<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
            var sayThis <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Prompt<span style="color: #000000;">&#40;</span>input<span style="color: #000000;">&#41;</span>;
            synth.<span style="color: #0000FF;">Speak</span><span style="color: #000000;">&#40;</span>sayThis<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></div></div>

<p>Next we need to define the interface to which all of our plugins will conform.  Plugins for now will need to tell the engine which grammars they support and then have an event handler for when their grammar is triggered (see <a href="http://blog.qurbit.com/2008/06/microsoft-speech-ii-getting-your-computer-to-listen/" title="Microsoft Speech II: Getting your computer to listen">Tutorial 2</a>).  Finally, they&#8217;ll need to tell the engine which grammars are theirs by providing a method for getting the grammar name.  Lets create an ISpeechPlugin interface that looks like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Speech.Recognition</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Speech_Project.<span style="color: #0000FF;">Core</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> ISpeechPlugin
    <span style="color: #000000;">&#123;</span>
        Grammar getGrammar<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
        <span style="color: #0600FF;">void</span> handleSpeechInput<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> input<span style="color: #000000;">&#41;</span>;
        <span style="color: #FF0000;">string</span> getGrammarName<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>In addition to the plugin interface we should add a plugin attribute class.  This will allow us to get some meta data about the plugins when we load them, look for version collisions, and other useful things down the road.  So lets add a SpeechPluginAttribute:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Speech_Project.<span style="color: #0000FF;">Core</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>AttributeUsage<span style="color: #000000;">&#40;</span>AttributeTargets.<span style="color: #FF0000;">Class</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #FF0000;">class</span> SpeechPluginAttribute <span style="color: #008000;">:</span> Attribute
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> SpeechPluginAttribute<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> name, <span style="color: #FF0000;">string</span> description, <span style="color: #FF0000;">string</span> version<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _description <span style="color: #008000;">=</span> description;
            _name <span style="color: #008000;">=</span> name;
            _version <span style="color: #008000;">=</span> version;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _description;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _name;
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _version;
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Description
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _description; <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> _description <span style="color: #008000;">=</span> value; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _name; <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> _name <span style="color: #008000;">=</span> value; <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Version
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> _version; <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> _version <span style="color: #008000;">=</span> value; <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></div></div>

<p>Now that we have our Interface defined, lets create our first plugin.  Start by creating a new Project in your solution for your Personality plugin, of the type class library.  Change its Build properties to output to the Plugins directory of the main Project (to get this working in VS debug mode make sure it is /bin/debug/Plugins/).  Next make sure you reference the main project and set the Main class to be an instance of the ISpeechPlugin Module (and make sure you add our custom attribute).</p>
<p>Now we can take the code that was in the Window1 class and move it into this Plugin.  So lets take the grammar construction code and the event handler and put it in the Personality class like so:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">Speech_Project.Core</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Speech.Recognition</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Speech_Project.<span style="color: #0000FF;">Plugins</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #000000;">&#91;</span>SpeechPluginAttribute<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Personality Plugin&quot;</span>, 
        <span style="color: #666666;">&quot;This plugin handles all of the personality like responses for the plugin&quot;</span>, 
        <span style="color: #666666;">&quot;1.0&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonalityPlugin <span style="color: #008000;">:</span> ISpeechPlugin
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">private</span> <span style="color: #FF0000;">string</span> _grammarName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;PersonalityPlugin&quot;</span>;
        <span style="color: #008080;">#region ISpeechPlugin Members</span>
&nbsp;
        <span style="color: #0600FF;">public</span> Grammar getGrammar<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;">//Create a set of choices</span>
            Choices thisChoices <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Choices<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Computer&quot;</span>,
                <span style="color: #666666;">&quot;What is your name?&quot;</span>,
                <span style="color: #666666;">&quot;What is your favorite blog?&quot;</span>
                <span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Create a grammar based on these choices</span>
            Grammar thisGrammar <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Grammar<span style="color: #000000;">&#40;</span>thisChoices.<span style="color: #0000FF;">ToGrammarBuilder</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #008080; font-style: italic;">// Set the Grammar name</span>
            thisGrammar.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">=</span> _grammarName;
&nbsp;
            <span style="color: #0600FF;">return</span> thisGrammar;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> handleSpeechInput<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> input<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">switch</span> <span style="color: #000000;">&#40;</span>input<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">&quot;Computer&quot;</span><span style="color: #008000;">:</span>
                    Talker.<span style="color: #0000FF;">Say</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Yes master?&quot;</span><span style="color: #000000;">&#41;</span>;
                    break;
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">&quot;What is your name?&quot;</span><span style="color: #008000;">:</span>
                    Talker.<span style="color: #0000FF;">Say</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;My name is Anna&quot;</span><span style="color: #000000;">&#41;</span>;
                    break;
                <span style="color: #0600FF;">case</span> <span style="color: #666666;">&quot;What is your favorite blog?&quot;</span><span style="color: #008000;">:</span>
                    Talker.<span style="color: #0000FF;">Say</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Qurbit of course&quot;</span><span style="color: #000000;">&#41;</span>;
                    break;
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> getGrammarName<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">return</span> _grammarName;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080;">#endregion</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now that we&#8217;ve done a little refactoring (yes you should do more: abstract out the strings, etc.), lets get to the fun part&#8211;dynamic binding.  Lets start by creating an Engine class that will do the heavy lifting.  The engine class will look in the plugins folder for any .dll files and if they implement the ISpeechPlugin will instantiate these into a List via Reflection.  After loading all of the plugins, we can get our engine to load all of their grammars.  Then when the engine recognizes any of the Choices in the loaded grammars we can trigger the event handler for the correct ISpeechPlugin.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.IO</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Collections.Generic</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Reflection</span>;
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Speech.Recognition</span>;
&nbsp;
<span style="color: #0600FF;">namespace</span> Speech_Project.<span style="color: #0000FF;">Core</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">class</span> Engine
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> List<span style="color: #008000;">&lt;</span>ISpeechPlugin<span style="color: #008000;">&gt;</span> _plugins;
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> LoadPlugins<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;">//Get all the assemblies in the Plugins folder</span>
            List<span style="color: #008000;">&lt;</span>Assembly<span style="color: #008000;">&gt;</span> assemblies <span style="color: #008000;">=</span> LoadAssemblies<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Load the plugins </span>
            _plugins <span style="color: #008000;">=</span> GetPlugIns<span style="color: #000000;">&#40;</span>assemblies<span style="color: #000000;">&#41;</span>;
&nbsp;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> List<span style="color: #008000;">&lt;</span>Assembly<span style="color: #008000;">&gt;</span> LoadAssemblies<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;">//Look in the plugin dir for .dlls</span>
            DirectoryInfo dInfo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DirectoryInfo<span style="color: #000000;">&#40;</span>Path.<span style="color: #0000FF;">Combine</span><span style="color: #000000;">&#40;</span>Environment.<span style="color: #0000FF;">CurrentDirectory</span>, <span style="color: #666666;">&quot;Plugins&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
            FileInfo<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> files <span style="color: #008000;">=</span> dInfo.<span style="color: #0000FF;">GetFiles</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;*.dll&quot;</span><span style="color: #000000;">&#41;</span>;
            List<span style="color: #008000;">&lt;</span>Assembly<span style="color: #008000;">&gt;</span> plugInAssemblyList <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>Assembly<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</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> <span style="color: #008000;">!=</span> files<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>FileInfo file <span style="color: #0600FF;">in</span> files<span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    plugInAssemblyList.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>Assembly.<span style="color: #0000FF;">LoadFile</span><span style="color: #000000;">&#40;</span>file.<span style="color: #0000FF;">FullName</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;
            <span style="color: #0600FF;">return</span> plugInAssemblyList;
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> List<span style="color: #008000;">&lt;</span>ISpeechPlugin<span style="color: #008000;">&gt;</span> GetPlugIns<span style="color: #000000;">&#40;</span>List<span style="color: #008000;">&lt;</span>Assembly<span style="color: #008000;">&gt;</span> assemblies<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            List<span style="color: #008000;">&lt;</span>Type<span style="color: #008000;">&gt;</span> availableTypes <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>Type<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>Assembly currentAssembly <span style="color: #0600FF;">in</span> assemblies<span style="color: #000000;">&#41;</span>
                availableTypes.<span style="color: #0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>currentAssembly.<span style="color: #0000FF;">GetTypes</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;">// get a list of objects that implement the ICalculator interface AND </span>
            <span style="color: #008080; font-style: italic;">// have the CalculationPlugInAttribute</span>
            List<span style="color: #008000;">&lt;</span>Type<span style="color: #008000;">&gt;</span> pluginList <span style="color: #008000;">=</span> availableTypes.<span style="color: #0000FF;">FindAll</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span>Type t<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                List<span style="color: #008000;">&lt;</span>Type<span style="color: #008000;">&gt;</span> interfaceTypes <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>Type<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>t.<span style="color: #0000FF;">GetInterfaces</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #FF0000;">object</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> arr <span style="color: #008000;">=</span> t.<span style="color: #0000FF;">GetCustomAttributes</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>SpeechPluginAttribute<span style="color: #000000;">&#41;</span>, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span>;
                <span style="color: #0600FF;">return</span> <span style="color: #008000;">!</span><span style="color: #000000;">&#40;</span>arr <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span> || arr.<span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> 0<span style="color: #000000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> interfaceTypes.<span style="color: #0000FF;">Contains</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>ISpeechPlugin<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>;
            <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">// convert the list of Objects to an instantiated list of ICalculators</span>
            <span style="color: #0600FF;">return</span> pluginList.<span style="color: #0000FF;">ConvertAll</span><span style="color: #008000;">&lt;</span>ISpeechPlugin<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span>Type t<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> Activator.<span style="color: #0000FF;">CreateInstance</span><span style="color: #000000;">&#40;</span>t<span style="color: #000000;">&#41;</span> <span style="color: #0600FF;">as</span> ISpeechPlugin; <span style="color: #000000;">&#125;</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></div></div>

<p>At this point, we have an infrastructure that allows us to abstract out the functionality in a given plugin, and so long as there is a .dll in the plugins folder that implements the ISpeechModule interface we can get an instance of it.  Now all we need to do is get the engine to route the events to the correct plugins when it recognizes input.  So lets add a SpeechRecognized Event handler to the engine that will look through the plugins to see if any have a handler for the recognized grammar name and if so then call the handler in that plugin</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> SpeechRecognized<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, SpeechRecognizedEventArgs e<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ISpeechPlugin plugin <span style="color: #0600FF;">in</span> _plugins<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">//This is the correct handler</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>e.<span style="color: #0000FF;">Result</span>.<span style="color: #0000FF;">Grammar</span>.<span style="color: #0000FF;">Name</span> <span style="color: #008000;">==</span> plugin.<span style="color: #0000FF;">getGrammarName</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    plugin.<span style="color: #0000FF;">handleSpeechInput</span><span style="color: #000000;">&#40;</span>e.<span style="color: #0000FF;">Result</span>.<span style="color: #0000FF;">Text</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></div></div>

<p>Finally, lets add an InitializeSRE method to the engine that will create the SpeechRecognitionEngine object and load the grammars from the plugins as well as attach the SpeechRecognized handler:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp csharp" style="font-family:monospace;">        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> SpeechRecognitionEngine InitializeSRE<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;">//Create the speech recognition engine</span>
            SpeechRecognitionEngine sre <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SpeechRecognitionEngine<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Set the audio device to the OS default</span>
            sre.<span style="color: #0000FF;">SetInputToDefaultAudioDevice</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Reset the Grammars</span>
            sre.<span style="color: #0000FF;">UnloadAllGrammars</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Load the plugins</span>
            LoadPlugins<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Load all of the grammars</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ISpeechPlugin plugin <span style="color: #0600FF;">in</span> _plugins<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                sre.<span style="color: #0000FF;">LoadGrammar</span><span style="color: #000000;">&#40;</span>plugin.<span style="color: #0000FF;">getGrammar</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;">//Set the recognition mode</span>
            sre.<span style="color: #0000FF;">RecognizeAsync</span><span style="color: #000000;">&#40;</span>RecognizeMode.<span style="color: #0000FF;">Multiple</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #008080; font-style: italic;">//Add an event Handler</span>
            sre.<span style="color: #0000FF;">SpeechRecognized</span> <span style="color: #008000;">+=</span>
                <span style="color: #008000;">new</span> EventHandler<span style="color: #008000;">&lt;</span>SpeechRecognizedEventArgs<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>Engine.<span style="color: #0000FF;">SpeechRecognized</span><span style="color: #000000;">&#41;</span>;
&nbsp;
            <span style="color: #0600FF;">return</span> sre;
        <span style="color: #000000;">&#125;</span></pre></div></div>

<p>Now we can just call Engine.InitializeSRE in our window constructor and it will load all the plugins and handle all of the event routing.  Build your plugin and run the WPF application and give it a try.  Pretty simple huh?  Now we can just keep building plugins to extend the functionality of our Speech Project.  Stay tuned for more plugins.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/microsoft-speech-iii-setting-up-a-pluggable-infrastructure/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Reasoning The Fast and Frugal Way: Models of Bounded Rationality</title>
		<link>http://blog.qurbit.com/2008/06/reasoning-the-fast-and-frugal-way-models-of-bounded-rationality/</link>
		<comments>http://blog.qurbit.com/2008/06/reasoning-the-fast-and-frugal-way-models-of-bounded-rationality/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 08:23:06 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[behavioral decision theory]]></category>

		<category><![CDATA[article]]></category>

		<category><![CDATA[behavioral]]></category>

		<category><![CDATA[decision theory]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=13</guid>
		<description><![CDATA[Authors: Gerd Gigerenzer and Daniel G. Goldstein
Source: Psychological Review 1996, Vol 103. No 4 650-669
Link: PDF
The central tenet of this paper is that rationality in human decision making (Homo Economicus), isn&#8217;t a realistic assumption, despite the niceties it provides for model creators.  It Notes that historically there have been 3 school of thought on [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Authors</strong>: Gerd Gigerenzer and <a href="http://www.dangoldstein.com/">Daniel G. Goldstein</a><br />
<strong>Source</strong>: Psychological Review 1996, Vol 103. No 4 650-669<br />
<strong>Link</strong>: <a href="http://www.dangoldstein.com/papers/FastFrugalPsychReview.pdf">PDF</a></p>
<p>The central tenet of this paper is that rationality in human decision making (<em>Homo Economicus)</em>, isn&#8217;t a realistic assumption, despite the niceties it provides for model creators.  It Notes that historically there have been 3 school of thought on human decision making:</p>
<ol>
<li>Classical thinkers such as Pierre, Laplace or Piaget asserted that humans make decisions based solely on the use of probability ans statistics.  In fast &#8220;the Enlightenment probabilists derived the laws of probability from what they believed to be the laws of human reasoning&#8221;.  Despite much of science moving on past this, Economics and Psychology have held on to this view for the most part</li>
<li>In the mid-late 20th century, the &#8220;heuristics and biases&#8221; movement, pioneered by the likes of Tversky and Kahneman concluded that &#8220;human inference is systematically biased and error prone.&#8221;  Despite the seeming repudiation of the 1st school of thought, this school holds on to probability and statistics as the normative way to make decisions, we humans are just in actuality broken or not up to the task.</li>
<li>The authors subscribe to Herbert Simon&#8217;s notion of <i>bounded rationality</i>, characterized by both cognitive and ecological bounds.  The cognitive bound is simply that humans do not have the mental tools to quickly do the complex calculations necessary to perform multiple regression.  Secondly, the ecological bound states the the human mind has adapted to live in real world environments.
</li>
</ol>
<p>The authors have taken these Simon&#8217;s two assertions and go on to propose a number of <i>satisficing</i> algorithms, that:</p>
<blockquote><p>&#8220;operate with simple psychological principles that satisfy the constraints of limited time, knowledge, and computational might, rather than those of classical rationality&#8221;</p></blockquote>
<p>For the experiment to test their algorithms, they take on a two alternative choice task where the subject is forced to make an inference based on knowledge that the user already has.  Forcing them to retrieve this from memory presumable simulates the ecological bound.  The theories that they propose build on Gigerenzer&#8217;s <a href="http://psycnet.apa.org/index.cfm?fa=search.displayRecord&#038;uid=2008-00265-010">previous work</a> on Probabilistic Mental Models (PMM).  The theory integrates 3 central ideas:</p>
<ol>
<li>&#8220;inductive inference needs to be studied with respect to natural environments&#8221; (Brunswik &#038; Simon)</li>
<li>&#8220;inductive inference is carried out by satisficing algorithms&#8221; (Simon)</li>
<li>&#8220;inductive inferences are based on frequencies of events in a reference class&#8221; (Reichenbach)</li>
</ol>
<p>Ultimately, the algorithms that conform to the PMM tenets don&#8217;t perform exhaustive memory search nor do they perform complex interactions between data points.  Gained by not performing these expensive operations is very fast decision making.  The authors assert that this is very valuable when being chased by a tiger, or say deciding whether or not to exit the freeway.  Always getting off at the <em>correct </em>exit is less important than always deciding <em>quickly enough</em> that you don&#8217;t crash.  Not taking into account all information conveniently allows for easily modeling of incomplete information instances, which are presumably the vast majority of real world decision making cases.</p>
<p>In their experiment they assess the capacity of a subject to guess whether city a has a greater population than that of city b.  They do this for a set of cities known, this set is the <em>reference class</em>.  The subject has certain data about each city, such as whether it has a soccer team or a university.  These data points are known as <em>cues</em>.  They model limited knowledge (incomplete information) as both an imperfect knowledge of all objects in the reference class and limited knowledge of the cue values (facts about the cities).</p>
<p>The authors finally propose a very simple satisficing algorithm called the &#8220;<em>Take the Best Algorithm</em>&#8220;.  This algorithm assumes a subjective rank order of cues according to their validities.  It has 5 steps:</p>
<ol>
<li><em>Recognition Principle</em>: This is invoked when recognizing an object is a predictor of the target variable.  In the case of population, there is an obvious correlation.  Thus, if we are predicting highest population size and one of the two cities is know, pick it.  If neither are known, randomize.  If both are known go to step 2.</li>
<li><em>Search For Cue Values</em></li>
<li><em>Discrimination Rule</em>: Decide if the cue discriminates.</li>
<li><em>Cue-Substitution Principle:</em> If so use it to pick, otherwise pick another cue (step 2)</li>
<li><em>Maximizing Rule For Choice:</em> Choose the value the cue would predict.  If they are the same randomize.</li>
</ol>
<p>This algorithm searches only a portion of the total knowledge, that is it reads only a subset of the cues for either object.  It also does not attempt to integrate information, but rather just substitute in the best cue.</p>
<p>The authors then assert that experimental evidence has shown that the less is more effect can be shown to exist empirically when one uses this algorithm.  This may explain why US students make slightly more correct inferences about German cities and vice versa.</p>
<p>Note that one may not know a cue value for all objects in the reference class.  Thus, the authors define two properties that they use to evaluate cues.  <em>Ecological Validity</em> is the proportion of cases in the reference class in which this cue is an accurate predictor (not a bad prediction).  <em>Discrimination rates</em> are the relative frequency with which the cue can be used to discriminate (not the same value).</p>
<p>They then present data comparing the Take the Best (TTB) algorithm wit h the following other algorithms:</p>
<ol>
<li>Tallying</li>
<li>WeightedTallying</li>
<li>Unit-Weight Linear Model</li>
<li>Weighter Linear Model</li>
<li>Multiple Regression</li>
</ol>
<p>Ultimately they conclude what you would predict.  The TTB algorithm is the fastest due to the small number of comparisons needed.  They also assert that it does just as well if not better than all of the other algorithms. While their data does seem to bear this out with 84 German cities and 6 cues, even with perturbation of the amount of known data (they randomize over which objects are recognized and which cue values are known), their methodology for cue selection isn&#8217;t explained in much detail.  I will be curious to see if there is follow up work that tries to see if these results were come by due to a fortuitous selection of cues and objects int he reference class.</p>
<p>At the end the suggest two simpler algorithms, the &#8220;Take the Last&#8221; algorithm and the &#8220;Minimalist&#8221; algorithm that require even fewer cue comparisons (calculations) and do only marginally worse then the TTB algorithm.</p>
<p>They conclude the paper by addressing &#8220;One Reason Decision Making&#8221;, that is the decision is made based on one good reason and there is no compensation between cues.  This is the case often when using the TTB algorithm.  They note that the recognition principle is an example of one reason decision making that exploits lack of knowledge.  They suggest as support for why one reason decision making may be plausible and good is that much evidence supports the notion that humans are ill equipped to deal with correlation between cues.</p>
<p>In summary the authors suggest that despite the cleanliness of many of the normative models that are so prevalent in much of academia, cognitive models based on normative assumptions are unrealistic and possibly unnecessary.  The brain is constrained in the complexity of calculations it can perform, the speed with which it can perform them, and the data upon which it can draw to make those calculations.  Thus, any realistic cognitive algorithm would take that into account.  They propose that the TTB algorithm is a reasonable attempt at an algorithm that meets all of those criteria.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/reasoning-the-fast-and-frugal-way-models-of-bounded-rationality/feed/</wfw:commentRss>
		</item>
		<item>
		<title>This blog as my notebook</title>
		<link>http://blog.qurbit.com/2008/06/this-blog-as-my-notebook/</link>
		<comments>http://blog.qurbit.com/2008/06/this-blog-as-my-notebook/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 07:10:50 +0000</pubDate>
		<dc:creator>Josh</dc:creator>
		
		<category><![CDATA[personal]]></category>

		<guid isPermaLink="false">http://blog.qurbit.com/?p=12</guid>
		<description><![CDATA[I thought I should give some context to the upcoming posts.  As I don&#8217;t imagine that anyone other than myself, and maybe my wife (if she is incredibly bored) will read this blog, I intent to use it as a kind of personal notebook.  I have found (along with many others), that writing [...]]]></description>
			<content:encoded><![CDATA[<p>I thought I should give some context to the upcoming posts.  As I don&#8217;t imagine that anyone other than myself, and maybe my wife (if she is incredibly bored) will read this blog, I intent to use it as a kind of personal notebook.  I have found (along with many others), that writing down my thoughts vastly increases the chance that I will remember them.  I intend to use this blog as that repository of things that I hope to remember, because even if I write them out and still forget, I&#8217;ll have a much smaller search space when I try and look them back up again.</p>
<p>For the most part I intend to study the Behavioral Economics literature and keep my notes here.  Given that I will also be writing about technology and the person who cares about both of these two topics is rare, I suggest to the would be reader that they subscribe to one of my topic feeds (programming, econ, etc) to help filter the noise.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.qurbit.com/2008/06/this-blog-as-my-notebook/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
