Confessions of a .NET Developer!

Tricky delegates

One day I stumbled upon a curious thing that I noticed while working with delegates.
Let me explain with an example:

using System;
using System.Collections.Generic;

namespace Weird
{
    class Program
    {
        //Delegate declared
        private delegate void ShowValue();

        static void Main(string[] args)
        {
            List<ShowValue> lst = new List<ShowValue>();

            for (int j = 0; j < 5; j++)
            {
                //Instantiating the delegates
                lst.Add(delegate { Console.WriteLine(j); });
            }

            //Invoking the delegates
            //for (int i = 0; i < 5; i++)
            //{
            //    lst[i]();
            //}           
            //In short, using ForEach extension
            lst.ForEach((ShowValue sv) => { sv(); });

            Console.ReadLine();
        }
    }
}

So I have declared a delegate, instantiating and adding them into a List and then invoking them later.
What do you think is the answer? Most of you might be thinking its 0 1 2 3 4. Not quite correct!

This is the result:

Result

Result


Suprising isn’t it!
Now how did that happen, I started investigating. I started to read John Skeet’s C# in Depth, from here I got the idea. The thing is, the delegate actually captures the variable i. Behind the scene, when we declare a delegate, a separate class is created by the compiler which derives from the MultiCastDelegate class. The delegate instance in the for-loop will create a reference to the variable i. So each time it’s instantiated, it actually refers to the same variable. After the loop gets over, i will be 5 and hence when invoked, 5 will be printed.

For the solution, well its quite simple. Here it goes, first the code:

class Program
    {
        private delegate void ShowValue();

        static void Main(string[] args)
        {
            List<ShowValue> lst = new List<ShowValue>();

            for (int j = 0; j < 5; j++)
            {
                int k = j;
                lst.Add(delegate { Console.WriteLine(k); });
            }

            //for (int i = 0; i < 5; i++)
            //{
            //    lst[i]();
            //}           
            //In short, using ForEach extension
            lst.ForEach((ShowValue sv) => { sv(); });

            Console.ReadLine();
        }
    }

The only change I made is to add a new variable k in the for loop. The trick is, as a new k variable is created for every loop, the delegate will always capture a new k and hence references a different variable. And the result will be: 0 1 2 3 4

FinalResult

FinalResult

Perfect! Hope you got the idea.
Happy Coding! 🙂

Advertisements

June 30, 2011 Posted by | C Sharp | 1 Comment

How to dynamically load assemblies including unreferenced assemblies

This post will explain how to load the dll dynamically and use the class’s methods in that dll. We will use the Activator class to create an instance of a class from the dll and invoke the required methods. So lets get started.

First of all, create a base class library and name it as AClassLibrary:

ClassLibrary

ClassLibrary

Add a new class named AClass, it will look like this:

    public class AClass
    {
        public void WriteDefault()
        {
            Console.WriteLine("A text");
        }

        public void WriteIt(string text)
        {
            Console.WriteLine(text);
        }

        public void WriteIt(string text1, string text2)
        {
            Console.WriteLine(text1 + text2);
        }
    }

Do note that we have two overloaded functions named WriteIt, I will let you know its significance later.

Now lets create another Console Application project in the same solution named CaptureAssembly.
After that, Add Reference to the project AClassLibrary:

AddReference

AddReference

Before explaining, let me show you the whole code:

using System;
using System.Reflection;

namespace CaptureAssembly
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly a = Assembly.LoadFrom("AClassLibrary.dll");

            Type clsType = a.GetType("AClassLibrary.AClass");
            
            //Create the instance of the class
            object clsInstance = Activator.CreateInstance(clsType, null);

            //Calls the WriteDefault method of AClass
            clsType.InvokeMember("WriteDefault", BindingFlags.InvokeMethod, null, clsInstance, null);

            //Calls the WriteIt methods
            clsType.InvokeMember("WriteIt", BindingFlags.InvokeMethod, null, clsInstance, new object[] { "Hello", " Tarun Kumar" });
            clsType.InvokeMember("WriteIt", BindingFlags.InvokeMethod, null, clsInstance, new object[] { "Hello" });

            Console.ReadLine();
        }
    }
}

First we get the type of AClass using the Reflection. The Activator class will use it to create the instance of the class which we name it as clsInstance.
Next step is to call the 3 methods of AClass. We will use the InvokeMember property using clsType. Let’s take the case of the fist InvokeMethod. The first parameter will take the name of the method, second will help us streamline the search for the method as Reflection is used for this purpose. Third parameter is of no use for now. Fourth parameter, the target is the class instance named clsIntance and the last parameter will take the array of objects used to pass the parameters for the method, as WriteDefault doesn’t have any parameters, hence it will remain null.
The next two invoke methods is for the two overloaded methods WriteIt, the first one will call the method which has two parameters as we are passing two items in the object array(last parameter). As the second invoke method has one item in the object array, hence WriteIt(string text) will be called.

And here is the result:

Result

Result

For loading Unreferenced Assemblies

You can also load the assembly without adding any reference. Suppose the base class library(dll) is in some location, then we can use Assembly.LoadFile method to load the assembly.

