Aurelia, NancyFX and Visual Studio Code

Having been a C, C++ and C# developer for several years, I’ve never really gotten into JavaScript for large projects. After all, you have to admit that having to do:

(function(){
    ...
})();

In order to work around JS scoping mess sucks. With ES6 (ES2015) and ES7 it seems that JS is finally cleaning up these (and other) legacy issues.

Some of the newer frameworks taking advantage the new JavaScript show promise and we may finally be able to build full stack web sites with reduced frustration. I’ve had a chance to explore Angular 2.0, React and Aurelia. Aurelia seems the cleanest thus far though React and Angular have a larger following. I figured there’d be enough documentation on how to set React/Angular elsewhere so I’d do one on Aurelia instead.

Also, while you can do lots of this stuff using the full blown Visual Studio, I’ve opted to use Visual Studio Code on MacOS. Everything here should work fine on Windows though here might be a few more setup steps to get the various tools used here properly running.

Tools

This article uses:
* Vistual Studio Code
* npm (part of NodeJS)
* DNX
* jspm
* yoeman
* grunt

Setup

You’re going to have to download and install the following to get going:

Once installed, you can add the following to your ~/.bash_profile

code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}

This is the MacOS equivalent to being able to launch VSCode by adding it to your windows PATH. In this case, by typing code . The rest of the setup is done in the command line.

Git Repo

Next, we can install the following as we need them but you can just as easily do so when you are ready to use the commands. On MacOS, you will have to prefix these with a sudo.

npm install jspm -g
npm install grunt -g
npm install yo -g

We’re now ready to set up a blank asp.net project. I usually set up a repo on GitHub or BitBucket first. Then go to your root Projects folder where you like to keep all your source and set up your project directory:

## Setup the folder
cd ~/Projects
mkdir aurelianancy
cd aurelianancy

## Initialize git
## Point to your git repo here. Mine's at github.com/nsainaney/aurelianancy.git 
git init
git remote add origin https://github.com/nsainaney/aurelianancy.git

## Setup a gitignore file
curl https://raw.githubusercontent.com/github/gitignore/master/Global/VisualStudioCode.gitignore -o .gitignore

## Launch VSCode
code .

Don't forget the period – it tells VSCode to launch with current directory as your workspace.

Nancy Setup

Next, we'll set up the Asp.Net Nancy project with yomen. Execute yo aspnet and you should see the following. Select Nancy ASP.NET Application and give it a name. I named mine AureliaNancy

     _-----_
    |       |    .--------------------------.
    |--(o)--|    |      Welcome to the      |
   `---------´   |   marvellous ASP.NET 5   |
    ( _´U`_ )    |        generator!        |
    /___A___\    '--------------------------'
     |  ~  |     
   __'.___.'__   
 ´   `  |° ´ Y ` 

? What type of application do you want to create? 
  Empty Application 
  Console Application 
  Web Application 
  Web Application Basic [without Membership and Authorization] 
  Web API Application 
❯ Nancy ASP.NET Application 
  Class Library 
  Unit test project 

You should now see an AureliaNancy folder in VSCode

Aurelia Folder Setup

Moving on, I'd like to organize my code with the following folder heirarchy:

AureliaNancy
|-- api
|--- HomeModule.cs
|-- wwwroot
|--- index.html
|- Startup.cs
|- project.json

Where the api folder will have the NancyModules and wwwroot will have my aurelia web files. We'll set up the routing later but first, let's set up the wwroot folder and I'm going to do this by also setting up Aurelia. For this, we use jspm install aurelia-framework with default values for everything except for the server baseURL:

cd AureliaNancy\
jspm install aurelia-framework

warn Running jspm globally, it is advisable to locally install jspm via npm install jspm --save-dev.

Package.json file does not exist, create it? [yes]:
Would you like jspm to prefix the jspm package.json properties under jspm? [yes]:
Enter server baseURL (public folder path) [./]:./wwwroot
Enter jspm packages folder [wwwroot/jspm_packages]:
Enter config file path [wwwroot/config.js]:
Configuration file wwwroot/config.js doesn't exist, create it? [yes]:
Enter client baseURL (public folder URL) [/]:
Do you wish to use a transpiler? [yes]:
Which ES6 transpiler would you like to use, Babel, TypeScript or Traceur? [babel]:

Then run jspm install aurelia-bootstrapper

At this point, you may want to add jspm_packages to your .gitignore. We can now create a static file index.html in the wwwroot folder

<html>
    <head>
    </head>
    <body>
        <h1>This is where Aurelia stuff will live</h1>
    </body>
</html>

OWIN Routing

Now we have to set up OWIN and the proper routing. For this, we first add dependancies to the project.json. We’ll need to add Microsoft.AspNet.StaticFiles and Microsoft.Framework.Runtime

{
    "dependencies": {
        "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta7",
        "Microsoft.AspNet.Owin": "1.0.0-beta7",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta7",
        "Microsoft.Framework.Runtime": "1.0.0-beta6",
        "Nancy": "1.2.0"
    },
    "commands": {
        "kestrel": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000"
    },
    "frameworks": {
        "dnx451": {}
    }
}

VSCode may prompt you to Restore nuget packages in order to download these dependancies. You can also just execute dnu restore in a command shell.

Now to get our routing set up in our Startup.cs:

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.StaticFiles;
using Nancy.Owin;

public class Startup
{        
    string WebRoot { get; set; }
    public Startup(IHostingEnvironment env)
    {
        // We can't use Server.MapPath so let's stash the WebRoot
        WebRoot = env.WebRootPath;
    }

    public void Configure(IApplicationBuilder app)
    {   
        var options = new FileServerOptions();
        options.EnableDefaultFiles = true;
        options.FileProvider = new PhysicalFileProvider(WebRoot + "/wwwroot");
        options.StaticFileOptions.FileProvider = options.FileProvider;
        options.StaticFileOptions.ServeUnknownFileTypes = true;
        options.DefaultFilesOptions.DefaultFileNames = new[] {"index.html"};
        app.UseFileServer(options);

        app.Map("/api", api=>{
            api.UseOwin(x => x.UseNancy());
        });            
    }
}

Now, if you launch the web server with dnx kestrel or Cmd-Shift-P kestrel, you should be able to navigate to http://localhost:5000 to view the static index.html and http://localhost:5000/api to see the “Hello World” from the HomeModule.

This is a great place to stop. You can now either set up AngularJS, React or Aurelia in the wwwroot folder.

References

Advertisements

Hitting the Product Sweet Spot

Getting a product out the door requires a tremendous amount of time, money and effort. There’s nothing worse than going through all that and then have little to no market adoption.

Unfortunately, there is no crystal ball when it comes to getting your product right. But there are a number of strategies at your disposal.

Imagine you are standing in a room where the other end of the room is pitch dark. Now also imagine there is a dartboard somewhere in the dark part of the room. This is a simple analogy to building products and hitting the illusive market bullseye. Each dart is costly. What are your options?

You could build one dart and hope to get lucky. Or, rather than building one expensive dart (I suppose darts have different aerodynamic properties based on shape and materials used), you could build a whole bunch of low cost darts and hope one of them hits the sweet spot.

You could do market research, but that’s like asking people who’ve wandered about in the darkness where they think the dartboard is.

Alternatively, you could do what the Lean Startup movement is all about: You build several low cost darts that have a light on each. And each time it lands in the dark side of the room, it illuminates a part of the wall so within a few darts, you can see the dartboard. If you’re having trouble with this analogy, the light on the dart is what user data analytics is all about and Google and many other companies take this approach.

Lastly, you could do what Apple does. You turn off the lights in your side of the room, drop some acid, put on some Dylan and wait till your eyes adjust to the darkness and are able to see the outline of the dartboard :). Few companies have mastered being able to see into the dark like Apple has.

My Core Coding Principles

Over the years, I have worked on and lead several development teams. The following core principles have helped guide me.

  1. Prime directive:  Let no one have cause to alter your code
  2. When meeting your manager/team lead/peer, be as prepared to tell them what you should be working on as they are
  3. If you spot bad or faulty code, find the person responsible and have them fix it or fix it yourself. Never scroll past bad code and think it’s someone else’s problem
  4. It doesn’t matter if some other part of the program is broken – if it’s broken, your product is broken and you are at cause. Take it personally
  5. Do not let your code cause other people’s code to break. Test, document and communicate
  6. Do not write code that, when you come back to months later, requires you to have to re-learn your thought process. Make your code self-evident. Otherwise, document/comment in detail
  7. Pay attention to what my change above or below your code in the architecture stack and code defensively – wherever possible, have code break at compile time instead of runtime
  8. Quality of code beats quantity of code any day. Bugs are a bigger measure of your skill level than late delivery
  9. If you have a gut feel that what you are coding is not good code/design. Stop and ask for a second opinion from a peer. Talk it out – never rush to completion
  10. Take effort to make your team aware of what areas of the product you are working on and what outcomes they can expect from your work instead of simply reporting timesheets
  11. Always be learning – share cool new concepts that you come across
  12. Take ownership of the product’s success even if someone else’s way of doing things prevails. It is after all, the sum of all our efforts

I hope they serve you as well. You may also wish to write down your own and share them with your team. Nothing is static in our ever changing field. I intend to review and update these from time to time.

AVG 8.0 and ZoneAlarm

I have been using AVG for anti-virus and ZoneAlarm as a personal firewall for many years now. Unfortunately, AVG started to inform me that some ZoneAlarm dll’s had been infected by “Trojan horse Agent_r.CX”. After some poking around, it was evident that this was a false positive. I have been having strange problems with ZoneAlarm (I seems to continue to prompt for things I’ve already granted permission to access the Internet with the “Remember” option checked), so I decided to try out another personal firewall: COMODO. So far so good…