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

Monday, 5 October 2015

Displaying the SQL of Entity Framework Linq to Entities queries

When working with Entity Framework or EF we often blindly run Linq to Entities queries and see that we get the results we are after, ignoring the SQL we are generating behind the scenes. This is often a bad strategy, as we risk the following:
  1. The SQL can be erroneuous and give wrong results
  2. The SQL can be inefficient and slow
  3. We abstract ourselves away from SQL and use the wrong logical constructs in EF
Here is an example of an extension method that allow ourselves to display the SQL of Linq to Entities queries:

public static class IQueryableExtensions
    {

        /// 
        /// Shows the sql the IQueryable query will be generated into and executed on the DbServer
        /// 
        /// The IQueryable to analyze
        /// Set to true if this method should try decoding the parameters
        /// This is the generated SQL query in use for Entity Framework
        public static string ShowSql(this IQueryable query, bool decodeParameters = false)
        {
            var objectQuery = (ObjectQuery)query; 

            string result = ((ObjectQuery)query).ToTraceString();

            if (!decodeParameters)
                return result; 

            foreach (var p in objectQuery.Parameters)
            {
                string valueString = p.Value != null ? p.Value.ToString() : string.Empty;
                if (p.ParameterType == typeof(string) || p.ParameterType == typeof(DateTime))
                    valueString = "'" + valueString + "'";
                result = result.Replace("@" +p.Name, p.Value != null ? valueString : string.Empty); 
            }
            return result; 
        }     

}

Next, here is a simple extension method that shows how we can use this in an integration test. If you want, you can output the sql string to the Output Window, using either Console.WriteLine() or Debug.WriteLine().

    [TestFixture]
    public class IqueryableExtensionsTest
    {

        [Test]
        public void QueryableReturnsSqlAndDoesNotThrow()
        {
            using (var dbContext = SomeObjectContextFactory.SomeObjectDataContext)
            {
                var somerows= from somerow in dbContext.SomeTable
                    where somerow.SomeStatus == (int) SomeStatus.SomeStatusValue
                    && somerow.SomeOtherDateColumn >= new DateTime(2015, 2, 12)
                    select somerow;
                string sql = someRows.ShowSql();
                Assert.IsNotNull(sql);
            }
        }

    }