Dialog boxes management in WPF application

I’ve just published an article which demonstrate an idea on how to manage dialog boxes in WPF application. You can read it here.

Implement UI Element Authorization in WPF

I’ve written an article which demonstrate how to implement UI element authorization/access control in WPF using the ICommand interface and Markup Extension. You can read it here.

Skinnable and Animated popup window in WPF

Skinnable and Animated popup window in WPFI’ve published a article in code project which demonstrate how to create a skinnable and animatable MSN Live Messenger style popup window in WPF with MVVM design patterns.

Types of Constructor

How many types of constructor that you know of from different programming languages? If you have more than what I’ve listed here, please share…

1. Default/Parameter-less Constructor
A public constructor which takes no argument.

2. Overloaded/Parameterized Constructor
A constructor that takes one or more argument.

3. Copy Constructor
A constructor which enable shallow or deep copy of the existing object.

4. Move Constructor
This is a new constructor defined in the new C++0x specification. Its usage primarily on Rvalue Reference and Return Value Optimization (RVO).

5. Virtual Constructor
This constructor is similar to a factory method. It can have any name, though the convention is to have a meaningful verb such as Create, Start, StartNew, Make etc. Creating an instance of a class works like calling a static method of a class: Partitioner.Create(…) or Task.StartNew(…).

6. Static Constructor
Static Constructor is currently available in managed languages such as C++/CLI and C#. A static constructor is a static data initializer. Static constructors allow complex static variable initialization. Static constructors can be called once and call is made implicitly by the run-time right before the first time the class is accessed. Any call to a class (static or constructor call), triggers the static constructor execution. Static constructors are thread safe and are a great way to implement a singleton pattern.

How do I set a field/property value in an C# Expression tree in .NET 3.5?

While learning and practicing Expression tree in .NET 3.5, I encountered a problem stated in the post’s Title. During initial search through the Google, I found that some articles saying that there is no way to achieve property assignment through Expression.Bind in .NET Framework 3.5 but can be resolved using the Expression.Assign method in .NET Framework 4.0. I was in doubt and would like to give it a try. Throughout hours of Trials and Errors, I finally came out with the solution, which uses reflection to invoke the Property Setter of the object’s field/property. The solution is shown below:

        /// <summary>
        /// Solution starts here
        /// </summary>
        static void Main(string[] args)
        {
            Person p = new Person("Joseph", "Albahari");

            Print("Authors of the book [C# 4.0 IN A NUTSHELL] are:", ConsoleColor.White);
            Print(p.ToString(), ConsoleColor.Yellow);

            Action<Person, string> setter = GetPropertySetter<Person, string>(p, "LastName");
            setter(p, "Ben");
            Print(p.ToString(), ConsoleColor.Yellow);

            Console.ReadLine();
        }

        /// <summary>
        /// An delegate which invoke the object's property setter through reflection
        /// </summary>
        static Action<TElement, TValue> GetPropertySetter<TElement, TValue>(TElement elem, string propertyName)
        {
            Type elementType = elem.GetType();

            PropertyInfo pi = elementType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
            MethodInfo mi = pi.GetSetMethod();  //  This retrieves the 'get_LastName' method

            ParameterExpression oParam = Expression.Parameter(elementType, "obj");
            ParameterExpression vParam = Expression.Parameter(typeof(TValue), "val");
            MethodCallExpression mce = Expression.Call(oParam, mi, vParam);
            Expression<Action<TElement, TValue>> action = Expression.Lambda<Action<TElement, TValue>>(mce, oParam, vParam);
            
            return action.Compile();
        }

        static void Print(string msg, ConsoleColor color)
        {
            Console.ForegroundColor = color;
            Console.WriteLine(msg);
            Console.ResetColor();
        }

Once I found this solution, I suddenly recalled that a Bonus Chatter by Raymond Chen quoted as “I wrote this series of entries nearly two years ago, and even then, I didn’t consider this to be anything particularly groundbreaking, but apparently some people rediscovered it a few months ago and are falling all over themselves to claim credit for having found it first. It’s like a new generations of teenagers who think they invented sex.”. This triggers me an alarm and I came to believe that I did not thoroughly search through the web, and did a final attempt in g.o.o.g.l.e…….

Oh-no, I found the official guidance on sex at StackOverflow at last.

class and struct in C++

One of the old but popular questions being asked is “What is the different between Class and Struct in C++”?

• Members of a class are private by default, whereas members of a struct are public by default.

• Inheritance between classes is also private by default, whereas inheritance between structs is public by default.

• In C++ structures and classes are passed by value, unless explicitly de-referenced. In other languages classes and structures may have distinct semantics – ie. objects (instances of classes) may be passed by reference and structures may be passed by value.

Boxing error in System.Linq.Expressions

Recently, I’ve run into a boxing error while invoking a delegate which composed from the Expression. As we know, most of the .NET type can be implicitly convert/cast to Object type and this can be easily verified through the following code.

private void ConvertableToObject()
{
    object o = null;

    o = 1;
    Console.WriteLine(o);

    o = true;
    Console.WriteLine(o);

    o = "Hello, Expression.";
    Console.WriteLine(o);
}

Let’s confirm one more thing. Code written in (C#,VB,F# or any CLI compliant languages) that converted back and forth from Expression without modification, they should/must be function the same. Right? Otherwise, it’s a disaster and defeats the purpose of meta-programming. Before we delve into the problem, let’s do another simple test. I’ve composed a delegate called Println which internally uses System.Console.WriteLine to print out message with any format.

The original System.Console.WriteLine method signature:

//
// Summary:
//    Writes the text representation of the specified array of objects, followed
//    by the current line terminator, to the standard output stream using the specified
//    format information.
//
// Parameters:
//   arg:
//    An array of objects to write using format.
//
//   format:
//    The format string.
//
// Exceptions:
//   System.FormatException:
//    The format specification in format is invalid.
//
//   System.IO.IOException:
//    An I/O error occurred.
//
//   System.ArgumentNullException:
//    format or arg is null.
public static void WriteLine(string format, params object[] arg);

The one composed with Expression is listed here:

private Action<string, object[]> Println()
{
    MethodInfo mi = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string), typeof(object[]) });

    //  Constructing method from Expression
    ParameterExpression format = Expression.Parameter(typeof(string), "format");
    ParameterExpression args = Expression.Parameter(typeof(object[]), "args");
    MethodCallExpression mce = Expression.Call(mi, format, args);
    Expression<Action<string, object[]>> printExpression = Expression.Lambda<Action<string, object[]>>(mce, format, args);

    //  Convert Expression into Executable Code
    return printExpression.Compile();
}

Execute both existing and expression’s composed method with the same argument should print out the same message, as you can see here:

DateTime now = DateTime.Now;
//  Existing Method
Console.WriteLine("Today is {0} - Date: {1}, Time: {2}", new object[] { "Friday", now.Date, now.TimeOfDay });
//  Expression method
Println()("Today is {0} - Date: {1}, Time: {2}", new object[] { "Friday", now.Date, now.TimeOfDay });
 
Console.ReadLine();

Let’s see the problem now. An expression statement can be nested, meaning it can be use compositionally with other expression statements to form a bigger expression, which ultimately turn/compiled itself into a delegate. However, there is a Catch here. Let’s see the example here, where I use InvocationExpression to invoke the Println expression, one with “String” and the other with “Integer” data type.

private static Expression<Action<string, object[]>> PrintlnExpression()
{
    MethodInfo mi = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string), typeof(object[]) });
 
    ParameterExpression format = Expression.Parameter(typeof(string), "format");
    ParameterExpression args = Expression.Parameter(typeof(object[]), "args");
    MethodCallExpression mce = Expression.Call(mi, format, args);
    return Expression.Lambda<Action<string, object[]>>(mce, format, args);
}
 
static void Main(string[] args)
{
    //  Running this method which prints "String(100) == String(100)" without the quotes
    Expression.Lambda(
        Expression.Invoke(PrintlnExpression(),
            Expression.Constant("String({0}) == String({1})", typeof(string)),
            Expression.NewArrayInit(typeof(string),
                Expression.Constant("100", typeof(string)),
                Expression.Constant("100", typeof(string)))
        )
    ).Compile().DynamicInvoke();
 
    //  Running the method below triggers an exception which prints
    //  Expression of type 'System.Int32[]' cannot be used for parameter of type 'System.Object[]'
    Expression.Lambda(
        Expression.Invoke(PrintlnExpression(),
            Expression.Constant("Integer({0}) == Integer({1})", typeof(string)),
            Expression.NewArrayInit(typeof(int), 
                Expression.Constant(100, typeof(int)),
                Expression.Constant(100, typeof(int)))
        )
    ).Compile().DynamicInvoke();
 
    Console.ReadLine();
}

 
Running the first delegate, it works as expected and print out:

 
Unfortunately, the second delegate failed mysteriously.

What’s on earth has happened? Is this a bug or a design feature? To me, It’s definitely not a feature, from the a few experiments that I carried out, it seems to only work with “String” and of course “Object”, but not the others like (int, bool, double and etc).

This behavior exhibits in .NET Framework 3.5, can anybody tell me what I’ve done wrong or anything that causes it? Any comments are welcome.

You’re free to download and experiment with the code here.

LINQ in Javascript

With the advent of LINQ (Language INtegrated Query) by Microsoft, it has influences programmers to write expressive and succinct code to work with local (in-memory collections or arrays) or remote data sources (DBMS or Cloud Storage). In the .NET world, LINQ is implemented as a set of extension methods, which makes it appear to be the methods of IEnumerable, IEnumerable<T>, IQueryable, IQueryable<T> and their derived classes. The .NET Standard Query Operators has 50 operators. But the community has grown this number to over 80 in the past few years and is still growing.

 

To a ASP.net web developer like me, I enjoy to use C# and its LINQ counterpart to query over datasets. As the Web 2.0 emerged, a lot of operations have been moved from Server to Client with the present of XHR (XMLHttpRequest), JQuery, Prototype, and Javascript framework like YUI, Ext and so on. In Web 2.0, web application has shifted from monolithic to mashup style where data or operations can be retrieved or executed through different data sources (local or remote databases) or web services. For example, authentication and authorization through OpenID, display the current logged in user’s location in the map with the use of Google or Bing map services. These operations can be carried out at client side without the need to go through its origin server, hence lots of data need to be queried and managed in client side. Can LINQ comes to rescue? The answer is depend!

 

There are some LINQ enthusiastic, whom has created LINQ for Javascript. For example, JSINQ, LINQ for Javascript and so on. I am one with less skillful but curios about writing LINQ in Javascript, and I’ve written myself a dozen of simple LINQ operators in Javascript as a plug-in to JQuery. Here you can see the Where operator:
 
var linq = {

//  Restriction Operators

Where  : function(predicate) {

var items = [];

this.each(function(index, item) {

if (predicate.apply(item, [item, index]))

items.push(item);

});

return $(items);

},

//  Projection Operators

Select : function (selector) {

var items = [];

this.each(function(index, item) {

items.push(selector(item));

});

return $(items);

},

//  The rest has been omitted for brevity

 

and you can see the code below on how easy I can plug my linq object as a plug-in to JQuery object.

 

//  Stuff the linq plugin into jQuery object

$.fn.extend(linq);

 

The usage is demonstrated here:

 

var items = $('li') //  Gets all the <li> elements

.Select(function(item) {

return parseInt($(item).text()); // Apply projection

})

.Where(function(item) {

return (item % 2) == 0; //  Apply filtering

})

.each(function(index, item) {

alert(item);    //  2, 4, 6, 8, 10

});

 

The sample implementation of LINQ to Javascript is included here. Happy Coding!

Fun with Dashboard

These are the Dashbaord screens that created by me from the month of July till August. and many more are coming…

Patterns with IDisposable and Using directive

IDisposable is one of the most important interface introducing in .NET Framework, the primary use of this interface is to release unmanaged, finite or expensive resources such as file or graphics handles, network and database connections. With the language construct support like using Directive, it is relatively easy to use and uarantee that code written in the Dispose method will be executed no matter what happen during the execution scope.

The code shown below is written without the using directive, if an exception happens between the creation and disposal of Graphics object, the graphics object will not be disposed and might cause memory leak in your application.

        void OnDraw(Rectangle rect)
        {
            Graphics g = CreateGraphics();  //  Resource creation
            g.DrawRectangle(Pens.Blue, rect);
            //  Drawing whatever shape here...
            //  Oops! What if an error occurred here...
            g.Dispose();                    //  Resource disposal
        }

 

A preferable way to rewrite the above code with the using directive is shown here:

        void OnDraw(Rectangle rect)
        {
            using (Graphics g = CreateGraphics())
            {
                g.DrawRectangle(Pens.Blue, rect);
                //  Drawing whatever shape here...
                //  Need not call g.Dispose as it will be disposed automatically when out of using scope
            }
        }

But this is not what we’re here for today. Instead, we’re going to focus some patterns derived from IDisposable interface and using directive.

1. Revertible with IDisposable

This pattern make use of the Dispose method to revert back the object’s current state to its original state when it goes out of the using scope.

Have you seen or written code like below in Windows Forms,


        void saveButton_Click(object sender, EventArgs e)
        {
            try
            {
                //  Use Wait Cursor to signal that the Form is loading...
                this.Cursor = Cursors.WaitCursor;

                //  Save routine which takes a while to finish...
            }
            finally
            {
                //  Revert back to default cursor
                this.Cursor = Cursors.Default;
            }
        }

With Revertible pattern, above code can be written as:

        void SaveButton_Click(object sender, EventArgs e)
        {
            using(ManagedCursor mc = new ManagedCursor(this, Cursors.WaitCursor))
            {
                //  Save routine which takes a while to finish...
            }
            //  Cursor now automatically revert back
        }

and the reusable helper class ManagedCursor is here:

  public sealed class ManagedCursor : IDisposable
  {
      Form _form;
      Cursor _oCursor;

      public ManagedCursor(System.Windows.Forms.Form form, Cursor cursor)
      {
          this._form = form;
          this._oCursor = form.Cursor;
          form.Cursor = cursor;
      }
      
      public void Dispose()
      {
          this._form.Cursor = _oCursor;
      }
  }

2. Actionable with IDisposable

This pattern make use of the Dispose method to perform a computation/action when it goes out of the using scope.

Below is an example of Actionable pattern, which is use to measure the execution time of a method or code segment.

     public sealed class TimeLog : IDisposable
     {
         Stopwatch _sw;
         TextWriter _writer;
         string _format = String.Empty;

         public TimeLog(TextWriter writer, string format = "Execution Time Taken: {0}")
         {
             _writer = writer;
             _format = format;
             _sw = new Stopwatch();
             _sw.Start();
         }

         public void Dispose()
         {
             _sw.Stop();
             _writer.WriteLine(_format, _sw.Elapsed);
         }
     }

and the usage of TimeLog:

        void MeasureTime()
        {
            using (TimeLog log = new TimeLog(Console.Out))
            {
                //  Simulate the execution time of a code block
                Console.WriteLine("Sleep for 2 seconds...");
                System.Threading.Thread.Sleep(2000);
            }
            Console.WriteLine();
        }
TimeLog 

That’s all.

Below is a F# example to demo the patterns illustrated earlier. Instead of writing a sealed class like C#,  it is easier to write a function values with the Object Expressions. With Object Expressions, we avoid the extra code and overhead that is required to create a new, named type.

 

namespace FSharp.Common

open System
open System.IO
open System.Drawing
open System.Windows.Forms
open System.Diagnostics

[<AutoOpen()>]
module ManagedHelpers =

    let TimeLog (writer:TextWriter, format:string) =
        let sw = new Stopwatch()
        do sw.Start()
       
        { new IDisposable with
            member x.Dispose() =
                sw.Stop()
                writer.WriteLine(format, sw.Elapsed)
        }

    let ManagedCursor(form:Form, cursor:Cursor) =
        let oldCursor = form.Cursor
        form.Cursor <- cursor

        { new IDisposable with
            member x.Dispose() =
                form.Cursor <- oldCursor }

    let ManagedConsoleColor(c:ConsoleColor) =
        let oldColor = Console.ForegroundColor
        Console.ForegroundColor <- c

        { new IDisposable with
            member x.Dispose() =
                Console.ForegroundColor <- oldColor }
 
If you run the demo code shown below, you shall see the output like it:
Demo 
namespace FSharp.Common

open System
open System.IO
open System.Drawing
open System.Windows.Forms
open System.Diagnostics


module Program =

    let doWait(msg:string) =
        Console.WriteLine(msg)
        Console.WriteLine("Press Enter to continue...")
        Console.ReadLine() |> ignore
   
    let Demo1() =
        doWait("Demo 1: ManagedConsoleColor")
        use d = ManagedConsoleColor(ConsoleColor.Red)
        Console.WriteLine("This line is a Red color Text.")
   
    let Demo2() =
        doWait("Demo 2: TimeLog")
        using(TimeLog(Console.Out, "Execution Time Taken: {0}")) (fun d ->
            Console.WriteLine("Sleep for 2 seconds...")
            System.Threading.Thread.Sleep(2000))
   
    let Demo3() =
        doWait("Demo 3: ManagedCursor")
        use f = new Form(Text="Cursor Demo")
        f.Visible <- true
        use d = ManagedCursor(f, Cursors.WaitCursor)
        //  Initialization code here...
        System.Threading.Thread.Sleep(5000)
       

    [<EntryPoint>]
    let main _ =
        Demo1()
        Console.WriteLine("nn");
        Demo2()
        Console.WriteLine("nn");
        Demo3()
        Console.ReadLine() |> ignore
        0

Last but not least, you can download the F# source file for ManagedHelpers.fs and Demo.fs. Happy Coding!

Follow

Get every new post delivered to your Inbox.