<?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"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Alteridem Consulting &#187; C#</title>
	<atom:link href="http://www.alteridem.net/category/net/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.alteridem.net</link>
	<description>Software by Design</description>
	<lastBuildDate>Thu, 02 Sep 2010 17:52:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Extending CopyHelper using Extension Methods</title>
		<link>http://www.alteridem.net/2008/07/22/extending-copyhelper-using-extension-methods/</link>
		<comments>http://www.alteridem.net/2008/07/22/extending-copyhelper-using-extension-methods/#comments</comments>
		<pubDate>Tue, 22 Jul 2008 13:14:00 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Libraries]]></category>
		<category><![CDATA[Tips'n'Tricks]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/?p=55</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/">last</a> <a href="http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/">two</a> 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 <a href="http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/"><strong>Copier</strong></a> 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;</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:364d24c2-3f44-49d3-b077-d600fcaece3c" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">Copier&lt;ICustomer&gt;.Copy( customer ).To&lt;ICustomerView&gt;( view );</pre>
</div>
<p>Today, I am going to use extension methods to simplify the above code even further. I want to be able to write</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:37699e1e-1b46-4f94-a84f-25266f64cba3" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">customer.CopyTo&lt;ICustomerView&gt;( view );</pre>
</div>
<p>or if we want to rely on type inferencing with the generic <strong>CopyTo</strong> method, you could write it as simply as</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:9c627046-fca3-4dc8-8ad8-df7c27291361" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">customer.CopyTo( view );</pre>
</div>
<p>How is this done? Using extension methods, it was actually much simpler than yesterday’s <a href="http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/"><strong>Copier</strong></a> class. In fact, it just ended up being one line of code for the <strong>CopyTo</strong> method and for the <strong>CopyFrom</strong> method. I simply wrapped the <a href="http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/"><strong>CopyHelper</strong></a> class like this.</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d57cca66-24bc-4e64-a84a-3b52c1c5ebb6" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">public static class CopierExtensions
{
    public static void CopyTo&lt;T&gt;( this object from, T to ) where T : class
    {
        CopyHelper.Copy( from.GetType(), from, typeof( T ), to );
    }

    public static void CopyFrom&lt;T&gt;( this object to, T from ) where T : class
    {
        CopyHelper.Copy( typeof( T ), from, to.GetType(), to );
    }
}</pre>
</div>
<p>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?</p>
<p>I have uploaded a copy of <a href="http://www.alteridem.net/wp-content/uploads/2008/07/modelviewhelpers.zip">the solution for this project</a> along with an <a href="http://www.nunit.org">NUnit</a> test project. Take a look, use it if you like and feel free to give me suggestions for improvements.</p>
<p>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?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/07/22/extending-copyhelper-using-extension-methods/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extending CopyHelper using Generics</title>
		<link>http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/</link>
		<comments>http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 15:33:55 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
				<category><![CDATA[.NET 2.0]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Libraries]]></category>
		<category><![CDATA[Tips'n'Tricks]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/">last post</a>, 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.</p>
</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d56ee549-681a-47e3-98f2-b8699e660de1" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">// 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;</pre>
</div>
<p>The newly created <a href="http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/"><strong>CopyHelper</strong> class</a> allows me to shorten that to this.</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:106cd999-9de2-4404-bfe0-d08445cb28ca" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">// Copy the data from the customer to the view (using reflection in .NET 1.x)
CopyHelper.Copy( typeof(ICustomer), customer, typeof(ICustomerView), view );</pre>
</div>
<p>Today, I want to extend that code using Generics and a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a> so that I can write code like this.</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:21d2f05d-c92d-4fc4-a163-9687494dddde" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">// Copy the data from the customer to the view (using reflection and generics in .NET 2.0)
Copier&lt;ICustomer&gt;.Copy( customer ).To&lt;ICustomerView&gt;( view );</pre>
</div>
</p>
<p>Internally, I use my <a href="http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/"><strong>CopyHelper</strong> class</a> from my last post. I extend that by creating a generic <strong>Copier</strong> 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 <strong>Copier</strong> class that was returned from that method, you can then copy <strong>To</strong> or <strong>From</strong> another class instance.</p>
<p>Here is the code.</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:e4d4e61e-e527-494e-b96d-0d4b4f9ba5ea" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">public sealed class Copier&lt;T1&gt; where T1 : class
{
    #region Private Members

    private readonly T1 _subject;

    #endregion

    #region Public Interface

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

    #endregion

    #region Construction

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

    #endregion

    #region Copier Methods

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

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

    #endregion
}</pre>
</div>
</p>
<p>I would like to constrain <strong>T1</strong> and <strong>T2</strong> 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 <strong>T1</strong> and <strong>T2</strong> are interfaces at run time, but I am a big believer in favouring compile time errors over run time errors.</p>
<p>In my <a href="http://www.alteridem.net/2008/07/22/extending-copyhelper-using-extension-methods/">next post</a>, I am going to use C# 3.0 extension methods to further simplify copying allowing you to write code like this.</p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:acf0083b-b819-41ac-801c-41c0f977934e" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">// Copy the data from the customer to the view (using extension methods in C# 3.0)
customer.CopyTo&lt;ICustomerView&gt;( view );</pre>
</div>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Method to Copy Data Between Objects of Different Types</title>
		<link>http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/</link>
		<comments>http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 16:05:00 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
				<category><![CDATA[.NET 1.x]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tips'n'Tricks]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/</guid>
		<description><![CDATA[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; [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that I find tiresome when using the various <a href="http://polymorphicpodcast.com/shows/mv-patterns/">Model/View patterns</a> 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 <strong>ICustomer</strong> and an <strong>ICustomerView</strong>;</p>
<p><a name="listing1"></a></p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:2ee7dfba-ed37-4b8e-9881-03d732dd1547" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#:nogutter">// 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;</pre>
</div>
<p>I would much rather write something like one of the following lines;</p>
<p><a name="listing2"></a></p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:d4534127-22e3-47de-9638-6bc33333d17b" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">// 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&lt;ICustomer&gt;.Copy( customer ).To&lt;ICustomerView&gt;( view );

// Copy the data from the customer to the view (using extension methods in C# 3.0)
customer.CopyTo&lt;ICustomerView&gt;( view );</pre>
</div>
<p>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,</p>
<p>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 &amp; 8 above.</p>
<p>Today, I will start with the .NET 1.x version. I will start with some design decisions;</p>
<ul>
<li>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. </li>
<li>For now, I am going to assume that if both interfaces have a non-static get/set property with the same <strong>name</strong> and <strong>type</strong> I will copy between them. </li>
<li>I need to check that neither object is null and that I am not trying to copy an object over to itself. </li>
</ul>
<p>This was simple enough. I created a static helper class called <strong>CopyHelper</strong> with one static <strong>Copy</strong> method. I use <a href="http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx">Type.GetProperties</a> to get the non-static, public properties with getters and setters. If the name and type match, I use the <a href="http://msdn.microsoft.com/en-us/library/b05d59ty.aspx">GetValue</a> and <a href="http://msdn.microsoft.com/en-us/library/xb5dd1f1.aspx">SetValue</a> methods on the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx">PropertyInfo</a> class to copy the value across from one object to the next. This is the result;</p>
<p><a name="listing3"></a></p>
<div class="wlWriterSmartContent" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:c3141718-afd0-45c0-af12-a896a062b949" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c#">#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

        /// &lt;summary&gt;
        /// Copies all public properties from one object to another.
        /// &lt;/summary&gt;
        /// &lt;param name="fromType"&gt;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.&lt;/param&gt;
        /// &lt;param name="from"&gt;The object to copy from&lt;/param&gt;
        /// &lt;param name="toType"&gt;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.&lt;/param&gt;
        /// &lt;param name="to"&gt;The object to copy to&lt;/param&gt;
        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&lt;string, PropertyInfo&gt; toProperties = new Dictionary&lt;string, PropertyInfo&gt;();
                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 );
                        }
                    }
                }
            }
        }
    }
}</pre>
</div>
<p>Using this <a href="#listing3">class</a>, you can now write code like in <a href="#listing2">line 2 of the second listing</a> above. In my <a href="http://www.alteridem.net/2008/07/21/extending-copyhelper-using-generics/">next post</a>, I am going to extend this code using generics and give it a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a> for better readability.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/07/09/method-to-copy-data-between-objects-of-different-types/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Read Properties from an MSI File</title>
		<link>http://www.alteridem.net/2008/05/20/read-properties-from-an-msi-file/</link>
		<comments>http://www.alteridem.net/2008/05/20/read-properties-from-an-msi-file/#comments</comments>
		<pubDate>Tue, 20 May 2008 18:52:10 +0000</pubDate>
		<dc:creator>Robert Prouse</dc:creator>
				<category><![CDATA[.NET 2.0]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MSI]]></category>

		<guid isPermaLink="false">http://www.alteridem.net/?p=47</guid>
		<description><![CDATA[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. Add a reference [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>It took a fair amount of searching and code tweaking, but I finally worked it all out. </p>
<ol>
<li>Add a reference to the COM <strong>Microsoft Windows Installer Object Library</strong>.
<li>Add a <font face="Courier New"><font color="#0000ff">using</font> WindowsInstaller;</font>
<li>Add the following static method to your code (error checking removed for brevity.)</li>
</ol>
<pre name="code" class="c-sharp:nogutter">
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;
}
</pre>
<p>If you want to look up the version, just pass in the name of the MSI file you want to inspect and &#8220;ProductVersion&#8221; for the property you want to return. For example;</p>
<pre name="code" class="c-sharp:nogutter">
string version = GetMsiProperty( msiFile, “ProductVersion” );
</pre>
<p>You can use this method to look up other properties in the installer. Some common ones you might want are <strong>ProductName, ProductCode, UpgradeCode, Manufacturer, ARPHELPLINK, ARPCOMMENTS, ARPCONTACT, ARPURLINFOABOUT</strong> and <strong>ARPURLUDATEINFO</strong>. For a full list of properties, see the <a href="http://msdn.microsoft.com/en-us/library/aa370905(VS.85).aspx">MSDN Reference</a>, but remember that most of the properties listed on that page are only for already installed applications and won&#8217;t be included in the installer.</p>
<p>If you find this code useful or the code is not self-explanatory, please leave a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2008/05/20/read-properties-from-an-msi-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</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( "This process took {0} ms", duration.TotalMilliseconds ); If you do, you should [...]]]></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)">"This process took {0} ms"</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)">"This process took {0} ms"</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>
		<slash:comments>3</slash:comments>
		</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)">"{0} {1}"</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)">"{0}{1}{1}{2}{1}{1}(Yes to continue, No to debug)"</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="Layout"/&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>"<span style="color: rgb(0,0,255)">1.0</span>"<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>"<span style="color: rgb(0,0,255)">utf-8</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;
   &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>"<span style="color: rgb(0,0,255)">log4net</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>"<span style="color: rgb(0,0,255)">log4net.Config.Log4NetConfigurationSectionHandler, log4net</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)">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>"<span style="color: rgb(0,0,255)">MessageBoxAppender</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>"<span style="color: rgb(0,0,255)">Alertidem.log4net.MessageBoxAppender, log4netExtensions</span>"<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>"<span style="color: rgb(0,0,255)">log4net.Layout.PatternLayout</span>"<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>"<span style="color: rgb(0,0,255)">%m</span>"<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>"<span style="color: rgb(0,0,255)">ERROR</span>"<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>"<span style="color: rgb(0,0,255)">MessageBoxAppender</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)">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>
		<slash:comments>5</slash:comments>
		</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)">// ...