Just replace

Assembly a = Assembly.LoadFrom("AClassLibrary.dll");

with

Assembly a = Assembly.LoadFile(@"C:\AClassLibrary\bin\Debug\AClassLibrary.dll");

and you will get the same result.

Happy coding!

June 30, 2011 Posted by | C Sharp, Winforms, WPF | 1 Comment

Using Extension methods – Convert Image to Byte or Base64

Lot of people have questions like, how to convert an Image to byte array or to a Base64 string. I will solve these problems using the Extension methods feature.

With extension methods, you don’t have the need to use Inheritance to use the methods. An extension method is applied to a particular class or structure. An example can help understand more about it.
To start using Extension methods, firstly you need to create a static class which (obviously) will have static methods. In our example, two methods will be created, one which converts Image to byte array and another converts Image to Base 64 string.

    static class ExtensionClass
    {
        public static byte[] GetImageInBytes(this Image img, System.Drawing.Imaging.ImageFormat format)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                if (format != null)
                {
                    img.Save(ms, format);
                    return ms.ToArray();
                }
                else
                {
                    img.Save(ms, img.RawFormat);
                    return ms.ToArray();
                }
            }
        }

        public static string GetImageInBase64(this Image img, System.Drawing.Imaging.ImageFormat format)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                if (format != null)
                {
                    img.Save(ms, format);
                    return Convert.ToBase64String(ms.ToArray());
                }
                else
                {
                    img.Save(ms, img.RawFormat);
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
        }
    }

The first parameter has “this” keyword which tells the compiler that “please add this method as an extension method to the Image class to be used by it’s object”. The second parameter takes the ImageFormat as parameter.

Let’s implement this.

    class Program
    {
        static string path = @"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg";
        static void Main(string[] args)
        {
            using (Image myImage = Image.FromFile(path))
            {
                //Extension method used here
                byte[] a = myImage.GetImageInBytes(System.Drawing.Imaging.ImageFormat.Gif);
            }

            using (Image myImage = Image.FromFile(path))
            {
                //Extension method used here also
                string s = myImage.GetImageInBase64(null);
            }
        }
    }

Simple to use, isn’t it. No need of inheritance.

When you type to find the extension method, you can see a down-arrow indicating an extension method.

ExtensionMethod

ExtensionMethod

June 29, 2011 Posted by | C Sharp | Leave a comment

Allow numbers or letters and disable right-click in textbox

I have seen a number of people asking how to allow only numbers to be added in to a textbox, sometimes only letters etc. Also to disable right-click to disable pasting. One such question can be found here: http://www.codeproject.com/Answers/208641/Wish-to-use-text-box-to-only-allow-numeric-Data-en/?cmt=114369#answer4 to which my friend Chanakya(a pro-photographer with excellent technical skills) gave an excellent, sweet and simple answer, also do read the comments. I got inspiration from him to write this post.
So I will create a new TextBox which will handle all the above things. Its a “derived” control where I create a class which derives from TextBox class.

Here is the class:

    class NewTextBox : System.Windows.Forms.TextBox
    {
        private ContextMenu OrgContextMenu;
        private RestrictType _restrictOptions = RestrictType.None;
        public RestrictType RestrictOptions
        {
            get { return _restrictOptions; }
            set { _restrictOptions = value; }
        }

        private bool _allowPaste = true;
        private ContextMenu PrevContextMenu { get; set; }
        private bool _setOnceFlag = false;

        public bool AllowPaste
        {
            get { return _allowPaste; }
            set
            {
                _allowPaste = value;
                DisableRightClick(value);
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            //To only allow numbers 
            if (RestrictOptions == RestrictType.OnlyNumbers)
            {
                if (char.IsNumber((char)e.KeyValue) || (((char)e.KeyData) == '\b'))
                {
                    e.SuppressKeyPress = false;
                }
                else { e.SuppressKeyPress = true; }
            }

            // To only allow letters
            else if (RestrictOptions == RestrictType.OnlyLetters)
            {
                if (char.IsLetter((char)e.KeyValue) || (((char)e.KeyData) == '\b'))
                {
                    e.SuppressKeyPress = false;
                }
                else { e.SuppressKeyPress = true; }
            }

            //To only allow 0's and 1's
            else if (RestrictOptions == RestrictType.OnlyBinary)
            {
                if (((char)e.KeyValue).Equals('1') || ((char)e.KeyValue).Equals('0')
                    || (((char)e.KeyData) == '\b'))
                {
                    e.SuppressKeyPress = false;
                }
                else { e.SuppressKeyPress = true; }
            }
        }

        //To disable Cntl + V for pasting
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (AllowPaste.Equals(false))
            {
                if (keyData == (Keys.Control | Keys.V))
                {
                    return true;
                }
                else { return false; }
            }
            else { return false; }
        }

        // Disable Right-click for pasting
        private void DisableRightClick(bool enable)
        {
            if (_setOnceFlag == false)
            {
                OrgContextMenu = this.ContextMenu;
                _setOnceFlag = true;
            }
            if (enable.Equals(false))
            {
                // This will create a new ContextMenu with no options, hence no dropdown will be visible.
                this.ContextMenu = new ContextMenu();
            }
            // Set the original context menu.
            else
            { this.ContextMenu = OrgContextMenu; }
        }
    }

And an enum called RestrictType:

    public enum RestrictType
    {
        OnlyNumbers,
        OnlyLetters,
        OnlyBinary,
        None
    }

The code is self-explanatory. To briefly explain, I have created three properties, one is RestrictOptions which is of type RestrictType to let the user choose he/she wants allow numbers or letters or binary. Then the second property is to whether to disable pasting or not. The ProcessCmdKey function will take care of Ctrl + V, disabling it whenever the combination is used, and then using DiableRightClick function to disable Right-click by showing an empty ContextMenu. These two will be set by the user and by default, AllowPaste is true and RestrictType is None. The other property which is private is OrgContextMenu which will store the initial and original ContextMenu of the Textbox which will be set only one time.

Time to use it:

        public Form1()
        {
            InitializeComponent();
            newTextBox1.RestrictOptions = RestrictType.OnlyNumbers;
            newTextBox1.AllowPaste = false;
        }

Please do give your comments and valuable suggestions for improvement. 🙂
Happy Coding!

June 26, 2011 Posted by | C Sharp, Winforms | 1 Comment

How to use Owner Drawn Controls

There are few controls which support Owner-drawing such as ListBox, ListView,
TreeView, Combobox to name a few. With owner-drawing, you can manipulate the individual items in the above mentioned controls. Each item can be painted using the Graphics object.

In our example, we will use a Listbox having a list of all names of Brushes. Then we will supply the BackColor of each item based on the item’s text(name of Brush).
First step is to set the DrawMode property which takes the DrawMode enum as value. It has three options:
1)Normal – Drawn by operating system, not in our control.
2)OwnerDrawFixed – To be drawn by using our logic with the condition that all the items will be having the same height and width.
3)OwnerDrawVariable – Same as OwnerDrawFixed except that we have to supply the logic for height and width.

Normal won’t be of use in this example as we are going to apply our own logic for drawing of items.
Lets consider using OwnerDrawFixed.
Now to draw the items, we would have to use DrawItem event of ListBox.

Before that, first let us load all the names of the Brushes in the ListBox.

        void Form1_Load(object sender, EventArgs e)
        {
            foreach (PropertyInfo info in typeof(Brushes).GetProperties())
            {
                listBox1.Items.Add(info.Name);
            }
        }

We are using Reflection here to get all the properties and adding each property’s name in to the ListBox.

This is how the window will look like:

SimpleView

SimpleView

Our next task is to give a Background Color for each item in the ListBox depending on the item’s text. For that we will set the DrawMode of ListBox1.

listBox1.DrawMode = DrawMode.OwnerDrawFixed;

Next use the DrawItem event.

listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);

And the method definition:

void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    Brush brush;
    // Take the text from the current listbox item
    string text = listBox1.Items[e.Index].ToString();
    brush = new SolidBrush(Color.FromName(text));
    // Fill the background
    e.Graphics.FillRectangle(brush, e.Bounds);
    // Display the text using the default font and with black foreground
    e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
}

And our window will look like this:

OwnerDrawFixed

OwnerDrawFixed

But one small issue is the spacing, the items are closely spaced. Lets provide more spacing by increasing the height of each item. For that we have to set the DrawMode property to OwnerDrawVariable.

listBox1.DrawMode = DrawMode.OwnerDrawVariable;

Our DrawItem event will remain the same but we have to use an additional event “MeasureItem” to alter the height.

listBox1.MeasureItem += new MeasureItemEventHandler(listBox1_MeasureItem);

And the method definition:

void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
   e.ItemHeight = 20;            
}

So now our final window will look like this:

OwnerDrawVariable

OwnerDrawVariable

This is the final source code:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
            //listBox1.DrawMode = DrawMode.OwnerDrawFixed;
            listBox1.DrawMode = DrawMode.OwnerDrawVariable;
            listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);
            listBox1.MeasureItem += new MeasureItemEventHandler(listBox1_MeasureItem);
        }

        void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            e.ItemHeight = 20;            
        }

        void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            Brush brush;
            string text = listBox1.Items[e.Index].ToString();
            brush = new SolidBrush(Color.FromName(text));
            e.Graphics.FillRectangle(brush, e.Bounds);

            e.Graphics.DrawString(text, e.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y);
        }

        void Form1_Load(object sender, EventArgs e)
        {
            foreach (PropertyInfo info in typeof(Brushes).GetProperties())
            {
                listBox1.Items.Add(info.Name);
            }
        }
    }

June 26, 2011 Posted by | Winforms | Leave a comment

ImageViewer

Well this post is about my small ImageViewer application that I made using WPF, though I still have little more work to do to finish it completely. Anyway here is a screenshot of what I have done so far. The added advantage is that you can drag the area where all the images are shown up and down. Hope you will like it. 🙂

ImageViewer

ImageViewer

June 15, 2011 Posted by | WPF | 1 Comment