Friday, 9 October 2015

Switchbased delay with Dispatcher in WPF

Extended my DispatcherUtil class today, with SwitchBasedDelay! Example of calling the new method, note we use a fixed Guid in this case to "group" calls into a logical switch:

 DispatcherUtil.SwitchbasedDelayedInvokeAction(Guid.Parse(@"{4E101F98-31F3-4E19-B18B-2820AEA60A1B}"), () =>
     {
      PublishEvent<ProcedureFreeTypeTextChangedEvent, ProcedureFreeTypeTextChangedEventArg>(
       new ProcedureFreeTypeTextChangedEventArg
        {
          FreshId = Context.CurrentOperationalUnit.FreshId,
          ProcedureCode = Model.ProcedureTypeFreeText,
          OperationId = Model.OperationId
        });
      }, 2000);


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;

namespace SomeAcme.SomePackage
{

    /// <summary>
    /// Contains helper methods for dispatcher operations 
    /// </summary>
    public static class DispatcherUtil
    {

        private static readonly List<DelayedAction> ActionsRegistered = new List<DelayedAction>();

        private static readonly Dictionary<Guid?, bool> SwitchDelays = new Dictionary<Guid?, bool>();

        /// <summary>
        /// Executes an action passed into this method by a timeout measured in millisecond in a switch-based manner. 
        /// </summary>
        /// <param name="keyToken">A key token (Guid) to identity the switch (basic grouping)</param>
        /// <param name="executeAction">Action to execute</param>
        /// <param name="timeOut">The timeout to wait before executing (in milliseconds)</param>
        /// <param name="priority">Priority of the dispatcher operation</param>
        /// <returns></returns>
        public static bool SwitchbasedDelayedInvokeAction(Guid keyToken, Action executeAction, int timeOut,
            DispatcherPriority priority = DispatcherPriority.Background)
        {
            if (SwitchDelays.ContainsKey(keyToken) && SwitchDelays[keyToken])
                return false; //do not execute, already in progress 

            SwitchDelays[keyToken] = true;

            DelayedInvokeAction(executeAction, timeOut, priority, keyToken);
            return true; //delayed action sent off
        }

        /// <summary>
        /// Executes an action passed into this method by a timeout measured in milliseconds
        /// </summary>
        /// <param name="executeAction">Action to execute</param>
        /// <param name="timeOut">The timeout to wait before executing (in milliseconds)</param>
        /// <param name="priority"></param>
        ///    /// <param name="keyToken">A key token to identity the switch (basic grouing). Will be used as a tag on the DispatcherTimer</param>
        public static bool DelayedInvokeAction(Action executeAction, int timeOut, DispatcherPriority priority = DispatcherPriority.Background, Guid? keyToken = null)
        {
            var delayedAction = new DelayedAction(executeAction, timeOut, keyToken);
            ActionsRegistered.Add(delayedAction);
            DispatcherTimer dtimer = new DispatcherTimer(priority);

            dtimer.Interval += new TimeSpan(0, 0, 0, 0, timeOut);
            dtimer.Tag = delayedAction.ExecuteGuid;
            dtimer.Tick += DelayedInvokeTimerTick;
            dtimer.IsEnabled = true;
            dtimer.Start();

            return true;
        }

        private static void DelayedInvokeTimerTick(object sender, EventArgs e)
        {
            var dtimer = sender as DispatcherTimer;
            if (dtimer != null)
            {
                dtimer.IsEnabled = false;
                dtimer.Stop();
                dtimer.Tick -= DelayedInvokeTimerTick; //unsubscribe
                Guid targetActionGuid = (Guid)dtimer.Tag;

                DelayedAction delayedAction = ActionsRegistered.Single(a => a.ExecuteGuid == targetActionGuid);
                delayedAction.ActionToExecute(); //now execute the action 
                ActionsRegistered.Remove(delayedAction);

                if (dtimer.Tag != null)
                {
                    Guid? keyToken = dtimer.Tag as Guid?; 
                    if (SwitchDelays.ContainsKey(keyToken))
                    {
                        SwitchDelays.Remove(keyToken); //remove the switch 
                    } //if 
                } //if 

                // ReSharper disable once RedundantAssignment
                dtimer = null; //ensure free up dispatcher timer - do not starve threading resources 
            } //if 
        }

        /// <summary>
        /// Invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool InvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        /// <summary>
        /// Asynchronously invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool BeginInvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        public static void AsyncWorkAndUiThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate)
        {
            // ReSharper disable once UnusedAnonymousMethodSignature
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                T resultAfterThreadWork = threadWork();
                // ReSharper disable once UnusedAnonymousMethodSignature
                // ReSharper disable once UnusedAnonymousMethodSignature
                currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate {
                    guiUpdate(resultAfterThreadWork);
                }), resultAfterThreadWork);

            });
        }

    }
}



Wednesday, 7 October 2015

DispatcherUtil - Elegant WPF Dispatcher programmatic handling

Don't you hate it when you need to tweak the Dispatcher to do what you expect and respect the main GUI thread can only work with GUI controls rule? Wouldn't you like to have some code that just does the things you want to do with the Dispatcher without getting the dreaded InvalidOperationException? Well here is the DispatcherUtil I use to achieve this!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;

namespace SomeAcme.SomePackage
{

    /// <summary>
    /// Contains helper methods for dispatcher operations 
    /// </summary>
    public static class DispatcherUtil
    {

        private static readonly List<DelayedAction> actionsRegistered = new List<DelayedAction>();


        /// <summary>
        /// Executes an action passed into this method by a timeout measured in milliseconds
        /// </summary>
        /// <param name="executeAction">Action to execute</param>
        /// <param name="timeOut">The timeout to wait before executing (in milliseconds)</param>
        /// <param name="priority"></param>
        public static bool DelayedInvokeAction(Action executeAction, int timeOut, DispatcherPriority priority = DispatcherPriority.Background)
        {
            var delayedAction = new DelayedAction(executeAction, timeOut);
            actionsRegistered.Add(delayedAction);
            DispatcherTimer dtimer = new DispatcherTimer(priority); 
            dtimer.Interval += new TimeSpan(0, 0, 0, 0, timeOut);
            dtimer.Tag = delayedAction.ExecuteGuid;
            dtimer.Tick += DelayedInvokeTimerTick;
            dtimer.IsEnabled = true;
            dtimer.Start();

            return true;
        }

        private static void DelayedInvokeTimerTick(object sender, EventArgs e)
        {
            var dtimer = sender as DispatcherTimer;
            if (dtimer != null)
            {
                dtimer.IsEnabled = false;
                dtimer.Stop();
                dtimer.Tick -= DelayedInvokeTimerTick; //unsubscribe
                Guid targetActionGuid = (Guid)dtimer.Tag;

                DelayedAction delayedAction = actionsRegistered.Single(a => a.ExecuteGuid == targetActionGuid);
                delayedAction.ActionToExecute(); //now execute the action 
                actionsRegistered.Remove(delayedAction); 

                if (dtimer != null)
                    dtimer = null; //ensure free up dispatcher timer - do not starve threading resources 
            } //if 
        }

        /// <summary>
        /// Invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool InvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        /// <summary>
        /// Asynchronously invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool BeginInvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        public static void AsyncWorkAndUIThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate)
        {
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                T resultAfterThreadWork = threadWork();
                currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate(T result)
                {
                    guiUpdate(resultAfterThreadWork);
                }), resultAfterThreadWork);

            });
        }

    }
}


Enjoy the code! It has helped me many times when I want to do work in other threads or using Tasks with TPL!

Displaying math in webpages with MathJax

