Skip to main content

VBA versus .NET

Decorator Pattern

This is an example of the Decorator pattern, in this case a decorator for ObservableCollection.  Working with WPF and ObservableCollection using threads, one will run into the problem whereby the ObservableCollection cannot be updated from outside the owning thread; Delegates and Invoke will not work. A solution is to contain and expand the class, as is done in this example on michIG's Blog.

This linked file contains the original code in C#, as well as the same code converted to VB.NET.

Salient Characteristic(s)
  • Sets an internal pointer to the decorated object, sending method calls and property actions to the internal object
  • Extends the object by wrapping it and adding some aspect handled by the decorator

Code

using System;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Collections.Specialized;
using System.ComponentModel;

namespace DesignPatterns
{
    /// <summary>  
    /// This class is an observablecollection which invokes automatically.  
    /// This means that any change will be done in the right thread.  
    /// </summary>  
    /// <typeparam name="T">The type of the elements</typeparam>  
    public class DispatchingObservableCollection<T> : ObservableCollection<T>
    {
        /// <summary>  
        /// The default constructor of the ObservableCollection  
        /// </summary>  
        public DispatchingObservableCollection()
        {
            //Assign the current Dispatcher (owner of the collection)  
            _currentDispatcher = Dispatcher.CurrentDispatcher;
        }

        private readonly Dispatcher _currentDispatcher;


        /// <summary>  

        /// Executes this action in the right thread  
        /// </summary>  
        ///<param name="action">The action which should be executed</param>  
        private void DoDispatchedAction(Action action)
        {
            if (_currentDispatcher.CheckAccess())
                action.Invoke();
            else
                _currentDispatcher.Invoke(DispatcherPriority.DataBind, action);
        }

        /// <summary>  

        /// Clears all items  
        /// </summary>  
        protected override void ClearItems()
        {
            DoDispatchedAction(BaseClearItems);
        }

        private void BaseClearItems()

        {
            base.ClearItems();
        }

        /// <summary>  

        /// Inserts a item at the specified index  
        /// </summary>  
        ///<param name="index">The index where the item should be inserted</param>  
        ///<param name="item">The item which should be inserted</param>  
        protected override void InsertItem(int index, T item)
        {
            DoDispatchedAction(() => BaseInsertItem(index, item));
        }

        private void BaseInsertItem(int index, T item)

        {
            base.InsertItem(index, item);
        }

        /// <summary>  

        /// Moves an item from one index to another  
        /// </summary>  
        ///<param name="oldIndex">The index of the item which should be moved</param>  
        ///<param name="newIndex">The index where the item should be moved</param>  
        protected override void MoveItem(int oldIndex, int newIndex)
        {
            DoDispatchedAction(() => BaseMoveItem(oldIndex, newIndex));
        }

        private void BaseMoveItem(int oldIndex, int newIndex)

        {
            base.MoveItem(oldIndex, newIndex);
        }

        /// <summary>  

        /// Removes the item at the specified index  
        /// </summary>  
        ///<param name="index">The index of the item which should be removed</param>  
        protected override void RemoveItem(int index)
        {
            DoDispatchedAction(() => BaseRemoveItem(index));
        }

        private void BaseRemoveItem(int index)

        {
            base.RemoveItem(index);
        }

        /// <summary>  

        /// Sets the item at the specified index  
        /// </summary>  
        ///<param name="index">The index which should be set</param>  
        ///<param name="item">The new item</param>  
        protected override void SetItem(int index, T item)
        {
            DoDispatchedAction(() => BaseSetItem(index, item));
        }

        private void BaseSetItem(int index, T item)

        {
            base.SetItem(index, item);
        }
        
        /// <summary>  
        /// Fires the CollectionChanged Event  
        /// </summary>  
        ///<param name="e">The additional arguments of the event</param>  
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            DoDispatchedAction(() => BaseOnCollectionChanged(e));
        }

        private void BaseOnCollectionChanged(NotifyCollectionChangedEventArgs e)

        {
            base.OnCollectionChanged(e);
        }

        /// <summary>  

        /// Fires the PropertyChanged Event  
        /// </summary>  
        ///<param name="e">The additional arguments of the event</param>  
        protected override void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            DoDispatchedAction(() => BaseOnPropertyChanged(e));
        }

        private void BaseOnPropertyChanged(PropertyChangedEventArgs e)

        {
            base.OnPropertyChanged(e);
        }
    }
}


Comments

  1. Hi,
    I really found your article informative. I would like to know more about design patterns, could you help me know what are elite sites for acquiring knowledge? Thanking in advance.

    ReplyDelete
  2. No sites, mostly reading books, as well as using the patterns in code:

    - Professional Enterprise .NET
    - Microsoft .NET: Architecting Applications for the Enterprise: Architecting Applications for the Enterprise
    - Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries
    - Design Patterns Explained: A New Perspective on Object-Oriented Design
    - Design Patterns: Elements of Reusable Object-Oriented Software

    James

    ReplyDelete

Post a Comment

Popular posts from this blog

VBA versus .NET

I was recently messaged by someone on LinkedIn, and since my response seemed full enough, I thought I'd share. Question I see that you also program in VBA but you have made the jump to .NET. Unfortunately, I have found C#/Excel coding to be quite slow and just wanted to hear about your experiences. Responses Slow? It depends on what you mean. Honest, I have had to make the pitch when building apps that it should be in .NET rather than VBA for speed. One particular app had a form that needed to fill about 20 dropdowns on load, so using async operations was essential. That same app, while executing one SQL statement in the foreground, also executed 2 background statements that filled panels. It wouldn't have performed well if done in VBA. If you mean that it takes longer, then yes, but that is a necessity for good code anyway. If you only need a local operation, non-threaded, that doesn't need to be used across the enterprise, VBA can make sense, but with .NET comes n

Do Algorithms Make You a Better Developer?

Responding to a question on HashNode, Developers who practise algorithms are better at software development than people who just do development. Is it true? , I wrote the following: My feeling is that algorithms help make one a better programmer, but that is likely true of many coding concepts. I did not have algorithms as an undergraduate, so my knowledge is acquired through reading and practice, but after reading and applying Algorithm's in a Nutshell, I felt the quality of my work improved. That said, my development work increased more after understanding Design Patterns, or after consuming books on database design.  Since many types of knowledge improve developing and architecting abilities, one has to consider how it helps and to what degree. Algorithms are coding-in-the-small, often narrowly focused solutions, but which can have a great impact at scale. For many applications, a focus on algorithms would be overkill as data sets and requirements do not require it. In this

Review - TFS/VSTS - Great Product, Ideal for Small Development Shops

This is a report a short review I provided for G2 regarding TFS : What do you like best? If you use Visual Studio for development, TFS, or its online equivalent VSTS, you can have a fairly seamless end-to-end integration. Out of the box, it provides code management, testing, work hierarchy in agile formats, automated build, and deployment. What do you dislike? Branching and merging can be a bit painful, in that it needs to be planned, and is not natively part of the process. Code review also needs to be planned and only recently has it become part of the process. Recommendations to others considering the product My only concern regarding TFS and VSTS is that Microsoft itself recommends using Git. What business problems are you solving with the product? What benefits have you realized? In my current role, I've joined a shop that has application development as secondary to their role of desktop OS and app deployment/maintenance, so their code management practi