21 Jun

Play Mp3 And Wav Files As Synchronous And Asynchronous In C#

Play A Wav File
SoundPlayer class in System.Media namespace controls playback of a sound from a .wav file. To play the Wav file, you should create a new SoundPlayer object. Then you should set the SoundLocation property to the location of your WAV file, and then use the Play method to play it.

Sample Usage:

            
            System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            player.SoundLocation = @"C:\Test\CSharpExamplesSound.wav";
            player.Play(); //in another thread
            player.PlaySync(); //in same thread

“Play” method in SoundPlayer class plays the .wav file using a new thread. But “PlaySync” method in SoundPlayer plays thw .wav file in same thread.

Play a MP3 File
Above example only plays the .wav files. If you want to play “.mp3” or any other files are supported by windows media player, you can use MediaPlayer class. To use this class, you must add a reference to MedialPlayer.

Add Windows Media Player Reference

Sample Usage:

            
            var mediaPlayer = new MediaPlayer.MediaPlayer();
            mediaPlayer.FileName = @"C:\Test\CSharpExamplesSound.mp3";
            mediaPlayer.Play();

21 Jun

C# Sort Listview Items By Columns

The ListView control enables us to use sorting other than that provided by the Sorting property. When the ListView control sorts items, it uses a class that implements the System.Collections.IComparer interface. This class provides the sorting features used to sort each item. To use a custom item sorter, we create an instance of IComparer class and assign it to the ListViewItemSorter property of the ListView. Following sample shows us String and Datetime comparison for string and datetime columns in ListView control.

Sample project can be downloaded from following link:
ListViewSortColumnsExample.rar

Class examples that implements the System.Collections.IComparer interface:
Example 1:

    /// 
    /// Implements the manual sorting of items by column.
    /// 
    class ListViewItemStringComparer : IComparer
    {
        private int col;
        private SortOrder order;
        public ListViewItemStringComparer()
        {
            col = 0;
            order = SortOrder.Ascending;
        }

        public ListViewItemStringComparer(int column, SortOrder order)
        {
            col = column;
            this.order = order;
        }

        public int Compare(object x, object y) 
        {
            int returnVal= -1;
            returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
                                       ((ListViewItem)y).SubItems[col].Text);

            // Determine whether the sort order is descending.
            if (order == SortOrder.Descending)
                // Invert the value returned by String.Compare.
                returnVal *= -1;

            return returnVal;
        }
    }

Example 2:

    class ListViewItemDateTimeComparer : IComparer
    {
        private int col;
        private SortOrder order;
        public ListViewItemDateTimeComparer()
        {
            col = 0;
            order = SortOrder.Ascending;
        }

        public ListViewItemDateTimeComparer(int column, SortOrder order)
        {
            col = column;
            this.order = order;
        }
        
        public int Compare(object x, object y)
        {
            int returnVal;
            // Determine whether the type being compared is a date type.
            try
            {
                // Parse the two objects passed as a parameter as a DateTime.
                System.DateTime firstDate =
                        DateTime.Parse(((ListViewItem)x).SubItems[col].Text);
                System.DateTime secondDate =
                        DateTime.Parse(((ListViewItem)y).SubItems[col].Text);

                // Compare the two dates.
                returnVal = DateTime.Compare(firstDate, secondDate);
            }
            // If neither compared object has a valid date format, compare
            // as a string.
            catch
            {
                // Compare the two items as a string.
                returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
                                           ((ListViewItem)y).SubItems[col].Text);
            }

            // Determine whether the sort order is descending.
            if (order == SortOrder.Descending)
                // Invert the value returned by String.Compare.
                returnVal *= -1;

            return returnVal;
        }
    }
21 Jun

C# Fast Bitmap Compare

This example controls that two bitmap object are same or not. In first method, we use the GetPixel method in Bitmap class. In second example, we use the memory comparison using BitmapData class. “Frog 1” and “Frog 2” files has 1024×768 pixel size. Their thumbnails are shown below. As result:

