Saturday, July 6, 2013

Debugging AngularJS Source with WebStorm

The great thing about AngularJS is that it comes with a very full featured test suite. This means that you can use tests if you:

  • want to play around and try to add new features in AngularJS 
  • or try to understand AngularJS internals
This is my quick guide on the steps I had to carry out to debug the code I downloaded. I'll be using windows and webstorm. Some of these are pretty standard steps if you know nodejs + karma but should be helpful nonetheless. All commands should be run the from main AngularJS folder. The git root folder (whatever you want to call it). Not the src folder. In particular the folder where you have package.json , Gruntfile.js, karma-config-* files.

Get AngularJS source

Download (git clone) from https://github.com/angular/angular.js

Make sure you have NodeJS installed 


Install the pre requisite global NodeJS packages

You need grunt and karma. Pretty painless after you have node: 
npm install -g grunt
npm install -g karma 

Download AngularJS prerequisite NodeJS packages

Run:
npm install

from the main AngularJS folder. This will basically read package.json and download any prerequisites. 

Setup your CHROME_BIN

I have this environment variable pointing to my chrome.exe (not chrome canary).

Build Angular

Build AngularJS (required if you want to run the tests):
grunt build

Run the karma server

Simple command: 
karma start karma-modules.conf.js --no-single-run --auto-watch --reporters dots
This should start chrome + run the tests (module tests in this case as I ran karma-modules.conf.js) 

Leave this command (i.e. karma) running in the background.

Now setup debug environment in WebStorm

Create a new WebStorm project from your AngularJS folder. Edit your run configurations: 
(Don't mind that I already have debug karma setup, you will not). 

Add a remote debug config: 

Add set it up as follows. Call it whatever you want but url to open and remote url are important: 
http://localhost:9876/debug.html
http://localhost:9876/base


Great. Now set a breakpoint, Start debugging and watch the magic happen. 

Friday, July 5, 2013

Origin null is not allowed by Access-Control-Allow-Origin Chrome fix

When working on simple html prototypes that don't really need a backend server (Single page app prototypes). You often need to load html / js files from disk. This is disallowed for your protection by default and you will get errors like:

Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin. file:///D:/asdf.html
XMLHttpRequest cannot load file:///D:/asdf.html. Origin null is not allowed by Access-Control-Allow-Origin. 

Simple solution for chrome: Start with --allow-file-access-from-files option :

chrome --allow-file-access-from-files

Saturday, June 29, 2013

ASP.NET MVC Single checkbox generates two values

So a single checkbox:

Will generate two input fields in MVC CheckboxFor:

It is because the browser does not post a checkbox when the value is false. MVC takes this into account and creates a dummy field for the case when the checkbox is unchecked. So when the checkbox is checked you get ‘true,false’ instead of ‘true’

TryUpdateModel will take this all into account and work out the correct value for you.

The most awesome option in SourceTree

Rebase by default:


Thursday, June 27, 2013

AngularJS minification

Just downloaded angular source. Its no secret that AngularJS uses google closure tools. In case you are wondering how here is the grunt config:


This uses the custom grunt task as follows:

And the contents of the grunt task are just calling google closure compiler with proper arguments:


Sunday, June 9, 2013

Typescript: Indexer enforces property compliance

Here is a new thing I found about typescript 0.9Alpha. Once you specify a string indexer all other properties must be of the same type (which makes sense):

interface IBar{
    bar: string;
}

interface IFoo{
    a?: {
        [key: string]: IBar; // Once you have a string indexer all other properties
        options?: IBar;        // e.g Options, must have the same type
    }
}

var x: IFoo = {
    a: {        
        'someKey': {
            bar:'asdf' // put any thing other than a string here and you get an error
        }        
    }
}

Trying the Latest Version of TypeScript for Visual Studio

There is a blog post on the topic by the TypeScript team over at : http://blogs.msdn.com/b/typescript/archive/2013/01/29/trying-the-latest-typescript-build.aspx

However that was for TypeScript 0.8 and the path is different for TypeScript 0.9.

For Visual Studio Extension

To try out the latest built version of TypeScript, just copy the typescriptServices.js file from  the bin folder of the file you checkout from release-0.9.0 branch at  https://git01.codeplex.com/typescript over to:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript

Overwriting what was already there.


For the Compiler

Additionally you might want to replace the tsc.js and typescript.js files in the following location:

C:\Program Files (x86)\Microsoft SDKs\TypeScript

Again using the files in the bin folder of the repository. 

Friday, June 7, 2013

Why use semicolons in JavaScript

I always use semicolons even though they are optional in JavaScript. A key reason for me is convention and javascript minification (although closure compiler will rewrite your js with semicolons inserted). But if you want to know what else could go wrong even if you do not do minification there is actually only one case. When a line starts with `(` it should have a semicolon before it.

An Example

When you have an immediately executed function to create a new scope:

// define a function with assignment
var fn = function () {
   //...
} // semicolon missing at this line

// then execute some code inside a new scope
(function () {
    //...
})();

Will get interpreted as :

var fn = function () {
    //...
}(function () {
    //...
})();

The second function will fail with a "... is not a function" error at runtime.

Another example 

// careful: will break
a = b + c
(d + e).print()
// Will get interpreted as:
a = b + c(d + e).print();

Alternate Solution

 A potential solution if you want to be a cowboy and not use semicolons everywhere is to use a semicolon before ‘(‘:

; (d + e).print()

Its also potentially a good idea when your file starts with '(' since if someone (who does not use semicolons) does concatenation of your file it might become a problem. 

An example was from this answer: http://stackoverflow.com/a/1169596/390330

Thursday, June 6, 2013

Inspect all the event handlers on a DOM Element


Here’s how chrome Developer Tools make it super simple. Just inspect an element and look inside the Event Listeners section as shown:


Expand any event and you can see what element level the event is handled on e.g. here blur is handled on document as well as the div:

You can even jump to the function body (this is a minified file so it’s all on line 1) by clicking on the filename

As an aside: there is no way to do this in your own code http://stackoverflow.com/a/2623352/390330

Saturday, June 1, 2013

YouTube video url transformations

There are some really innovative ways that you can transform the youtube url quite easily. Here are a few

Just the video frame

Use /v/ 

Download YouTube Video

Provided by a third party (save from). Add ss after www.

Tuesday, May 28, 2013

Trick question : Closures in Javascript

Closures are one of the most powerful features of the Javascript language. If there is one thing that makes JS so versatile, it has to be closures. But they can be tricky if you do not understand:
  1. Closures capture the variable not just its value.
  2. Scope only changes using functions in Javascript.
So the question, What does the following code print:

var funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

The intuitive answer is 0,1,2,3…9 . However that is not the case. This is because each function in setup captured the variable i and not its value. When the for loop finished the variable i has a value 10 and therefore all functions print out 10. You now understand what (1) means. 

Now let’s make these functions print 0,1,2,3…9. The solution would be to create a new variable within the scope of the for loop so that each function gets a new variable. Now the only way to create a new scope is using a function (2). Lets say you don't know this and try the following which will not work. It will print 9 instead of 10 however since that is the last value that gets assigned to foo:

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    var foo = i;
    funcs.push(function () {
        console.log(foo)
    });
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

To fix this we use the concept of immediately executing functions i.e. we declare a function (to create a new scope) and immediately execute it (to fall into that scope). The following will work. :

// Clear
funcs = [];
// Setup
for (var i = 0 ; i < 10 ; i++) {
    (function () {
        var foo = i;
        funcs.push(function () {
            console.log(foo)
        });
    })();
}
// Call
for (var j = 0 ; j < funcs.length ; j++) {
    funcs[j]();
}

You now understand (2). You can find the code here : http://jsfiddle.net/basarat/U9brW/

As a aside you might think the following is a good idea (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {       
    funcs.push(function () {
        var foo = i;
        console.log(foo)
    });   
}

But it’s actually no different than (will not work as expected):

// Setup
for (var i = 0 ; i < 10 ; i++) {
    funcs.push(function () { console.log(i) });
}

Because the only variable that is captured by the function is still i from the outer scope.

Monday, May 27, 2013

Using Actions to clean up your code

I am a firm believer of DRY “If you are doing the same thing thrice, you are doing it wrong” . Within reasonable effort ofcourse.

So when I see code like this:

List<string> permissions = new List<string>();
// The ones we care about:
if (Session.HasPermissions(Permission.AdministrationSetPoints))
{
    permissions.Add(Permission.AdministrationSetPoints.ToString());
}
if (Session.HasPermissions(Permission.Administration))
{
    permissions.Add(Permission.Administration.ToString());
}

There is no wonder that I want there to be a function to abstract out the if conditions. But creating a new function at class level looks a bit dirty. Not only do you have a new function that is only called from one place but you need to pass in a ref argument (permissions list). Later on its unclear at first sight (without reading xml comments perhaps) why this new function was created. Additional constraints like making sure your private functions are at the end may increase the distance between your original function and this new function. 

Lucky for us C# 3.0 gave us an excellent solution with inline lambdas:

List<string> permissions = new List<string>();

Action<Permission> addPermission = (Permission p) =>
    {
        if(Session.HasPermissions(p))
            permissions.Add(p.ToString());                   
    };
           
// The ones we care about:
addPermission(Permission.AdministrationSetPoints);
addPermission(Permission.Administration);

Notice that:
  • the action (addPermission) does not need to be passed in the permissions object since the outer scope variable is available.
  • The function is declared closer to where it is used and you can tell at first look why it was created.


To be honest. For this I was inspired by JavaScript closures.

Thursday, May 23, 2013

Add Existing Item as Link in Visual Studio


It is a feature that is used very commonly for code sharing between project. But I could not find good screenshots to show someone so here they are.

Right lick project folder and select Add - Existing Item:


Now select your file and choose “Add As Link”


An additional useful option is Copy if newer:

Wednesday, May 22, 2013

Setup maxlength for strings in ASP.NET MVC

String length is an attribute available in the System.ComponentModel.DataAnnotations; namespace for your viewmodels. It sets up validation for max length e.g:

[StringLength(100, ErrorMessage = "Length must be less than or equal to 100")]

In html this will warn the user if the length exceeds 100. But if you want the html input to disallow the user to even type more than 100 characters then that functionality is not provided out of the box. You can use the attribute added to the html tag because of StringLength ie. data-val-length-max to add the maxlength attribute using one line of jquery:

$('[data-val-length-max]').each(function () { $(this).attr("maxlength", $(this).attr('data-val-length-max')); });

The maxlength attribute prevents the user from entering more characters than are allowed. This one line does it for all inputs that have this attribute setup in a view. 

Sunday, May 19, 2013

AngularJS + RequireJS

TypeScript has excellent support for AMD / RequireJS and you can see that over here

http://www.youtube.com/watch?v=4AGQpv0MKsA

Now that I am working on throwing AngularJS into the mix it feels a bit awkward to integrate AngularJS / RequireJS / TypeScript.

I've done it before and infact this presentation uses all three:
http://basarat.github.io/TypeScriptDeepDive/
It provides a great sample for you to experiment with if you need to (based on RequireJS + AngularJS seed project https://github.com/tnajdek/angular-requirejs-seed)

It becomes a lot less relevant when you do your bundling and minification on the server e.g. http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification . Let me explain.

There are two reasons behind organization of your script files.

First: 

Items that are declared in the global namespace are available before they are used.
e.g. $ should be available before your code runs e.g. even the init: 
Or for that matter angular should be available before you go on creating your modules. This is the area where RequireJS is still relevant when you use AngularJS. This is the area that can also be solved by ordering in your JS bundles.

Second:

Functions declared are called in order. AngularJS does this inherantly. Any module declaration / service declaration / scope declarations are just declarations. These are executed depending upon the order they are defined as a dependency. e.g

Directives controllers and services all get instantiated (using function calls) before the module gets instantiated. This is a region of overlap between RequireJS and AngularJS and if you are using Angular then RequireJS loses a bit of its charm.

Finally:

The final decision is of course up to you and you will have to make it for your project based on your requirements. If you are using a lot of script tags and don't have a server side alternative then yes, I feel requireJS is a must for you. Otherwise, not so much.

Additionally: 

The angular team itself depends on closure compiler to do its minification (confirmed fact) along with sourcemaps (my assumption) to do its debugging. So they can effectively use a single script tag since the ordering logic is maintained by the closure compiler. 





Saturday, May 11, 2013

NodeJS Debugging with WebStorm

WebStorm makes getting started with NodeJS a breeze. I made a short video tutorial to show this that you can check out on youtube http://www.youtube.com/watch?v=6bKsDoFj83o also embedded below:


Friday, May 10, 2013

Getting Started with NodeJS on Windows

NodeJS on windows has come a long way since the early days. Now windows is pretty much a first class citizen in node world. I did a quick video to show how to get started with NodeJS on windows:


Wednesday, May 8, 2013

TypeScript AMD with RequireJS

Using TypeScript files with RequireJS is incredibly simple. However using JS files that are not aware of RequireJS can be a bit tricky. Also mixing Typescript with JavaScript all along using RequireJS can use a bit more documentation. So ... I made a video. Check it out here: http://www.youtube.com/watch?v=4AGQpv0MKsA

Covers Using TypeScript with RequireJS, using a non RequireJS file with TypeScript when in the RequireJS mode and a RequireJS Module with TypeScript.

Sunday, May 5, 2013

Getting Started with GIT on Windows : SourceTree

Getting started with GIT on windows has never been easier thanks to the great folk at Atlassian that made SourceTree. That is the "ONLY" software you need to install. It is extremely straightforward but I thought I would take you through a screenshot tour anyways.

Note: I found no need to make any change in the program defaults. 
That is rare and shows the great work the developers have done. 

Start http://sourcetreeapp.com/

Launch:
Install:
Watch the installer be awesome and download all you need:

Enter your details. Configuring automatic line ending handling is really great for open source work since people can use Unix and Windows without hassling about line endings:
Leave Putty selected:

It will ask you for your putty files. Just click cancel if you don't have putty installed (I don't):
Click Finish:

When sourcetree starts it will ask you for a license. Don't worry, its free: 


Use Register Now and you will be all set: 

Now you are all setup to get cracking with git. Painless wasn't it? 

Load a repository from GitHub

Just copy the git https url of the repository: 
Click Clone in SourceTree: 
Paste in the URL, put in the destination and click clone: 

Watch the magic happen: 
And you are all set: 

Using git terminal

Source tree comes with git terminal integrated. I did not have to install any separate software to get this git awesomeness. Just click the terminal button and get cracking with bash awesomeness on windows: 

Further Reading: 

Saturday, May 4, 2013

Setting up duplicate view of image in Photoshop

When doing high quality color work this becomes sort of a necessity since my Dell U2711 color profile is simply awesome.

You can open a duplicate view of the same image using Window > Arrange > New window for as shown:


Then you can work directly on your lovely Cintiq and view the outcome on an even better monitor.

It also helps to give another perspective on what you working on.

Thursday, May 2, 2013

TypeScript Deep Dive

I recently gave an indepth advanced talk on TypeScript at Melbourne ALT.NET:
http://www.meetup.com/Melbourne-ALT-NET/events/115068682/

I had a lot of fun preparing the slides for this presentation. They are based on RevealJS / HTML. I addtionally strapped in TypeScript / Angular / RequireJS for my future talks.

You can find the slides here: https://github.com/basarat/TypeScriptDeepDive and I encourage you to use these in your own talks and contributions are appreciated.

Slides embedded here as well (click on slide to make active and press f to go fullscreen):

Sunday, April 28, 2013

Wacom Cintiq 22HD with Ergotron LX arm

I got a Cintiq 22HD for various reasons (after trying the 24HD touch). But I really wanted a more ergotronic drawing position, so I got the Ergotron LX arm. Here is a tutorial I wished I had when I was making the decision.

Here is my final setup for drawing:


How to Setup

Take the Cintiq off the stand and place on a cloth:

Unscrew the mount:
 Notice the black washer:
 Split the mount to take it off the cable:
 Move the cables down:
 And now open your ergotron lx box:

 Mount the Erogotron using the four provided screws:



Mount it on the desk:

 Put the tablet on the desk mount:
 And you are golden:
 I prefer to have to dropped all the way down for added stability:
 Use as dual monitors:

 Later on I decided to remove the extension for even more stability and added desk space:



And we are in business: