Extending CopyHelper using Generics

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.

Read more

Read Properties from an MSI File

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.

Read more

The Stopwatch Class in .NET

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 = Stopwatch.StartNew();

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

stopwatch.Stop();
Console.WriteLine( "This process took {0} ms", stopwatch.ElapsedMilliseconds );

Read more

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.

Read more

Null Coalescing Operator

The first time I saw the ?? operator in C#, I did a double take and had to look it up. The operator, called the null coalescing operator was added in C# 2.0 and is pretty useful, but still fairly unknown.

Order order = GetOrder( id ) ?? new Order();

In the above code, if the return value of GetOrder() is not null, it is assigned to order. If it is null, a new Order is created and assigned. Before the ?? operator, you would have to write something like this;

Order order = GetOrder( id );
if ( order == null )
    order = new Order();

It is also really useful for output. For example, instead of using the conditional operator,

Console.WriteLine( filename != null ? filename : "Filename is undefined" );

You can use the null coalescing operator,

Console.WriteLine( filename ?? "Filename is undefined" );

Read more