A Standard CRC-16 and CRC-16 Kermit implementation in C#

Been a while since I posted anything, but here’s an update to my original CRC-16 class that does CRC-16 with CRC-CCITT Kermit code that I posted over on Stack Overflow a while ago. Unlike the code over there this doesn’t have a static look-up table (feel free to get the code from over there if you wanted the static table, but I’m actually not too fond of static look-up tables on example source code though they are more efficient).

using System;

public enum Crc16Mode : ushort { Standard = 0xA001, CcittKermit = 0x8408 }

public class Crc16 {
    readonly ushort[] table = new ushort[256];

    public ushort ComputeChecksum( params byte[] bytes ) {
        ushort crc = 0;
        for(int i = 0; i < bytes.Length; ++i) {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    public byte[] ComputeChecksumBytes( params byte[] bytes ) {
        ushort crc = ComputeChecksum( bytes );
        return BitConverter.GetBytes( crc );
    }

    public Crc16( Crc16Mode mode ) {
        ushort polynomial = (ushort)mode;
        ushort value;
        ushort temp;
        for(ushort i = 0; i < table.Length; ++i) {
            value = 0;
            temp = i;
            for(byte j = 0; j < 8; ++j) {
                if(((value ^ temp) & 0x0001) != 0) {
                    value = (ushort)((value >> 1) ^ polynomial);
                }else {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}
C#

If you need for this code to be CLS compliant, you can change the method signature’s return type from ushort to int and it will operate the same (the ushort crc value will be implicitly converted from ushort to int)

Links to the other C# CRC implementations the original CRC-16 implementation, CRC16-CCITT, CRC-32, and CRC-8

I’ve consolidated all of these into a single library on GitHub here: NullFX.CRC.

I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package

A CRC8 implementation in C#

So I’ve tackled CRC32, CRC16, CRC16-CCITT (and now CRC16-CCITT Kermit) implementations, and found myself wanting a CRC8 class to create checksums for small data (1-2 bytes) sets. Not having ever used or seen CRC8 in use before, I did some reading, and as far as I can tell, I’ve implemented it correctly… It works anyway, so without further ado, here’s my implementation:

public static class Crc8 {
    static byte[] table = new byte[256];
    // x8 + x7 + x6 + x4 + x2 + 1
    const byte poly = 0xd5;

    public static byte ComputeChecksum(params byte[] bytes ) {
        byte crc = 0;
        if ( bytes != null && bytes.Length > 0 ) {
            foreach ( byte b in bytes ) {
                crc = table[crc ^ b];
            }
        }
        return crc;
    } 

    static Crc8( ) {
        for ( int i = 0; i < 256; ++i ) {
            int temp = i;
            for ( int j = 0; j < 8; ++j ) {
                if ( ( temp & 0x80 ) != 0 ) {
                    temp = ( temp << 1 ) ^ poly;
                } else {
                    temp <<= 1;
                }
            }
            table[i] = (byte)temp;
        }
    }
}
C#

This one differs slightly (API wise) from my previous ones, mainly because I was using it for check-summing smaller bits of data, so I made the ComputeChecksum method a params argument instead of a first class array type.

Here’s a sample of how I was using it (and testing it):

byte crc = Crc8.ComputeChecksum( 1, 2, 3 );
byte check = Crc8.ComputeChecksum( 1, 2, 3, crc );
// here check should equal 0 to show that the checksum is accurate
if ( check != 0 ) {
    Console.WriteLine( "Error in the checksum" );
}
C#

I’ve consolidated all of these into a single library on GitHub here: NullFX.CRC.

I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package

Pre-increment vs post-increment operators

OK, so here’s a question for you that most people should have learned in school, but didn’t. You have to answer this without running to visual studio.

  1. What is the difference between ++i and i++?
  2. What is the output of the following piece of code:
for(int i = 0; i < 5; ++i) {
    Console.WriteLine(i);
}
C#

Is it A)

1 2 3 4

or B)

0 1 2 3 4

I’m sure there are quite a few who would choose A, but this is in fact incorrect (go ahead and run it in visual studio now).

Most of us when we learned C style programming were taught that pre-increment increments the value before taking the value, and that post increment takes the value then increments. After being taught that, pretty much every professor, every code sample, and everybody under the sun used post increment for every single iterative example in existence.

Question is… WHY?

Inside a loop, I cannot see why anyone would use post increment. What is the order of operation? Declare, loop body, compare, increment, loop body, compare, increment, ….

Unlike C++ (where there are there are actually 2 distinct operators: a pre and a post increment operator) C#, has only one generic “increment” / “decrement” operator, so exactly how the operator works is left completely out of our hands (and is handled internally by the framework). As stated in the ECMA spec (page 176 of the 4th edition of the ECMA-334):

The run-time processing of a postfix increment or decrement operation of the form x++ or x– consists of the following steps:

  • If x is classified as a variable:
    • x is evaluated to produce the variable.
    • The value of x is saved.
    • The saved value of x is converted to the operand type of the selected operator and the operator is invoked with this value as its argument.
    • The value returned by the operator is converted to the type of x and stored in the location given by the evaluation of x.
    • The saved value of x becomes the result of the operation.

By comparison, here is what is stated for a pre-increment operation (page 196 of ECMA-334 4th edition):

The run-time processing of a prefix increment or decrement operation of the form ++x or –x consists of the following steps:

  • If x is classified as a variable:
    • x is evaluated to produce the variable.
    • The value of x is converted to the operand type of the selected operator and the operator is invoked with this value as its argument.
    • The value returned by the operator is converted to the type of x. The resulting value is stored in the location given by the evaluation of x and becomes the result of the operation.

So in the case of post increment, a copy has to be made, the op_Increment is invoked using the copy, the value is returned, and the copy overwrites the original value.

With pre-increment, the value is passed into the op_Increment method, and its value is returned.

In the case of a loop, we are not using the value returned pre-increment, and are therefore only using the increment operation to alter the original value, so using post increment is completely pointless. Why anyone uses it is beyond me. Maybe its a case of not actually understanding whats going on.

There are a few places where it actually makes sense to use a post increment operation, but even these probably have better solutions to them as well:

int i = 0;
int j = i++;
// or
int[] table = { 0, 1, 2, 3, 4, 5, 6 };
int i = 0;
int j = table[i++];
int k = table[i++];
int l = table[i++];
C#

So the moral of the story is… post increment wisely (have a good reason to use it, otherwise pre-increment).

A C# Command Line Args processing class

The other day I was working on our video game’s content server app. The way its set up is fairly complicated. It basically has 3 modes that it can run in (as a windows service, as a fully blown console shell, or as a windows application).

Being tired of writing long ugly blocks of code for command line arg’s processing, I decided to build out an object (not at all like my last command line parser class) that would manage the command line args in an intuitive manner.

There are Three basic ways to use this class:

  1. Sort of like a dictionary
  2. With one big event handler
  3. By registering specific event handlers

What I typically do is add the args that are passed into the main function into an arraylist or List<string> and simply ask if the list contains this switch or that switch:

static class Program {
    static void Main(string[] args) {
        List<string> cmdArgs = new List<string>(args);
        if(cmdArgs.Contains("/myswitch"))) {
            // ... whatever ...
        }
    }
}
C#

As you can see, it still takes quite a bit of code. My first iteration of my CommandLineArgs class parsed out the command line switches and placed everything in a dictionary

static class Program {
    static void Main(string[] args) {
        CommandLineArgs cmdArgs = new CommandLineArgs();
        cmdArgs.IgnoreCase = true;
        // this adds a switch prefix regular expression used to determine 
        // what is a switch and what is not.whats passed in is a normal Regex pattern.
        cmdArgs.PrefixRegexPatternList.Add("/{1}");   // forward slash or 
        cmdArgs.PrefixRegexPatternList.Add("-{1,2}"); // - / -- options
        cmdArgs.ProcessCommandLineArgs(args);
        if(cmdArgs.ContainsSwitch("myswitch"))) {
            // ... whatever ...
        }
    }
}
C#

But that was pretty much just like using the list like I had been doing.

The next iteration added a SwitchMatch event so that when ProcessCommandLineArgs was called, as switches were parsed, it would kick of an event for each match, providing the switch name (minus the switch prefix) and the value of that switch.

static class Program {
    static void Main(string[] args) {
        CommandLineArgs cmdArgs = new CommandLineArgs();
        cmdArgs.IgnoreCase = true;
        cmdArgs.PrefixRegexPatternList.Add("/{1}");
        cmdArgs.PrefixRegexPatternList.Add("-{1,2}");
        cmdArgs.SwitchMatch += (sender, e) => {
            if(!e.IsValidSwitch) return
            switch(e.Switch) {
                case "foo": {
                    // ... handle the /foo -foo or --foo switch logic here ...
                } break;
            }
        };
        cmdArgs.ProcessCommandLineArgs(args);
    }
}
C#

By the way, I’m using .NET 3.5 here (notice the nice lambda event handler there… yes, I am lazy and lambda’s lend themselves nicely to how I do things) if you couldn’t tell. If you’re using .NET 1.1 or 2.0 then you can just create an event handler like you normally would.

This worked nicely. Only problem now is that I have to have the huge switch statement in my main class. So in the next iteration I decided it would be nice to be able to register specific switch handlers (one for “/foo”, one for “–bar” and so on.

static class Program {
    static void Main(string[] args) {
        CommandLineArgs cmdArgs = new CommandLineArgs();
        cmdArgs.IgnoreCase = true;
        cmdArgs.PrefixRegexPatternList.Add("/{1}");
        cmdArgs.PrefixRegexPatternList.Add("-{1,2}");
        cmdArgs.RegisterSpecificSwitchMatchHandler("foo", (sender, e) => {
            // handle the /foo -foo or --foo switch logic here.
            // this method will only be called for the foo switch.
        });
        cmdArgs.ProcessCommandLineArgs(args);
    }
}
C#

One other item I should also note is that there is also an InvalidArgs array too. On the events, there is an IsValidSwitch property that will let you know whether or not the switch is valid or not (since the SwitchMatch event is triggered whether or not the switch is valid) so if your command line contains any values that are not directly tied to a switch. For instance if you don’t quote a string with spaces: /foo this is a string like this /foo “this is a string” then /foo’s value will be “this” and is, a, string will all be contained in the invalid args list. If you use a switch prefix not accounted for in your prefix regex list, it will also be added to your InvalidArgs list (ex: yourapp.exe ^switch “values” both ^switch and values will be placed in your InvalidArgs list.

This class accepts the following formats:

  • <switch prefix>switch=value
  • <switch prefix>switch value

So in the spirit of sharing, here is my CommandLineArgs class:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class CommandLineArgs {
    public const string InvalidSwitchIdentifier = "INVALID";
    List<string> prefixRegexPatternList = new List<string>();
    Dictionary<string, string> arguments = new Dictionary<string, string>();
    List<string> invalidArgs = new List<string>();
    Dictionary<string, EventHandler<CommandLineArgsMatchEventArgs>> handlers = 
        new Dictionary<string, EventHandler<CommandLineArgsMatchEventArgs>>();
    bool ignoreCase = true;

    public event EventHandler<CommandLineArgsMatchEventArgs> SwitchMatch;

    public int ArgCount { get { return arguments.Keys.Count; } }

    public List<string> PrefixRegexPatternList {
        get { return prefixRegexPatternList; }
    }

    public bool IgnoreCase {
        get { return ignoreCase; }
        set { ignoreCase = value; }
    }

    public string[] InvalidArgs {
        get { return invalidArgs.ToArray(); }
    }

    public string this[string key] {
        get {
            if (ContainsSwitch(key)) return arguments[key];
            return null ;
        }
    }

    protected virtual void OnSwitchMatch(CommandLineArgsMatchEventArgs e) {
        if (handlers.ContainsKey(e.Switch) && handlers[e.Switch] != null ) handlers[e.Switch](this, e);
        else if (SwitchMatch != null ) SwitchMatch(this, e);
    }

    public void RegisterSpecificSwitchMatchHandler(string switchName, EventHandler<CommandLineArgsMatchEventArgs> handler) {
        if (handlers.ContainsKey(switchName)) handlers[switchName] = handler;
        else handlers.Add(switchName, handler);
    }

    public bool ContainsSwitch(string switchName) {
        foreach (string pattern in prefixRegexPatternList) {
            if (Regex.IsMatch(switchName, pattern, RegexOptions.Compiled)) {
                switchName = Regex.Replace(switchName, pattern, "", RegexOptions.Compiled);
            }
        }
        if (ignoreCase) {
            foreach (string key in arguments.Keys) {
                if (key.ToLower() == switchName.ToLower()) return true;
            }
        } else {
            return arguments.ContainsKey(switchName);
        }
        return false;
    }

    public void ProcessCommandLineArgs(string[] args) {
        for (int i = 0; i < args.Length; i++) {
            string value = ignoreCase ? args[i].ToLower() : args[i];
            foreach (string prefix in prefixRegexPatternList) {
                string pattern = string.Format("^{0}", prefix);
                if (Regex.IsMatch(value, pattern, RegexOptions.Compiled)) {
                    value = Regex.Replace(value, pattern, "", RegexOptions.Compiled);
                    if (value.Contains("=")) { // "<prefix>Param=Value"
                        int idx = value.IndexOf('=');
                        string n = value.Substring(0, idx);
                        string v = value.Substring(idx + 1, value.Length - n.Length - 1);
                        OnSwitchMatch(new CommandLineArgsMatchEventArgs(n, v));
                        arguments.Add(n, v);
                    } else { // "<prefix>Param Value"
                        if (i + 1 < args.Length) {
                            string @switch = value;
                            string val  = args[i + 1];
                            OnSwitchMatch(new CommandLineArgsMatchEventArgs(@switch, val));
                            arguments.Add(value, val);
                            i++;
                        } else {
                            OnSwitchMatch(new CommandLineArgsMatchEventArgs(value, null ));
                            arguments.Add(value, null );
                        }
                    }
                } else { // invalid arg ...
                    OnSwitchMatch( new CommandLineArgsMatchEventArgs( 
                        InvalidSwitchIdentifier, value, false));
                    invalidArgs.Add(value);
                }
            }
        }
    }
}

public class CommandLineArgsMatchEventArgs : EventArgs {
    string @switch;
    string value;
    bool isValidSwitch = true;

    public string Switch {
        get { return @switch; } 
    }

    public string Value {
        get { return value; }
    }

    public bool IsValidSwitch {
        get { return isValidSwitch; }
    }

    public CommandLineArgsMatchEventArgs(string @switch, string value)
        : this(@switch, value, true) { }

    public CommandLineArgsMatchEventArgs(string @switch, string value, bool isValidSwitch) {
        this.@switch = @switch;
        this.value = value;
        this.isValidSwitch = isValidSwitch;
    }
}
C#

C# .NET Single Instance Application

Today I wanted to refactor some code that prohibited my application from running multiple instances of itself.

Previously I had use System.Diagnostics.Process to search for an instance of my myapp.exe in the process list. While this works, it brings on a lot of overhead, and I wanted something cleaner.

Knowing that I could use a mutex for this (but never having done it before) I set out to cut down my code and simplify my life.

In the class of my application main I created a static named Mutex (the GUID is irrelevant, just a “globally unique name” that we can use for our application):

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    ...
}
C#

Having a named mutex allows us to stack synchronization across multiple threads and processes which is just the magic I’m looking for.

Mutex.WaitOne has an overload that specifies an amount of time for us to wait. Since we’re not actually wanting to synchronizing our code (more just check if it is currently in use) we use the overload with two parameters: Mutex.WaitOne(Timespan timeout, bool exitContext). Wait one returns true if it is able to enter, and false if it wasn’t. In this case, we don’t want to wait at all; If our mutex is being used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 milliseconds), and set the exitContext to true so we can exit the synchronization context before we try to acquire a lock on it. Using this, we wrap our Application.Run code inside something like this:

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    static void Main() {
        if(mutex.WaitOne(TimeSpan.Zero, true)) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            mutex.ReleaseMutex();
        } else {
            MessageBox.Show("only one instance at a time");
        }
    }
}
C#

