Programming Windows 8: The Sublime To The Strange

Microsoft unveiled Windows 8 at the //build/ conference in September. Since then I've spent time seeing how to put together Windows 8 metro applications with HTML and JavaScript.

The Sublime

The following is all you need for a native Windows 8 Metro application.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Hello App</title>
</head>
<body>
    <h1>Hello!</h1>    
</body>
</html>

There are some other small administrative details, like a manifest file. And, the above application is plain looking without styles or colors, but it is a real, native Metro application. To the user, the product is indistinguishable from a Windows 8 application written in C++ or C#. In Windows 8, HTML (and its friends JavaScript and CSS) are first class citizens.

Contrast this model against other platforms whose creators tout the benefits of HTML 5, but provide second-rate support. Their users still demand native applications on those platforms because they can feel the difference between an application written in Objective-C or Java, and an application written in HTML, just like they can taste the difference between grandma's peach pie and a vacuum packed peach pie they bought from the bottom of a freezer bin in a convenience store.

The support for HTML 5 in Windows 8 is an impressive, bold move for Microsoft and also validates the capabilities of the new web specifications. When you build an HTML application in Windows 8 you can feel an amazing potential. Consider what web development would be like if we had flexible-box layout, grid layout, rounded borders, and box shadows 5 years ago. The gross domestic product of the planet would be measurably higher as developers and designers spent less time creating useless images, less time cursing three column layouts, and less time searching and hacking to vertically center text in a div.

CSS has a history of making easy things difficult (and that's without the troubles of IE6, 7, and 8), but all of the above scenarios are trivial with the new standards.

CSS animations and transitions are another pleasure to work with. Consider what's inside the following style rule:

.class
{
    transition: all 1s ease-in-out;                
}                    

That's pretty much all the code you need to add subtle, realistic animations to an otherwise herky-jerky effect. Contrast this against the mind numbering amount of namespace infested XML required by XAML for simple animations.

It's not all about CSS, though. There is scriptable video, bitmapped graphics, and vector graphics. There's WebWokers, WebStorage, and a NOSQL database built in. Everything you need, including all the APIs of the Windows Runtime - the same API available to C# and C++ applications - is available to JavaScript, and that's where this post reaches a turning point.

The Strange

Programming Windows 8 with HTML and CSS is a joy. Programming Windows 8 with JavaScript is . . . different. It's not that you can't use utility belt libraries like jQuery and Underscore – you can. You can even use a library like jQuery UI (but keep it mind that jQuery UI doesn't process touch events or produce touch-sized widgets, so it's not a good idea).

There was some other feeling that kept growing on me as I wrote code and browsed the samples. Code like the following (but don't read the code, just look at the shape):

js2_thumb3

The code is verbose. I don't mind verbosity, but noisy code is a pet peeve. The SDK samples for Windows 8 are noisy and often have consecutive lines of code stretching over 120+ columns. It looks like a wall of text.

wot7Nobody wants to read a wall of text, much less comprehend it, debug it, and maintain it.

This is a difficult problem, because the Windows Runtime API is expansive and will grow. Namespaces are required, but there is no automatic and simple "imports" or "using" in JavaScript. What we'll need is an automated refactoring operation. "I see you are using the Windows.ApplicationModel.DataTransfer.SendTarget namespace, would you like me to alias that to a module-scoped variable named wads?" Yes!

I also don't feel comfortable with the built-in declarative data binding.

<span data-win-bind="innerHTML: productName"></span>

This approach easily avoids all 'flash of unbound content' problems, but it feels significantly different from every other JavaScript templating technology. Navigation is also cumbersome and complex. I was expecting some template loading and a pushState API based on the new history specifications, like every other one page HTML application, but there appears to be an entire API designed around the concepts of fragments, navigation, and state, and I find it difficult to wrap my head around the magic.

There are some good points in the JavaScript code. Modern practices are in play with the module pattern appearing in the default project template. There is a nod to ECMAScript 5 with "use strict" in the module scope. And, with the Windows Runtime offering only non-blocking asynchronous APIs, it's good to see the Windows JavaScript libraries implement the CommonJS specification for a Promise. Promises remove noise by getting rid of the "continuation tail of curly braces". I'll save details of that topic for a future post.

The Summary

I'm impressed by Microsoft's implementation of the Windows Runtime, the bindings from the runtime to JavaScript, and the implementation of HTML, CSS, and JavaScript standards. Ironically, it makes me think more about the day when we are using all these new features to implement web applications (and finally retire support for obstinate, outdated browsers), and less about desktop development for Windows 8. Because …

I'm not 100% sold on Metro.

There are a couple challenges I see.

First, even though you are writing an application with HTML 5, CSS, and JavaScript, as soon as you take a dependency on Windows.Runtime you have at least some of your code tied to Windows. It's not a script you can send to anything but a Metro app on Windows 8. This in itself isn't a problem, because we can expect millions of machines to run Windows 8 in the future. But, right now the Metro sweet spot is tablets. All of the oversized, touch-optimized controls feel ridiculous when running on a desktop machine – it's a like drawing on high quality graph paper with crayons. Unless we get a way to put a Metro app in a Window, I think the success of Metro will depend entirely on Microsoft's success in the ultra-competitive tablet market. That's a wait and see game, and a game where many will hedge their bets.

Secondly, with regards to Metro and native HTML applications, I just don't see JavaScript programmers getting excited about the platform. I have flashbacks to the ASP.NET Control Toolkit when writing Metro code. It's heavy. It's noisy. It's a lot of ceremony surrounding little nuggets of essence. It's going to require some work to properly architect and design an application to hide the infrastructure details and promote maintainability.

Finally, on a personal note, the way the whole thing went down leaves me with a bit of a bad taste and a slight bias. For the last few years many people have been working hard at turning Microsoft into a "kindler, gentler" entity that listens to a wider community and addresses issues forthright. Then earlier this year came the "Silverlight is dead" whispers, followed an enforced silence, followed by more talk of dead platforms, followed by panicked customers followed by total silence. No, I haven't talked to anyone with a blue badge about this scenario, but I did have a mental imagine of Mafioso heavies roaming the halls of Redmond wielding clubs emblazoned with a Windows 8 team logo and holding people up against walls to demonstrate what might happen if they don't stay ... "on message".

And for what?

It's not that Metro is revolutionary. Metro primarily represents a shift in focus from the enterprise to the consumer. The languages, the development environment, the technologies – they've been with us for some time. You'll see many familiar controls and paradigms in Metro applications as it builds upon things we've been using for years (except in the case of the JavaScript libraries, where everything is written from scratch, and going through the Metro SDK samples you'd think the earth was devoid of any other JavaScript libraries that might possibly help build stuff for a web browser). It's the old Microsoft – the corporate giant that does everything right and doesn't need your help or feedback.

Hopefully that behavior was not a harbinger of things to come.

Getting Intrinsic HTML5 Video Dimensions

The HTML 5 DOM interface for a video element allows you to get the underlying video's width and height in pixels, but, be careful not to ask for the dimensions too early. If you ask as soon as the DOM is ready, like in the following code, you'll probably see width and height as 0.

$(function () {

    var video = $("#video").get(0);
    var width = video.videoWidth;
    var height = video.videoHeight;

    // ...
});

You'll want to wait for the video element to raise the loadedmetadata event before asking for the dimensions. The event is documented as firing when "the user agent has just determined the duration and dimensions of the media resource and the text tracks are ready".

Example:

$(function () {

    $("#video").bind("loadedmetadata", function () {
        var width = this.videoWidth;
        var height = this.videoHeight;
        // ...
        
    });

});

Composing Entity Framework Fluent Configurations

The canonical example for fluent configuration with the Entity Framework is to take a few simple entity definitions:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Version { get; protected set; }
}

... and configure them all inside of the DbContext's OnModelCreating method:

protected override void OnModelCreating(
    DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().ToTable("products");
    // ... more configuration

    base.OnModelCreating(modelBuilder);
}

This approach doesn't scale well as we add more entities, so let's try an alternate approach. We'll put the configuration for each entity into a distinct class.

public class ProductConfiguration : EntityTypeConfiguration<Product>
{
    public ProductConfiguration()
    {
        ToTable("products");            
        Property(p => p.Name).HasMaxLength(255);
        Property(p => p.Version)
            .IsConcurrencyToken()
            .IsRowVersion();
    }
}

Now model building is as simple as adding all the configuration objects into the model builder's configuration registrar.

protected override void OnModelCreating(
                            DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new ProductConfiguration());
    // ...  and so on, for each configuration class

    base.OnModelCreating(modelBuilder);
}

The new drawback is someone needs to instantiate every configuration object during OnModelCreating, which is a boring, silly, maintenance concern to worry about when things start to change. The next improvement is to automate this chore. 

Enter MEF

We can use reflection, or any decent composition / IoC container to find all of the  configuration classes in an application and hand them to us in a collection. It's easy to fall into a line of thinking that says we need this collection to be a collection of  EntityTypeConfiguration<TEntity>, because it's easy to picture the model building code like this:

foreach (var configuration in allConfigurations)
{
    modelBuilder.Configurations.Add(configuration);
}

It turns out this approach is not only limiting, it can also be difficult to pull off. Since the TEntity parameter in EntityTypeConfiguration<TEntity> will vary across all the entities, you either end up working with things like open generic types (EntityTypeConfiguration<>) or a closed type of EntityTypeConfiguration<object>. It's ugly and I'll spare you the details. Let's take a different approach that starts with an interface.

public interface IEntityConfiguration
{
    void AddConfiguration(ConfigurationRegistrar registrar);
}

And then a class that will collect (via MEF) all the objects that want to participate in the configuration of a context.

public class ContextConfiguration
{
    [ImportMany(typeof(IEntityConfiguration))]
    public IEnumerable<IEntityConfiguration> Configurations
    {
        get; set;
    }        
}

The individual configuration objects then get decorated with MEF export attributes and implement the IEntityConfiguration interface.

[Export(typeof(IEntityConfiguration))]
public class ProductConfiguration : 
    EntityTypeConfiguration<Product>,
    IEntityConfiguration
{
    public ProductConfiguration()
    {
        ToTable("products");   
        // ... more configuration         
    }

    public void AddConfiguration(ConfigurationRegistrar registrar)
    {
        registrar.Add(this);
    }
}

Then a brute force approach to model building might look like this:

protected override void OnModelCreating(
                            DbModelBuilder modelBuilder)
{
    var contextConfiguration = new ContextConfiguration();
    var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
    var container = new CompositionContainer(catalog);            
    container.ComposeParts(contextConfiguration);

    foreach (var configuration in 
        contextConfiguration.Configurations)
    {
        configuration.AddConfiguration(
            modelBuilder.Configurations);    
    }            
    base.OnModelCreating(modelBuilder);
}

With this approach the code inside OnModelCreating never has to change, even when new entity configurations appear in the application. Also, there are no messy type issues with generic parameters, and the relationship between model building and configurations is a bit more flexible (in a double-dispatch / visitor pattern kind of way).

Modernizr.js: Polyfills

In the last post we looked at feature detection with Modernizr. Before moving forward, let me answer a few questions that came up.

First, you can build a custom Modernizr download containing only the tests you care about when you visit  http://www.modernizr.com/download/. If you don't care about the geolocation APIs, then don't check the geolocation checkbox. The script file you download will be smaller, and more importantly there are fewer tests to run when the script hits the browser. Chances are good you will only care about a handful of the possible tests.

Secondly, Modernizr doesn't add any missing features to a browser. Modernizr only tests to see if specific features are available. The single exception is that Modernizr does create HTML 5 elements for older versions of IE. We looked at this capability in the first post of this series. Everything else is just a test. Modernizer can tell you if the geolocation API is available, or if it isn't. If the API is available you can use it. If the API is not available then you have a decision to make. Do you gracefully degrade the page and hide content that requires the user's location? Or, do you enter the world of polyfills and web shims?

eraseaholePolyfills

Polyfills are spackling paste for web browsers. They fill the holes left behind when a browser doesn't implement a feature. There are dozen of polyfills available, and some are more elaborate than others.  Ideally a polyfill API will mimic the real HTML 5 API so you can use a single codebase for all browsers, but this ideal scenario is not always possible.

Let's say, for example, that you want to use the geolocation API to display a user's current latitude and longitude. You might use something like the following:

navigator.geolocation.getCurrentPosition(
    onGeoSuccess, onGeoError);

function onGeoSuccess(position) {
    var display = $("#position").tmpl(position.coords);
    $("body").append(display);
}

function onGeoError(e) {            
    $("body").append(e.message);
}

And use the following template to display the result:

<script id="position" type="text/x-tmpl">
    <div>
        Latitude: ${latitude} Longitude: ${longitude}
    </div>
</script>

 

Now imagine someone with a new Kindle Fire comes to your website. The Fire's browser (Silk) doesn't support the geolocation API. You could discover this if you just ask Modernizr.

if (!Modernizr.geolocation) {
    // 
}

To support geolocation on browsers like Silk, you could use the Webshims Lib by Alexander Farkas. The WebShims lib includes scripts to polyfill not just geolocation features, but also ECMAScript 5 features, new HTML 5 inputs, canvas, and more. You just need to load the polyfiller.js bootstrapping code (which requires jQuery and Modernizr's script loader). 

<script src="jquery.js"></script>
<script src="modernizr-geo.js"></script>
<script src="polyfiller.js"></script>            
<script>
    $.webshims.polyfill();
</script>

 

The beauty of the geolocation polyfill is how the script lets you use the same API you would use when a browser natively implements geolocation – no code has to change! Of course, not all polyfills are as easy, but hopefully we won't have to live with them for more than a few more years. Or 5. Or 10 ...

Related

.NET Rocks – Scott Allen and Modernizr

Architectural Tragedy of the Commons

From Wikipedia:


The tragedy of the commons is a dilemma arising from the situation in which multiple individuals, acting independently and rationally consulting their own self-interest, will ultimately deplete a shared limited resource, even when it is clear that it is not in anyone's long-term interest for this to happen.

Some rights reserved by heyjoewhereyougoinwiththatguninyourhandIt might seem odd to take a term related to environmental issues and apply the term to software, but please allow some poetic license around the meaning of "shared limited resource".

The architecture and design of an existing application is a resource providing a benefit to the developers and operational people who have to build features in an application and keep it running in production. It's a limited resource since misuse will reduce the benefit for everyone.

"Architectural tragedy of the commons" is a term that jumped into my mind a few years ago as something that can happen (not always, but sometimes) when:

- developers build new features into a  product without talking to each other (individuals act in their own self interest.

- teams build new features for a product without coordinating (teams can act in their own self interest).

- companies go through developers like Netflix goes through business plans (in a body shop, nearly everyone acts in their own self interest).

You've probably worked on applications where shortcuts and hacks make a codebase fragile and inconsistent. Maybe you've even worked on products where the developers took shortcuts that made the application more difficult to deploy and operate (thus making the IT department's life miserable).  This are examples of what I'd call an architectural tragedy of the commons.

Tree-iconCommunication and leadership can commonly prevent an architectural tragedy of the commons, and often leads to sustainable design.

Modernizr.js : Feature Detection

As we saw in a previous post, Modernizr allows you to work with the new HTML 5 elements, like nav, and still support browsers that don't know anything about a nav, or HTML 5.

However, HTML 5 is more than just a few dozen semantically meaningful elements. There are WebSockets, WebWorkers, WebStorage, and a number of other features that are interesting from a programmability perspective (not to mention all new CSS3 capabilities). The questions is: how do you know if a specific user's browser supports a particular feature?

For years we've relied on browser sniffing (user agent sniffing) to determine browser capabilities, but user agent string are often manipulated, sometimes misleading, and constantly mutating. If you truly want to know if a browser supports a particular feature, like local storage, then the most honest answer you'll receive is by interrogating the browser directly with script.

In other words - if you truly want to know if a browser is a duck, then ask it to quack.

The Tests

When Modernizr loads, it executes a series of tests to see what features the environment supports. For example, here is the test for canvas capabilities:

tests['canvas'] = function() {
    var elem = document.createElement('canvas');
    return !!(elem.getContext && elem.getContext('2d'));
};

There are presently over 40 tests, from applicationcache to webworkers. The result of each test is made available on the Modernizr object for easy access from script. If you want to know if canvas is available, for example, you can just ask Modernizr.

if (Modernizr.canvas) {
    // do something canvasy
}

If you want to see all the available test results, try out my featureDump. This uses underscore and jQuery templates, excerpt below, to grab all the Modernizr test results.

$(function () {

    var featureMap =
        _(_.keys(Modernizr))
            .chain()
            .filter(noFunctionsOrPrivates)
            .map(toNameAndResult)
            .sortBy(name)
            .value();

    function noFunctionsOrPrivates(key) {
          return typeof Modernizr[key] !== "function" &&
                 key.substring(0, 1) !== "_";
    }

    function toNameAndResult(key) {
        return {
            "name": key,
            "result": Modernizr[key]
        };
    }

    function name(feature) {
        return feature.name;
    }

    $("#mainTable").tmpl({ "feature": featureMap })
                   .appendTo($("body"));
});                

The code should produce a table like the following:

image

CSS, Too

In addition to adding test results as properties to the Modernizr object, Modernizr also adds the test results as classes to the root html element. This is a technique used by several libraries to write CSS rules that apply to specific environments. In a live DOM explorer (what you get with Inspect Element in Chrome), you can see these classes. 

image

Notice that if a test passes, you get the test name (canvas). If a test fails, you get a "no-" prefix (as in no-touch). These classes are useful if you want to write CSS style rules that will only apply themselves to browsers that implement (or don't implement) a specific feature.

.no-cssgradients body {
    /* styles */
}

.cssgradients body {
    /* styles */
}

But – What If The Answer Is No?

If a browser does not implement a particular feature – you don't always have to give up. In a future post we'll look at how Modernizr's script loading capabilities can combine with polyfills to bring some old browsers up to speed.

ParallelLoopState and Parallel.ForEach

The Task Parallel Library is a joy to work with – it's easy to use and thorough. Recently I was using Parallel.ForEach to process a large collection, but wanted to stop processing early, across all threads, if an individual item met specific criteria. It's as easy as adding a ParallelLoopState parameter to the action body.

var result = Parallel.ForEach(messages, (message, loopState) =>
{                
    if (message.IsOneThatStopsProcessing)
    {
        loopState.Stop();
    }

    // ...
    // other processing
    // ...

    outputStack.Push(message);
});

You can halt processing early by calling either Break or Stop on the loop state parameter. Break is for ordered collection where you want to halt at a specific location.

Modernizr.js

modernizrModernizr.js is a little library that will help "modernize" old browsers.

As an example, let's say you create a new ASP.NET MVC 3 application with the "Use HTML 5 semantic markup" checkbox selected. If you peek into the layout view for the app, you'll find the following markup:

<nav>
    <ul id="menu">
        <li>@Html.ActionLink("Home", "Index", "Home")</li>
        <li>@Html.ActionLink("About", "About", "Home")</li>
    </ul>
</nav>

The nav element represents a section with navigation links, and is a new element in the HTML 5 spec. The idea is that using nav gives more meaning to the page, and allows user agents like screen readers to identify navigation information (contrast nav against using a regular div element as the container  - a div carries relatively no semantic value by itself).

There is a problem, however. Older versions of Internet Explorer (anything before version 9) do not recognize the nav element. IE refuses to apply style rules to unidentified elements, and will also not allow unidentified elements to have children in the DOM. If you have to support older versions of IE this will sound like a dire situation, but it turns out there is an easy solution.

HTML5 Shiv

You can "register" elements in IE using document.createElement. For example…

document.createElement("foo");

... is all you need to do for IE to apply style rules to <foo> elements, and construct them appropriately in the DOM. Years ago Remy Sharp created the html5shiv project, which was the first library to essentially execute createElement for all of the new HTML 5 elements, including nav, article, footer, header, etc. html5shiv then allows IE to recognize all HTML 5 elements. 

Modernizr also "registers" all HTML 5 elements, meaning the HTML 5 MVC web application you build will work just fine on older versions of IE (as long as you leave Modernizer in your layout view). One note: you'll want to keep the script tag for Modernizr inside the <head> element. All the calls to createElement for new elements must happen before IE reaches the <body> tag.

Enabling HTML 5 elements is just one of the features Modernizr provides. In future posts we'll look at Modernizr's ability to detect features, and inject fallback scripts.

Rise and Fall of Classic OOP

When I was making the switch from C and assembly to C++ I did quite a bit of reading on object oriented programming. It's hard to find material on OOP that doesn't praise the classical pillars of encapsulation, inheritance, and polymorphism. In the early years these three pillars were advertised as solution to all the ills of software development. Object oriented programming was my first "silver bullet" experience in the software industry.

Dr. Brumble's OOP Elixir!

OOP has been successful. The majority of the today's most popular programming languages support classical OOP techniques as first class language features. The techniques have even pushed their way into languages like Perl and PHP, and developers including myself have used OOP to build frameworks, applications, and libraries for desktops, devices, and the web.

So then, why did I recently debate an old friend about the decline of OOP?

The Application Framework Mirage

My friend is die hard OOP proponent. He recognizes some of the flaws in the classical OOP principle of inheritance, but for him OOP is the hammer for every nail. He proposed that the most successful UI frameworks he's ever used are all built using classic OOP principles, and therefore objects afford the most modular, reusable, and extensible software possible.

I had some time to think about this argument on a recent flight to Norway, and I think holding up frameworks like Swing and Silverlight (or to go back in time, MFC and OWL) isn't fair. You can always find places where a certain paradigm is the best solution, and for application frameworks in general, and UI frameworks in particular, OOP might have found a sweet spot. A sweet spot because UI frameworks represent an alternate reality. The architects and developers get to make the rules of the reality, and implement the code. Where else but in a UI framework can you find a workable inheritance hierarchy 9 layers deep?

It's not that UI frameworks don't face constraints. There are performance constraints, memory constraints, video constraints. Still, UI frameworks are far away from the messy (and sometimes absurd) realities of the physical world. It is the application code where IS-A relationships are difficult to find and break down quickly. It is application code where roles and responsibilities are difficult to classify and harden into code because domain knowledge can span decades and domain experts will evolve the rules with every passing fiscal quarter.

It's in application code where I've found, over the last few years, that modularization and reuse come about easier by going very big, or going very small. Big in the form of web services, where you can hide an entire platform behind well defined interfaces and standards. Small in the form of functions with well defined meanings, clean inputs and outputs, and nothing but a black box in-between.

Services, classes, functions!

Classes? They get stuck in the middle. There is no generally accepted standard even within a single programming language like C# on how to approach class design, or how to consume a class. Do I inherit from it? Create it with the constructor? Use a factory methods? Use a factory object? Call into the base class method override before I do my work? Or After? Too many choices make simple chores complicated.

To You, My Friend

Look again at the list of the most popular programming languages and see how many languages support more than a single paradigm. It's not that OOP has failed, or is failing. It's just easy to see the other choices now that the silver has worn off the bullet.

Execute<T> With IronRuby

Imagine (or dream) that you have some IronRuby code to execute.

require 'net/telnet'

host = Net::Telnet.new(:Host => 'localhost')

#...
#...
#...

return data

One way to execute the code and capture the result is to use Execute<T> on the ScriptEngine object.

public T Execute<T>(string fileName)
{
    var script = File.ReadAllText(fileName);
    var engine = IronRuby.Ruby.CreateEngine();
    engine.SetSearchPaths(
        SearchPaths // will contain paths like: 
        // @"C:\Program Files (x86)\IronRuby 1.1\Lib\ironruby" and
        // @"C:\Program Files (x86)\IronRuby 1.1\Lib\ruby\1.9.1"        
    );
    var result = engine.Execute<T>(script);
    return result;
}

However, if you want syntax checks and error messages with line numbers, you'll need to take a couple additional steps. First, define a class that derives from the abstract ErrorListener class in Microsoft.Scripting.Hosting. The ErrorReported method can provide details about errors.

public class ReportingErrorListener  : ErrorListener
{
    private readonly TextWriter _writer;

    public ReportingErrorListener(TextWriter writer)
    {
        _writer = writer;
    }

    public override void ErrorReported(
        ScriptSource source, string message, 
        SourceSpan span, int errorCode, 
        Severity severity)
    {
        _writer.WriteLine("Error starting at line {0} column {1}",
                           span.Start.Line, span.Start.Column);
        _writer.WriteLine(message);
    }
}

Now you can create a ScriptSource from the Ruby file, and use the ScriptSource object to Compile and Execute the result.

public T Execute<T>(string fileName)
{
    var engine = IronRuby.Ruby.CreateEngine();
    engine.SetSearchPaths(SearchPaths);
    var source = engine.CreateScriptSourceFromFile(fileName);
    source.Compile(new ReportingErrorListener(Console.Out));
    var result = source.Execute<T>();
    return result;
}