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

<channel>
	<title>Alteridem Consulting</title>
	<atom:link href="http://www.alteridem.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.alteridem.net</link>
	<description>Software by Design</description>
	<pubDate>Thu, 06 Mar 2008 16:07:06 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>log4net Slides and Example Code</title>
		<link>http://www.alteridem.net/2008/02/29/log4net-slides-and-example-code/</link>
		<comments>http://www.alteridem.net/2008/02/29/log4net-slides-and-example-code/#comments</comments>
		<pubDate>Fri, 29 Feb 2008 21:03:34 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[Education]]></category>

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

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

		<guid isPermaLink="false">http://www.alteridem.net/2008/02/29/log4net-slides-and-example-code/</guid>
		<description><![CDATA[I have been contacted people who cannot attend my Toronto Code Camp session on log4net tomorrow requesting a copy of my presentation and example code.  I cannot find it posted on the Code Camp site, so here is a copy for anyone who is interested.
The presentation is in PowerPoint 2007 and the example code [...]]]></description>
			<content:encoded><![CDATA[<p>I have been contacted people who cannot attend my <a href="http://www.torontocodecamp.net/">Toronto Code Camp</a> session on <a href="http://www.torontocodecamp.net/Sessions/tabid/55/CodecampId/1/SessionId/16/Default.aspx">log4net</a> tomorrow requesting a copy of my presentation and example code.  I cannot find it posted on the Code Camp site, so here is a copy for anyone who is interested.</p>
<p>The presentation is in PowerPoint 2007 and the example code is for Visual Studio 2008.  <b>update:</b> I have uploaded a PDF version of the presentation for those people without Office 2007.</p>
<ul>
<li><a href='http://www.alteridem.net/wp-content/uploads/2008/02/introduction-to-log4net_presentation.zip' title='Introduction to log4net Presentation'>Introduction to log4net Presentation</a></li>
<li><a href='http://www.alteridem.net/wp-content/uploads/2008/02/introductiontolog4net_code.zip' title='Introduction to log4net Example Code'>Introduction to log4net Example Code</a></li>
<li><a href='http://www.alteridem.net/wp-content/uploads/2008/03/introduction-to-log4net.pdf' title='Presentation in PDF Format'>Introduction to log4net Presentation in PDF Format</a></li>
</ul>
<p>If you are attending, I am looking forward to meeting you tomorrow at 9 AM.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/02/29/log4net-slides-and-example-code/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Visual Studio Macro to switch between CPP and H files</title>
		<link>http://www.alteridem.net/2008/02/26/visual-studio-macro-to-switch-between-cpp-and-h-files/</link>
		<comments>http://www.alteridem.net/2008/02/26/visual-studio-macro-to-switch-between-cpp-and-h-files/#comments</comments>
		<pubDate>Tue, 26 Feb 2008 15:30:02 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[Tips'n'Tricks]]></category>

		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2008/02/26/visual-studio-macro-to-switch-between-cpp-and-h-files/</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of managed C++ programming lately and I had forgotten what a pain it is switching back and forth between the header file and source file.&#160; Back in the days of Visual Studio 6 I had a macro that switched between the CPP and H file, so I went googling, but [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of managed C++ programming lately and I had forgotten what a pain it is switching back and forth between the header file and source file.&nbsp; Back in the days of Visual Studio 6 I had a macro that switched between the CPP and H file, so I went googling, but the macro I <a href="http://www.codeguru.com/cpp/v-s/devstudio_macros/article.php/c3093/">found</a> didn&#8217;t work very well in VS2008.&nbsp; Like any good coder, I decided to write it myself instead.</p>
<p>If you haven&#8217;t written a macro before, here are the steps.</p>
<ol>
<li>In Visual Studio, go to <strong>Tools | Macros | Macros IDE</strong>. A new window should open and in the Project Explorer, the MyMacros project should be open.
<li>Right click on the <em>MyMacros</em> project and select <strong>Add | Add Module</strong>. Name it <em>CppUtilities</em>.&nbsp; The <em>CppUtilities</em> should open in the editor window.
<li>Add the code from below into the module and save the project.</li>
</ol>
<pre class="code"><font size="1"><span style="color: rgb(0,128,0)">&#8216;=====================================================================
</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216; If the currently open document is a CPP or an H file, attempts to
</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216; switch between the CPP and the H file.
</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216;=====================================================================
</span><span style="color: rgb(0,0,255)">Public</span> <span style="color: rgb(0,0,255)">Sub</span> SwitchBetweenSourceAndHeader()
  <span style="color: rgb(0,0,255)">Dim</span> currentDocument <span style="color: rgb(0,0,255)">As</span> </font><font size="1"><span style="color: rgb(0,0,255)">String
</span>  <span style="color: rgb(0,0,255)">Dim</span> targetDocument <span style="color: rgb(0,0,255)">As</span> </font><font size="1"><span style="color: rgb(0,0,255)">String

</span>  currentDocument = ActiveDocument.FullName

  <span style="color: rgb(0,0,255)">If</span> currentDocument.EndsWith(<span style="color: rgb(163,21,21)">&#8220;.cpp&#8221;</span>, StringComparison.InvariantCultureIgnoreCase) </font><font size="1"><span style="color: rgb(0,0,255)">Then
</span>    targetDocument = Left(currentDocument, Len(currentDocument) - 3) + </font><font size="1"><span style="color: rgb(163,21,21)">&#8220;h&#8221;
</span>    OpenDocument(targetDocument)
  <span style="color: rgb(0,0,255)">ElseIf</span> currentDocument.EndsWith(<span style="color: rgb(163,21,21)">&#8220;.h&#8221;</span>, StringComparison.InvariantCultureIgnoreCase) </font><font size="1"><span style="color: rgb(0,0,255)">Then
</span>    targetDocument = Left(currentDocument, Len(currentDocument) - 1) + </font><font size="1"><span style="color: rgb(163,21,21)">&#8220;cpp&#8221;
</span>    OpenDocument(targetDocument)
  <span style="color: rgb(0,0,255)">End</span> </font><font size="1"><span style="color: rgb(0,0,255)">If

</span><span style="color: rgb(0,0,255)">End</span> </font><font size="1"><span style="color: rgb(0,0,255)">Sub

</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216;=====================================================================
</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216; Given a document name, attempts to activate it if it is already open,
</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216; otherwise attempts to open it.
</span></font><font size="1"><span style="color: rgb(0,128,0)">&#8216;=====================================================================
</span><span style="color: rgb(0,0,255)">Private</span> <span style="color: rgb(0,0,255)">Sub</span> OpenDocument(<span style="color: rgb(0,0,255)">ByRef</span> documentName <span style="color: rgb(0,0,255)">As</span> <span style="color: rgb(0,0,255)">String</span>)
  <span style="color: rgb(0,0,255)">Dim</span> document <span style="color: rgb(0,0,255)">As</span> EnvDTE.Document
  <span style="color: rgb(0,0,255)">Dim</span> activatedTarget <span style="color: rgb(0,0,255)">As</span> </font><font size="1"><span style="color: rgb(0,0,255)">Boolean
</span>  activatedTarget = </font><font size="1"><span style="color: rgb(0,0,255)">False

</span>  <span style="color: rgb(0,0,255)">For</span> <span style="color: rgb(0,0,255)">Each</span> document <span style="color: rgb(0,0,255)">In</span> Application.Documents
    <span style="color: rgb(0,0,255)">If</span> document.FullName = documentName <span style="color: rgb(0,0,255)">And</span> document.Windows.Count &gt; 0 </font><font size="1"><span style="color: rgb(0,0,255)">Then
</span>      document.Activate()
      activatedTarget = </font><font size="1"><span style="color: rgb(0,0,255)">True
</span>      <span style="color: rgb(0,0,255)">Exit</span> </font><font size="1"><span style="color: rgb(0,0,255)">For
</span>    <span style="color: rgb(0,0,255)">End</span> </font><font size="1"><span style="color: rgb(0,0,255)">If
</span>  </font><font size="1"><span style="color: rgb(0,0,255)">Next
</span>  <span style="color: rgb(0,0,255)">If</span> <span style="color: rgb(0,0,255)">Not</span> activatedTarget </font><font size="1"><span style="color: rgb(0,0,255)">Then
</span>    Application.Documents.Open(documentName, <span style="color: rgb(163,21,21)">&#8220;Text&#8221;</span>)
  <span style="color: rgb(0,0,255)">End</span> </font><font size="1"><span style="color: rgb(0,0,255)">If
</span><span style="color: rgb(0,0,255)">End</span> </font><font size="1"><span style="color: rgb(0,0,255)">Sub</span></font></pre>
<p>If you switch back to Visual Studio and open the Macro Explorer, you should see the new module <em>CppUtilities</em> and the new macro <em>SwitchBetweenSourceAndHeader</em> in the tree.&nbsp; You could run the macro from here, but it is much easier to bind it to a keystroke.</p>
<ol>
<li>Click on <strong>Tools | Options</strong> then go to the <strong>Environment | Keyboard</strong> tab.</li>
<li>In the <strong>Show commands containing: </strong>box, type <em>CppUtilities.</em> This should filter the list down to one entry, <em>Macros.MyMacros.CppUtilitities.SwitchBetweenSourceAndHeader</em>.</li>
<li>Click on the <strong>Press shortcut keys:</strong> text box and then press the keystroke you would like to use to run the macro. If the keystroke is already used, it will show you below in the <strong>Shortcut currently used by:</strong> dropdown.&nbsp; When you find one that is unused, click the <strong>Assign</strong> button to use it.&nbsp; I use <strong>Ctrl+Shift+Alt+Bkspce</strong>.</li>
<li>Click <strong>OK</strong> then open a CPP or H file and give it a try.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/02/26/visual-studio-macro-to-switch-between-cpp-and-h-files/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Speaking at Toronto Code Camp</title>
		<link>http://www.alteridem.net/2008/01/28/speaking-at-toronto-code-camp/</link>
		<comments>http://www.alteridem.net/2008/01/28/speaking-at-toronto-code-camp/#comments</comments>
		<pubDate>Tue, 29 Jan 2008 04:14:08 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[Education]]></category>

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

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

		<guid isPermaLink="false">http://www.alteridem.net/2008/01/28/speaking-at-toronto-code-camp/</guid>
		<description><![CDATA[ I found out last week that I will be speaking at this year&#8217;s Toronto Code Camp on March 1st.&#160; I will be giving an Introduction to log4net from 9:00 AM to 10:15 AM.
I will begin the session with an overview of the license, features and capabilities of log4net, including log levels, log hierarchies, logging [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.alteridem.net/wp-content/uploads/2008/01/tcc-logosmall.gif"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="143" alt="tcc-logosmall" src="http://www.alteridem.net/wp-content/uploads/2008/01/tcc-logosmall-thumb.gif" width="142" align="right" border="0"></a> I found out last week that I will be speaking at this year&#8217;s <a href="http://www.torontocodecamp.net/">Toronto Code Camp</a> on March 1st.&nbsp; I will be giving an <a href="http://www.torontocodecamp.net/Sessions/tabid/55/CodecampId/1/SessionId/16/Default.aspx">Introduction to log4net</a> from 9:00 AM to 10:15 AM.</p>
<p>I will begin the session with an overview of the license, features and capabilities of <a href="http://logging.apache.org/log4net/">log4net</a>, including log levels, log hierarchies, logging contexts, configuration and filters.&nbsp;
<p>I will then dive into code by adding logging to a simple application. Next, I will configure the logging to output the logs to multiple destinations. I will end by discussing best practices for logging with <a href="http://logging.apache.org/log4net/">log4net</a> and answer questions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/01/28/speaking-at-toronto-code-camp/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The Stopwatch Class in .NET</title>
		<link>http://www.alteridem.net/2008/01/14/the-stopwatch-class-in-net/</link>
		<comments>http://www.alteridem.net/2008/01/14/the-stopwatch-class-in-net/#comments</comments>
		<pubDate>Mon, 14 Jan 2008 20:13:21 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[.NET 2.0]]></category>

		<category><![CDATA[C#]]></category>

		<category><![CDATA[Tips'n'Tricks]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2008/01/14/the-stopwatch-class-in-net/</guid>
		<description><![CDATA[Do you ever find yourself using DateTime to time a section of code?&#160; Do you have code like the following?
  DateTime start = DateTime.Now;

  // Perform a long process
   Thread.Sleep( 1968 );

  DateTime end = DateTime.Now;
  TimeSpan duration = end.Subtract( start );
  Console.WriteLine( &#8220;This process took {0} ms&#8221;,
 [...]]]></description>
			<content:encoded><![CDATA[<p>Do you ever find yourself using <strong>DateTime</strong> to time a section of code?&nbsp; Do you have code like the following?</p>
<pre class="code">  <span style="color: rgb(128,0,128)">DateTime</span> start <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(128,0,128)">DateTime</span><span style="color: rgb(255,0,0)">.</span>Now;

  <span style="color: rgb(0,128,0)">// Perform a long process
</span>   <span style="color: rgb(43,145,175)">Thread</span><span style="color: rgb(255,0,0)">.</span>Sleep( <span style="color: rgb(128,0,128)">1968</span> );

  <span style="color: rgb(128,0,128)">DateTime</span> end <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(128,0,128)">DateTime</span><span style="color: rgb(255,0,0)">.</span>Now;
  <span style="color: rgb(128,0,128)">TimeSpan</span> duration <span style="color: rgb(255,0,0)">=</span> end<span style="color: rgb(255,0,0)">.</span>Subtract( start );
  <span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>WriteLine( <span style="color: rgb(163,21,21)">&#8220;This process took {0} ms&#8221;</span>,
    duration<span style="color: rgb(255,0,0)">.</span>TotalMilliseconds );</pre>
<p>If you do, you should look at the <strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx">System.Diagnostics.Stopwatch</a></strong> class that was introduced in the 2.0 framework.&nbsp; You can convert the code above to the much more readable</p>
<pre class="code">  <span style="color: rgb(43,145,175)">Stopwatch</span> stopwatch <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">Stopwatch</span>();
  stopwatch<span style="color: rgb(255,0,0)">.</span>Start();

  <span style="color: rgb(0,128,0)">// Perform a long process
</span>  <span style="color: rgb(43,145,175)">Thread</span><span style="color: rgb(255,0,0)">.</span>Sleep( <span style="color: rgb(128,0,128)">1968</span> );

  stopwatch<span style="color: rgb(255,0,0)">.</span>Stop();
  <span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>WriteLine( <span style="color: rgb(163,21,21)">&#8220;This process took {0} ms&#8221;</span>,
    stopwatch<span style="color: rgb(255,0,0)">.</span>ElapsedMilliseconds );</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/01/14/the-stopwatch-class-in-net/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Writing An Appender For log4net</title>
		<link>http://www.alteridem.net/2008/01/10/writing-an-appender-for-log4net/</link>
		<comments>http://www.alteridem.net/2008/01/10/writing-an-appender-for-log4net/#comments</comments>
		<pubDate>Thu, 10 Jan 2008 14:38:58 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[C#]]></category>

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

		<guid isPermaLink="false">http://www.alteridem.net/2008/01/10/writing-an-appender-for-log4net/</guid>
		<description><![CDATA[In log4net speak, an appender is an output destination for a log such as a file, the console, a database or even email.&#160; log4net ships with so many appenders that most of us will never need to write our own.&#160; There are cases where you may find a need for your own appender, for example, [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://logging.apache.org/">log4net</a> speak, an appender is an output destination for a log such as a file, the console, a database or even email.&nbsp; <a href="http://logging.apache.org/">log4net</a> ships with so many appenders that most of us will never need to write our own.&nbsp; There are cases where you may find a need for your own appender, for example, you may want to log errors to your company&#8217;s bug tracking software.&nbsp; </p>
<p>In our case, we simply wanted error logs to pop up a message box with the error and location.&nbsp; We run this internally so that developers run into errors immediately during development and can break into the debugger to fix them.&nbsp; We found that logging to a file was too easy to ignore.</p>
<p><img height="232" alt="MessageBoxAppender" src="http://www.alteridem.net/wp-content/uploads/2008/01/messageboxappender.jpg" width="484" border="0"> </p>
<p>I was pleasantly surprised how easy it is to write a new appender, but there is very little information on the web, so I thought it would be best to give an example.</p>
<ol>
<li>Create a new Class Library project in Visual Studio.
<li>Add a reference to log4net. My appender also uses MessageBox, so I also added references to System.Drawing and System.Windows.Forms.
<li>Remove the default Class1.cs added to the project.
<li>Add your appender class. In my case, MessageBoxAppender.cs.
<li>You could implement the <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.IAppender.html">log4net.Appender.IAppender</a> interface, but it is easiest to derive from <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.AppenderSkeleton.html">log4net.Appender.AppenderSkeleton</a>, then most of the work is done for you.
<li>At a minimum, override the <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.AppenderSkeleton.Append_overload_2.html">Append</a> method. This is where you do your work.
<li>If you are going to use the <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.AppenderSkeleton.RenderLoggingEvent_overload_1.html">RenderLoggingEvent</a> method to create your logging message based on the configured layout (such as PatternLayout), override the <a href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.AppenderSkeleton.RequiresLayout.html">RequiresLayout</a> property and return true.
<li>When you configure your appender, you must give the assembly qualified name for your appender.&nbsp; For example,</li>
</ol>
<p>&lt;appender name=&#8221;&#8230;&#8221; type=&#8221;MyNamespace.MyAppender, MyAssembly&#8221;&gt;</p>
<p>Here is the simplified code for the MessageBoxAppender that I wrote.</p>
<pre class="code"><span style="color: rgb(0,0,255)">using</span> System;
<span style="color: rgb(0,0,255)">using</span> System<span style="color: rgb(255,0,0)">.</span>Windows<span style="color: rgb(255,0,0)">.</span>Forms;
<span style="color: rgb(0,0,255)">using</span> System<span style="color: rgb(255,0,0)">.</span>Diagnostics;

<span style="color: rgb(0,0,255)">using</span> log4net<span style="color: rgb(255,0,0)">.</span>Core;
<span style="color: rgb(0,0,255)">using</span> log4net<span style="color: rgb(255,0,0)">.</span>Appender;
<span style="color: rgb(0,0,255)">
namespace</span> Alteridem<span style="color: rgb(255,0,0)">.</span>log4net
{
   <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;summary&gt;
</span>   <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> Displays a MessageBox for all log messages.
</span>   <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;/summary&gt;
</span>   <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">MessageBoxAppender</span> : <span style="color: rgb(43,145,175)">AppenderSkeleton
</span>   {
      <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;summary&gt;
</span>      <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> Writes the logging event to a MessageBox
</span>      <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;/summary&gt;</span>
<span style="color: rgb(0,0,255)">      override</span> <span style="color: rgb(0,0,255)">protected</span> <span style="color: rgb(0,0,255)">void</span> Append( <span style="color: rgb(43,145,175)">LoggingEvent</span> loggingEvent )
      {
         <span style="color: rgb(0,0,255)">string</span> title <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">string</span><span style="color: rgb(255,0,0)">.</span>Format( <span style="color: rgb(163,21,21)">&#8220;{0} {1}&#8221;</span>,
            loggingEvent<span style="color: rgb(255,0,0)">.</span>Level<span style="color: rgb(255,0,0)">.</span>DisplayName,
            loggingEvent<span style="color: rgb(255,0,0)">.</span>LoggerName );

         <span style="color: rgb(0,0,255)">string</span> message <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">string</span><span style="color: rgb(255,0,0)">.</span>Format(
            <span style="color: rgb(163,21,21)">&#8220;{0}{1}{1}{2}{1}{1}(Yes to continue, No to debug)&#8221;</span>,
            RenderLoggingEvent( loggingEvent ),
            <span style="color: rgb(43,145,175)">Environment</span><span style="color: rgb(255,0,0)">.</span>NewLine,
            loggingEvent<span style="color: rgb(255,0,0)">.</span>LocationInformation<span style="color: rgb(255,0,0)">.</span>FullInfo );

         <span style="color: rgb(43,145,175)">DialogResult</span> result <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(43,145,175)">MessageBox</span><span style="color: rgb(255,0,0)">.</span>Show( message, title,
            <span style="color: rgb(43,145,175)">MessageBoxButtons</span><span style="color: rgb(255,0,0)">.</span>YesNo );

         <span style="color: rgb(0,0,255)">if</span> ( result <span style="color: rgb(255,0,0)">==</span> <span style="color: rgb(43,145,175)">DialogResult</span><span style="color: rgb(255,0,0)">.</span>No )
         {
            <span style="color: rgb(43,145,175)">Debugger</span><span style="color: rgb(255,0,0)">.</span>Break();
         }
      }
      <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;summary&gt;
</span>      <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> This appender requires a </span><span style="color: rgb(128,128,128)">&lt;see cref=&#8221;Layout&#8221;/&gt;</span><span style="color: rgb(0,128,0)"> to be set.
</span>      <span style="color: rgb(128,128,128)">///</span><span style="color: rgb(0,128,0)"> </span><span style="color: rgb(128,128,128)">&lt;/summary&gt;
</span>      <span style="color: rgb(0,0,255)">override</span> <span style="color: rgb(0,0,255)">protected</span> <span style="color: rgb(0,0,255)">bool</span> RequiresLayout
      {
         <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(0,0,255)">true</span>; }
      }
   }
}</pre>
<p>There isn&#8217;t much to see here. I use the log level and the log name in the titlebar. I display the rendered message string and the calling location in the MessageBox and I break into the debugger if you press No.</p>
<p>Now, to configure this for your developers to see ERROR messages, the following configuration would work.</p>
<pre class="code"><span style="color: rgb(0,0,255)">&lt;?</span><span style="color: rgb(163,21,21)">xml</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">version</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">1.0</span>&#8220;<span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">encoding</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">utf-8</span>&#8220;<span style="color: rgb(0,0,255)"> ?&gt;
&lt;</span><span style="color: rgb(163,21,21)">configuration</span><span style="color: rgb(0,0,255)">&gt;
   &lt;</span><span style="color: rgb(163,21,21)">configSections</span><span style="color: rgb(0,0,255)">&gt;
      &lt;</span><span style="color: rgb(163,21,21)">section</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">name</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">log4net</span>&#8221;
<span style="color: rgb(0,0,255)">        </span><span style="color: rgb(255,0,0)">type</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">log4net.Config.Log4NetConfigurationSectionHandler, log4net</span>&#8220;<span style="color: rgb(0,0,255)"> /&gt;
   &lt;/</span><span style="color: rgb(163,21,21)">configSections</span><span style="color: rgb(0,0,255)">&gt;
   &lt;</span><span style="color: rgb(163,21,21)">log4net</span><span style="color: rgb(0,0,255)">&gt;
      &lt;</span><span style="color: rgb(163,21,21)">appender</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">name</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">MessageBoxAppender</span>&#8220;<span style="color: rgb(0,0,255)"></span>
            <span style="color: rgb(255,0,0)">type</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">Alertidem.log4net.MessageBoxAppender, log4netExtensions</span>&#8220;<span style="color: rgb(0,0,255)">&gt;
         &lt;</span><span style="color: rgb(163,21,21)">layout</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">type</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">log4net.Layout.PatternLayout</span>&#8220;<span style="color: rgb(0,0,255)">&gt;
            &lt;</span><span style="color: rgb(163,21,21)">ConversionPattern</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">value</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">%m</span>&#8220;<span style="color: rgb(0,0,255)"> /&gt;
         &lt;/</span><span style="color: rgb(163,21,21)">layout</span><span style="color: rgb(0,0,255)">&gt;
      &lt;/</span><span style="color: rgb(163,21,21)">appender</span><span style="color: rgb(0,0,255)">&gt;
      &lt;</span><span style="color: rgb(163,21,21)">root</span><span style="color: rgb(0,0,255)">&gt;
         &lt;</span><span style="color: rgb(163,21,21)">level</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">value</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">ERROR</span>&#8220;<span style="color: rgb(0,0,255)">/&gt;
         &lt;</span><span style="color: rgb(163,21,21)">appender-ref</span><span style="color: rgb(0,0,255)"> </span><span style="color: rgb(255,0,0)">ref</span><span style="color: rgb(0,0,255)">=</span>&#8220;<span style="color: rgb(0,0,255)">MessageBoxAppender</span>&#8220;<span style="color: rgb(0,0,255)"> /&gt;
      &lt;/</span><span style="color: rgb(163,21,21)">root</span><span style="color: rgb(0,0,255)">&gt;
   &lt;/</span><span style="color: rgb(163,21,21)">log4net</span><span style="color: rgb(0,0,255)">&gt;
&lt;/</span><span style="color: rgb(163,21,21)">configuration</span><span style="color: rgb(0,0,255)">&gt;</span></pre>
<p>The only thing to not here is that the log4netExtensions in the appender line is the assembly.</p>
<p>This should be enough to give you a basic framework to build whatever type of appender you want.&nbsp; Every time I delve into a new area of <a href="http://logging.apache.org/log4net/">log4net</a>, I am once again surprised how easy it is to work with and how well designed it is.&nbsp; If you aren&#8217;t using it, I would highly recommend it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/01/10/writing-an-appender-for-log4net/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Quickly Find/Open a File in Visual Studio</title>
		<link>http://www.alteridem.net/2007/09/11/quickly-findopen-a-file-in-visual-studio/</link>
		<comments>http://www.alteridem.net/2007/09/11/quickly-findopen-a-file-in-visual-studio/#comments</comments>
		<pubDate>Tue, 11 Sep 2007 20:02:57 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[Tips'n'Tricks]]></category>

		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2007/09/11/quickly-findopen-a-file-in-visual-studio/</guid>
		<description><![CDATA[Here is a cool Visual Studio feature that almost nobody knows about. If you want to open up a file in your solution, but can&#8217;t be bothered to dig down through your projects and folders to find it, try this,

Click in the Find box in the toolbar,
Type &#62;of followed by a space, then begin the [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a cool Visual Studio feature that almost nobody knows about. If you want to open up a file in your solution, but can&#8217;t be bothered to dig down through your projects and folders to find it, try this,</p>
<ol>
<li>Click in the Find box in the toolbar,
<li>Type &gt;of followed by a space, then begin the name of the file you are looking for.
<li>An auto-complete drop down will appear as you type filtering all the files in all your projects in your solution. Continue typing until the list is short enough to fine the one you want. Select it and hit enter.
<li>The file will open in the editor.</li>
</ol>
<div align="center"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="218" alt="openfile" src="http://www.alteridem.net/wp-content/uploads/2007/09/openfile.png" width="265" border="0"></div>
<p><b>Update:</b> After this post made the front page of <a href="http://www.dotnetkicks.com/">DotNetKicks</a>, Aaron Lerch wrote a <a href="http://www.aaronlerch.com/blog/2007/09/11/the-talented-mr-editgotofindcombo/">great post</a> on his blog with more things that you can do with the find combo. One thing that is very useful is that with the <strong>></strong>, you can issue any command, the alias <strong>>of</strong> mentioned here is just one of many. For a list of the commands, check out <a href="http://msdn2.microsoft.com/en-us/library/c3a0kd3x(VS.80).aspx">this MSDN page</a>.</p>
<p>Another useful tip is that <strong>Ctrl+D</strong> or <strong>Ctrl+/</strong> will automatically jump to the find box, so your hands don&#8217;t even need to leave your keyboard.</p>
<p><b>Update:</b> This trick was also mentioned on Just Sayin More Words as a part of his <a href="http://john-sheehan.com/blog/index.php/stupid-visual-studio-trick-part-3/">Stupid Visual Studio Trick</a> series. Thanks.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2007/09/11/quickly-findopen-a-file-in-visual-studio/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Debugging C++ Method Parameters</title>
		<link>http://www.alteridem.net/2007/09/11/debugging-c-method-parameters/</link>
		<comments>http://www.alteridem.net/2007/09/11/debugging-c-method-parameters/#comments</comments>
		<pubDate>Tue, 11 Sep 2007 19:20:04 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[C++]]></category>

		<category><![CDATA[C++/CLR]]></category>

		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2007/09/11/debugging-c-method-parameters/</guid>
		<description><![CDATA[New Rule: Make sure your parameter names are consistent between your declarations and definitions in C++.
Here is why&#8230;
I was trying to debug some C++/CLR code today when I ran into an interesting behavior (bug?) in Visual Studio 2005. I had a breakpoint in the first line of my method which I hit fine. I then [...]]]></description>
			<content:encoded><![CDATA[<p><strong>New Rule: Make sure your parameter names are consistent between your declarations and definitions in C++.</strong></p>
<p>Here is why&#8230;</p>
<p>I was trying to debug some <strong>C++/CLR</strong> code today when I ran into an interesting behavior (bug?) in <strong>Visual Studio 2005</strong>. I had a breakpoint in the first line of my method which I hit fine. I then tried to inspect the value of the two integers that were passed in. The first one showed up fine when I moused over it, but the second one didn&#8217;t appear. Strange, but I&#8217;ve come to expect that debugging in C++.</p>
<p>The next thing I tried was the Watch window (Ctrl+Alt+W,1). I added both of the parameters. The first showed up fine, but the second said <strong>&#8220;error: identifier &#8216;maxRows&#8217; out of scope.&#8221;</strong> How could it be out of scope, I was on the first line in the method?</p>
<p>Next I looked at the Locals window (Ctrl+Alt+V,L). The parameter was showing up fine there! Then I noticed the difference, the name of the parameter in the locals window wasn&#8217;t pluralized. Sure enough, I looked in the header file and it was spelled <strong>maxRow</strong> there.</p>
<p>It turns out that the debug symbols are taken from the header files, so when you step into a method with parameters that are spelled differently, then you must use the values in the header file to inspect the variables.</p>
<p>Here is an example I mocked up where the parameters were x and y in the header files.</p>
<p><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="184" alt="CppDebugging" src="http://www.alteridem.net/wp-content/uploads/2007/09/cppdebugging.jpg" width="443" border="0"> </p>
<p>I also tried this in unmanaged C++ and got the same result.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2007/09/11/debugging-c-method-parameters/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Easier Debugging with Attributes</title>
		<link>http://www.alteridem.net/2007/09/05/easier-debugging-with-attributes/</link>
		<comments>http://www.alteridem.net/2007/09/05/easier-debugging-with-attributes/#comments</comments>
		<pubDate>Wed, 05 Sep 2007 15:41:56 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[.NET]]></category>

		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2007/09/05/easier-debugging-with-attributes/</guid>
		<description><![CDATA[Unless you have been inspecting some of the code generated by Visual Studio, you probably haven&#8217;t realized that there are several attributes that you can add to your code to make debugging easier. Some prevent you from stepping into sections of code, others change the way variables are displayed in the watch window. 
The following [...]]]></description>
			<content:encoded><![CDATA[<p>Unless you have been inspecting some of the code generated by Visual Studio, you probably haven&#8217;t realized that there are several attributes that you can add to your code to make debugging easier. Some prevent you from stepping into sections of code, others change the way variables are displayed in the watch window. </p>
<p>The following are some of the more useful attributes found in the System.Diagnostics namespace.</p>
<h3>DebuggerStepThrough</h3>
<p>I don&#8217;t know about you, but I hate it when I try to step into a method, but before I get there, I have to step into the getter for every property that is being passed in as a parameter. You have to step in/step out repeatedly until you end up in the method. Half the time, I end up missing it and step out of the method!</p>
<p>To prevent this dance, just add the <strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx">DebuggerStepThrough</a></strong> attribute to the getter for your simple properties and the debugger will no longer step into them. This also works on methods and even entire classes.</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">string</span> Name
{
   [<span style="color: rgb(43,145,175)">DebuggerStepThrough</span>]
   <span style="color: rgb(0,0,255)">get</span> { <span style="color: rgb(0,0,255)">return</span> _name; }
   <span style="color: rgb(0,0,255)">set</span> { _name <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">value</span>; }
}</pre>
<h3>DebuggerBrowsable</h3>
<p>Do you want to simplify or change the way your class appears in the watch window? This attribute allows you to hide members and properties or even hide the root of a collection.&nbsp;<strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx">DebugBrowsable</a></strong> is constructed with the <strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsablestate.aspx">DebuggerBrowsableState</a></strong> enum which has the following members;</p>
<table cellspacing="4" cellpadding="2" width="100%">
<tbody>
<tr valign="top">
<td><b>Collapsed</b></td>
<td>Show the element as collapsed.</td>
</tr>
<tr valign="top">
<td><b>Never</b></td>
<td>Never show the element.</td>
</tr>
<tr valign="top">
<td><b>RootHidden</b></td>
<td>Do not display the root element; display the child elements if the element is a collection or array of items.</td>
</tr>
</tbody>
</table>
<p>For example, adding
<pre class="code">[<span style="color: rgb(43,145,175)">DebuggerBrowsable</span>( <span style="color: rgb(43,145,175)">DebuggerBrowsableState</span><span style="color: rgb(255,0,0)">.</span>Never )]</pre>
<p>to the private members of a class will cause them to be hidden in the watch window, thus cleaning up the view.</p>
<p><img height="134" src="http://www.alteridem.net/wp-content/uploads/2007/09/windowslivewritereasierdebuggingwithattributes-a2c2debuggerdisplay13.jpg" width="486"></p>
<h3>DebuggerDisplay</h3>
<p><strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx">DebuggerDisplay</a></strong> is my favourite attribute. Add it to a class and construct it with a string, and it will display that string in the watch window. Add any properties you want displayed within curly braces and they will automatically be substituted in. For example;</p>
<pre class="code">[<span style="color: rgb(43,145,175)">DebuggerDisplay</span>( <span style="color: rgb(163,21,21)">"Name: {Name}, Age: {Age}"</span> )]
<span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Person
</span>{
   <span style="color: rgb(0,128,0)">// &#8230;
</span>}</pre>
<p><img height="132" src="http://www.alteridem.net/wp-content/uploads/2007/09/windowslivewritereasierdebuggingwithattributes-a2c2debuggerdisplay20.jpg" width="486"> </p>
<p>These are the three attributes that I use most often, but you may also want to look up <strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggerstepperboundaryattribute.aspx">DebuggerStepperBoundary</a></strong>, <strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggertypeproxyattribute.aspx">DebuggerTypeProxy</a></strong> and <strong><a href="http://msdn2.microsoft.com/en-us/library/system.diagnostics.debuggervisualizerattribute.aspx">DebuggerVisualizer</a>.</strong></p>
<p>Happy Debugging!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2007/09/05/easier-debugging-with-attributes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Win32 COLORREF vs .NET Color</title>
		<link>http://www.alteridem.net/2007/08/23/win32-colorref-vs-net-color/</link>
		<comments>http://www.alteridem.net/2007/08/23/win32-colorref-vs-net-color/#comments</comments>
		<pubDate>Thu, 23 Aug 2007 13:19:13 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[.NET]]></category>

		<category><![CDATA[C#]]></category>

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

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

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

		<guid isPermaLink="false">http://www.alteridem.net/2007/08/23/win32-colorref-vs-net-color/</guid>
		<description><![CDATA[I have been migrating a large application from Win32/MFC to .NET and ran into an interesting problem. We store all of the application colors in the database as integers that represent the Win32 COLORREF value. COLORREF is just a DWORD representing the RGB value, so&#160;I&#160;thought that&#160;I could just take the value and get a .NET [...]]]></description>
			<content:encoded><![CDATA[<p>I have been migrating a large application from Win32/MFC to .NET and ran into an interesting problem. We store all of the application colors in the database as integers that represent the Win32 <a href="http://msdn2.microsoft.com/en-us/library/ms532655.aspx">COLORREF</a> value. <a href="http://msdn2.microsoft.com/en-us/library/ms532655.aspx">COLORREF</a> is just a DWORD representing the RGB value, so&nbsp;I&nbsp;thought that&nbsp;I could just take the value and get a .NET <a href="http://msdn2.microsoft.com/en-us/library/system.drawing.color.aspx">Color</a>&nbsp;structure using the static <a href="http://msdn2.microsoft.com/en-us/library/2zys7833.aspx">FromArgb</a> method.</p>
<p>This didn&#8217;t go too well. It turns out that the byte orders are different. <a href="http://msdn2.microsoft.com/en-us/library/ms532655.aspx">COLORREF</a>&nbsp;is in the order <strong>0&#215;00bbggrr </strong>and <a href="http://msdn2.microsoft.com/en-us/library/system.drawing.color.aspx">Color</a>&nbsp;is in the order <strong>0xaarrggbb</strong>. Notice that the high order byte in .NET is the alpha channel, but in Win32 it is always zero (fully transparent in .NET) Also notice that the byte order is backwards in Win32, Blue/Green/Red compared to the more standard Red/Green/Blue in .NET.</p>
<p>We began by doing the conversion in code using a bit of bit fiddling;</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(128,0,128)">Color</span> ConvertFromWin32Color( <span style="color: rgb(0,0,255)">int</span> color )
{
   <span style="color: rgb(0,0,255)">int</span> r <span style="color: rgb(255,0,0)">=</span> color <span style="color: rgb(255,0,0)">&amp;</span> <span style="color: rgb(128,0,128)">0&#215;000000FF</span>;
   <span style="color: rgb(0,0,255)">int</span> g <span style="color: rgb(255,0,0)">=</span> ( color <span style="color: rgb(255,0,0)">&amp;</span> <span style="color: rgb(128,0,128)">0&#215;0000FF00</span> ) <span style="color: rgb(255,0,0)">&gt;&gt;</span> <span style="color: rgb(128,0,128)">8</span>;
   <span style="color: rgb(0,0,255)">int</span> b <span style="color: rgb(255,0,0)">=</span> ( color <span style="color: rgb(255,0,0)">&amp;</span> <span style="color: rgb(128,0,128)">0&#215;00FF0000</span> ) <span style="color: rgb(255,0,0)">&gt;&gt;</span> <span style="color: rgb(128,0,128)">16</span>;
   <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(128,0,128)">Color</span><span style="color: rgb(255,0,0)">.</span>FromArgb( r, g, b );
}</pre>
<p>This worked well at first, but it was error prone converting between the values. As new code was written, we often forgot that we needed to convert. Finally we decided to do the right thing and convert the values in the database. To do this, I wrote a simple upgrade script for our SQL Server database that consisted of one method which was then applied to each column in the database that contained color values.</p>
<pre class="code"><span style="color: rgb(0,128,0)">&#8211; =============================================
&#8211; Author: Rob Prouse
&#8211; Date: 15/08/07
&#8211; Description: Convert control colors from
&#8211; </span>  <span style="color: rgb(0,128,0)">Win32 COLORREF (0&#215;00BBGGRR) values to .NET
&#8211; </span>  <span style="color: rgb(0,128,0)">Color Values (0xFFRRGGBB)
&#8211; =============================================
</span><span style="color: rgb(0,0,255)">CREATE </span>FUNCTION SwapColorBytes( @Color <span style="color: rgb(0,0,255)">int </span>)
RETURNS <span style="color: rgb(0,0,255)">int
AS
BEGIN
</span>   <span style="color: rgb(0,0,255)">RETURN </span><span style="color: rgb(128,0,128)">0xFF000000 </span>+
          ((@Color &amp; <span style="color: rgb(128,0,128)">0&#215;00FF0000</span>)/<span style="color: rgb(128,0,128)">0&#215;00010000</span>) +
          (@Color &amp; <span style="color: rgb(128,0,128)">0&#215;0000FF00</span>) +
          (( @Color &amp; <span style="color: rgb(128,0,128)">0&#215;000000FF</span>)*<span style="color: rgb(128,0,128)">0&#215;00010000</span>)

<span style="color: rgb(0,0,255)">END
</span>GO

<span style="color: rgb(0,128,0)">&#8211; Do the following for every column in the DB that contains colors</span>
<span style="color: rgb(0,128,0)"></span><span style="color: rgb(0,0,255)">UPDATE </span>mytable <span style="color: rgb(0,0,255)">SET </span>colorcolumn = SwapColorBytes(colorcolumn)
GO</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2007/08/23/win32-colorref-vs-net-color/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The Yield Statement in C#</title>
		<link>http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/</link>
		<comments>http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/#comments</comments>
		<pubDate>Wed, 22 Aug 2007 20:50:50 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
		
		<category><![CDATA[.NET 2.0]]></category>

		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/</guid>
		<description><![CDATA[Another often overlooked C# statement that was introduced in .NET 2.0 is yield. This keyword is used to return items from a loop within a method and retain the state of the method through multiple calls. That is a bit hard to wrap your head around, so as always, an example will help;
public static IEnumerable&#60;int&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Another often overlooked C# statement that was introduced in .NET 2.0 is <strong>yield</strong>. This keyword is used to return items from a loop within a method and retain the state of the method through multiple calls. That is a bit hard to wrap your head around, so as always, an example will help;</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(43,145,175)">IEnumerable</span><span style="color: rgb(255,0,0)">&lt;</span><span style="color: rgb(0,0,255)">int</span><span style="color: rgb(255,0,0)">&gt;</span> Range( <span style="color: rgb(0,0,255)">int</span> min, <span style="color: rgb(0,0,255)">int</span> max )
{
   <span style="color: rgb(0,0,255)">for</span> ( <span style="color: rgb(0,0,255)">int</span> i <span style="color: rgb(255,0,0)">=</span> min; i <span style="color: rgb(255,0,0)">&lt;</span> max; i<span style="color: rgb(255,0,0)">++</span> )
   {
      <span style="color: rgb(0,0,255)">yield</span> <span style="color: rgb(0,0,255)">return</span> i;
   }
}</pre>
<p>Each time <strong>Range</strong> is called, it will return one value in the given range. Of interest is that it maintains the state between calls. The best way to think of it is that for the first call to the method, execution starts at the first line and continues until it hits a yield statement at which time it returns the value. The subsequent runs through the method continue execution at the statement after the yield, continuing to yield values or exiting at the end of the method.</p>
<p>Using this, you can write the following code;</p>
<pre class="code"><span style="color: rgb(0,0,255)">foreach</span> ( <span style="color: rgb(0,0,255)">int</span> i <span style="color: rgb(0,0,255)">in</span> Range( <span style="color: rgb(128,0,128)">10</span>, <span style="color: rgb(128,0,128)">20</span> ) )
{
   <span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>Write( i<span style="color: rgb(255,0,0)">.</span>ToString() <span style="color: rgb(255,0,0)">+</span> <span style="color: rgb(163,21,21)">&#8221; &#8220;</span> );
}</pre>
<p>Which will return the following;</p>
<p>10 11 12 13 14 15 16 17 18 19</p>
<p>Why bother you say? Why not just iterate through the numbers yourself? The answer&nbsp;lies in the fact that each call maintains state, so you don&#8217;t have to. The above example doesn&#8217;t really show you the power, so let&#8217;s try a more complex example, calculating prime numbers.</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(43,145,175)">IEnumerable</span><span style="color: rgb(255,0,0)">&lt;</span><span style="color: rgb(0,0,255)">int</span><span style="color: rgb(255,0,0)">&gt;</span> Primes( <span style="color: rgb(0,0,255)">int</span> max )
{
   <span style="color: rgb(0,0,255)">yield</span> <span style="color: rgb(0,0,255)">return</span> <span style="color: rgb(128,0,128)">2</span>;
   <span style="color: rgb(43,145,175)">List</span><span style="color: rgb(255,0,0)">&lt;</span><span style="color: rgb(0,0,255)">int</span><span style="color: rgb(255,0,0)">&gt;</span> found <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">List</span><span style="color: rgb(255,0,0)">&lt;</span><span style="color: rgb(0,0,255)">int</span><span style="color: rgb(255,0,0)">&gt;</span>();
   found<span style="color: rgb(255,0,0)">.</span>Add( <span style="color: rgb(128,0,128)">3</span> );
   <span style="color: rgb(0,0,255)">int</span> candidate <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(128,0,128)">3</span>;
   <span style="color: rgb(0,0,255)">while</span> ( candidate <span style="color: rgb(255,0,0)">&lt;=</span> max )
   {
      <span style="color: rgb(0,0,255)">bool</span> isPrime <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">true</span>;
      <span style="color: rgb(0,0,255)">foreach</span> ( <span style="color: rgb(0,0,255)">int</span> prime <span style="color: rgb(0,0,255)">in</span> found )
      {
         <span style="color: rgb(0,0,255)">if</span> ( prime <span style="color: rgb(255,0,0)">*</span> prime <span style="color: rgb(255,0,0)">&gt;</span> candidate )
         {
            <span style="color: rgb(0,0,255)">break</span>;
         }
         <span style="color: rgb(0,0,255)">if</span> ( candidate <span style="color: rgb(255,0,0)">%</span> prime <span style="color: rgb(255,0,0)">==</span> <span style="color: rgb(128,0,128)">0</span> )
         {
            isPrime <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">false</span>;
            <span style="color: rgb(0,0,255)">break</span>;
         }
      }
      <span style="color: rgb(0,0,255)">if</span> ( isPrime )
      {
         found<span style="color: rgb(255,0,0)">.</span>Add( candidate );
         <span style="color: rgb(0,0,255)">yield</span> <span style="color: rgb(0,0,255)">return</span> candidate;
      }
      candidate <span style="color: rgb(255,0,0)">+=</span> <span style="color: rgb(128,0,128)">2</span>;
   }
}</pre>
<p>Notice that there are multiple yields within this method and that the state is maintained through each call. You can now print out all of the prime numbers below 50 with;</p>
<pre class="code"><span style="color: rgb(0,0,255)">foreach</span> ( <span style="color: rgb(0,0,255)">int</span> prime <span style="color: rgb(0,0,255)">in</span> Primes( <span style="color: rgb(128,0,128)">50</span> ) )
{
   <span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>Write( prime<span style="color: rgb(255,0,0)">.</span>ToString() <span style="color: rgb(255,0,0)">+</span> <span style="color: rgb(163,21,21)">&#8221; &#8220;</span> );
}</pre>
<p>There is also the <strong>yield break</strong> statement. If a <strong>yield break</strong> statement is hit within a method, execution of that method stops with no return. Using this, the first method could be rewritten like this;</p>
<pre class="code"><span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(43,145,175)">IEnumerable</span><span style="color: rgb(255,0,0)">&lt;</span><span style="color: rgb(0,0,255)">int</span><span style="color: rgb(255,0,0)">&gt;</span> Range( <span style="color: rgb(0,0,255)">int</span> min, <span style="color: rgb(0,0,255)">int</span> max )
{
   <span style="color: rgb(0,0,255)">while</span> ( <span style="color: rgb(0,0,255)">true</span> )
   {
      <span style="color: rgb(0,0,255)">if</span> ( min <span style="color: rgb(255,0,0)">&gt;=</span> max )
      {
         <span style="color: rgb(0,0,255)">yield</span> <span style="color: rgb(0,0,255)">break</span>;
      }
      <span style="color: rgb(0,0,255)">yield</span> <span style="color: rgb(0,0,255)">return</span> min<span style="color: rgb(255,0,0)">++</span>;
   }
}</pre>
<p>It is not as useful in this case, but I&#8217;ll leave it to you to find more interesting reasons to break out of a loop. Also, even though I used the generic <strong>IEnumerable&lt;T&gt;</strong> for all of my examples, you can also use <strong>IEnumerable</strong>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
