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.

Receive Key Messages irrespective of Key Modifiers

C#, Component Development, Win Forms No Comments »

As covered in a previous article, you can overrride the IsInputKey method on a control to inform winforms that you require keyboard event notification for special keys like tabe and cursor keys which are used but the hosting form for control navigation.

When writing a control, I was trying to capture the SHIFT - Right Cursor combination.  I already had the following implementation in IsInputKey

                        switch (keyData)

            {
                case Keys.Up:
                case Keys.Down:
                case Keys.Left:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                    {
                        return true;
                    }
            }
            return base.IsInputKey(keyData);
 

However, althought control-Right and Alt-Right events came through Shift-Right wouldn’t.  These were passed to the base implementation which returned true to be handled by the control but fals for the shift right.

So to force the processing of keys irrespective of the key modifiers simply chnage the case statement to read

            switch (keyData & ~Keys.Modifiers)

 Which removes and modifier bit flags from the keydata fro the switch comparison.

How to determine if a control or one of it’s child controls has focus

C#, Component Development, Win Forms 1 Comment »

Focus returns a boolean to indicate whether or not a control has focus or not, but when trying to paint your own focus rectangle in your control and you have allowed your controls scrollbars to accept focus, then the Focus property will return false. 

Instead of using Focus, check the ContainsFocus property that returns true if the control or a child control has focus.

Notifying the Collection Editor of changes

C#, Component Development, Win Forms No Comments »

When you are building your own collections of objects it is common to use an overridden ToString implementation to display some property of your object in the collection editor instead of the full class name which is the default.

For example, when developing a Column collection, I override the ToString() to return the Columns caption.  However, when the caption property of my column is updated in the standard collection editor, the respective item in the list of items in the collection editor is not updated. 

The collection editor can be notified to refresh it’s properties and therefore the list by adding a RefreshProperties attribute to the property that causes the required change.

e.g.

    public class TreeColumn
    {
        private String _Caption;
 
        [RefreshProperties(RefreshProperties.All)]
        [Browsable(true)]
        [Description("The Caption for the column")]
        public String Caption
        {
            get { return _Caption; }
            set { _Caption = value; }
        }
 
        public override string ToString()
        {
            if (!String.IsNullOrEmpty(_Caption))
                return _Caption;
            return base.ToString();
        }
    }

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

Gettting Visual Studion 2005 Help to work with a Proxy Server

C# No Comments »

For some reason Visual Studio Help does not correctly determine the proxy server setttings from Internet Explorer, or if it does it is very slow.

To get it working add the following to the dexplore.exe.config file located in “C:\Program Files\Common Files\Microsoft Shared\Help 8″

 

<system.net>

<defaultProxy enabled=”true” useDefaultCredentials=”true”>
<proxy bypassonlocal=”True” proxyaddress=”http://yourProxyServer:PortNo”/>
</defaultProxy>

</system.net>

Runtime Resizable Panel Control

C#, Component Development, Win Forms 1 Comment »

Below is a complete resizable panel the can be resized on the right and bottom. It uses the windows SysCommand message and some little know options to cause the window (control) to resize.

If you want to allow moving or resizing in other directions, then extend the mouse location check and call the appropriate syscommand values.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

 

namespace YourAssembly

{

    public partial class ResizablePanel : Panel

    {

        private Boolean _ResizeParent;

 

        private class NativeCalls

        {

            [DllImport("USER32.DLL", EntryPoint = "SendMessage")]

            public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref int lParam);

            [DllImport("user32")]

            public static extern int ReleaseCapture(IntPtr hwnd);

            public const int WM_SYSCOMMAND = 0×0112;

            public const int SC_DRAGMOVE = 0xF012;

            public const int SC_DRAGSIZE_N = 0xF003;

            public const int SC_DRAGSIZE_S = 0xF006;

            public const int SC_DRAGSIZE_E = 0xF002;

            public const int SC_DRAGSIZE_W = 0xF001;

            public const int SC_DRAGSIZE_NW = 0xF004;

            public const int SC_DRAGSIZE_NE = 0xF005;

            public const int SC_DRAGSIZE_SW = 0xF007;

            public const int SC_DRAGSIZE_SE = 0xF008;

        }

 

        public Boolean ResizeParent

        {

            get { return _ResizeParent; }

            set { _ResizeParent = value; }

        }

 

        public ResizablePanel()

        {

            InitializeComponent();

            MinimumSize = new Size(50, 50);

            Margin = new Padding(0, 0, 0, 0);

            Padding = new Padding(0, 0, 3, 3);

            BackColor = SystemColors.ControlLight;

        }

 

        private enum MousePos {NoWhere, Right, Bottom, BottomRight}

       

        private MousePos GetMousePos(Point location)

        {

            MousePos result = MousePos.NoWhere;

 

            Rectangle TestRect;

 

            int RightSize = Padding.Right;

            int BottomSize = Padding.Bottom;

 

            // Resize right border

            TestRect = new Rectangle(Width - RightSize, 0, Width - RightSize, Height - BottomSize);

            if (TestRect.Contains(location)) result = MousePos.Right;

 

            // Resize bottom border

            TestRect = new Rectangle(0, Height - BottomSize, Width - RightSize, Height);

            if (TestRect.Contains(location)) result = MousePos.Bottom;

 

            // Resize bottom Corner

            TestRect = new Rectangle(Width - RightSize, Height -BottomSize, Width, Height);

            if (TestRect.Contains(location)) result = MousePos.BottomRight;

            return result;

        }

 

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

 

            IntPtr hwnd = this.Handle;

 

            if ((ResizeParent) && (this.Parent != null) && (this.Parent.IsHandleCreated))

            {

                hwnd = Parent.Handle;

            }

 

            int nul = 0;

            MousePos mousePos = GetMousePos(e.Location);

            switch (mousePos)

            {

                case MousePos.Right:

                    {

                        NativeCalls.ReleaseCapture(hwnd);

                        NativeCalls.SendMessage(hwnd, NativeCalls.WM_SYSCOMMAND, NativeCalls.SC_DRAGSIZE_E, ref nul);

                    } break;

                case MousePos.Bottom:

                    {

                        NativeCalls.ReleaseCapture(hwnd);

                        NativeCalls.SendMessage(hwnd, NativeCalls.WM_SYSCOMMAND, NativeCalls.SC_DRAGSIZE_S, ref nul);

                    } break;

                case MousePos.BottomRight:

                    {

                        NativeCalls.ReleaseCapture(hwnd);

                        NativeCalls.SendMessage(hwnd, NativeCalls.WM_SYSCOMMAND, NativeCalls.SC_DRAGSIZE_SE, ref nul);

                    } break;

            }

 

        }

 

        protected override void OnMouseMove(MouseEventArgs e)

        {

            base.OnMouseMove(e);

 

            MousePos mousePos = GetMousePos(e.Location);

            switch (mousePos)

            {

                case MousePos.Right: Cursor = Cursors.SizeWE; break;

                case MousePos.Bottom: Cursor = Cursors.SizeNS; break;

                case MousePos.BottomRight: Cursor = Cursors.SizeNWSE; break;

                default: Cursor = Cursors.Default; break;

            }

        }

 

        protected override void OnResize(EventArgs eventargs)

        {

            base.OnResize(eventargs);

            if (this.Width < this.MinimumSize.Width) this.Width = this.MinimumSize.Width;

            if (this.Height < this.MinimumSize.Height) this.Height = this.MinimumSize.Height;

        }

 

        protected override void OnMouseLeave(EventArgs e)

        {

            base.OnMouseLeave(e);

            Cursor = Cursors.Default;

        }

    }

 

 

}

 

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

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