In my last two posts, I have been developing a small utility library to do the grunt work of copying data from an instance of one class to an instance of another type. The Copier class from my last post allows me to copy all public properties from one class to another class as long as the properties have the same name and type. All that is done with one line of code;

Copier<ICustomer>.Copy( customer ).To<ICustomerView>( view );

Today, I am going to use extension methods to simplify the above code even further. I want to be able to write

customer.CopyTo<ICustomerView>( view );

or if we want to rely on type inferencing with the generic CopyTo method, you could write it as simply as

customer.CopyTo( view );

How is this done? Using extension methods, it was actually much simpler than yesterday’s Copier class. In fact, it just ended up being one line of code for the CopyTo method and for the CopyFrom method. I simply wrapped the CopyHelper class like this.

public static class CopierExtensions
{
    public static void CopyTo<T>( this object from, T to ) where T : class
    {
        CopyHelper.Copy( from.GetType(), from, typeof( T ), to );
    }

    public static void CopyFrom<T>( this object to, T from ) where T : class
    {
        CopyHelper.Copy( typeof( T ), from, to.GetType(), to );
    }
}

The only problem I have with this is that the class that the extension methods are applied to are not constrained by an interface, so all matching properties are copied. Does anyone have any ideas on that?

I have uploaded a copy of the solution for this project along with an NUnit test project. Take a look, use it if you like and feel free to give me suggestions for improvements.

In the next few posts I was thinking of extending these classes even further. I might add attributes that allow you to ignore certain properties, maybe add an attribute that specifies interfaces that you are allowed to copy to, possibly an attribute that allows properties to automatically be converted between types. What would you find useful or like to see? Would you like to see a post on the performance using these methods?

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

In my last post, I created a method that does the grunt work of copying data from an instance of one class to an instance of another type. I often find myself copying data between the properties of my data layer classes and those of my user interface like this.

// Copy the data from the customer to the view
view.Address = customer.Address;
view.Country = customer.Country;
view.FirstName = customer.FirstName;
view.LastName = customer.LastName;
view.PostalCode = customer.PostalCode;
view.Province = customer.Province;

The newly created CopyHelper class allows me to shorten that to this.

// Copy the data from the customer to the view (using reflection in .NET 1.x)
CopyHelper.Copy( typeof(ICustomer), customer, typeof(ICustomerView), view );

Today, I want to extend that code using Generics and a fluent interface so that I can write code like this.

// Copy the data from the customer to the view (using reflection and generics in .NET 2.0)
Copier<ICustomer>.Copy( customer ).To<ICustomerView>( view );

Internally, I use my CopyHelper class from my last post. I extend that by creating a generic Copier class. I make the constructor private so that it can only be created as a part of the fluent interface, in this case the static copy method. Using the instance of the Copier class that was returned from that method, you can then copy To or From another class instance.

Here is the code.

public sealed class Copier<T1> where T1 : class
{
    #region Private Members

    private readonly T1 _subject;

    #endregion

    #region Public Interface

    /// <summary>
    /// Begin the copying process.
    /// </summary>
    /// <param name="interface1">The object you are copying from or to</param>
    /// <returns>An instance of the Copier class so that you can
    /// continue with the copy to/from in a fluent interface.</returns>
    public static Copier<T1> Copy( T1 interface1 )
    {
        return new Copier<T1>( interface1 );
    }

    #endregion

    #region Construction

    /// <summary>
    /// Private constructor so that it can only be created as a part of a fluent interface.
    /// </summary>
    /// <param name="subject"></param>
    private Copier( T1 subject )
    {
        _subject = subject;
    }

    #endregion

    #region Copier Methods

    /// <summary>
    /// Copies properties from the subject to the passed in object.
    /// </summary>
    /// <typeparam name="T2">The type of object you are copying into.</typeparam>
    /// <param name="to">The object to copy into.</param>
    /// <returns>The modified object that you passed in.</returns>
    public T2 To<T2>( T2 to ) where T2 : class
    {
        CopyHelper.Copy( typeof( T1 ), _subject, typeof( T2 ), to );
        return to;
    }