Total time in first example(Lazy Comparison): ~1644 ms
Total time in second example(Fast Comprasion): ~10 ms

Usage:

            Bitmap bmp1 = (Bitmap)Bitmap.FromFile(@"C:\test\Frog 1.bmp");
            Bitmap bmp2 = (Bitmap)Bitmap.FromFile(@"C:\test\Frog 2.bmp");

            Stopwatch sw = new Stopwatch();
            
            sw.Start();
            bool res1 = BitmapComprasion.CompareBitmapsLazy(bmp1, bmp2);
            sw.Stop();
            Console.WriteLine(string.Format("CompareBitmapsLazy Time: {0} ms", sw.ElapsedMilliseconds));

            sw.Restart();
            bool res2 = BitmapComprasion.CompareBitmapsFast(bmp1, bmp2);
            sw.Stop();
            Console.WriteLine(string.Format("CompareBitmapsFast Time: {0} ms", sw.ElapsedMilliseconds));

            //Output:
            //CompareBitmapsLazy Time: 1644 ms
            //CompareBitmapsFast Time: 10 ms
Frog 1 Thumbnail Frog 2 Thumbnail
Frog 1 Frog 2

Fast Bitmap Comparison Example:

        public static bool CompareBitmapsFast(Bitmap bmp1, Bitmap bmp2)
        {
            if (bmp1 == null || bmp2 == null)
                return false;
            if (object.Equals(bmp1, bmp2))
                return true;
            if (!bmp1.Size.Equals(bmp2.Size) || !bmp1.PixelFormat.Equals(bmp2.PixelFormat))
                return false;

            int bytes = bmp1.Width * bmp1.Height * (Image.GetPixelFormatSize(bmp1.PixelFormat) / 8);

            bool result = true;
            byte[] b1bytes = new byte[bytes];
            byte[] b2bytes = new byte[bytes];

            BitmapData bitmapData1 = bmp1.LockBits(new Rectangle(0, 0, bmp1.Width, bmp1.Height), ImageLockMode.ReadOnly, bmp1.PixelFormat);
            BitmapData bitmapData2 = bmp2.LockBits(new Rectangle(0, 0, bmp2.Width, bmp2.Height), ImageLockMode.ReadOnly, bmp2.PixelFormat);

            Marshal.Copy(bitmapData1.Scan0, b1bytes, 0, bytes);
            Marshal.Copy(bitmapData2.Scan0, b2bytes, 0, bytes);

            for (int n = 0; n <= bytes - 1; n++)
            {
                if (b1bytes[n] != b2bytes[n])
                {
                    result = false;
                    break;
                }
            }

            bmp1.UnlockBits(bitmapData1);
            bmp2.UnlockBits(bitmapData2);

            return result;
        }

Classic Bitmap Comparison Example:

        public static bool CompareBitmapsLazy(Bitmap bmp1, Bitmap bmp2)
        {
            if (bmp1 == null || bmp2 == null)
                return false;
            if (object.Equals(bmp1, bmp2))
                return true;
            if (!bmp1.Size.Equals(bmp2.Size) || !bmp1.PixelFormat.Equals(bmp2.PixelFormat))
                return false;

            //Compare bitmaps using GetPixel method
            for (int column = 0; column < bmp1.Width; column++)
            {
                for (int row = 0; row < bmp1.Height; row++)
                {
                    if (!bmp1.GetPixel(column, row).Equals(bmp2.GetPixel(column, row)))
                        return false;
                }
            }

            return true;
        }
19 Jun

C# All Need To Know About Reflection

