Wednesday 7 October 2015

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

    }

Friday 2 October 2015

DistinctBy in LINQ

The operator DistinctBy is lacking in LINQ, but we can achieve it with the GroupBy operator.

using System;
using System.Collections.Generic;
using System.Linq;

namespace GroupingLinq
{
    
  

        public static class EnumerableExtensions
        {

            /// <summary>
            /// Returns a ienumerable which is distinct by a given property key selector. If a custom equality 
            /// comparer is to be used, pass this in as the comparer. By setting the comparer default to null,
            /// the default comparer is used. 
            /// </summary>
            /// <typeparam name="T">The item type in the ienumerable</typeparam>
            /// <typeparam name="TKey">The type of the key selector (property to disinct elements by)</typeparam>
            /// <param name="coll">The source ienumerable</param>
            /// <param name="keySelector">The key selector, use a member expression in a lambda expression</param>
            /// <param name="comparer">Custom comparer to use, pass in null here to specify that default comparer is used,
            /// however, this is default set to null and not required parameter</param>
            /// <returns></returns>
            public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> coll, Func<T, TKey> keySelector,
                IEqualityComparer<TKey> comparer = null)
            {
                if (coll == null)
                    throw new ArgumentNullException("coll");
                if (keySelector == null)
                    throw new ArgumentNullException("keySelector");

                var result = coll.GroupBy(keySelector, comparer).Select(g => g.First()).ToList();
                return new List<T>(result).AsEnumerable();
            }

        }
    

}

The following entertaining example which is a console application shows how we can use this operator:

class Program
    {

        static void Main(string[] args)
        {

            var cars = new []
            {
                new Car {Model = "Audi", Make = "A4", Color = "Black"},
                new Car {Model = "Audi", Make = "A8", Color = "Red"},
                new Car {Model = "Audi", Make = "TT", Color = "Black"},
                new Car {Model = "Volvo", Make = "XC90", Color = "Black"},
                new Car {Model = "Volvo", Make = "S90", Color = "Black"},
                new Car {Model = "Ferrari", Make = "F500", Color = "Yellow"},
                new Car {Model = "Ferrari", Make = "F500", Color = "Red"},
                new Car {Model = "Lada", Make = "Limousine", Color = "Rusty"}
            };

            var groupedCars = cars.DistinctBy(c => new {c.Model, c.Color});


            foreach (var gc in groupedCars)
            {
                Console.WriteLine(gc.ToString()); 
            }

            Console.WriteLine("Press any key to continue ...");
            Console.ReadKey(); 
        }




        // Define other methods and classes here

    }

The sample output is then:

Model: Audi, Make: A4, Color: Black
Model: Audi, Make: A8, Color: Red
Model: Volvo, Make: XC90, Color: Black
Model: Ferrari, Make: F500, Color: Yellow
Model: Ferrari, Make: F500, Color: Red
Model: Lada, Make: Limousine, Color: Rusty
Press any key to continue ...

In the example we used DistinctBy some Cars based on their properties Model and Color. We want in other words unique combinations of Model AND Color. I.e. we can have multiple Cars of the same Model but WITH different Color OR we can have multiple cars with same Color but then the Model but be different. Uniqueness Criterion: (Model, Color) We did not get the item "Audi TT Black" because we already got a black Audi. We did not get the "Volvo S90 Black" because we already got a black Volvo. We got both the Ferrari F500 because they got different colors. And sadly, we are stuck with the "Lada Limousine Rusty" since it was the only combination of Model and Color.