MathJax is a powerful Library for displaying math in webpages. It is possible to write mathematical symbols and equations with MathML syntatax or LateX syntax, and even other formats. In this article, LateX will be used. LaTeX has got all the necessary support for writing mathematical symbols and equations, note though that this does not mean everything in LateX is supported in browsers through MathJax. In this article, only simple examples will be used. First off, to use MathJax, just add a Reference to the MathJax JavaScript Library in the <HEAD>HEAD section of Your HTML page:

<html>
<head>
<script type="text/javascript"
  src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  tex2jax: {
    inlineMath: [['$','$'], ['\\(','\\)']],
    processEscapes: true
  }
});

</script>

</head>

Now we are ready to insert some mathematical symbols and Equations on our web page!
Let's first add the Quadratic Equation:

<font size="+2">
Quadratic equation:

$$ \begin{array}{*{20}c} { x = \frac{ -b \pm \sqrt {b^2 - 4ac}}{2a} } & {{\rm{when}}} & {ax^2 + bx + c = 0} \\ \end{array} $$ </font>

And let us also list the Greek alphabet: <div style="color:charcoal;width:300px;background:white"> <font size="+2"> $$ \\ Greek \hspace{2mm} Alphabet. \\ letter - small symbol - large symbol \\ alpha \hspace{1mm} \alpha \hspace{2mm} A \hspace{2mm} \cdotp beta \hspace{1mm} \beta \hspace{2mm} B \hspace{2mm} \cdotp gamma \hspace{1mm} \gamma \hspace{2mm} \Gamma \hspace{2mm} \cdotp delta \hspace{1mm} \delta \hspace{2mm} \Delta \hspace{2mm} \cdotp epsilon \hspace{1mm} \epsilon \hspace{2mm} E \hspace{2mm} \cdotp zeta \hspace{1mm} \zeta \hspace{2mm} Z \hspace{2mm} \cdotp \\ eta \hspace{1mm} \eta \hspace{2mm} H \hspace{2mm} \cdotp theta \hspace{1mm} \theta \hspace{2mm} \Theta \hspace{2mm} \cdotp iota \hspace{1mm} \iota \hspace{2mm} I \hspace{2mm} \cdotp kappa \hspace{1mm} \kappa \hspace{2mm} K \hspace{2mm} \cdotp lambda \hspace{1mm} \lambda \hspace{2mm} \Lambda \hspace{2mm} \cdotp mu \hspace{1mm} \mu \hspace{2mm} M \hspace{2mm} \cdotp nu \hspace{1mm} \nu \hspace{2mm} N \hspace{2mm} \cdotp xi \hspace{1mm} \xi \hspace{2mm} \Xi \hspace{2mm} \cdotp omicron \hspace{1mm} \omicron \hspace{2mm} O \hspace{2mm} \cdotp \\ pi \hspace{1mm} \pi \hspace{2mm} \Pi \hspace{2mm} \cdotp rho \hspace{1mm} \rho \hspace{2mm} P \hspace{2mm} \cdotp sigma \hspace{1mm} \sigma \hspace{2mm} \Sigma \hspace{2mm} \cdotp tau \hspace{1mm} \tau \hspace{2mm} T \hspace{2mm} \cdotp upsilon \hspace{1mm} \upsilon \hspace{2mm} Y \hspace{2mm} \cdotp phi \hspace{1mm} \phi \hspace{2mm} \Phi \hspace{2mm} \cdotp chi \hspace{1mm} \chi \hspace{2mm} X \hspace{2mm} \cdotp psi \hspace{1mm} \psi \hspace{2mm} \Psi \hspace{2mm} \cdotp omega \hspace{1mm} \omega \hspace{2mm} \Omega \hspace{2mm} \cdotp $$ </font> </div>
As you have noted, we use the $$ .. $$ enclosing syntax to insert our LateX code that constitute the mathematical symbols and Equations. MathJax is really powerful! You can display triple integrals, matrices and vector Equations - both elementary, Intermediate and Advanced Math can be displayed on a web page. The web site of MathJax is available here: MathJax webiste - MathJax.org Ok, so how does the code above look like?


Displayed in IFRAME next - the source is: http://toreaurstad.ddns.net/website/index2.htm