24 Jun

C# ReadOnly Wrapper Collection

This examples shows how to create a readonly wrapper collection. If you have a private collection in a class and you only want to access as readonly, you can use AsReadOnly method in “List” generic class in System.Collections.Generic namespace. This method says that “I don’t want people to be able to modify the list content.” It returns a read-only wrapper collection.

Also you can expose your list through a property of type IEnumerable. ( “AsReadOnly” method is mentioned above is prefered.)

Sample Usage:

    public class ReadOnlyCollectionExample
    {
        private List<string> _collection = new List<string>();
        public IList<string> Collection1
        {
            get
            {
                return _collection.AsReadOnly();
            }
        }

        // Adding is not allowed - only iteration
        public IEnumerable<string> Collection2
        {
            get { return _collection; }
        }
    }

23 Jun

C# Disable Or Hide Close Button(X) in Windows Form

This examples show how to hide/disable close button(X) in C#. To achieve this, we must override the CreateParams method in Form class.

Disable Close Button:

            
        //Disable close button
        private const int CP_DISABLE_CLOSE_BUTTON = 0x200;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ClassStyle = cp.ClassStyle | CP_DISABLE_CLOSE_BUTTON;
                return cp;
            }
        }

Disable Close Button

Remove The Entire System Menu:

        //remove the entire system menu:
        private const int WS_SYSMENU = 0x80000;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style &= ~WS_SYSMENU;
                return cp;
            }
        }            

Remove Entire System Menu

22 Jun

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 Jun

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