Saturday 20 July 2013

Presentation of Underscore.Js

Underscore.Js library presentation

I am working with a presentation of Underscore.Js Javascript library. The powerpoint file (.pptx) is available for download here:

Underscore.Js presentation [PPTX]



Underscore.Js presentation [PDF]

Created with Powerpoint 2013.

Wednesday 17 July 2013

Using TypeScript to implement OOP inherited Loggers

TypeScript is a framework for creating compile type checking and simplifying OOP (Object Oriented Programming) in Javascript. It is a framework available on Codeplex and its primary initiator is Microsoft. The source code is freely available at the following Git url: https://git01.codeplex.com/typescript

Note, by using Git ,it did take some time to download the entire source code, as there are many files. I would like to have the Codeplex Projects available instead for Mercurial / Hg. The website of TypeScript is available here:
http://www.typescriptlang.org/

Note - there is also a video from Channel9 MSDN, where Anders Hejlsberg presents TypeScript: One of the employees from Microsoft involved in TypeScript then is Anders Hejlsberg. He is actually the core Developer. He is one of Microsoft best scientists/developers and he has also been very much involved in C# and LINQ. It is promising for TypeScript that such a well-known core developer is on the team. TypeScript offers a compiler, tsc (TypeScript compiler), that converts typescript files (.ts) to JavaScript files (.js).

TypeScript is basically a code generation language for Javascript that will make it easier to create and scale Object Oriented Javascript applications. But it is also more than that. It is an entire new way of developing Javascript that will let more developers with traditional C# background and application developers in general be able to create Javascript code with basic understanding in Javascript, but still let them write structured, object oriented Javascript. Many developers know enough Javascript to implement basic functionality, but to support Object Orientation via prototypes is a less common skill. Now, with the help of TypeScript, you can write code that looks a bit like C#, but generates the necessary Javascript to allow OOP paradigm and structuring of your code. You can also create modules, which are similar to namespaces, which are either external or internal modules. For exernal modules, RequireJs is often used. In this example we will use the simpler internal modules to create a simple set of loggers to be used in the web client with the help of TypeScript. Before I present the code, you can download a TypeScript Visual Studio 2012 plugin from here:

TypeScript Visual Studio 2012 plugin

Please note, there are more editors capable of editing typescript and generating Javascript, such as Sublime Text. There is though little doubt that the best editor for TypeScript files (.ts) is Visual Studio, preferably the 2012 Version. The files you reference in the html files will still be Javascript, of course. TypeScript will usually generate a .js file, a js.min file and a source map with the extension js.map, which is needed for debugging your TypeScript code.

To generate source map files, download the Web Essentials plugin for Visual Studio from here:

Visual Studio Web Essentials Extensions for VS2012

You can also download this extension from Tools-Extensions in Visual Studio. After you have installed the Web Essentials Extensions, go to the option Options-Web Essentials-TypeScript. Activate the options Generate Source Map, Show Preview Window, Minify Generated Javascript, Compile TypeScript on Save and Add Generated files to Project. You obviously want to check in all four file types into your Version Control System (VCS), the .ts, .js, .js.min and .js.map files. Note that editing the .ts file in Visual Studio will generate the .js, js.min and .js.map files. The .js file will be shown in a preview window. Experienced Javascript programmers that are comfortable with prototypes in Javascript will note how TypeScript generates closures, iffys (immediately executing functions) and use prototypes to support OOP. The problem is that the syntax does not scale well with deep inheritance and OOP in Javascript. TypeScript converts your TypeScript code to Javascript and aids you in realising OOP based Javascript and also provided compile type checking. Let's first generate a TypeScript Application. Note that you can add TypeScript to an existing MVC Application for example. It is easiest to begin with the project solution for TypeScript for initial testing, HTML Application With TypeScript:
Note that TypeScript do work with ordinary Web Projects also such as MVC Applications where the Views and Scripts resides (GUI Project in your solution).

You can add a new TypeScript file explicitly:

Check that your options for Web Essentials are correct before you continue:

I also add the following NuGet packages in this sample: jquery, jquery.ui.combined and toastr with the Install-Package command in Package Manager Console in VS2012. It is not uncommon to add RequireJs also if you will create external modules with TypeScript. Here, we will create a simple external module.

Let's look at a TypeScript file with Loggers next:
/// <reference path="TypeDefinitions/jqueryui.d.ts" />
/// <reference path="TypeDefinitions/jquery.d.ts" />
/// <reference path="TypeDefinitions/toastr.d.ts" />

// Module App.Util.Loggers 
module App.Util.Loggers {

    export enum LogLevel {
        Information  = 0,
        Warning = 1,
        Error = 2,    
    }

    // Interface ILogger
    export interface ILogger {
        Log(message: string): void;
        LogLevel: LogLevel; 
    }

    export class BaseLogger {

        private logLevel : LogLevel;

        constructor(logLevel: LogLevel) {
            this.LogLevel = logLevel;
        }
        
        get LogLevel() {
            return this.logLevel; 
        } 

        set LogLevel(logLevel) {
            if (this.logLevel != logLevel) {
                this.logLevel = logLevel; 
            }
        }

    }

    // Class DialogLogger
    export class DialogLogger extends BaseLogger implements ILogger {

        private anchorId: string; 
        private modal : bool;

        constructor(logLevel: LogLevel, anchorId : string, modal? : bool) {
            super(logLevel); 
            this.AnchorId = anchorId; 
            this.Modal = modal; 
        }

        public Log(message: string): void {

            var dialog = $("#" + this.AnchorId).dialog({
                title: message,
                buttons: {
                    Ok: function () {
                        $(this).dialog("close");
                    }
                },
                modal: this.Modal
            });                 

            switch (this.LogLevel) {
            
                case LogLevel.Information:
                    dialog.parent().addClass("ui-icon-information");       
                    break;

                case LogLevel.Error:               
                    dialog.parent().addClass("ui-state-error");       
                    break;

                case LogLevel.Warning:
                    dialog.parent().addClass("ui-state-warning");       
                    break;

            }
          
        }

        get AnchorId() {
            return this.anchorId;
        }

        set AnchorId(anchorId: string) {
            if (this.anchorId != anchorId) {
                this.anchorId = anchorId; 
            }
        }

        get Modal(){
            return this.modal; 
        }

        set Modal(modal : bool) {
            if (this.modal != modal) {
                this.modal = modal; 
            }
        }

    }

    //Class ToasterLogger
    export class ToasterLogger extends BaseLogger implements ILogger {

        constructor(logLevel: LogLevel) {
            super(logLevel);
        }

        public Log(message: string): void {

            switch (this.LogLevel) {

                case LogLevel.Information:
                    toastr.info(message);
                    break;

                case LogLevel.Error:
                    toastr.error(message); 
                    break;

                case LogLevel.Warning:
                    toastr.warning(message); 
                    break;

            }
        
        }    
    }

    //Class ConsoleLogger
    export class ConsoleLogger extends BaseLogger implements ILogger {

        constructor(logLevel: LogLevel) {
            super(logLevel); 
        }

        public Log(message: string): void {
            switch (this.LogLevel) {

                case LogLevel.Information:
                    console.info(message);
                    break;

                case LogLevel.Error:
                    console.error(message);
                    break;

                case LogLevel.Warning:
                    console.warn(message);
                    break;

            }
        }
    }


}


The Javascript generated from the Logger.ts TypeScript file is:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var App;
(function (App) {
    (function (Util) {
        /// 
        /// 
        /// 
        // Module App.Util.Loggers
        (function (Loggers) {
            (function (LogLevel) {
                LogLevel[LogLevel["Information"] = 0] = "Information";
                LogLevel[LogLevel["Warning"] = 1] = "Warning";
                LogLevel[LogLevel["Error"] = 2] = "Error";
            })(Loggers.LogLevel || (Loggers.LogLevel = {}));
            var LogLevel = Loggers.LogLevel;

            var BaseLogger = (function () {
                function BaseLogger(logLevel) {
                    this.LogLevel = logLevel;
                }
                Object.defineProperty(BaseLogger.prototype, "LogLevel", {
                    get: function () {
                        return this.logLevel;
                    },
                    set: function (logLevel) {
                        if (this.logLevel != logLevel) {
                            this.logLevel = logLevel;
                        }
                    },
                    enumerable: true,
                    configurable: true
                });

                return BaseLogger;
            })();
            Loggers.BaseLogger = BaseLogger;

            // Class DialogLogger
            var DialogLogger = (function (_super) {
                __extends(DialogLogger, _super);
                function DialogLogger(logLevel, anchorId, modal) {
                    _super.call(this, logLevel);
                    this.AnchorId = anchorId;
                    this.Modal = modal;
                }
                DialogLogger.prototype.Log = function (message) {
                    var dialog = $("#" + this.AnchorId).dialog({
                        title: message,
                        buttons: {
                            Ok: function () {
                                $(this).dialog("close");
                            }
                        },
                        modal: this.Modal
                    });

                    switch (this.LogLevel) {
                        case LogLevel.Information:
                            dialog.parent().addClass("ui-icon-information");
                            break;

                        case LogLevel.Error:
                            dialog.parent().addClass("ui-state-error");
                            break;

                        case LogLevel.Warning:
                            dialog.parent().addClass("ui-state-warning");
                            break;
                    }
                };

                Object.defineProperty(DialogLogger.prototype, "AnchorId", {
                    get: function () {
                        return this.anchorId;
                    },
                    set: function (anchorId) {
                        if (this.anchorId != anchorId) {
                            this.anchorId = anchorId;
                        }
                    },
                    enumerable: true,
                    configurable: true
                });


                Object.defineProperty(DialogLogger.prototype, "Modal", {
                    get: function () {
                        return this.modal;
                    },
                    set: function (modal) {
                        if (this.modal != modal) {
                            this.modal = modal;
                        }
                    },
                    enumerable: true,
                    configurable: true
                });

                return DialogLogger;
            })(BaseLogger);
            Loggers.DialogLogger = DialogLogger;

            //Class ToasterLogger
            var ToasterLogger = (function (_super) {
                __extends(ToasterLogger, _super);
                function ToasterLogger(logLevel) {
                    _super.call(this, logLevel);
                }
                ToasterLogger.prototype.Log = function (message) {
                    switch (this.LogLevel) {
                        case LogLevel.Information:
                            toastr.info(message);
                            break;

                        case LogLevel.Error:
                            toastr.error(message);
                            break;

                        case LogLevel.Warning:
                            toastr.warning(message);
                            break;
                    }
                };
                return ToasterLogger;
            })(BaseLogger);
            Loggers.ToasterLogger = ToasterLogger;

            //Class ConsoleLogger
            var ConsoleLogger = (function (_super) {
                __extends(ConsoleLogger, _super);
                function ConsoleLogger(logLevel) {
                    _super.call(this, logLevel);
                }
                ConsoleLogger.prototype.Log = function (message) {
                    switch (this.LogLevel) {
                        case LogLevel.Information:
                            console.info(message);
                            break;

                        case LogLevel.Error:
                            console.error(message);
                            break;

                        case LogLevel.Warning:
                            console.warn(message);
                            break;
                    }
                };
                return ConsoleLogger;
            })(BaseLogger);
            Loggers.ConsoleLogger = ConsoleLogger;
        })(Util.Loggers || (Util.Loggers = {}));
        var Loggers = Util.Loggers;
    })(App.Util || (App.Util = {}));
    var Util = App.Util;
})(App || (App = {}));
//@ sourceMappingURL=Logger.js.map

As noted before, TypeScript generates this Javascript file and can also create a minified Version, in addition a sourceMappingURL is also set to give the Javascript file(s) a source map, so we can debug the TypeScript file. You edit the .ts file and edit the .ts file. TypeScript in other ways lets you work in a higher level Language than Javascript to let you work with more familiar code and also adds compilation type level safety and checking. Whenever you edit and save the .ts file, the generation of a .js, js.min and js.map files are done. Note that this can take some seconds when you work in the IDE. I expect future versions of TypeScript to have a quicker compiler. I have used TypeScript 0.9.1 in this example.

I test out the Logger.ts TypeScript file above with the following HTML:
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>TypeScript HTML App</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="app.js"></script>
    <link href="content/toastr.min.css" rel="stylesheet" />
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery-ui-1.10.3.min.js"></script>
    <link href="content/themes/base/jquery.ui.all.css" rel="stylesheet" />
    <script src="Scripts/toastr.min.js"></script>
    <script src="Scripts/Logger.js"></script>
</head>
<body>
    <h1>TypeScript Logging demo</h1>

    <script type="text/javascript">

        function consoleLogger() {
            var logger = new App.Util.Loggers.ConsoleLogger(App.Util.Loggers.LogLevel.Warning);
            logger.Log("Hello from console logger!"); 
        }

        function toastrLogger() {
            var logger = new App.Util.Loggers.ToasterLogger(App.Util.Loggers.LogLevel.Information);
            logger.Log("Hello from toastr logger!");
        }

        function dialogLogger() {
            var logger = new App.Util.Loggers.DialogLogger(App.Util.Loggers.LogLevel.Error, "dialog-message", true);
            logger.Log("Hello from dialog logger!");
        }

    </script>

    <div id="content">

        <input type="button" value="Test console logger" onclick="consoleLogger()" />

        <input type="button" value="Test toastr logger" onclick="toastrLogger()" />

        <input type="button" value="Test dialog logger" onclick="dialogLogger()" />

        <div id="dialog-message" style="display: none">
            <p>This dialog was launched by App.Util.Loggers.DialogLogger!</p>
        </div>

    </div>

</body>
</html>
As you can see from the TypeScript code above, we generated Javascript where one BaseLogger class was inherited three times. We used the high level constructs of TypeScript such as:
  • class - Ability to defined a class/closure,container in TypeScript
  • module - Ability to create a module (internal in this case) that can assemble a collection of classes, Interfaces, Methods/functions in a namespace like collection or closure/container. Note I set the module name and namespace App.Util.Logging.
  • export - Here we define the visible members of our module
  • Interface - Interfaces or code contracts are a new concept in TypeScript - for Javascript that is.
  • enums - Enums are supported in TypeScript!
  • implements - keyword to implement an Interface
  • constructor - constructors are supported in TypeScript (you can have a multiple overloads)
  • extends - defines which baseclass to inherit
  • super - calling the base class constructor - this is required for derived classes in TypeScript.


We also use some features in TypeScript here:

  • Access level identifiers - we can use public, private - even static
  • Strong typing - we define a function parameter to be for example of type string by suffixing the data type with a colon in between. This is removed from the generated Javascript, but it gives you compile time type checking and safety previously not available in Javascript except another Third party framework
  • Compile time error checking - When you type errors in the .ts file, the errors are actually listed in the Error List in Visual Studio.


The code above also uses TypeScript Type definition files, with the extension .d.ts. You can see that I have put a reference at the top of the TypeScript file. For internal modules, you use this technique. For external modules, you can use RequireJs to avoid adding the script references in the HTML file, with the AMD loader.

Boris Yankov has collected a large collection of d.ts files here:
https://github.com/borisyankov/DefinitelyTyped These are required files, such that TypeScript can understand and consume Third party Libraries within the Typescript .ts file. A positive side effect of this is compile level syntax checking and IntelliSense. Using Third party libraries for Javascript such as Jquery, KnockoutJs, Toastr and Jquery UI (plus a ton of others) have never been more easy to work with. We all know the difficulties around writing correct Javascript with correct casing, well now TypeScript will throw in a compiler clever enough to check that you write correct TypeScript and consume Third party Libraries correct for you. This will make an impact on how we code Javascript.

Does this mean that Javascript will be "hidden" under the covers of TypeScript? No, definitely a solid background in Javascript is always positive when it comes to web Client Development. But TypeScript will enable developers not conformtable with Javascript to write more Javascript. And in the end, this will help more developers create better and more scalable Javascript Applications. There is no need to write pure Javascript always, when TypeScript can let you structure your code in a more natural manner with traditional OOP Language. This will help developers becoming more productive, deliver functionality quicker and help the industry shift a little bit more towards Javascript. Douglas Crockford has often ridiculed parts of Javascript as being a bunch of bologny, but there are also The Good Parts. I will actually say that TypeScript should be such a good part. It is of course important that the Javascript generated from the TypeScript is correct. With Anders Hejlsberg at the core team, we have no reason to speculate that TypeScript is really a promising Javascript framework, coming soon to a developer box near you.

Note: I have also used EcmaScript 5 Properties in the sample above. IE 8 should support ES5, and newer browsers too. To support Ecmascript 5, edit the Project file and make sure you add ES5 as the version:

<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <TypeScriptTarget>ES5</TypeScriptTarget>
    <TypeScriptIncludeComments>true</TypeScriptIncludeComments>
    <TypeScriptSourceMap>true</TypeScriptSourceMap>
    <TypeScriptModuleKind>AMD</TypeScriptModuleKind>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)' == 'Release'">
    <TypeScriptTarget>ES5</TypeScriptTarget>
    <TypeScriptIncludeComments>false</TypeScriptIncludeComments>
    <TypeScriptSourceMap>false</TypeScriptSourceMap>
    <TypeScriptModuleKind>AMD</TypeScriptModuleKind>
  </PropertyGroup>

Note in the Project file above, I set the TypeScriptTarget to ES5, to support Ecmascript 5 properties. I think that one must also use Properties in TypeScript if your target audience can use it. It is, after all a more correct way of doing OOP.

I have worked some with Javascript, but often I work individually on projects with Javascript. Collaborating and sharing Javascript is often hard to do. The structured code of TypeScript will make it easier for more developers and large part of entire teams to work with and enhance Javascript frameworks. More work will be done on the clients and richer user experiences will be the result (RIAs). This was just an introduction to TypeScript, but I find it a very promising technology. If you want to play around with the source code above, I have packaged the solution in a ZIP file here:
TypeScriptLogger.zip

Happy coding with TypeScript! I suggest you watch the video where Anders Hejlsberg explains TypeScript on the TypeScript website. If you have access to Pluralsight, there is a 4 1/2 hour long video covering TypeScript fundamentals in quite a complete manner. I have watched this entire course and it is quite good.

Sunday 14 July 2013

MEF and Memory in MEF 2

MEF - or Managed Extensibility Framework - is Microsoft's official Inversion Of Control (IoC) and Dependency Injection (DI) framework. Although MEF is not a true DI container, it has a lot of features compared to many other IoC frameworks. However, MEF is often measured as a slow IoC framework in tests and therefore is not very tempting to use. MEF on the other side is readily available in .NET. If you use .NET 4.5, you will have access to MEF 2 features such as ExportFactory. The worst feature in MEF is arguable the way the IoC container disposes objects. If you have a nonshared Part or instance (i.e not a singleton, but a part you can instantiate multiple instances of), and this instance type implements IDisposable, most likely this object will not be disposed until the container is teared down. This is not a desired feature, as object instances will accumulate and memory consumption of your application using MEF will go up. With the aid of ExportFactory, we can be able to free up object instances on demand. Let's use the ServiceLocator to get our instances from ExportFactory. When you use ExportFactory, you call CreateExport(), which returns an ExportLifetimeContext<T>. This object can then be used to dispose the object. By disposing the ExportLifetimeContext<T>, the object that was created with the ExportFactory is truly disposed and released at the same time from the IoC, finally making it possible to gather with Garbage Collection (GC), in the end freeing up memory. The code for retrieving the object instance via an ExportFactory can look like this:

    [Export]
    public class ExportFactoryProvider<T>
    {

        [Import]
        public ExportFactory<T> Factory { get; set; }

    }

Let's test out this ExportFactoryProvider with service locator. First let's create a part we can test. Let's say we got a simple view model:

    [Export(typeof(ITestViewModel))] 
    public class TestViewModel : ITestViewModel, IDisposable
    {

        public void SayHello(string message)
        {
            Debug.WriteLine(string.Format("Hi {0}!", message));
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this); 
        }

        private void Dispose(bool p)
        {
            Console.WriteLine("Disposed TestViewModel");
        }

    }

We can then create an instance of the TestViewModel using ServiceLocator using this:

            var serviceFactory = ServiceLocator.Current.GetInstance<ExportFactoryProvider<ITestViewModel>>().Factory;

            var testViewModelExport = serviceFactory.CreateExport(); 
            MessageBox.Show("About to dispose an instance of ITestViewModel: ");

            testViewModelExport.Value.SayHello("Johnny");
            testViewModelExport.Dispose();

As you can see above, we must first use the ExportFactoryProvider, then call CreateExport, then use the Value property and then use the ExportLifetimeContext<T> to control the disposing of the object from the IoC container. But as you can see, we must do some juggling to keep a reference to the lifetime context and the instance itself. These two objects are inherently tied together. Let's create a generic class to keep them together.

    [Export]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    public class ExportFactoryInstantiator<T> : IPartImportsSatisfiedNotification
    {

        [Import]
        public ExportFactory<T> Factory { get; set; }

        public T Instance { get; private set; }

        private ExportLifetimeContext<T> lifeTime;

        public void OnImportsSatisfied()
        {
            lifeTime = Factory.CreateExport();
            Instance = lifeTime.Value;
        }

        public bool DisposeOnDemand()
        {
            if (lifeTime == null)
                return false;
            lifeTime.Dispose();
            return Instance == null; 
        }

    }

You can use the class above, ExportFactoryInstantiator to create NonShared parts (object instances) via ExportFactory and via the instance created access the Instance property to get to the actual object and use the method DisposeOnDemand, which returns true if the object was set to null during the execution of this method. You can also see that we use IPartImportsSatisfiedNotification to await the resolution.

            var anotherTestViewModel = ServiceLocator.Current.GetInstance<ExportFactoryInstantiator<ITestViewModel>>();
            anotherTestViewModel.Instance.SayHello("Bob");
            anotherTestViewModel.DisposeOnDemand(); 
Note that the instance now can be easily worked against. However, still it is a bit verbose, we can create a static method to help us with that:

        public static ExportFactoryInstantiator<T> ResolveViaExportFactory<T>()
        {
            return ServiceLocator.Current.GetInstance<ExportFactoryInstantiator<T>>();
        }

We have finally reduced the complexity of being able to dispose MEF parts on demand in our applications:

            var yetAnotherTestViewModel = ResolveViaExportFactory<ITestViewModel>();
            yetAnotherTestViewModel.Instance.SayHello("Joey");
            yetAnotherTestViewModel.DisposeOnDemand(); 

To sum up, MEF 2 provides a feature where we can now dispose parts from the container on demand. This is a great improvement and will reduce the issues around memory leaks substantially. If you have complex viewmodels, disposing a view model high up in the object graph will usually dispose all child view models, properties and so on and reduce memory usage. But always be careful when disposing objects from your container. You must be sure that the object will not be useful anymore. In this StackOverflow thread you can also see an example of how to use a Part only when you need it, inside a using block: Nicholas Blumhardt on using ServiceLocator and ExportFactory As you can see, I use Nicholas Blumhardt's code as a starting point and refine it a bit to reduce complexity and tie together the Instance and provide DisponseOnDemand method. You must yourself judge when to release a part, be it a view model or some other resource. The using block are handy when you are sure you do not need the instance more than temporarily. You should consider doing that instead of importing many parts to your view model. Yes, the object creation of your view models will be quicker and yes, the execution will in fact be slower because of the need to create imported parts on demand via ServiceLocator, but at the same time, your application will keep a very low memory profile. I haven't had the opportunity to test out the code above yet against production code, so do not use it in production without verifying its validity in for example Red Gate ANTS Memory Profiler and testing it. I would like to hear from other developers using MEF and have experienced its memory usage woes for more views about MEF. If you have also tips against efficiency and performance of MEF containers, please let us other MEF developers know.