    /// <summary>
    /// Copies properties from the passed in object into the subject.
    /// </summary>
    /// <typeparam name="T2">The type of object you are copying from.</typeparam>
    /// <param name="from">The object to copy from.</param>
    /// <returns>The modified subject that you originally passed in the Copy method.</returns>
    public T1 From<T2>( T2 from ) where T2 : class
    {
        CopyHelper.Copy( typeof( T2 ), from, typeof( T1 ), _subject );
        return _subject;
    }

    #endregion
}

I would like to constrain T1 and T2 to interfaces at compile time, but I am not sure if that can be done. If you have ideas, please post them in the comments. I thought of using reflection to check if T1 and T2 are interfaces at run time, but I am a big believer in favouring compile time errors over run time errors.

In my next post, I am going to use C# 3.0 extension methods to further simplify copying allowing you to write code like this.

// Copy the data from the customer to the view (using extension methods in C# 3.0)
customer.CopyTo<ICustomerView>( view );

I am very interested in hearing your feedback on this, so be sure to post to the comments. Do you think this is a good idea? Do you have suggestions for improvements? Let me know.

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

One thing that I find tiresome when using the various Model/View patterns is the constant copying of data between the model and the view. Too often, I find myself writing code like this to copy data between an ICustomer and an ICustomerView;

// Copy the data from the customer to the view
view.Address = customer.Address;
view.Country = customer.Country;
view.FirstName = customer.FirstName;
view.LastName = customer.LastName;
view.PostalCode = customer.PostalCode;
view.Province = customer.Province;

I would much rather write something like one of the following lines;

// Copy the data from the customer to the view (using reflection in .NET 1.x)
CopyHelper.Copy( typeof(ICustomer), customer, typeof(ICustomerView), view );

// Copy the data from the customer to the view (using reflection and generics in .NET 2.0)
Copier<ICustomer>.Copy( customer ).To<ICustomerView>( view );

// Copy the data from the customer to the view (using extension methods in C# 3.0)
customer.CopyTo<ICustomerView>( view );

It got me to thinking that there must be a better way, so I began writing code that would do the grunt work for me. Too often,

Over the next few days, I will blog about my thought process in developing this method and take it through the various iterations that can be seen in lines 2, 5 & 8 above.

Today, I will start with the .NET 1.x version. I will start with some design decisions;

  • I want to be able to specify the types that I am copying between, not infer them using reflection. This way, I can use the interfaces, not the concrete classes when I am copying between the objects.
  • For now, I am going to assume that if both interfaces have a non-static get/set property with the same name and type I will copy between them.
  • I need to check that neither object is null and that I am not trying to copy an object over to itself.

This was simple enough. I created a static helper class called CopyHelper with one static Copy method. I use Type.GetProperties to get the non-static, public properties with getters and setters. If the name and type match, I use the GetValue and SetValue methods on the PropertyInfo class to copy the value across from one object to the next. This is the result;

#region Copyright © Alteridem Consulting 2008
//
// All rights are reserved. Reproduction or transmission in whole or in part, in
// any form or by any means, electronic, mechanical or otherwise, is prohibited
// without the prior written consent of the copyright owner.
//
// Filename: CopyHelper.cs
// Date:     06/06/2008 11:18 AM
// Author:   Rob Prouse
//
#endregion

#region Using Directives

using System;
using System.Collections.Generic;
using System.Reflection;

#endregion

namespace Alteridem.ModelViewHelpers
{
    public static class CopyHelper
    {
        #region Private Members

        // We are interested in non-static, public properties with getters and setters
        private const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty;

        #endregion

        /// <summary>
        /// Copies all public properties from one object to another.
        /// </summary>
        /// <param name="fromType">The type of the from object, preferably an interface. We could infer this using reflection, but this allows us to contrain the copy to an interface.</param>
        /// <param name="from">The object to copy from</param>
        /// <param name="toType">The type of the to object, preferably an interface. We could infer this using reflection, but this allows us to contrain the copy to an interface.</param>
        /// <param name="to">The object to copy to</param>
        public static void Copy( Type fromType, object from, Type toType, object to )
        {
            if ( fromType == null )
                throw new ArgumentNullException( "fromType", "The type that you are copying from cannot be null" );

            if ( from == null )
                throw new ArgumentNullException( "from", "The object you are copying from cannot be null" );

            if ( toType == null )
                throw new ArgumentNullException( "toType", "The type that you are copying to cannot be null" );

            if ( to == null )
                throw new ArgumentNullException( "to", "The object you are copying to cannot be null" );

            // Don't copy if they are the same object
            if ( !ReferenceEquals( from, to ) )
            {
                // Get all of the public properties in the toType with getters and setters
                Dictionary<string, PropertyInfo> toProperties = new Dictionary<string, PropertyInfo>();
                PropertyInfo[] properties = toType.GetProperties( flags );
                foreach ( PropertyInfo property in properties )
                {
                    toProperties.Add( property.Name, property );
                }

                // Now get all of the public properties in the fromType with getters and setters
                properties = fromType.GetProperties( flags );
                foreach ( PropertyInfo fromProperty in properties )
                {
                    // If a property matches in name and type, copy across
                    if ( toProperties.ContainsKey( fromProperty.Name ) )
                    {
                        PropertyInfo toProperty = toProperties[fromProperty.Name];
                        if ( toProperty.PropertyType == fromProperty.PropertyType )
                        {
                            object value = fromProperty.GetValue( from, null );
                            toProperty.SetValue( to, value, null );
                        }
                    }
                }
            }
        }
    }
}

Using this class, you can now write code like in line 2 of the second listing above. In my next post, I am going to extend this code using generics and give it a fluent interface for better readability.

I am very interested in hearing your feedback on this, so be sure to post to the comments. Do you think this is a good idea? Do you have suggestions for improvements? Let me know.

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

Today I was working writing auto-updating for some software. I wanted to base it on the Product Version property in the installer MSI file, so I needed some code to read that from the file.

It took a fair amount of searching and code tweaking, but I finally worked it all out.

  1. Add a reference to the COM Microsoft Windows Installer Object Library.
  2. Add a using WindowsInstaller;
  3. Add the following static method to your code (error checking removed for brevity.)
public static string GetMsiProperty( string msiFile, string property )
{
   string retVal = string.Empty;

   // Create an Installer instance
   Type classType = Type.GetTypeFromProgID( “WindowsInstaller.Installer” );
   Object installerObj = Activator.CreateInstance( classType );
   Installer installer = installerObj as Installer;

   // Open the msi file for reading
   // 0 - Read, 1 - Read/Write
   Database database = installer.OpenDatabase( msiFile, 0 );

   // Fetch the requested property
   string sql = String.Format(
      “SELECT `Value` FROM `Property` WHERE Property=’{0}’”, property );
   View view = database.OpenView( sql );
   view.Execute( null );

   // Read in the fetched record
   Record record = view.Fetch();
   if ( record != null )
      retVal = record.get_StringData( 1 );

   return retVal;
}

If you want to look up the version, just pass in the name of the MSI file you want to inspect and “ProductVersion” for the property you want to return. For example;

string version = GetMsiProperty( msiFile, “ProductVersion” );

You can use this method to look up other properties in the installer. Some common ones you might want are ProductName, ProductCode, UpgradeCode, Manufacturer, ARPHELPLINK, ARPCOMMENTS, ARPCONTACT, ARPURLINFOABOUT and ARPURLUDATEINFO. For a full list of properties, see the MSDN Reference, but remember that most of the properties listed on that page are only for already installed applications and won’t be included in the installer.

If you find this code useful or the code is not self-explanatory, please leave a comment.

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

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: