Friday, January 8, 2010

Null Coalescing Assignment Operator for C#

Great post by Chris Eargle about a null coalescing assignment operator for c#.

How would you like to be able to say:

myObj ??= new MyObj();

instead of:

myObj = myObj ?? new MyObj();

Seems like a trivial "enhancement" to the language but makes sense to me.

Monday, January 4, 2010

Flags enum attribute

I've just learned about the [Flags] attribute for enums. I'm surprised that I hadn't stumbled across it before. Consider the following code snippet:

enum Direction { North = 1, East = 2, South = 4, West = 8 }
static void EnumTesting()
{
    Direction ne = Direction.North | Direction.East;
    Console.WriteLine(ne);
}

The output is: 3

Now add the [Flags] attribute to the enum:

[Flags]
enum Direction { North = 1, East = 2, South = 4, West = 8 }
static void EnumTesting()
{
    Direction ne = Direction.North | Direction.East;
    Console.WriteLine(ne);
}

The output is now: North, East

Enumeration constants are generally used for lists of mutually exclusive elements. However, sometimes you may want to use them for lists of elements that might occur in combination. Permissions to access resources is a good example of this.

 

Thursday, December 31, 2009

Five best things I didn't get for Christmas


I'm posting this here so that I can find it again. This is Life Hacker's most popular Hive Five Topics of 2009.

I hadn't seen this before I bought my Netbook but it turns out that the one I bought was an update to the most voted Netbook on their Five Best Netbooks posting.

Wednesday, December 23, 2009

Managing IP addresses as integers

I was recently involved in a discussion about IP addresses and discovered that not everyone understands an IP address. I was told that an IP address is not an integer. Well, it is an integer, a 32-bit integer, but it is rarely represented as such. It is usually represented as four octets joined together with periods.

This is what most people know as an IP address: 127.0.0.1 and if I showed you the value 2130706433 you probably wouldn't recognize it as the same IP address.

I blogged some extension methods in Converting a string IP to and int and back that will help you if you need to convert an IP between the two formats using C#. The code is fairly obvious and easily ported to other languages.

The question often asked is why do you need to convert it?

The answer is speed and space.

Most often, when you receive an IP address it is in the string notation. Storing it in this notation inefficient because it takes between 7 (0.0.0.0) and 15 (255.255.255.255) bytes to store each address. Compare this to storing it as an Int32 which takes 4 bytes each time. A space saving of between 42% and 73%.

My advice is to convert it into an Int32 as soon as you receive it and then work with it as such from there onwards. Working with an IP as an Int32 will be faster because sorting and comparing Int32's will outstrip the same when using strings. Setting up an index against an Int32 column in a database will also be faster and smaller than doing the same against a varchar column.

When you need to show an integer IP to a user you'll need to convert it back to its string notation. This is easily done with the extension methods linked above.

The only draw back to using this approach for managing IP addresses is when you list IP's directly from your database. If they were stored as strings they'd be easy to recognize but listed as integers they're pretty useless.

Converting a string IP to an int and back

I often need to convert a string IP to an Int32 and then back again. To facilitate converting an Int32 to its string representation I have added this extension method to my IntExtensions class in C#:

public static class IntExtensions
{
    /// <summary>
    /// Converts an integer that represents an IPv4 to the string equivalent
    /// Source: http://guyellisrocks.com/coding/converting-a-string-ip-to-an-int-and-back/
    /// </summary>
    /// <param name="solidIP">The integer representation of an IPv4</param>
    /// <returns>A string of the format x.x.x.x representing an IPv4</returns>
    public static string ToIPv4(this int solidIP)
    {
        byte ip1 = (byte)(solidIP >> 24);
        byte ip2 = (byte)(solidIP >> 16);
        byte ip3 = (byte)(solidIP >> 8);
        byte ip4 = (byte)(solidIP);
        return ip1 + "." + ip2 + "." + ip3 + "." + ip4;
    }
}

And to convert the string representation of an IP to an Int32 I have added this extension method to my StringExtensions class:

public static class StringExtensions
{
    /// <summary>
    /// Converts a string that holds an IPv4 address with the pattern x.x.x.x
    /// to the integer equivalent. If the string cannot be split into 4 parts
    /// using a . or if the 4 parts cannot by parsed
    /// into bytes then 0 will be returned.
    /// Source: http://guyellisrocks.com/coding/converting-a-string-ip-to-an-int-and-back/
    /// </summary>
    /// <param name="IP">A string representing an IPv4 address</param>
    /// <returns>An integer representing an IPv4 address or zero if failure</returns>
    public static int ToIPv4(this string IP)
    {
        try
        {
            string[] fourIP = IP.Split('.');

            Int32 ip =
                (Byte.Parse(fourIP[0]) << 24) +
                (Byte.Parse(fourIP[1]) << 16) +
                (Byte.Parse(fourIP[2]) << 8) +
                Byte.Parse(fourIP[3]);

            return ip;
        }
        catch
        {
            return 0;
        }
    }
}

 

Monday, December 21, 2009

Vertical Wireless Router


While I was researching the buying of a new wireless router I read a customer review comment on a router that said something about a particular router/model that would overheat if left in the horizontal position which would cause connections to be dropped. This intrigued me because my router/modem/wireless access point has always lived in the horizontal position and is prone to rebooting when a wireless device connects to it. So my theory is that more of this device is in use when a wireless device is connected to it so it might get hotter.
Could this be the problem with the flaky wireless that I have?
Well after reading that I tried standing the router vertically and have been aggressivley using the wireless and so far (a couple of days) we have had no disconnects. The evidence points to the overheating in the horizontal position, so far. The jury is still out on this one though because I know as well as anyone else that this could be a fluke and we may return to flakiness in the near future. I'll update this post in a couple of months with more info.

Saturday, December 19, 2009

Belkin N+ Wireless Router

The ASUS Netbook that I mentioned in this post arrived yesterday and I've started playing with it. So far it's good and a bit faster than I was expecting. The only two changes that I was going to make to it before buying it were to replace the 250GB drive with a 128GB SSD (Solid State Drive) and upgrade the RAM from 1GB to 2GB. However, it's a lot nippier than expected so will not worry about that yet. It arrived with Windows 7 Starter. I stuck in a thumb drive and immediately installed Windows 7 Ultimate. It was really tricky getting it to boot from the thumb drive because the hot key that you had to hit to get to the BIOS and then to pick the "boot from USB option" was difficult to time. You basically had to hit the escape key twice immediately after it was powered on.

It supports the new (yet to be finished) higher speed network standard of 802.11 N. My current wireless access point goes up to G and is flaky (update on why it might be flaky) often knocking the modem offline if a wireless device is connected to it. As such I've just been doing a whole ton of research to see what I can add to my network that will give me that best quality wireless and hopefully last several years. I hate shopping for stuff like this that I'm not expert in as I never know if I'm going to get a good deal or not. I'm also suspicious of the specs published by many of the comparison sites and even the manufacturer as they are sometimes inaccurate and I never know if the customer reviews are written by the company trying to boost their product or by a competitor trying to discredit their product.

Anyway I had to make a decision and finally went with the BELKIN N+ Wireless Router. I was comparing this to the BELKIN N Wireless Router and the only difference that I could find was that the N+ has gigabit ports while the N has 10/100MBS ports. Considering that I'm all about speed and constantly wanting to saturate my network I selected the former. I'll report back when it's installed.