Happy 7th Birthday

Ubuntu is 7 today, so happy birthday to U.

Thanks to Canonical and the community for making my computing life more inspiring and more productive.

Posted in Software, Ubuntu | Comments Off

How to check object instances are of a specific class or inherited from a specific class

You can determine if an object is of a specific class by using the typeof keyword.

if (myObj.GetType() == typeof(MyClass))
{
    // Do something
}

If you want to check to see if an object is of a specific type, or can be cast to a specific type then use the is operator.

if (myObj is MyClass)
{
    // Do something
}
Posted in c#, Code | Comments Off

How to override constructors and pass extra parameters

If you want to descend from a class that requires parameters passed in its constructor, and you wish to introduce extra parameters in the descendants constructor then when you define the derived classes constructor, simply add : base() to the constructors signature to get c# to call the inherited constructor.

If you need to pass parameters through to the inherited call, use :base(param1, param2)

As soon as you add a descendant that overrides the parameter list for a classes constructor, any other descendant classes will have to have a constructor implementation, similar to the Derived class below, to let the compiler know which of the inherited constructors needs calling when the descendant class is created. Otherwise a “No overload for method ‘x’ takes ‘0′ arguments” error may occur

Posted in c#, Code | Comments Off

How to create a bit-based enumeration

If you want to create an enumeration that acts like a set, where the value of the enumeration can be a combination of any of the members of the enumeration then you C# allows you to do this using the FlagsAttribute.

Simply add the attribute to the start of the enumeration and the enumeration values will be treated as bit flags instead.

[FlagsAttribute]
enum Colors : short
{
	None = 0,
	Red = 1,
	Green = 2,
	Blue = 4,
	White = 7
};

You can use bitwise operators Not, And, Or and XOR on the enumeration.

e.g. to see if an enumeration value is set

if ( Colors & Red == Red)
{
	// do something
}

Note that the not (!) does not work on bitwise operations so the complement(~) operator is required.

So to remove a the red and green flag from the set…

Colors = Colors & ~(Red | Green);
Posted in c#, Code | Comments Off

Custom Exceptions and Serialization.

Microsoft state that if you want to raise custom exceptions in your application then you should derive them from the ApplicationException class and not the Exception class.

ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system.

However, the blog entry by Microsoft’s Brad Adams states that ApplicationException should not be used !

I found that descending from Exception, at least gives a nice error message detailing the exception that was raised as opposed to ApplicationExceptiosn, “Application Error ocurred” message.

So how do we serialize a custom exception class ?

Step 1) Add the Serializable attribute to the exception

Step 2) Provide a contructor that takes the serialization information and context e.g. MyException(SerializationInfo info, StreamingContext context)
Step 3) If you have a constructor that passes state information to the exception to be included in the data collection ensure this is copied from the exception object to the info in the serialization constructor (step2)

e.g.

[Serializable]
public class MyException : Exception
{
	public MyException(String sessionId)
		: base()
	{
		this.Data.Add("SessionID", sessionId);
	}
 
	public MyException(SerializationInfo info, StreamingContext context)
		: base(info, context)
	{
		info.AddValue("SessionID",Data["SessionID"]);
	}
 
	public override void GetObjectData(SerializationInfo info, StreamingContext context)
	{
		base.GetObjectData(info, context);
	}
}
Posted in c#, Code | Comments Off

Nullable Types

In C# and .net you can define a variable of the standard values types to be nullable as well. This is extremely useful in circumstances when you want to check if a varaible has been intialized correctly.

For example, if you have a class that represents a user which has an integer user id and it is not initialized in the constructor. Rather than having the user id intitialize to 0 (zero) (which would be the default for an integer) as the User id 0 may well be a valid user’s id. the type can be defined as a nullable integer using int? UserID and will default to null instead.

Examples of nullable declarations

int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];
Posted in c#, Code | Comments Off

Hex String to byte array converter

The following simple static class will take a string of Hexdecimal characters and convert it to a byte array.

static class HexStringConverter
    {
        public static byte[] ToByteArray(String HexString)
        {
            int NumberChars = HexString.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
            }
            return bytes;
        }
    }

or an alternative supplied by Peter Speybrouck:

public static byte[] ToByteArray(String HexString)
{
    for (int i = 0; i < NumberChars; i += 2)
    {
        try
        {
            bytes[i / 2] = Convert.ToByte(Hex.Substring(i, 2), 16);
        }
        catch
        {
            //failed to convert these 2 chars, they may contain illegal charracters
            bytes[i / 2] = 0;
        }
    }
    return bytes;
}

* fixes uneven number of hex characters by adding a zero in front of the string
* handles illegal characters gracefully

or

ASKORO: December 24, 2009 at 10:59 am

How about this:

    if (sVal.Length % 2 != 0) throw new ArgumentException(“Hex string is of odd length”);
    Regex re = new Regex(@”[^0-9A-Fa-f]);
    if (re.IsMatch(sVal)) throw new ArgumentException(“Hex string contains invalid characters”);
    return Encoding.ASCII.GetBytes(sVal);
Posted in c#, Code | Comments Off

How to create an Expandable Object Converter that will drop down a list of Class Types

This article provides an example of a TypeConverter which, when displayed in a Property Grid, will allow the user to select an class type from the drop down list. When an item is selected, it creates and instance of that class type. This can be used, for example, if you had a property of type Shape, and wanted to allow the user to choose a shape to assign to that property, e.g. Circle, Rectangle, etc. The property has a type of the base class Shape, but ends up with the appropriate instance of a descendant class. In the following example, I have a abstract base class of GridStyleBorder which is a property on an object.

[Category("Appearance")]
[Browsable(true)] 
[TypeConverter(typeof(GridBorderTypeConverter))] 
[RefreshProperties(RefreshProperties.All)] 
[Description("Change the Border Style")] 
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 
public GridStyleBorder Border { get {  return _border; } set { _border = value; } }

Notice the TypeConvert is set to GridBorderTypeConverter this is a new TypeConvert descended from ExpandableObjectConverter. The code is below:

 using System;
 using System.Collections.Generic;
 using System.Text;
 using System.ComponentModel;
 using System.Collections;
 using System.Drawing;
 using System.Drawing.Drawing2D;
 using System.Reflection;
 
 namespace SomeAssemby {
     /// Provides the type converter that displays a list of types. 
     /// When the user selects an item from the list, an instance of that type is created.
     /// Note : requires customization to work with other property types. (see comments)
     /// 
 
    class GridBrushTypeConverter : ExpandableObjectConverter
    {
        // set the next array to be an array of types you wish to display in the drop down
 
        private static readonly Type[] TypesToDisplay = new Type[] 
            { 
                typeof(SolidBrush), 
                typeof(LinearGradientBrush) 
            };
 
 
        // Change the modify region to If Else tests for each type you support and return appropriate instances of the types.
 
        public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value.GetType() == typeof(string))
            {
                string fullClassName = (string)value;
 
                #region —- need to modify this section ———————
                // check the full classname and return a new instance of that class for each of the types you support
 
                if (fullClassName == typeof(LinearGradientBrush).FullName)
                    return new LinearGradientBrush(new Point(0,0), new Point(0,100),SystemColors.Control, SystemColors.ControlDark);
                else
                    return new SolidBrush(SystemColors.Control);
                #endregion
            }
            else
                return base.ConvertFrom(context, culture, value);
        }
 
        #region —- No need to change this code —————————————
        private ArrayList TypesToDisplayArray = new ArrayList(TypesToDisplay);
 
        public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
        {
            return true;
        }
 
        public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(TypesToDisplayArray);
        }
 
        public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType)
        {
            if (sourceType == typeof(string))
                return true;
            else
                return base.CanConvertFrom(context, sourceType);
        }
        #endregion
 
    }
}
Posted in c#, Code | Comments Off

How to use an inline delegate with the Find method on collections

C# provides a very powerful and concise method of locating items in collections. The find Method on collections and generic lists (and other collection type classes) take a predicate as the parameter. To the beginner programmer the power of this parameter is not obvious.

Lets take a simple collection of objects, MyClass defined as follows:

    class MyClass
    {
        public int Id;
        public String Name;
    }

and an associated collection, in this cas a simple generic list.

    class MyClassCollection : List<MyClass>
    {
        ...
    }

Implementing a couple of methods to Find by Id or name is really simple with the Find method. We create an inline delegate that returns a boolean true of false if a match occurs. e.g.

    public MyClass FindByID(int id)
    {
        return this.Find(
            delegate(MyClass itemInCollection)
            {
                return (itemInCollection.Id == id);
            }
        );
    }

The FindByID method returns an instance of MYClass that the Find method locates.

The FindMethod takes and inline delegate that expects the current instance that the find method is looking at to be passed in (itemInCollection).

As the delegate is inline, it can reference the id parameter passed into the FindByID method and this can be used in the comparison.

An alternative to method of implementation is to pass as the predicate, a equality method that is defiend on the collection class, but this would mean that the value you are trying to find would have to be set as public field on the collecttion class, and therefore mutliple threads could not search the collection at the same time.

Below is an example of the class with a FindByName delegate as well.

    class MyClassCollection : List<MyClass>
    {
        public MyClass FindByID(int id)
        {
            return this.Find(
                delegate(MyClass itemInCollection)
                {
                    return (itemInCollection.Id == id);
                }
            );
        }
 
        public MyClass FindByID(string name)
        {
            return this.Find(
                delegate(MyClass itemInCollection)
                {
                    return (itemInCollection.Name == name);
                }
            );
        }
    }
Posted in c#, Code | Comments Off

Create a string of Repeating Characters

Creating a string of repeating characters is really simple in c#, however it is not in the obvious place you would look. First I tried the String class, hoping there would be a static like String.RepeatString, and even looked in the StringBuilder class. Eventually found it in a very logical place when you think about it, the String classes constructor.
String (Char, Int32)
So to create a repeating string simply use

String myString = newString('x', 12);

which will create a string of x’s 12 characters long.

Posted in c#, Code | Comments Off