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 is for Visual Studio 2008. update: I have uploaded a PDF version of the presentation for those people without Office 2007.

If you are attending, I am looking forward to meeting you tomorrow at 9 AM.

If you found this post helpful, please "Kick" it so others can find it too:

I’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.  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 found didn’t work very well in VS2008.  Like any good coder, I decided to write it myself instead.

If you haven’t written a macro before, here are the steps.

  1. In Visual Studio, go to Tools | Macros | Macros IDE. A new window should open and in the Project Explorer, the MyMacros project should be open.
  2. Right click on the MyMacros project and select Add | Add Module. Name it CppUtilities.  The CppUtilities should open in the editor window.
  3. Add the code from below into the module and save the project.
‘=====================================================================
‘ If the currently open document is a CPP or an H file, attempts to
‘ switch between the CPP and the H file.
‘=====================================================================
Public Sub SwitchBetweenSourceAndHeader()
  Dim currentDocument As String
  Dim targetDocument As String

  currentDocument = ActiveDocument.FullName

  If currentDocument.EndsWith(“.cpp”, StringComparison.InvariantCultureIgnoreCase) Then
    targetDocument = Left(currentDocument, Len(currentDocument) - 3) + “h”
    OpenDocument(targetDocument)
  ElseIf currentDocument.EndsWith(“.h”, StringComparison.InvariantCultureIgnoreCase) Then
    targetDocument = Left(currentDocument, Len(currentDocument) - 1) + “cpp”
    OpenDocument(targetDocument)
  End If

End Sub

‘=====================================================================
‘ Given a document name, attempts to activate it if it is already open,
‘ otherwise attempts to open it.
‘=====================================================================
Private Sub OpenDocument(ByRef documentName As String)
  Dim document As EnvDTE.Document
  Dim activatedTarget As Boolean
  activatedTarget = False

  For Each document In Application.Documents
    If document.FullName = documentName And document.Windows.Count > 0 Then
      document.Activate()
      activatedTarget = True
      Exit For
    End If
  Next
  If Not activatedTarget Then
    Application.Documents.Open(documentName, “Text”)
  End If
End Sub

If you switch back to Visual Studio and open the Macro Explorer, you should see the new module CppUtilities and the new macro SwitchBetweenSourceAndHeader in the tree.  You could run the macro from here, but it is much easier to bind it to a keystroke.

  1. Click on Tools | Options then go to the Environment | Keyboard tab.
  2. In the Show commands containing: box, type CppUtilities. This should filter the list down to one entry, Macros.MyMacros.CppUtilitities.SwitchBetweenSourceAndHeader.
  3. Click on the Press shortcut keys: 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 Shortcut currently used by: dropdown.  When you find one that is unused, click the Assign button to use it.  I use Ctrl+Shift+Alt+Bkspce.
  4. Click OK then open a CPP or H file and give it a try.
If you found this post helpful, please "Kick" it so others can find it too:

tcc-logosmall I found out last week that I will be speaking at this year’s Toronto Code Camp on March 1st.  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 contexts, configuration and filters. 

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 log4net and answer questions.

If you found this post helpful, please "Kick" it so others can find it too:

Do you ever find yourself using DateTime to time a section of code?  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( “This process took {0} ms”,
    duration.TotalMilliseconds );

If you do, you should look at the System.Diagnostics.Stopwatch class that was introduced in the 2.0 framework.  You can convert the code above to the much more readable

  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();

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

  stopwatch.Stop();
  Console.WriteLine( “This process took {0} ms”,
    stopwatch.ElapsedMilliseconds );
If you found this post helpful, please "Kick" it so others can find it too:

In log4net speak, an appender is an output destination for a log such as a file, the console, a database or even email.  log4net ships with so many appenders that most of us will never need to write our own.  There are cases where you may find a need for your own appender, for example, you may want to log errors to your company’s bug tracking software. 

In our case, we simply wanted error logs to pop up a message box with the error and location.  We run this internally so that developers run into errors immediately during development and can break into the debugger to fix them.  We found that logging to a file was too easy to ignore.

