22 Haz

C# Generic Cache Manager Example

This examples shows how to implement a generic cache manager class in C#. We often need to cache to the some objects in our programs, ecpecially for objects that frequently access. Following sample is implemented for this purpose.

Usage:


            CacheManager<string> cm = new CacheManager<string>(); //keep this instance in a class

            cm.Add("key1", "data1", 5000);  //remove after 5 sc
            cm.Add("key2", "data2");        //don't remove from cache
            cm.Add("key3", "data3", 3000);  //remove after 3 sc
            cm.Add("key4", "data4");        //don't remove from cache

Also if we want to use only one cache manager instance, we can use Singleton Pattern in Design Patterns.

For more information about Singleton Pattern:
https://csharpexamples.com/c-multithread-singleton-pattern-example

Generic Cache Manager Class:


    public class CacheManager<T>
    {
        private Dictionary<string, T> _items = null;
        public CacheManager()
        {
            _items = new Dictionary<string, T>();
        }

        private void TimerProc(object state)
        {
            //Remove the cached object
            string key = state.ToString();
            this.Remove(key);
        }

        public void Add(string key, T obj, int cacheTime = System.Threading.Timeout.Infinite)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key is null.");

            if (_items.Keys.Contains(key))
                throw new ArgumentException("An element with the same key already exists.");

            //Set timer
            System.Threading.Timer t = new System.Threading.Timer(new TimerCallback(TimerProc), 
                                                                 key, 
                                                                 cacheTime, 
                                                                 System.Threading.Timeout.Infinite);

            _items.Add(key, obj);
        }
        
        public bool Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key is null.");
            
            return _items.Remove(key);
        }

        public T Get(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key is null.");

            if (!_items.Keys.Contains(key))
                throw new KeyNotFoundException("key does not exist in the collection.");

            return _items[key];
        }

        public void Clear()
        {
            _items.Clear();
        }
    }
22 Haz

C# Resize A Bitmap Example

This example shows how to resize a bitmap file in C#. To resize a bitmap image, we use Graphics class in System.Drawing namespace.

Usage:

            //Size of "testimage.bmp" file is 1024x1024.
            Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\testimage.bmp");
            Bitmap newImage = ResizeBitmap(bmp, 512, 512);

Resize Method Example:

        public Bitmap ResizeBitmap(Bitmap bmp, int width, int height)
        {
            Bitmap result = new Bitmap(width, height);
            using (Graphics g = Graphics.FromImage(result))
            {
                g.DrawImage(bmp, 0, 0, width, height);
            }

            return result;
        }
21 Haz

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 Haz

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 Haz

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