</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>
		<slash:comments>4</slash:comments>
		</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>0x00bbggrr </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)">0x000000FF</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)">0x0000FF00</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)">0x00FF0000</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)">-- =============================================
-- Author: Rob Prouse
-- Date: 15/08/07
-- Description: Convert control colors from
-- </span>  <span style="color: rgb(0,128,0)">Win32 COLORREF (0x00BBGGRR) values to .NET
-- </span>  <span style="color: rgb(0,128,0)">Color Values (0xFFRRGGBB)
-- =============================================
</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)">0x00FF0000</span>)/<span style="color: rgb(128,0,128)">0x00010000</span>) +
          (@Color &amp; <span style="color: rgb(128,0,128)">0x0000FF00</span>) +
          (( @Color &amp; <span style="color: rgb(128,0,128)">0x000000FF</span>)*<span style="color: rgb(128,0,128)">0x00010000</span>)

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

<span style="color: rgb(0,128,0)">-- 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>
		<slash:comments>2</slash:comments>
		</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 [...]]]></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)">" "</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)">" "</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>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Null Coalescing Operator</title>
		<link>http://www.alteridem.net/2007/08/17/null-coalescing-operator/</link>
		<comments>http://www.alteridem.net/2007/08/17/null-coalescing-operator/#comments</comments>
		<pubDate>Fri, 17 Aug 2007 18:11:38 +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/17/null-coalescing-operator/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<pre class="code"><span style="color: rgb(43,145,175)"></span></pre>
<pre class="code">Order order <span style="color: rgb(255,0,0)">=</span> GetOrder( id ) <span style="color: rgb(255,0,0)">??</span> <span style="color: rgb(0,0,255)">new</span> Order();</pre>
<p>In the above code, if the return value of&nbsp;GetOrder()&nbsp;is not null, it is assigned to order. If it is null,&nbsp;a new Order is created and assigned. Before the ?? operator, you would have to write something like this;</p>
<pre class="code">Order order <span style="color: rgb(255,0,0)">=</span> GetOrder( id );
<span style="color: rgb(0,0,255)">if</span> ( order <span style="color: rgb(255,0,0)">==</span> <span style="color: rgb(0,0,255)">null</span> )
    order <span style="color: rgb(255,0,0)">=</span> <span style="color: rgb(0,0,255)">new</span> Order();</pre>
<p>It is also really useful for output. For example, instead of using the conditional operator,</p>
<pre class="code"><span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>WriteLine( filename <span style="color: rgb(255,0,0)">!=</span> <span style="color: rgb(0,0,255)">null</span> <span style="color: rgb(255,0,0)">?</span> filename : <span style="color: rgb(163,21,21)">"Filename is undefined"</span> );</pre>
<p>You can use the null coalescing operator,</p>
<pre class="code"><span style="color: rgb(43,145,175)">Console</span><span style="color: rgb(255,0,0)">.</span>WriteLine( filename <span style="color: rgb(255,0,0)">??</span> <span style="color: rgb(163,21,21)">"Filename is undefined"</span> );</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.alteridem.net/2007/08/17/null-coalescing-operator/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
