How to get the running exe File Version

C#, C# Language, Win Forms 1 Comment »

 

Nice and simple, get the running assembly, get the AssemblyName details object, get the version property.

 

            Assembly asm =  Assembly.GetExecutingAssembly();
            AssemblyName AssDetails = asm.GetName();
            String versionAsString = AssDetails.Version.ToString();

Performance Iterating Generic Lists

C#, C# Language 5 Comments »

There are 3 obvious ways of iterating through each item in a generic list, but which is the most efficient.

  1. using a for statement
  2. using a foreach statement
  3. using the List.ForEach method with a delegate

 

I created the following simple application to test the differences:

    public partial class Form1 : Form

    {
        List<ListItem> items = new List<ListItem>();
        ProfileTimer timer = new ProfileTimer();
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void buttonAllocate_Click(object sender, EventArgs e)
        {
            int itemCount = (int)numericUpDown1.Value;
            textBox1.Clear();
            textBox1.AppendText("Allocating " + itemCount.ToString() + " items.\n");
            items.Capacity = itemCount;
            timer.Start();
            for (int i = 0; i < itemCount; i++)
            {
                items.Add(new ListItem());
            }
            timer.End();
            textBox1.AppendText("Took:" + timer.TimeTaken().ToString() + "\n");
        }
 
        private void buttonForLoop_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("----------------------------------------------\n");
            textBox1.AppendText("Iterating with for loop\n");
            timer.Start();
            int itemCount = items.Count;
            for (int i = 0; i < itemCount; i++)
            {
                items[i].Value++;
            }
            timer.End();
            textBox1.AppendText("Took:" + timer.TimeTaken().ToString() + "\n");
        }
 
        private void ButtonForEachStatement_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("----------------------------------------------\n");
            textBox1.AppendText("Iterating with foreach\n");
            timer.Start();
            foreach(ListItem item in items)
            {
                item.Value++;
            }
            timer.End();
            textBox1.AppendText("Took:" + timer.TimeTaken().ToString() + "\n");
        }
 
        private void buttonForEachDelegate_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("----------------------------------------------\n");
            textBox1.AppendText("Iterating with foreach delegate\n");
            timer.Start();
            items.ForEach(delegate(ListItem item)
                {
                    item.Value++;
                }
            );
            timer.End();
            textBox1.AppendText("Took:" + timer.TimeTaken().ToString() + "\n");
        }
    }

 

Where the list item is defined as

    class ListItem
    {
        public int Value;
    }

 

The following results were obtained in Seconds 




No of items in the list For Statement ForEach Statement ForEach Delegate
100,000 0.000909729 0.00154351 0.001170701
1,000,000 0.009031616 0.015998993 0.011646201
10,000,000 0.093305468 0.160015975 0.114651431

Tests run on an Intel Pentium Dual Core 3.2GHz  with 3Gb Ram.

As we can see the choice of iterator makes very little difference when there are a small amount of items in the list, but as we move upto iterating lists containing hundreds of thousands of items, there are some performance improvements between the methods.

The For statement out performs the rest, 71% faster than the ForEach Statement, but it should be noted that the itemcount check in the for loop needs to be stored and not checked on each iteration. i.e. don’t use for(int i=0; i<items.count;i++) If the items.count is called on every iteration the perfromace is the same as the ForEach Delegate.

The ForEach delegate comes in second, 39% faster than the ForEach Statement.

Conclusion

For most applications there is not much performance impact in the iteration times, but if time is critical or you have nested iterations then you should be using a basic for loop (BUT rememeber to store the limit in an integer and use in the comparison and DONT allocate a new ListItem variable in the iterator). 

Personally, having come from a delphi background and tending to use the iterator pattern, I’ll be using the ForEach delegate. I think it reads nicer and gets a reasonable performance.

Create a string of Repeating Characters

C#, C# Language No Comments »

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 = new String('x', 12);

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

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

C#, C# Language 3 Comments »

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

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

C# Language, Component Development 2 Comments »

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 {
    /// <summary>

    /// 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)

    /// </summary>

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

Hex String to byte array converter

C#, C# Language 6 Comments »

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

Nullable Types

C#, C# Language No Comments »

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

[csharp]

int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = ‘a’;
int?[] arr = new int?[10];

[/csharp]

Custom Exceptions and Serialization.

C#, C# Language, Win Forms No Comments »

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.

[csharp]

[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);
}
}
[/csharp]

How to create a bit-based enumeration

C#, C# Language No Comments »

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.

[csharp]

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

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

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

[csharp]

if ( Colors & Red == Red)

{

// do something
}

[/csharp]

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…

[csharp]

Colors = Colors & ~(Red | Green);
[/csharp]

How to override constructors and pass extra parameters

C#, C# Language No Comments »

If you want to descend from a class that requires parameters passed in its constructor, and you wish to introduce extra parameters in the descedants constructor then when you define the derived classes constructor, simply add : base() to the constructors signiture 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

WP Theme &Design by minus19.com & Icons
Entries RSS Comments RSS Log in