Reflection is the ability of a managed code to read its own metadata at runtime. .NET Framework allows us the type information. For example, we can learn to the method names of a given type in C#. To do this, we use the “GetMethods” method in System.Type class.

    /// 
    /// Sample class
    /// 
    public class ReflectionExample
    {
        public void SampleMethod1(string message)
        {
            Console.WriteLine("My name is SampleMethod1");
            Console.WriteLine("Your message is " + message);
        }

        public void SampleMethod2(int id)
        {
            Console.WriteLine("My name is SampleMethod2");
            Console.WriteLine("Your id is " + id.ToString());
        }
    }

Usage:

            MethodInfo[] allMethods = typeof(ReflectionExample).GetMethods();
            foreach (MethodInfo method in allMethods)
            {
                Console.WriteLine("MethodName=" + method.Name + " "+
                                  "IsPublic=" + method.IsPublic.ToString());
            }

            //Output:
            //MethodName=SampleMethod1 IsPublic=True
            //MethodName=SampleMethod2 IsPublic=True
            //MethodName=ToString IsPublic=True
            //MethodName=Equals IsPublic=True
            //MethodName=GetHashCode IsPublic=True
            //MethodName=GetType IsPublic=True

ToString, Equals, GetHashCode and GetType methods are founded in object class. So “GetMethods” method returns these methods, too. Using reflection, we can also fetch the parameters of a method.

            MethodInfo m = typeof(ReflectionExample).GetMethod("SampleMethod1");
            ParameterInfo[] parameters = m.GetParameters();
            foreach (ParameterInfo p in parameters)
            {
                Console.WriteLine("Parameter Name=" + p.Name + " " +
                                  "Type=" + p.ParameterType.Name);
            }

            //Output:
            //Parameter Name=message Type=String

Also we can create an instance of a given type and invoke its methods or properties at runtime without compiling.
This technology is named as “Late binding” or “Dynamic Invocation” in .NET. Following sample shows the sample usage.

            Type type = typeof(ReflectionExample);
            object obj = Activator.CreateInstance(type);
            MethodInfo mi = type.GetMethod("SampleMethod1");
            mi.Invoke(obj, new object[]
            {
                "Hello Method!"
            });

            //Output:
            //My name is SampleMethod1
            //Your message is Hello Method!
18 Jun

[Flags] Enum Attribute And Bitwise Operation In C#

The flags attribute should be used whenever the enumerable represents a collection of flags, rather than a single value. We must use multiples of two in our enumeration to use bitwise operations. Such collections are usually manipulated using bitwise operators, For example:

MyColors themeColors = MyColors.Yellow | MyColors.Red;

Example enum decleration:

    [Flags]
    public enum MyColors : int
    {
        Yellow  = 1,
        Green   = 2,
        Red     = 4,
        Blue    = 8,
        Orange  = 16,
        Black   = 32,
        White   = 64,
    }

The flags attribute doesn’t change enum values. It is enable a nice representation by the .ToString() method:

"themeColors.ToString" =>  "Yellow, Red"

Enumeration values looks like this:
Yellow = 0000001
Green = 0000010
Red = 0000100
Blue = 0001000
Orange = 0010000
Black = 0100000
White = 1000000

themeColors instance looks like this:
themeColors = 0000101

To retrieve the distinct values in our property one can do this,
Usage:

            if ((themeColors & MyColors.Red) == MyColors.Red)
            {
                Console.WriteLine("Red is a theme color.");
            }

            if ((themeColors & MyColors.Green) == MyColors.Green)
            {
                Console.WriteLine("Green is a theme color.");
            }

themeColors is 0000101
MyColor.Red is 0000100
———————————–(BITWISE AND)
Result is 0000100 -> It is a red color

Also we can use the bit-shifting for setting the enum values. It is more simple and more readable.
Example enum decleration using bit-shifting:

    /// 
    /// using bit-shifting
    /// 
    [Flags]
    public enum MyColors_SetValuesWithBitShifting
    {
        Yellow  = 1 << 0,
        Green   = 1 << 1,
        Red     = 1 << 2,
        Blue    = 1 << 3,
        Orange  = 1 << 4,
        Black   = 1 << 5,
        White   = 1 << 6,
    }