Expand an array to a given size

Some functions expect an array with a minimum size. While this is generally bad coding sometimes you can’t avoid it (e.g. with csv files).

That’s when this piece of code comes in handy: (it’s an extension method, so it only works on .NET 3.5)

public static class ArrayHelper
{
    /// <summary>
    /// Expands an array to the given <paramref name="size"/>
    /// </summary>
    /// <typeparam name="T">The type of the array (not neccesairy, can be infered).</typeparam>
    /// <param name="array">The array</param>
    /// <param name="size">The size it should become</param>
    /// <returns>The array expanded to the given size</returns>
    public static T[] Expand<T>(this T[] array, int size)
    {
        if (size < array.Length)
        {
            throw new ArgumentException("size < array.Length, this will cause data to be truncated, canceling", "size");
        }

        T[] list = new T[size];

        for (int index = 0; index < array.Length; index++)
        {
            list[index] = array[index];
        }

        return list;
    }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string[] array = new string[] { "test1", "test2", "test3" };

        //array1 has a length of 3
        Console.WriteLine("array.Length = {0}", array.Length); 

        array = array.Expand<string>(10);

        //now array has a length of 10
        Console.WriteLine("array.Length = {0}", array.Length);

        Console.ReadLine();
    }
}

Enjoy 🙂

String comparison

Something not many people know: when you need to compare 2 strings in C#.NET you can use the == operator overload:

if(firstString == secondString)
{
    //...
}

This is case sensitive. But when you need to ignore the case please don’t use this:

if(firstString.ToLower() == secondString.ToLower())
{
    //...
}

or this:

if(firstString.ToLower().Equals(secondString.ToLower()))
{
    //...
}

A Framework provides you with utilities, please use them. They are usually better than your implementation!

Use this:

if (firstString.Equals(secondString, StringComparison.OrdinalIgnoreCase))
{
    //...
}

StringComparison is an enum. So please look at the options 🙂

Cast vs ‘as’

What’s the difference?

object dinner = new Dinner();
Dinner myDinner2 = (Dinner) dinner;
Dinner myDinner = dinner as Dinner;

Well, the first cast (which is really a cast) throws an error if dinner is null.

The second one doesn’t, so you have to check that by yourself.

Also see the MSDN reference on the ‘as’ keyword.

WinForms: Labels and ampersands

Today I bumped into this problem at work. I had a label on a form and I had to display an employee’s department.

Quite easy, but the department sometimes contains an ampersand. And that ampersand was not displayed. I went looking for this problem and I bumped into this property (in System.Windows.Forms.Label): Label.UseMnemonic Property

Setting this property true means: an ampersand that precedents a character underlines that character, so that it can be used in conjunction with the alt key.

The problem arises when you for example pull a department from the database with an ampersand (for example: shipping & hauling). Putting this into the label causes the & not to be displayed since the label assumes that the ampersand means ‘underline the character after the ampersand’.

To display the ampersand you’ve got two choices:

  1. set UseMnemonic to false so that it doesn’t parse the ampersand.
  2. if you need the mnemonic: replace the & with &&, that displays 1 ampersand in the label.

LINQ to Entities: EntityReference

When creating one to many relationships one might bump into the following problem:

Consider the following database design:

Tables:

Customers
-Id
-FirstName
-LastName
-…snip…
-City

Cities
-Id
-Name
-Zip

With a many to one relation from Customers.City to Cities.Id

While this is easy to do in SQL, the LINQ to Entities syntax might seem a bit different.

Consider the following piece of code:

City c = (from city in ctx.CitySet
where city.Name == cityName && city.Zip == cityZip
select city).FirstOrDefault();

This selects the city (if it exists) or null.

Now the problem is: IF the city exists, how do I point the current customer’s city to that particular city.

I tried this:

//customer is a customer object
customer.City = c;

But that resulted in duplicate cities in the database.

The solution was actually quite easy, I browsed through all the properties (Intellisense!) and found this:

customer.CityReference.EntityKey = c.EntityKey;

This resulted in the one to many relationship I had in mind. No duplicate cities in my database.

I love database normalization!

WPF: FileDialogs on Vista 64-bit, use the Manifest!

Rick Brewster made this comment on my previous post about the Inconsistent FileDialogs.

So I decided to fire up his solution:

I’ve created an empty WPF project, with a Window called ‘Main’ with the following code:

using System.Windows;
using Microsoft.Win32;

namespace OpenFileDialogNewStyle
{
	/// 
	/// Interaction logic for Main.xaml
	/// 
	public partial class Main : Window
	{
		/// 
		/// Constructor
		/// 
		public Main()
		{
			this.InitializeComponent();

			OpenFileDialog myOpenFileDialog = new OpenFileDialog();

			myOpenFileDialog.ShowDialog();
		}
	}
}

This opens the ‘old’ style FileDialog, with the outdated icons.

old-filedialog

To resolve this you can add a manifest in your project:

add-manifest

The manifest should be named NameOfYourStartUpProject.exe.manifest (as pointed out above), it should be a text file containing the following code:


	
	Description
	
		
			
		
	

Change the name on the 5th line to the name of your project!

Now go to properties and point to the manifest.

select-manifest

Now compile, and test if you see the new type icons 🙂

new-filedialog

C#: Structs and parameters

struct MyStruct
{
	public int X { get; set; }
	public int Y { get; set; }

	public MyStruct(int x, int y)
	{
		this.X = x;
		this.Y = y;
	}
}

Will trigger an error on line 8:

The ‘this’ object cannot be used before all of its fields are assigned to

So I thought I might fix it by assigning a value to the fields. Since we have automatic properties, let’s convert them to normal properties:

struct MyStruct
{
	private int _x = 0;
	public int X
	{
		get
		{
			return _x;
		}
		set
		{
			_x = value;
		}
	}
	private int _y = 0;
	public int Y
	{
		get
		{
			return _y;
		}
		set
		{
			_y = value;
		}
	}

	public MyStruct(int x, int y)
	{
		this.X = x;
		this.Y = y;
	}
}

Let’s press F5. Oeh noes, another error:

‘MyStruct._x’ cannot have its instance field initializers in structs

So you can’t do field initialization in a struct (apart from in a function / constructor / getter / setter).

Let’s go back to the first piece of code and make it work by adding 7 characters:

struct MyStruct
{
	public int X { get; set; }
	public int Y { get; set; }

	public MyStruct(int x, int y) : this()
	{
		this.X = x;
		this.Y = y;
	}
}

The this() initializes the struct, and in the constructor itself the struct’s vars & properties are set to their default values. It’s weird though that an int needs initialization…

C#: Extending Outlook.(_)Application.

Does not work.

Outlook.Application and Outlook._Application are both interfaces. And I want to use them as a class in my program (I don’t know how they made that work).

I wanted to extend Outlook.Application and add a simple method to create a new email. But that does not work since you have to implement a bunch of methods which I hardly understand.

Thank Microsoft for creating extension methods, so here is my solution:

using System;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace SendToExtended
{
	static class OutlookExtensions
	{
		/// 
		/// Creates and returns an Microsoft Outlook MailItem
		/// 
		/// an instantiated Outlook application
		/// A new MailItem object
		public static Outlook.MailItem CreateMailItem(this Outlook.Application outlook)
		{
			if (outlook == null)
				throw new ArgumentException("outlook parameter cannot be null");

			return (Outlook.MailItem)outlook.CreateItem(Outlook.OlItemType.olMailItem);
		}
	}
}

A fluent approach to C# parameter validation

Normally I don’t do this, but since this is such a great article:

http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/

From the creator of Paint.NET.

It’s really worth reading, if you do a lot of parameter validation. It might come in handy for your forms, or maybe even for a website.

I think I’ll write something based on that really soon 🙂

C#: Smaller syntax for event handlers.

Using lambda functions you can shorten your event handlers.

E.g.:

With a normal event hander:

class Test
{
	private Timer timer;

	private void Timer_Elapsed(object sender, ElapsedEventArgs e)
	{
		Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));
	}

       public Test()
	{
		this.timer = new Timer();

		this.timer.Elapsed += new ElapsedEventHandler(this.Timer_Elapsed);

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

With an anonymous function:

class Test
{
	private Timer timer;

        public Test()
	{
		this.timer = new Timer();

		this.timer.Elapsed += delegate(object sender, ElapsedEventArgs e)
					 {
						 Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));
					 };

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

And with an anonymous lamba:

class Test
{
	private Timer timer;

        public Test()
	{
		this.timer = new Timer();

		this.timer.Elapsed += (sender, e) => Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));
		//or you can explicitly type your parameters:
		this.timer.Elapsed += (object sender, ElapsedEventArgs e) => Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

And with a named lamda:

class Test
{
	private ElapsedEventHandler elapsedEventHander;
        private Timer timer;

        public Test()
	{
		this.timer = new Timer();

		this.elapsedEventHander = (sender, e) => Console.WriteLine(string.Format("Object: {0} sends: {1}", sender, e));

		this.timer.Elapsed += this.elapsedEventHander;

		this.timer.Interval = 100;
		this.timer.Start();
	}
}

Which one to take? The one that suits you and your current application / case!

Sidenote: sorry for the layout, I will fix it ASAP. Fixed 🙂