§ July 28, 2012

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;
        }
    }
}
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
Article Sections :: C # Articles

  § February 4, 2010

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;
        }
    }
}

This one differs slightly (API wise) from my previous ones, mainly because I was using it for checksum'ing 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" );
}

If you have any questions / comments / corrections, post them in the forums.

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
Article Sections :: C # Articles

  § December 18, 2008

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);
}
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?

    Read the rest of this article... (558 words)
Article Sections :: C # Articles

  § January 31, 2008

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 ...
        }
    }
}

    Read the rest of this article... (2439 words)
Article Sections :: C # Articles

  § June 6, 2007

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:

static class Program {
    static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
    [STAThread]
    ...
}
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 aquire a lock on it. Using this, we wrap our Application.Run code inside something like this:

    Read the rest of this article... (872 words)
Article Sections :: C # Articles

  § April 4, 2007

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
}
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:

    Read the rest of this article... (2536 words)
Article Sections :: C # Articles

  § February 13, 2007

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
Article Sections :: C # Articles

  § January 26, 2007

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
» Code Project Article

Screen Shot in Visual Studio

Article Sections :: C # Articles :: Tech. Articles

  § January 6, 2007

.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 {}
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;
}
Typically we'd never have a class that looked like this. After all, the complier 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 thats 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() { }
}
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:

    Read the rest of this article... (1364 words)
Article Sections :: C # Articles

  § December 15, 2006

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;
        }
    }
}
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
Article Sections :: C # Articles

  § November 8, 2006

CRC 16 CCITT in C#

Once again I found myself needing another type of CRC algorithm in C#. I found one on code project, but their implementation of CRC 16 CCITT didn't produce that checksum I needed. Come to find out there are different methods to calculate CRC 16 CCITT which use different initial values for the crc.

I ended up writing this one for my own purposes:

using System;

public enum InitialCrcValue { Zeros, NonZero1 = 0xffff, NonZero2 = 0x1D0F }

public class Crc16Ccitt {
    const ushort poly = 4129;
    ushort[] table = new ushort[256];
    ushort initialValue = 0;

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

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

    public Crc16Ccitt(InitialCrcValue initialValue) {
        this.initialValue = (ushort)initialValue;
        ushort temp, a;
        for(int i = 0; i < table.Length; ++i) {
            temp = 0;
            a = (ushort)(i << 8);
            for(int j = 0; j < 8; ++j) {
                if(((temp ^ a) & 0x8000) != 0) {
                    temp = (ushort)((temp << 1) ^ poly);
                } else {
                    temp <<= 1;
                }
                a <<= 1;
            }
            table[i] = temp;
        }
    }
}


This was used for testing during the time we were looking at the Battlefield 2142 auth token, and were trying to figure out what the last 2 bytes of that token were made of.  Battlefield 2142's auth token uses the CRC 16 CCITT with the initial value of 0 (new Crc16Ccitt(InitialCrcValue.Zeros) in the above class. 

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 CRC32, CRC16, CRC16-CCITT Kermit, 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
Article Sections :: C # Articles

  § October 4, 2006

A Generic Singleton Pattern in C#

I don't know why its never occured to me to implement the singleton pattern as a generic type before. I've always just created the singleton pattern as part of my class (not that we're talking about a lot of coding here), but it occured to me that a singleton could be a lot easier to implement and spot if I used a generic type.

Here is my generic Singleton class:
public class Singleton<T> where T : class {
    static object SyncRoot = new object( );
    static T instance;
    public static T Instance {
        get {
            if ( instance == null ) {
                lock ( SyncRoot ) {
                    if ( instance == null ) {
                        ConstructorInfo ci = typeof( T ).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null );
                        if ( ci == null ) { throw new InvalidOperationException( "class must contain a private constructor" ); }
                        instance = (T)ci.Invoke( null );
                    }
                }
            }
            return instance;
        }
    }
}


Now, instead of implementing this same thing in every single class you want to act as a singleton, you simply use the generic definition: Foo.Instance.Whatever turns into Singleton<Foo>.Instance.Whatever.

Update: I've updated this implementation from using a mutex to using a simple lock (double checked) object. A mutex is pointless for a singleton (which I may go into in another article at some later time) as you can never have 2 separate execution contexts accessing one singleton anyway (which is where you would need a mutex over a simple lock object), and I changed the where T : new() to where T : class and changed the instantiation to use reflection to call the private default constructor instead, which I think is the correct implementation.
Article Sections :: C # Articles

  § September 28, 2006

Triple DES between PHP and C#

The past while at work I've been working through some annoyingly overcomplicated encryption issues. The problem is not that Triple DES is all that complicated or annoying, it's just that when you have 2 different technologies (one doing the encrypting and one doing the decrypting) at work; it can be frustrating to get anything accomplished.

Our issues stemmed around the fact that we were using .NET 1.1 and they were using Java (with the standard crypto providers). There are a few subtleties between Microsoft's crypto providers and Java's. .NET provides 3 (ok, really only 2) Padding modes, and Java provides like 5, but they don't provide any in common. One easy padding mode is to append 0x00 bytes to the end of the final block to make it an even 64 bits wide. The Java provider didn't have this, but its easy enough to add ( by appending null char's '\0' to the end of the string then calling getBytes() ). So that's the route we took. After overcoming a few problems with "How do we encode our bytes used for the key and IV and still be compatible" we were off and running.

That made me wonder how compatible PHP and .NET's 3DES were. Since I didn't see any "Padding Mode" for PHP's, I simply hand coded the padding the same way we did with the Java code.

Here's my php script:    Read the rest of this article... (676 words)
Article Sections :: C # Articles :: PHP Articles

  § August 8, 2006

A Command Line style string parser (in C#)

Last week I was writing a service that could be run as a console app. I needed to be able to parse a single string into an array like the shell does for command line apps, and the service does for start parameters. I did a little googling, but found only command line arg classes that put command line args into associative array's for easy indexing, which isn't what I was looking for.

The class had basically 2 requirements:
  1. It had to be able to split the string on spaces (simple right?)
  2. It had to escape spaces that were quoted (as well as quotes that were escaped).
First I tried to iterate through the string a character at a time, looking for spaces keeping the state of whether we were inside a quote or not, whether the current character was an escaped quote, and so on.

That was a major pain, so I stepped back and rethought my algorithm. this is what I ended up with, which was much simplier, and did exactly what I wanted without a lot of fuss.

So here's my command line parser:
public class CommandLineParser {
    CommandLineParser() { }
    public static string[] Parse(string str) {        
        if(str == null || !(str.Length > 0)) return new string[0];
        int idx = str.Trim().IndexOf(" "); 
        if(idx == -1) return new string[] { str };
        int count = str.Length;
        ArrayList list = new ArrayList(); 
        while(count > 0) {
            if(str[0] == '"') {
                int temp = str.IndexOf("\"", 1, str.Length - 1);
                while(str[temp - 1] == '\\') {
                    temp = str.IndexOf("\"", temp + 1, str.Length - temp - 1);
                }
                idx = temp+1;
            }
            if(str[0] == '\'') {   
                int temp = str.IndexOf("\'", 1, str.Length - 1);
                while(str[temp - 1] == '\\') {
                    temp = str.IndexOf("\'", temp + 1, str.Length - temp - 1);
                }
                idx = temp+1;
            }
            string s = str.Substring(0, idx);
            int left = count - idx;
            str = str.Substring(idx, left).Trim();
            list.Add(s.Trim('"'));
            count = str.Length;
            idx = str.IndexOf(" ");
            if(idx == -1) {
                string add = str.Trim('"', ' ');
                if(add.Length > 0) {
                    list.Add(add);
                }
                break;
            }
        }
        return (string[])list.ToArray(typeof(string));
    }
}

Article Sections :: C # Articles

  § July 31, 2006

An IPAddress Control (the Win32 SysIPAddress32 control in C#)

The Common Controls library from the Platform SDK provides a control that Microsoft failed to provide a .NET counterpart to: the IPAddress Control (known as SysIPAddress32).

The TCP/IP Properties dialog


Quite a while ago I wrote a C# / .NET control that wrapped the functionality of the SysIPAddress32 control from comctl32.dll

My IPAddress Control Implementation

I had a much better implementation back then (with quite a few nice things included), but the hard drive that it lived on has since died, and I just haven't wanted to spend the time putting all that stuff back into the control.

Some time after having written the "nice" version of this control, I posted the following code to another website. Now, it's all I have left of the original. There is a known problem with the handle to the font being disposed incorrectly, but the code that fixed that, was given to me by jfo from Microsoft, and I did a cut/paste of the solution without really paying much attention to it (kind of regretting that now...). You may notice that all "system" fonts will always be displayed in BOLD in the forms designer (even when the font is set to something else). THIS GOES AWAY AT RUNTIME, so don't worry! It's only a problem in the designer.

Anyway, here it is, my IPAddress Control:

/******************************************************/
/*          NULLFX FREE SOFTWARE LICENSE              */
/******************************************************/
/*  IPAddressControl                                  */
/*  by: Steve Whitley                                 */
/*  © 2004 NullFX Software                            */
/*                                                    */
/* NULLFX SOFTWARE DISCLAIMS ALL WARRANTIES,          */
/* RESPONSIBILITIES, AND LIABILITIES ASSOCIATED WITH  */
/* USE OF THIS CODE IN ANY WAY, SHAPE, OR FORM        */
/* REGARDLESS HOW IMPLICIT, EXPLICIT, OR OBSCURE IT   */
/* IS. IF THERE IS ANYTHING QUESTIONABLE WITH REGARDS */
/* TO THIS SOFTWARE BREAKING AND YOU GAIN A LOSS OF   */
/* ANY NATURE, WE ARE NOT THE RESPONSIBLE PARTY. USE  */
/* OF THIS SOFTWARE CREATES ACCEPTANCE OF THESE TERMS */
/*                                                    */
/* USE OF THIS CODE MUST RETAIN ALL COPYRIGHT NOTICES */
/* AND LICENSES (MEANING THIS TEXT).                  */
/*                                                    */
/******************************************************/


namespace NullFX.Controls {
    using System;
    using System.Net;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Drawing;
    [StructLayout(LayoutKind.Sequential)]
    public struct Nmhdr {
        public IntPtr HWndFrom;
        public UIntPtr IdFrom;
        public int Code;
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct NmIPAddress {
        public Nmhdr Hdr;
        public int Field;
        public int Value;
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct InitCommonControlsEX {
        public int Size;
        public int Icc;
    }
    public enum IPField { OctetOne = 0, OctetTwo = 1, OctetThree = 2, OctetFour = 3 }
    public delegate void FieldChangedHandler(object sender, FieldChangedEventArgs e);
    public class FieldChangedEventArgs : EventArgs {
        private int _field, _value;
        public int Field {
            get { return _field; }
        }
        public int Value {
            get { return _value; }
        }
        public FieldChangedEventArgs(int field, int value)
            : base() {
            _field = field;
            _value = value;
        }
    }
    public class IPAddressControl : TextBox {
        private const int WM_NOTIFY = 0x004E,
            WM_USER = 0x0400,
            WM_REFLECT = WM_USER + 0x1C00,
            IPN_FIRST = -860,
            IPM_SETRANGE = (WM_USER + 103),
            IPM_GETADDRESS = (WM_USER + 102),
            IPM_SETADDRESS = (WM_USER + 101),
            IPM_CLEARADDRESS = (WM_USER + 100),
            IPM_ISBLANK = (WM_USER + 105),
            ICC_INTERNET_CLASSES = 0x00000800,
            CS_VREDRAW = 0x0001,
            CS_HREDRAW = 0x0002,
            CS_DBLCLKS = 0x0008,
            CS_GLOBALCLASS = 0x4000,
            WS_CHILD = 0x40000000,
            WS_VISIBLE = 0x10000000,
            WS_TABSTOP = 0x00010000,
            WS_EX_RIGHT = 0x00001000,
            WS_EX_LEFT = 0x00000000,
            WS_EX_RTLREADING = 0x00002000,
            WS_EX_LTRREADING = 0x00000000,
            WS_EX_LEFTSCROLLBAR = 0x00004000,
            WS_EX_RIGHTSCROLLBAR = 0x00000000,
            WS_EX_NOPARENTNOTIFY = 0x00000004,
            WS_EX_CLIENTEDGE = 0x00000200;
        private int[] values = new int[4];
        bool initialized = false;		
        public event FieldChangedHandler FieldChanged;
        public IPAddressControl()
            : base() {
            for(int i = 0; i < 4; i++)
                values[i] = 0;
        }
        [DllImport("comctl32")]
        static extern bool InitCommonControlsEx(ref InitCommonControlsEX lpInitCtrls);

        protected virtual void OnFieldChanged(FieldChangedEventArgs e) {
            if(FieldChanged != null) FieldChanged(this, e);
        }
        protected override CreateParams CreateParams {
            get {
                if(!initialized) {
                    InitCommonControlsEX ic = new InitCommonControlsEX();
                    ic.Size = Marshal.SizeOf(typeof(InitCommonControlsEX));
                    ic.Icc = ICC_INTERNET_CLASSES;
                    initialized = InitCommonControlsEx(ref ic);
                }
                if(initialized) {
                    CreateParams cp = base.CreateParams;
                    cp.ClassName = "SysIPAddress32";
                    cp.Height = 23;
                    cp.ClassStyle = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_GLOBALCLASS;
                    cp.Style = WS_CHILD | WS_VISIBLE | WS_TABSTOP | 0x80;
                    cp.ExStyle = WS_EX_NOPARENTNOTIFY | WS_EX_CLIENTEDGE;
                    if(RightToLeft == RightToLeft.No 
                                                    || (RightToLeft == RightToLeft.Inherit 
                                                    && Parent.RightToLeft == RightToLeft.No)) {
                        cp.ExStyle |= WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR;
                    } else {
                        cp.ExStyle |= WS_EX_RIGHT | WS_EX_RTLREADING | WS_EX_LEFTSCROLLBAR;
                    }
                    return cp;
                } else {
                    return base.CreateParams;
                }
            }
        }
        public bool SetIPRange(IPField field, byte lowValue, byte highValue) {
            if(!initialized) return false;		
            Message m = Message.Create(Handle, IPM_SETRANGE, (IntPtr)((int)field), MakeRange(lowValue, highValue));
            WndProc(ref m);
            return m.Result.ToInt32() > 0;
        }
        public System.Net.IPAddress IPAddress {
            get {
                if(!initialized) return IPAddress.None;			
                return IPAddress.Parse(base.Text);
            }
        }
        public bool IsBlank {
            get {
                if(!initialized) return !(base.Text.Length > 0);
                Message m = Message.Create(Handle, IPM_ISBLANK, IntPtr.Zero, IntPtr.Zero);
                WndProc(ref m);
                return m.Result.ToInt32() > 0;
            }
        }
        new public void Clear() {
            if(!initialized) {
                base.Clear();
                return;
            }		
            Message m = Message.Create(Handle, IPM_CLEARADDRESS, IntPtr.Zero, IntPtr.Zero);
            WndProc(ref m);
        }
        private System.Net.IPAddress GetIpAddress(IntPtr ip) {
            if(!initialized) return IPAddress.None;		
            return new IPAddress(ip.ToInt64());
        }
        private IntPtr MakeRange(byte low, byte high) {
            return (IntPtr)((int)((high << 8) + low));
        }
        protected override void WndProc(ref Message m) {
            if(m.Msg == (WM_REFLECT + WM_NOTIFY)) {
                NmIPAddress ipInfo = (NmIPAddress)Marshal.PtrToStructure(m.LParam, typeof(NmIPAddress));
                if(ipInfo.Hdr.Code == IPN_FIRST) {
                    if(values[ipInfo.Field] != ipInfo.Value) {
                        values[ipInfo.Field] = ipInfo.Value;
                        OnFieldChanged(new FieldChangedEventArgs(ipInfo.Field, ipInfo.Value));
                    }
                }
            }
            base.WndProc(ref m);
        }
    }
}


It does have one wrapped event from the original control and that is FieldChanged, which provides feedback when each octet is changed (similar to TextChanged for a text box, but only fires after the user has entered the entire text for that octet). Likewise, if the value of that octet is larger than a byte, it is automatically changed back to 255 (or the max value of a byte). When the event fires, it passes back, the Octet that was changed, and its value.

You can specify the IP Range (which the original control allows, and I've wrapped into this control as well) so that you can edit the control to only accept a specified IP Address Range.

I've also provided Native Clear functionality as well as the IsBlank from the original control. I added a System.Net.IPAddress property so that when accessing the IPAddress of the control, you didn't need to parse the System.Net.IPAddress every time. My original control completely removed the "Text" property so that you got and set the IPAddress through this property, but alas, that functionality doesn't exist in this control.

UPDATE: 8/25/2006 - Made 2 changes to the source code. 1. added some Initialization logic to keep InitCommonCtrls from being called multiple times and, 2. added styles for ClassStyle, StyleEX and Style to keep an exception from being thrown in certain cases when a WM_GETTEXTLENGTH message was sent.

For questions, comments, bugs, or anything else in this control, feel free to use the Windows Controls section of the forum here.
Article Sections :: C # Articles

  § July 29, 2006

The C# 3.0 language specification

I know I'm a bit late here, but better late than never.

I've been reading over some of the changes to C# for version 3. I had heard that v3 would be v2 with the addition of the new WPF, but looking over the new spec (well, fairly new anyway), there is quite a bit more.

Implicit types, method extensions, lambda expressions, object / collection initializers, and LINQ... C# is going to look really weird! So much for simplicity.

Implicit types (csharp meets vb or php) allow you to define the variable without a (or with an implied) type:
var foo = "hello";
var bar = 32;


so foo is implied to be of type string, and bar is implied to be of some numeric type.

Method extensions look very strange. Think of old dog learns new tricks meets operator overloading. Method extensions allow you to create "extension" methods for existing types:
public class Bar {
    string what = "hello";
    public string What { get { return what; } set { what = value; } }
    public Bar() {}
    public void Hello() { 
        Console.WriteLine(what); 
    }
}

public static class Foo {
    public static void SayHelloToSteve(this Bar bar) {
        bar.What += " steve";
        bar.Hello();
    }
    public static void SayHelloToSomeone(this Bar bar, string who) {
        bar.What = who;
        bar.Hello();
    } 
}

public class Program {
    static void Main(string[] args) {
        Bar b = new Bar();
        b.Hello();
        b.SayHelloToSteve();
        b.SayHelloToSomeone("Hello Bob!");
    }
}


Notice that SayHelloToSteve() and SayHelloToSomeone(string s) are not member methods of the Bar class, but are invoked as if they were (by virtue of the Method extension defined in Foo that are available to Bar). This seems like a feature that will be abused to defeat inheritance (by adding reflection to the method extenstions to manipulate internal class memebers without inheriting and changing functionality of the object) that would otherwise look odd and ugly.

OUTPUT:
hello
hello steve
Hello Bob!


At this point lambda expressions dont make much sense to me, but it seems its a way to define more than one method body in an anonymous method.

Object / collection initialization makes initialization a lot easier. I don't know if you've ever wanted to declare a new object inline inside a method, only to realize that you needed to set a few properties before it was used, well this is the answer to that:

myObject.Blah(new SomeObject() { PropertyA = 1, PropertyB = "dude", PropertyC = false });


Then there's LINQ: which feels something like SQL for C#.

feel free to download the spec here


fin
Article Sections :: C # Articles :: Tech. Articles

  § July 3, 2006

PHP Webservices and C# / .NET SOAP Clients

Code Zulu Bind Maker is a project I started working on about 3 years ago. Its a stupid little app that configures game settings for Counter-Strike. When I wrote it, version 1.6 was in beta, and everybody played version 1.5 (which was ever so different). Anyway I run a website that supports the app, and of course, its written in PHP / MySql (my poison of choice on the web).

The reason for the boring and seemingly pointless background is that ever since I wrote the app, I always wanted to integrate the website and application, but never really thought of a "good" way to do it. A couple days ago, I had some spare time and sat down to see how easy it would be to create some PHP webservices that I could easily consume in C#. I had been considering expanding the community aspect of the bind maker website into the application so that they'd work seamlessly together. I also wanted to add a common place that gaming communities could spend their time (which I had previously planned for just the website, but was thinking of the possibilities of bringing that into the app as well), and a PHP webservice combined with a C# windows app seemed like the best option.

C# webservices (server side) are about as easy-as-it-gets to write. C#'s SOAP client is completely transparent (or I should say completely generated so you code just like you would use any other objects) and is completely brainless to use. Since I'd never done webservice work in PHP, I started asking Mr. Google how it worked, and what would you now but that I stumbled across the NuSOAP library for php. It sure beat the heck out of writing all my WSDL files by hand, wrapping and unwrapping stupidly simple SOAP messages, and hacking everything very poorly.

My first PHP webservice iteration was a simple "hello <name> " web method. It used a simple type (xsd:string) as its parameter and returned a simple type (again another xsd:string) as its return value and looked like this:
 /**
 * ProcessSimpleType method
 * @param string $who name of the person we'll say hello to
 * @return string $helloText the hello  string
 */
function ProcessSimpleType($who) {
	return "Hello $who";
}
NuSoap was great. It took care of all the nitty-gritty work that I had previously done myself. All it took was about 8 lines of code to set up the SOAP server and register the method and my types.
require_once("lib/nusoap/nusoap.php");
$namespace = "http://sanity-free.org/services";
// create a new soap server
$server = new soap_server();
// configure our WSDL
$server->configureWSDL("SimpleService");
// set our namespace
$server->wsdl->schemaTargetNamespace = $namespace;
// register our WebMethod
$server->register(
                // method name:
                'ProcessSimpleType', 		 
                // parameter list:
                array('name'=>'xsd:string'), 
                // return value(s):
                array('return'=>'xsd:string'),
                // namespace:
                $namespace,
                // soapaction: (use default)
                false,
                // style: rpc or document
                'rpc',
                // use: encoded or literal
                'encoded',
                // description: documentation for the method
                'A simple Hello World web method');
                
// Get our posted data if the service is being consumed
// otherwise leave this data blank.                
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) 
                ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';

// pass our posted data (or nothing) to the soap service                    
$server->service($POST_DATA);                
exit();
That was it. From visual studio I was then able to consume the webservice by adding a web reference

Add A Web Reference

This article was first written with visual studio 2005. Visual studio 2008 and 2010 no longer have the "Add Web Reference" menu item. Instead they have an option to add a service reference. Selecting this option ends up generating a WCF C# client proxy, but we'll want to use the asmx style web service client proxy, so we'll navigate to the add web reference dialog which is hidden deep inside Add Service Reference dialog.

Visual Studio 2008 and 2010 Only
Right click on the references folder, and select Add Service Reference

Add A Service Reference


Click on the advanced button

Advanced

Click Add A Web Reference

Finally click the Add Web Reference button

Add A Web Reference Dialog

Add A Web Reference

With the reference added, I put a button on my form, and added the following button click event handler:
    Read the rest of this article... (928 words)
Article Sections :: C # Articles :: PHP Articles

  § March 23, 2006

Dependency Scanner (for .NET 1.1)

download Download Project & Source Code


.NET Dependency Resolver for .NET 1.1

Here's a little tool I wrote a while ago. Right now its only for .NET 1.1, but I'm working on a port for 2.0 (which should look a lot nicer).

When I wrote this, I was dealing with assemblies that had very complex inner-dependencies. Some assemblies were private, others were shared, and I ended up having to have a ton of ildasm.exe's open to the assembly manafest to try to see which assembly had referenced which assembly and had to verify that the assembly version referenced was correct. On top of that I needed to verify that assemblies that were referenced--that had policy files--were being redirected to the correct versions.

Basically all this tool does, is load an assembly, display its version, and lists any referenced assemblies, their versions, and whether or not the reference version resolves to any other version. It doesn't look like much, but its saved me a lot of time and head ache. It also has a copy / paste feature that can copy selected listview data to the clipboard in a nice column formatted manner.

    Read the rest of this article... (952 words)
Article Sections :: C # Articles

  § September 6, 2005

Stupid .NET 1.1 Service Pack 1

Service pack 1 strikes again.

    using System;
    using System.Drawing;
    using System.IO;
    using System.Reflection;
    public class Resources {
        private Resources() {}
        public static Image LoadImageFromResource(string path) {
            Image i = null;
            using ( Stream s = 
                      Assembly.GetExecutingAssembly().GetManifestResourceStream(path) ) {
                if(s != null) i = Image.FromStream(s, true, true);
            }
            return i;
        }
    }
This is part of a general use utility that I frequently use. An odd bug that came out of this is that the overloaded method

Image.FromStream(Stream, Boolean, Boolean)

was added in Service Pack 1 for .net v1.1 BUT NEVER DOCUMENTED!!!. Well, ok, that's not entirely true, It is documented... in v2.0 documentation... So if you wrote this in 1.1sp1 and deploy it to a machine with out sp1 you'll get a method not found exception when trying to load the image from stream using the above overload--non sp1 only has FromStream(Stream, Boolean)

Nothing like being incompatible with the same version of the framework eh?
Article Sections :: C # Articles :: Tech. Articles

  § August 10, 2005

C# Binary Serialization Oddities

Ok, it's been a while since I wrote about anything, so sue me!

Today's topic is an interesting find (at least to me)... When you serialize an object that has events (or a delegate) that have been assigned a value (and that value is outside of the class containing the event or delegate), .NET's binary serializer will attempt to serialize the enitre object who's function is assigned to it (it's an interesting thing to think about why they attempt to persist the event association as well). Said more simply, it will attempt to save the class being serialized, as well as all other classes who contain function definitions for those events or delegates.

Take the following example:

namespace SerializationWoes {
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    class Class1 {
        Class1() {}

        [STAThread]
        static void Main(string[] args) {
            BinaryFormatter bf = new BinaryFormatter(); 
            byte[] bytes;
            BigDeal bd = new BigDeal();
            bd.Something = "blah blah blah";
            using ( MemoryStream ms = new MemoryStream() ) {
                bf.Serialize(ms, bd);
                ms.Seek(0,0);
                bytes = ms.ToArray();
            }
        }
    }

    // serialized object
    [Serializable]
    public class BigDeal {
        string something = "";
        public string Something {
            get { return this.something; }
            set { 
                this.something = value; 
            }
        }
        public BigDeal() {
        }
    }
}

BigDeal serializes perfectly into the memory stream and therefore to the byte array.

Now, let's throw in an event (and the event handler) with a non-serializable object who contains the definition of that event method handler:

namespace SerializationWoes {
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    class Class1 {
        [NonSerialized]
        static Class1 c = new Class1();
        Class1() {} 
        private void bd_MyEvent(object sender, EventArgs e) {
            Console.WriteLine("hey some event just happened");

        } 

        [STAThread]
        static void Main(string[] args) {
            BinaryFormatter bf = new BinaryFormatter(); 
            byte[] bytes;
            BigDeal bd = new BigDeal();
            bd.MyEvent += new EventHandler(c.bd_MyEvent);
            bd.Something = "blah blah blah";
            using ( MemoryStream ms = new MemoryStream() ) {
                bf.Serialize(ms, bd);
                ms.Seek(0,0);
                bytes = ms.ToArray();
            }
        }
    }

    // serialized object
    [Serializable]
    public class BigDeal {
        string something = "";
        public event EventHandler MyEvent;
        protected virtual void OnEvent(EventArgs e) {
            if(MyEvent != null) MyEvent(this, e);
        }
        public string Something {
            get { return this.something; }
            set { 
                this.something = value; 
                OnEvent(EventArgs.Empty);
            }
        }
        public BigDeal() {
        }
    }
}


Now, when we run the app, we get the following exception:

[ Image of the exception ]


An unhandled exception of type 'System.Runtime.Serialization.SerializationException'
occurred in mscorlib.dll

Additional information: The type SerializationWoes.Class1 in Assembly 
SerializationWoes, Version=1.0.0.39766, Culture=neutral, PublicKeyToken=null 
is not marked as serializable.

    Read the rest of this article... (1524 words)
Article Sections :: C # Articles
© 2003 - 2024 NullFX
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License