So, if our app is running, WaitOne will return false, and we’ll get a message box.

Instead of showing a message box, I opted to utilize a little Win32 to notify my running instance that someone forgot that it was already running (by bringing itself to the top of all the other windows). To achieve this I used PostMessage to broadcast a custom message to every window (the custom message was registered with RegisterWindowMessage by my running application, which means only my application knows what it is) then my second instance exits. The running application instance would receive that notification and process it. In order to do that, I overrode WndProc in my main form and listened for my custom notification. When I received that notification I set the form’s TopMost property to true to bring it up on top.

Here is what I ended up with:

Program.cs

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    static void Main() {
        if(mutex.WaitOne(TimeSpan.Zero, true)) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            mutex.ReleaseMutex();
        } else {
            // send our Win32 message to make the currently running instance
            // jump on top of all the other windows
            NativeMethods.PostMessage(
                (IntPtr)NativeMethods.HWND_BROADCAST,
                NativeMethods.WM_SHOWME,
                IntPtr.Zero,
                IntPtr.Zero);
        }
    }
}
C#

NativeMethods.cs

// this class just wraps some Win32 stuff that we're going to use
internal class NativeMethods {
    public const int HWND_BROADCAST = 0xffff;
    public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
    [DllImport("user32")]
    public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
    [DllImport("user32")]
    public static extern int RegisterWindowMessage(string message);
}
C#

and our Form1.cs (front side partial)

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }
    protected override void WndProc(ref Message m) {
        // handle the WM_SHOWME message and bring 
        // this window to the top
        if(m.Msg == NativeMethods.WM_SHOWME) {
            ShowMe();
        }
        base.WndProc(ref m);
    }
    private void ShowMe() {
        if(WindowState == FormWindowState.Minimized) {
            WindowState = FormWindowState.Normal;
        }
        // get our current "TopMost" value (ours will always be false though)
        bool top = TopMost;
        // make our form jump to the top of everything
        TopMost = true;
        // set it back to whatever it was
        TopMost = top;
    }
}
C#

Creating Fake Enums

In .NET Enums are a strongly typed flag-like object. Flags would normally defined as a macro, or constant variable. The trouble with typical numeric flags is that a) the coder using the flag may or may not know all of the possible values, or b) might accidentally type the wrong constant or macro. Since the flag is just some magic number they may end up with a logic error that may be hard to find under certain circumstances. With Enums I can provide the same logic (some numeric flag) but create a type that I can use to enforce some subset of numbers that are checked at compile time, and can be verified at run time ( Enum.IsDefined ). As with everything, Enums have their faults. What if I want to extend some Enum object (polymorphic Enums?), or give it additional functionality or meta data. Yesterday at work we ran across a case where being able to extend an Enum was mandatory. All of our Enums have numeric and string values, and are typically written like:

public enum Foo {
    [FriendlyName("One Foo")]
    One = 1,
    [FriendlyName("Two Foo")]
    Two = 2,
    [FriendlyName("Three Foo")]
    Three = 3
}
C#

the FriendlyName attribute enables you to have both a numeric flag value as well as some human readable value of the enum element other than “One” or “Two” or “SomeEnumValue”(ie: Foo.One.ToString())

Our company uses code generation like most fish use water. We use Enums quite a bit and each Enum type and all of their values are stored in a database which is used by the code generation tool to generate 99% of our business and data layer code. Since our code is generated, if we go in and manually add additional values that don’t need to be stored in the database, our generation tool will blow away any hand written changes on every build. We would have killed to have something like a partial Enum, but alas, no such thing exists.

I set out to try to create a “Fake Enum” class that acted and felt like an Enum but allowed us to extend it by way of the partial class or inheritance. Well after a little poking around, inheritance flew out the window (just over complex without resorting to some generics base type), but the ability to do a partial fake Enum was definitely doable.

Here’s the code I came up with:

using System;
using System.ComponentModel;
using System.Globalization
using System.Reflection;

[TypeConverter(typeof(FakeEnum.FakeEnumConverter))]
public partial class FakeEnum {

    // typical "Enum" declarations, sort of like One = 1, Two = 2, Three
    public static readonly FakeEnum One = new FakeEnum(1, "One's Friendly Name");
    public static readonly FakeEnum Two = new FakeEnum(2, "Two's Friendly Name");
    public static readonly FakeEnum Three = new FakeEnum(3, "Three's Friendly Name");
    public static readonly FakeEnum Four = new FakeEnum(4);
    public static readonly FakeEnum Five = new FakeEnum(5);
    public static readonly FakeEnum Six = new FakeEnum(6);


    // implementation to provide "Enum" like functionality
    int value;
    string friendlyName;

    public string FriendlyName { get { return friendlyName; } }

    public override string ToString() {
        return ToString("");
    }

    public virtual string ToString(string format) {
        foreach(FieldInfo staticField in GetType().GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)) {
            FakeEnum temp = staticField.GetValue(null) as FakeEnum;
            if(temp == null) continue;
            if(temp.value == value) {
                switch(format) {
                    case "fn": {
                        return temp.friendlyName;
                    }
                    default: {
                        return staticField.Name;
                    }
                }
            }
        }
        return base.ToString();
    }

    public override int GetHashCode() {
        return value.GetHashCode();
    }

    public override bool Equals(object obj) {
        if(object.ReferenceEquals(obj, null)) return false;
        FakeEnum temp = obj as FakeEnum;
        if(!object.ReferenceEquals(temp, null)) {
            return temp.value == value;
        } else {
            return false;
        }
    }

    public static object Parse(Type type, int value) {
        foreach(FieldInfo fieldInfo in type.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public)) {
            FakeEnum enumValue = fieldInfo.GetValue(null) as FakeEnum;
            if(enumValue != null) {
                if(enumValue.value == value) {
                    return enumValue;
                }
            }
        }
        throw new ArgumentException(string.Format("{0} is not defined in {1}", value, type.Name));
    }

    public static object Parse(Type type, string value) {
        return Parse(type, value, false);
    }

    public static object Parse(Type type, string value, bool ignoreCase) {
        if(string.IsNullOrEmpty(value)) throw new ArgumentNullException("value was either null or empty");
        foreach(FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)) {
            bool isMatch = false;
            if(ignoreCase) {
                isMatch = StringComparer.InvariantCultureIgnoreCase.Compare(field.Name, value) == 0;
            } else {
                isMatch = StringComparer.InvariantCulture.Compare(field.Name, value) == 0;
            }
            if(isMatch) {
                FakeEnum temp = field.GetValue(null) as FakeEnum;
                if(temp == null) throw new InvalidOperationException(string.Format("{0} not convertable to {1}", type, typeof(FakeEnum)));
                object instance = Activator.CreateInstance(type, new object[] { temp.value, temp.friendlyName });
                return instance;
            }
        }
        throw new ArgumentException(string.Format("{0} is not defined in {1}", value, type.Name));
    }

    public static bool IsDefined(Type type, object value) {
        if(object.ReferenceEquals(value, null)) throw new ArgumentNullException("value");
        if(typeof(FakeEnum).IsAssignableFrom(type)) {
            return IsDefined(type, ((FakeEnum)value).value);
        }
        return false;
    }

    public static bool IsDefined(Type type, int value) {
        foreach(FieldInfo staticField in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)) {
            object temp = staticField.GetValue(null);
            if(temp == null) continue;
            if(typeof(FakeEnum).IsAssignableFrom(type)) {
                if(((FakeEnum)temp).value == value) return true;
            }
        }
        return false;
    }

    public static bool IsDefined(Type type, string value) {
        return IsDefined(type, value, false);
    }

    public static bool IsDefined(Type type, string value, bool ignoreCase) {
        foreach(FieldInfo staticField in type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy)) {
            bool isMatch = false;
            if(ignoreCase) {
                isMatch = StringComparer.InvariantCultureIgnoreCase.Compare(staticField.Name, value) == 0;
            } else {
                isMatch = StringComparer.InvariantCulture.Compare(staticField.Name, value) == 0;
            }
            if(isMatch) return true;
        }
        return false;
    }

    public static explicit operator FakeEnum(int value) {
        foreach(FieldInfo staticField in typeof(FakeEnum).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)) {
            FakeEnum temp = staticField.GetValue(null) as FakeEnum;
            if(null == temp) continue;
            if(temp.value == value) return temp;
        }
        return null;
    }

    public static explicit operator int(FakeEnum fakeEnum) {
        return fakeEnum.value;
    }

    public static implicit operator FakeEnum(string value) {
        if(string.IsNullOrEmpty(value)) return null;
        foreach(FieldInfo field in typeof(FakeEnum).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)) {
            if(StringComparer.InvariantCultureIgnoreCase.Compare(field.Name, value) == 0) {
                FakeEnum temp = field.GetValue(null) as FakeEnum;
                if( null == temp) throw new InvalidOperationException(string.Format("{0} not convertable to {1}", value, typeof(FakeEnum)));
                FakeEnum instance = new FakeEnum(temp.value, temp.friendlyName);
                return instance;
            }
        }
        return null;
    }

    public static bool operator == (FakeEnum a, FakeEnum b) { 
        if(object.ReferenceEquals(a, null)) return false;      
        return a.Equals(b);
    }

    public static bool operator != (FakeEnum a, FakeEnum b) { 
        if(object.ReferenceEquals(a, null)) return true;
        return !a.Equals(b);
    }

    protected FakeEnum(int value) : this(value, null) { }

    protected FakeEnum(int value, string friendlyName) {
        this.value = value;
        this.friendlyName = friendlyName;
        if(string.IsNullOrEmpty(friendlyName)) {
            this.friendlyName = ToString();
        }
    }

    public class FakeEnumConverter : TypeConverter {
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
            if(value is string) {
                return (FakeEnum)((string)value);
            }
            return base.ConvertFrom(context, culture, value);
        }
    }
}
C#

Since we were generating these guys, we’d put the class implementation in one file, and our enum like declarations in another. It made it look a bit more “enum” like.

From there, you can use it just like a normal enum except that you now have a built in friendly name that you can access:

public void MyMethod(FakeEnum flag) {
    switch(flag) {
        case FakeEnum.One: {
            Console.WriteLine(flag.FriendlyName);
        }
    }
}
C#

Since additional partial classes would be added, I didn’t want to have to provide some functionality of ToString or explicit conversion for each partial class, so I resolved the ability to get the numeric value, string member name value through reflection. Since I had full control over the type, I decided it would be nice to add the FriendlyNameAttribute functionality into my fake enum, so I did.

Its implementation uses .net reflection to iterate over its members and obtain the enum like member and its associated and values (since every member we use like an enum will be a static instance of itself) and additionally its friendly name. actually we could make our fake enum non-numeric based (this would kind of defeat the ability to do a flag like operation) but that wasn’t something needed at the time so we just stuck with int.

To be able to use these objects like a bit field (like enums are), one would need to add the | and & operators so that fields could be combined or extracted (perhaps if I’m bored I’ll add this to a future version).

C# 3.0 Lambda expressions

I’ve finally seen the light for these little buggers. As I wrote in my original post that I really didn’t glean much from the description of lambda expressions that are mentioned in the specification, but I ran across a great article on it on the code project that did a really good job at explaining it.

So my meta blog for the day is a link to that article:

» http://www.codeproject.com/csharp/lambdaexpressions.asp

Phalanger, PHP for .NET

I ran across an article on the code project about a PHP compiler / language extension for .NET.

PHP has an extension for .NET that allows you to use .NET resources in PHP code, but this allows you to use PHP from .NET, with support for native PHP API’s as well as managed compilation. This project may end up making my article on nusoap & C# obsolete, though it should make writing web services in PHP as easy as it is in C#.

» Phalanger Home (now peachpie, link updated to new project)
» Code Project Article (long since abandoned)

.NET Reflection

What is reflection? Its the image we seen in a mirror. In .NET however its a system that lets you do at runtime what you would normally do in a text editor or visual studio.

Like most object oriented programming languages, .net has the concept of a “type.” a Type defines what an object is. Whether your using a primitive such as an integer, or a complex data type, each thing in .net has a type that corresponds to what it is.

public class Foo {}
C#

This class is of type Foo. Now this class is basically pointless… Why? Well because it has no members. Actually it does have members because everything inherits from System.Object, and System.Object has 12 member methods some have overloads, some are static, some are private some are protected others are public. For the sake of simplicity, we wont discuss System.Object, but will stick only to Foo.

public class Foo {
    private int a;
}
C#

Typically we’d never have a class that looked like this. After all, the compiler would never let us access Foo::a because it is a private member. What does this have to do with reflection you may ask yourself? The rules of the compiler do not apply to reflection.

To understand reflection, you need to understand what a class is, how encapsulation works (what access modifiers are), what a function is and what variables are. We could go a little further, but that’s a good starting point.

Lets take our previous class declaration and spice it up a bit.

public class Foo {
    private int a;

    public int A { 
        get { return a; }
        set { a = value; }
    }

    public bool Bar(string input) {
        return input == "Baz";
    }

    protected void Bing() {
        Console.WriteLine("I'm not very creative");
    }    

    public Foo() { }
}
C#

I’ve given Foo a makeover. It now has a private variable, a public property, a public and a protected method and a constructor. I’ve given Foo a few “members.”

On the surface (which I wont scratch much) reflection allows you to access, modify or invoke members of an object.

In our editor we can do this very easily:

Foo f = new Foo();
bool b = f.Bar("Baz");
C#

So lets look at what we’re doing here.

Where does Foo come from?

At the top (or bottom, depending on your endianness) of the Reflection world is the Assembly (a dll or exe). .NET assemblies are files that (can) contain namespaces and classes. Each assembly contains a manifest (aka a list) of other assemblies that it references. It also contains info about what classes it contains.

When a .NET application starts up, the framework spiders out and loads each assembly in each referenced assembly’s manifest until everything referenced is loaded into the current AppDomain. If Foo happens to be in one of these dll’s then everything is fine, but what if it isn’t? Lets start there. The AppDomain object contains a list of all loaded “Assemblies” (if you cared to look at whats loaded).

Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
C#

if an assembly is not loaded, we can load it ourselves (unlike other technologies, once an assembly is loaded into the app domain, it cannot be unloaded until the app domain is unloaded).

Assembly fooAsm = Assembly.LoadFile(@"C:\My Path\foo.dll");
C#

The Assembly object represents the actual dll or exe file and all that is contained within it. From it, we can get a list of types that the assembly contains:

Type[] types = fooAsm.GetTypes();
C#

or request a particular type:

Type fooType = fooAsm.GetType("Foo");
C#

if fooAsm did not contain a class named “Foo” then GetType would return null.

So, now we’ve loaded the dll / assembly that contained our class, and we’ve gotten a Type object that contains information about the class Foo. From fooType, we can get a list of Foo‘s members:

MemberInfo[] memberInfo = fooType.GetMembers();
C#

MemberInfo is the base class for other member specific things like fields, methods, properties and constructors. MemberInfo has a property named Name which will match the name you give the member at the source code level (variable a, property A, method Bar, and constructor Foo). The System.Type object can also be used to get specific types of members like fields, methods, constructors and properties.

MethodInfo[] methods = fooType.GetMethods();
PropertyInfo[] properties = fooType.GetProperties();
FieldInfo[] fields = fooType.GetFields();
ConstructorInfo[] constructors = fooType.GetConstructors();
C#

These objects contains more member specific info, such as method parameters, and return type, whether the property has a get and set or just a getter. Each of these Get…() methods also has an overload that takes a BindingFlags parameter. BindingFlags are things that must be considered when looking for a member. if we use the GetMember(field,property,method or constructor) that takes a string, it will look for a member who’s name matches that. Reflection uses more than just the name to find the member that you’re requesting, the binding flags give additional info as to the members access modifier (public / non-public), whether it’s an instance member or a static member, and so on.

FieldInfo aField = fooType.GetField("a", BindingFlags.NonPublic | BindingFlags.Instance);
C#

In the above code, I get a FieldInfo object which represents the private int variable “a” and I can do the same with the method Bar, the parameterless constructor and the property.

Great right? Who the heck cares? What does this have to do with the price of tea? Lets see…

When we simply wrote the code:

Foo f = new Foo();

the compiler had to locate the assembly that contains foo, load the foo type and create an instance. so lets do the same, but using reflection.

Assembly fooAsm = Assembly.LoadFile(@"C:\My Path\foo.dll");
Type fooType = fooAsm.GetType("Foo");
object foo = Activator.CreateInstance(fooType);
C#

Keep in mind that when we load the assembly at runtime, we cannot simply do:

Foo f = (Foo)Activator.CreateInstance(fooType);
C#

unless we add a reference to foo.dll inside visual studio or in our command line compile statement. If we did that, then we don’t need to use reflection. We simply need an instance of foo. At the time we code it, we don’t care what its type actually is. We know we have an instance of it, and can invoke its methods, access its properties and set its members through reflection (using the MemberInfo, MethodInfo, PropertyInfo, FieldInfo‘s that we get from its Type object). With reflection, the boundaries of encapsulation no longer apply (but should still be respected). We can access internal objects, we can access and manipulate private class members, or invoke private methods. Back to the matter of creating the instance of foo… One thing to keep in mind about using Activator.CreateInstance is that it actually uses the objects constructor to create the instance that gets returned, so if you CreateInstance as I have above, make sure you have a parameter-less constructor in your class. Otherwise, you’ll also have to pass in the constructor args as the second set of parameters after the System.Type in CreateInstance.

now lets imagine something crazy that we want to do:

Foo foo = new Foo();
foo.a = 32;
C#

we could never write code that would do this unless it was inside a member (method or property) of Foo (a is a private member and therefore isn’t accessible externally to Foo).

Assembly fooAsm = Assembly.LoadFile(@"C:\My Path\foo.dll");
Type fooType = fooAsm.GetType("Foo");
object foo = Activator.CreateInstance(fooType);
FieldInfo fooFieldA = fooType.GetField("a", BindingFlags.NonPublic | BindingFlags.Instance);
fooFieldA.SetValue(foo, 32);
int aVal = (int)fooFieldA.GetValue(foo);
C#

so in the above code, we loaded the foo.dll, got the type that we were looking for (Foo), created an instance of it (using Activator.CreateInstance), got the field that we wanted to set, and used the FieldInfo object to set that field in our instance. then for good measures, we got the value that we just set using that field info object.

Each of the derived objects of MemberInfo (MethodInfo, FieldInfo, PropertyInfo, ConstructorInfo, EventInfo) all use the same concepts. First, you obtain an instance of the object you wish to reflect upon, then you obtain the XXXXInfo object that represents the member you want to manipulate, then you use that object to get, set, invoke or handle whatever your trying to do. That necessitates having a valid instance (which you have) and that’s pretty much the basics of using reflection.

This has been an end to end application of the use of reflection. It is not meant as a style guide in how you use reflection. You may very well know everything about the type you’re reflecting upon. In that instance, you may just want to reflectively invoke a method, or set a property. You may actually want to modify the look and feel or a Windows control which provides no public means of achieving what you wish to achieve.

Here’s a little parting sample using the reflection to access an modify various parts of Foo.

Assembly fooAsm = Assembly.LoadFile(@"C:\My Path\foo.dll");
Type fooType = fooAsm.GetType("Foo");
object foo = Activator.CreateInstance(fooType);
MethodInfo barMethod = fooType.GetMethod("Bar", BindingFlags.Public | BindingFlags.Instance);
// invoke ( instance, method parameters );
bool isBar = barMethod.Invoke(foo, new object[] { "Baz" });

MethodInfo bingMethod = fooType.GetMethod("Bing", BindingFlags.NonPublic | BindingFlags.Instance);
bingMethod.Invoke(foo, null);

PropertyInfo propertyA = fooType.GetProperty("A", BindingFlags.Public | BindingFlags.Instance);
propertyA.SetValue(foo, 33);
int aVal = propertyA.GetValue(foo, null); // second parameter is for if the property was in indexer
C#

All of which equates to the following lines of code:

Foo foo = new Foo();
bool isBar = foo.Bar("Baz");
foo.Bing();
foo.A = 33;
int aVal = foo.A;
C#

Standard CRC 16 in C#

I’ve been working on a service at work that will end up being this big cluster of servers that all talk with each other.  One of the things I needed was a small CRC checksum for some of the more compact UDP messages that get sent around.  I thought about just using the CRC16-CCITT library I already had, but decided on using the standard CRC16 algorithm.  Since I posted the CRC32 and CRC16-CCITT implementations I thought I’d post this one too.

using System;

public class Crc16 {
    const ushort polynomial = 0xA001;
    ushort[] table = new ushort[256];

    public ushort ComputeChecksum(byte[] bytes) {
        ushort crc = 0;
        for(int i = 0; i < bytes.Length; ++i) {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    public byte[] ComputeChecksumBytes(byte[] bytes) {
        ushort crc = ComputeChecksum(bytes);
        return BitConverter.GetBytes(crc);
    }

    public Crc16() {
        ushort value;
        ushort temp;
        for(ushort i = 0; i < table.Length; ++i) {
            value = 0;
            temp = i;
            for(byte j = 0; j < 8; ++j) {
                if(((value ^ temp) & 0x0001) != 0) {
                    value = (ushort)((value >> 1) ^ polynomial);
                }else {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}
C#

If you need for this code to be CLS compliant, you can change the method signature’s return type from ushort to int and it will operate the same (the ushort CRC value will be implicitly converted from ushort to int)

Links to the other C# CRC implementations CRC16-CCITT, CRC16-CCITT Kermit, CRC32, and CRC8

I’ve consolidated all of these into a single library on GitHub here: NullFX.CRC.

I’m also very into Swift at the moment and have created Swift versions of these same classes and released a Swift PM version of this library here as well Swift NullfxCrc Package