MessageBoxAppender

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.

  1. Create a new Class Library project in Visual Studio.
  2. Add a reference to log4net. My appender also uses MessageBox, so I also added references to System.Drawing and System.Windows.Forms.
  3. Remove the default Class1.cs added to the project.
  4. Add your appender class. In my case, MessageBoxAppender.cs.
  5. You could implement the log4net.Appender.IAppender interface, but it is easiest to derive from log4net.Appender.AppenderSkeleton, then most of the work is done for you.
  6. At a minimum, override the Append method. This is where you do your work.
  7. If you are going to use the RenderLoggingEvent method to create your logging message based on the configured layout (such as PatternLayout), override the RequiresLayout property and return true.
  8. When you configure your appender, you must give the assembly qualified name for your appender.  For example,

<appender name=”…” type=”MyNamespace.MyAppender, MyAssembly”>

Here is the simplified code for the MessageBoxAppender that I wrote.

using System;
using System.Windows.Forms;
using System.Diagnostics;

using log4net.Core;
using log4net.Appender;

namespace Alteridem.log4net
{
   /// <summary>
   /// Displays a MessageBox for all log messages.
   /// </summary>
   public class MessageBoxAppender : AppenderSkeleton
   {
      /// <summary>
      /// Writes the logging event to a MessageBox
      /// </summary>
      override protected void Append( LoggingEvent loggingEvent )
      {
         string title = string.Format( “{0} {1}”,
            loggingEvent.Level.DisplayName,
            loggingEvent.LoggerName );

         string message = string.Format(
            “{0}{1}{1}{2}{1}{1}(Yes to continue, No to debug)”,
            RenderLoggingEvent( loggingEvent ),
            Environment.NewLine,
            loggingEvent.LocationInformation.FullInfo );

         DialogResult result = MessageBox.Show( message, title,
            MessageBoxButtons.YesNo );

         if ( result == DialogResult.No )
         {
            Debugger.Break();
         }
      }
      /// <summary>
      /// This appender requires a <see cref=”Layout”/> to be set.
      /// </summary>
      override protected bool RequiresLayout
      {
         get { return true; }
      }
   }
}

There isn’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.

Now, to configure this for your developers to see ERROR messages, the following configuration would work.

<?xml version=1.0 encoding=utf-8 ?>
<configuration>
   <configSections>
      <section name=log4net        type=log4net.Config.Log4NetConfigurationSectionHandler, log4net />
   </configSections>
   <log4net>
      <appender name=MessageBoxAppender
            type=Alertidem.log4net.MessageBoxAppender, log4netExtensions>
         <layout type=log4net.Layout.PatternLayout>
            <ConversionPattern value=%m />
         </layout>
      </appender>
      <root>
         <level value=ERROR/>
         <appender-ref ref=MessageBoxAppender />
      </root>
   </log4net>
</configuration>

The only thing to not here is that the log4netExtensions in the appender line is the assembly.

This should be enough to give you a basic framework to build whatever type of appender you want.  Every time I delve into a new area of log4net, I am once again surprised how easy it is to work with and how well designed it is.  If you aren’t using it, I would highly recommend it.

If you found this post helpful, please "Kick" it so others can find it too:

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’t be bothered to dig down through your projects and folders to find it, try this,

  1. Click in the Find box in the toolbar,
  2. Type >of followed by a space, then begin the name of the file you are looking for.
  3. 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.
  4. The file will open in the editor.
openfile

Update: After this post made the front page of DotNetKicks, Aaron Lerch wrote a great post on his blog with more things that you can do with the find combo. One thing that is very useful is that with the >, you can issue any command, the alias >of mentioned here is just one of many. For a list of the commands, check out this MSDN page.

Another useful tip is that Ctrl+D or Ctrl+/ will automatically jump to the find box, so your hands don’t even need to leave your keyboard.

Update: This trick was also mentioned on Just Sayin More Words as a part of his Stupid Visual Studio Trick series. Thanks.

If you found this post helpful, please "Kick" it so others can find it too:

New Rule: Make sure your parameter names are consistent between your declarations and definitions in C++.

Here is why…

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 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’t appear. Strange, but I’ve come to expect that debugging in C++.

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 “error: identifier ‘maxRows’ out of scope.” How could it be out of scope, I was on the first line in the method?

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’t pluralized. Sure enough, I looked in the header file and it was spelled maxRow there.

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.

Here is an example I mocked up where the parameters were x and y in the header files.

CppDebugging

I also tried this in unmanaged C++ and got the same result.

If you found this post helpful, please "Kick" it so others can find it too:

Unless you have been inspecting some of the code generated by Visual Studio, you probably haven’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 are some of the more useful attributes found in the System.Diagnostics namespace.

DebuggerStepThrough

I don’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!

To prevent this dance, just add the DebuggerStepThrough 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.

public string Name
{
   [DebuggerStepThrough]
   get { return _name; }
   set { _name = value; }
}

DebuggerBrowsable

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. DebugBrowsable is constructed with the DebuggerBrowsableState enum which has the following members;

Collapsed Show the element as collapsed.
Never Never show the element.
RootHidden Do not display the root element; display the child elements if the element is a collection or array of items.

For example, adding

[DebuggerBrowsable( DebuggerBrowsableState.Never )]

to the private members of a class will cause them to be hidden in the watch window, thus cleaning up the view.

DebuggerDisplay

DebuggerDisplay 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;

[DebuggerDisplay( "Name: {Name}, Age: {Age}" )]
public class Person
{
   // …
}

These are the three attributes that I use most often, but you may also want to look up DebuggerStepperBoundary, DebuggerTypeProxy and DebuggerVisualizer.

Happy Debugging!

If you found this post helpful, please "Kick" it so others can find it too:

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 I thought that I could just take the value and get a .NET Color structure using the static FromArgb method.

This didn’t go too well. It turns out that the byte orders are different. COLORREF is in the order 0×00bbggrr and Color is in the order 0xaarrggbb. 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.

We began by doing the conversion in code using a bit of bit fiddling;

public static Color ConvertFromWin32Color( int color )
{
   int r = color & 0×000000FF;
   int g = ( color & 0×0000FF00 ) >> 8;
   int b = ( color & 0×00FF0000 ) >> 16;
   return Color.FromArgb( r, g, b );
}

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.

– =============================================
– Author: Rob Prouse
– Date: 15/08/07
– Description: Convert control colors from
–   Win32 COLORREF (0×00BBGGRR) values to .NET
–   Color Values (0xFFRRGGBB)
– =============================================
CREATE FUNCTION SwapColorBytes( @Color int )
RETURNS int
AS
BEGIN
   RETURN 0xFF000000 +
          ((@Color & 0×00FF0000)/0×00010000) +
          (@Color & 0×0000FF00) +
          (( @Color & 0×000000FF)*0×00010000)

END
GO

– Do the following for every column in the DB that contains colors
UPDATE mytable SET colorcolumn = SwapColorBytes(colorcolumn)
GO
If you found this post helpful, please "Kick" it so others can find it too:

22nd Aug, 2007

The Yield Statement in C#

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<int> Range( int min, int max )
{
   for ( int i = min; i < max; i++ )
   {
      yield return i;
   }
}

Each time Range 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.

Using this, you can write the following code;

foreach ( int i in Range( 10, 20 ) )
{
   Console.Write( i.ToString() + ” “ );
}

Which will return the following;

10 11 12 13 14 15 16 17 18 19

Why bother you say? Why not just iterate through the numbers yourself? The answer lies in the fact that each call maintains state, so you don’t have to. The above example doesn’t really show you the power, so let’s try a more complex example, calculating prime numbers.

public static IEnumerable<int> Primes( int max )
{
   yield return 2;
   List<int> found = new List<int>();
   found.Add( 3 );
   int candidate = 3;
   while ( candidate <= max )
   {
      bool isPrime = true;
      foreach ( int prime in found )
      {
         if ( prime * prime > candidate )
         {
            break;
         }
         if ( candidate % prime == 0 )
         {
            isPrime = false;
            break;
         }
      }
      if ( isPrime )
      {
         found.Add( candidate );
         yield return candidate;
      }
      candidate += 2;
   }
}

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;

foreach ( int prime in Primes( 50 ) )
{
   Console.Write( prime.ToString() + ” “ );
}

There is also the yield break statement. If a yield break statement is hit within a method, execution of that method stops with no return. Using this, the first method could be rewritten like this;

public static IEnumerable<int> Range( int min, int max )
{
   while ( true )
   {
      if ( min >= max )
      {
         yield break;
      }
      yield return min++;
   }
}

It is not as useful in this case, but I’ll leave it to you to find more interesting reasons to break out of a loop. Also, even though I used the generic IEnumerable<T> for all of my examples, you can also use IEnumerable.

If you found this post helpful, please "Kick" it so others can find it too: