CmdPrompt Real developers live on the command line. Way back in 1996, Microsoft released the Command Prompt Here Power Toy to ease their pain. Industrious developers who preferred the Visual Studio command prompt took it and adopted it to run a Visual Studio command prompt with all of the paths to Visual Studio and .NET tools in the path.

In the fine, time honored tradition, I have continued to update with each new Visual Studio release and have finally done so for Visual Studio 2010.

To install, download, unzip and right click and install the INF file, it will add a “VS 2010 Cmd Prompt Here” menu item when you right click on a folder in Explorer. Clicking on the menu item will launch a DOS prompt in that directory with all of the Visual Studio and .NET paths set correctly.

This assumes that you have installed Visual Studio to the default directory on the C drive. If that is not the case, edit the INF file and change line 38 to the correct path for your installation.

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

I have been planning on learning Ruby on Rails for awhile now, but I have heard that running it on Windows was problematic. The download page makes it sound pretty easy though, so I thought I would give it a try.

Install Ruby

First we need the Ruby language itself. I picked up the 1.9.1 windows installer from RubyForge. When I installed, I checked Add Ruby executables to your PATH and Associate .rb and .rbw files.

Capture

Install Ruby Gems

Next, we need the Ruby package manager which allows us to install Rails and other Ruby packages. Download and extract the latest Ruby Gems ZIP file from RubyForge.

Open a DOS command prompt where you unzipped Gems and run the command,

ruby setup.rb

Install Rails

At the DOS prompt, run

gem install rails

Wow, that was easy! Next, create an application and try it out.

Install MySQL Driver

Slow down, not so quick. A few steps ahead, I discovered that the MySQL driver is no longer distributed with Rails 2.2, so I had to install it with the command

gem install mysql

You may also run into a problem later when you try to run db:migrate and it says Not Connected. If you do, follow the steps in this post, they got it working for me.

Initializing an Application

To start out, I am going to run through the screencast Creating a weblog in 15 minutes with Rails 2, so I will create the application for that. Once again, at the command line, first cd to your test web root. I use XAMPP for web development on Windows, so I am going to keep my Rails apps there.

cd \xampp\htdocs
rails –d mysql blog
cd blog

The rails command created the blog application to use MySQL as the database. Next open the blog\config\database.yml file. Update the username and password where appropriate. Now let’s try it.

ruby script/server

The ruby command runs a development server on port 3000. If you see the Windows Firewall prompt, allow it. Test the installation by going to http://localhost:3000, you should see the following.

web_1

What about Apache?

Once again, I am using XAMPP, so I tried several ways to get it working, but never managed to get either the mod_rewrite and/or the CGI handlers working. I found quite a few tutorials. All got me to the Welcome Aboard page, but none actually worked when I clicked the About your application’s environment link. I guess for now I am going to have to stick with the built in WEBrick server.

Next Steps

We are now setup and configured, so what next?

General Impressions

The general installation was easy, but I ran into several problems like the setting up Apache on Windows and getting MySQL working. At the bottom of the article Roadmap for Learning Rails, it states,

When you’re first starting out, don’t make unusual choices, such as learning to program Rails on Windows. One of the strengths of Rails is the community, but if you’ve made unusual choices, you’ll quickly find yourself without much help.

In my opinion, Rails is not suitable for production deployment on Windows and probably anything beyond casual development is probably better on Linux or a Mac. If I stick with it, I will probably move all of my development over to Linux.

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

I have been reading about Git and Mercurial everywhere lately, so I wanted to give them a try. I mainly develop on Windows and the tools for Windows are better for Mercurial, so I decided to start with it.

The best way to get a feel for is with real code, so I decided to migrate my Subversion repository to Mercurial.

The first step was to install TortoiseHg, the Windows shell extension for Mercurial. I then read that it is much quicker to work with a local copy of a Subversion repository, so my next step was to pull a copy down from the server.

Sync Subversion to the Local Machine

  1. Create an \scm\svn (source control management) directory to house the local copy of the repository.
      mkdir \scm\svn
  2. Create the local Subversion repository.
      svnadmin create \scm\svn\myrepository
  3. Create an empty hooks\pre-revprop-change.bat file
      echo @ECHO OFF > \scm\svn\myrepository\hooks\pre-revprop-change.bat  
  4. Initialize the local repository for syncing to the remote repository
      svnsync init file:///scm/svn/myrepository http://remote.repository.com/svn/myrepository
  5. Now run the sync.
      svnsync sync file:///scm/svn/myrepository

The last command pulls in all the revisions from the remote repository one at a time until it mirrors all of the changesets. Once this is done, you have a fully functional local copy of the SVN repository to work with.

Configure TortoiseHg


At a minimum, you should set your username and enable the convert extension. To do this, in Explorer, right click and select TortoiseHg | Global Settings. Set your username in the Commit section to your name/email in the format First Last <youremail@domain.com>. Next go to the Extensions section and make sure the Convert extension is enabled.

TortoiseHg

Do the Initial Convert of the Repository


I then did a trial run of converting the local SVN repository to an Hg repository.

  1. Create an \scm\hg directory to house the Mercurial repository.
      mkdir \scm\hg
  2. Create the Mercurial repository to import the SVN repository into.
      hg init \scm\hg\myrepository
  3. Run the conversion.
      hg convert -s svn \scm\svn\myrepository \scm\hg\myrepository

Cleaning up the Conversion


Looking through the history of my newly imported repository, I noticed that my username changed over time depending on the Linux user account I was working with at the time. It would be nice to change all of these to the preferred mercurial format. Luckily, that is pretty easy, hg convert can use a file to map SVN usernames to Hg users. To do that, create a file called authors.txt with conversions like the following;

robprouse = Rob Prouse <rob@email.com>
rprouse = Rob Prouse <rob@email.com>
jdoe = John Doe <john@doe.com>

My repository is also a bit of a mess. It started out as a CVS repository years ago which was later migrated to SVN. Over the years, every project I worked on was filed away in there. One thing about Mercurial, is that it is best to have one project per repository since you can only clone the whole thing. To do this, I created a filemap.txt file and used it to pull out each project into its own repository.

include /projects/Project1/
include /projects/Project1.Tests/


For more information, check out the documentation. I then reran the conversion that I did above, except I pull now from my newly converted Hg repository and I used the author and file map files. I updated the filemap.txt for each project that I wanted to export and re-ran the conversion.

hg init \scm\hg\project1
hg convert --authors authors.txt --filemap filemap.txt -s hg \scm\hg\myrepository \scm\hg\project1
If you found this post helpful, please "Kick" it so others can find it too:

21st Jul, 2010

The dangers of Macros

Another developer came to me with a problem today that he couldn’t figure out. He couldn’t believe what he was seeing in the debugger and needed a second set of eyes. He had a line of code like the following;

return max( eRetVal, GetNumber() );

While debugging, he noticed that he was stepping into the GetNumber() method twice, and in his code, it had side-effects. We both puzzled over it for awhile. We looked at the disassembly and sure enough, it was getting called twice, but why? Then it hit me, max is a macro, not a function. If you go to the definition of max, you find;

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

So, if you expand that macro out, the original code gets compiles as;

return (((eRetVal) > (GetNumber()) ? (eRetVal) : (GetNumber());

Once the macro is expanded, it is easy to see why the method is called twice. Obviously I have not being doing enough C++ lately. There was a time when I would have seen that immediately as it is the classic example, but I have been working in .NET so long now that I am forgetting all of the little ways that C++ can bite you.

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

log4net is a great logging framework for .NET, but it hasn’t been updated in years. When we moved to Windows Vista, we noticed that the UdpAppender stopped working with Chainsaw and with our internal logging tools when logging to localhost. After some Googling, we discovered that replacing localhost with 127.0.0.2 got everything working and we promptly forgot about it.

Earlier this week, we moved one of our projects over to .NET 4.0 and once again logging failed. In the console window while debugging the app, I noticed the following,

log4net.Util.TypeConverters.ConversionNotSupportedException: Cannot convert from type [System.String]
  value [127.0.0.2] to type [System.Net.IPAddress] --->
  System.Net.Sockets.SocketException: No such host is known
       at System.Net.Dns.InternalGetHostByAddress(IPAddress address, Boolean includeIPv6)
       at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
       at log4net.Util.TypeConverters.IPAddressConverter.ConvertFrom(Object source)

So, I tried changing back to localhost and the error changed to,

log4net:ERROR [UdpAppender] Unable to send logging event to remote host ::1 on port 7071.
      System.Net.Sockets.SocketException (0x80004005): An address incompatible with
      the requested protocol was used
       at System.Net.Sockets.Socket.SendTo(Byte[] buffer, Int32 offset, Int32 size, SocketFlags
         socketFlags, EndPoint remoteEP)
       at System.Net.Sockets.UdpClient.Send(Byte[] dgram, Int32 bytes, IPEndPoint endPoint)
       at log4net.Appender.UdpAppender.Append(LoggingEvent loggingEvent)

At this point, I have some clues, specifically that localhost was being resolved as the IPv6 address ::1, not the IPv4 address 127.0.0.1. Looking through the reported issues I found that this problem had been reported and fixed in 2007. Unfortunately, that code isn’t in the release, so I downloaded the latest source and recompiled log4net. Of course, they don’t release the signing key, so I generated my own and signed the assembly myself.

This fixed my problems with the UdpAppender, although, if you use localhost on a Windows Vista or Windows 7 machine, it will resolve to the IPv6 address, so make sure that your receiver is listening on the IPv6 address. For example, in log2console, under Receivers, set Use IPv6 Addresses to true for the UDP receiver. If your receiver does not support IPv6, use 127.0.0.2 for the address.

To save other people the hassle of recompiling log4net themselves to get the latest fixes, I have uploaded a release version of the assembly. Download it here.

We are using this version of the assembly in our own projects, but I make no guarantees as to its stability.

Update: Just to  be clear, this is not an official log4net release and it is only compiled against .NET 2.0. I have made no code changes, it is just the code that is currently in the repository. This is only intended to save you having to download and compile if you run into the same problems I did. It is also not extensively tested. We are using it and File, Rolling File, Event Log and UDP Appenders seem to be working fine.

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

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: