How to avoid dependancies being compiled in TypeScript

You actually can’t do this (at the time of this post). But you can work around it.

The  Problem

Let me explain what I am talking about. When you use the typescript compiler (tsc or use any extension of it such as the grunt-typescript), when you specify a set of .ts files to be compiled to a specific destination, tsc would compile the given files as expected. However if you have references in the list of .ts files to other .ts files that are not include in the given list of files, the files that were not included also will get compiled along with the given .ts files and placed relatively in the given destination path. There is no actual way to avoid this or restrict this when compiling.

This might sound like something you don’t need but as  your project grows you may need to restructure the project or do targeted compiling of only specific files, you can’t simply use a compiler switch to do this. A very good example is placing source and test files in different locations. Take the following structure (an outcome of my previous post). The app/ folder only contains .ts files. The test/ and www/script folders are expected to have the compiled .js


Now if you want to compile your scripts and your tests (from app) to go into two different locations (respectively www/script/ and test/), it’s not as simple as running two tsc commands with the related source and destination paths. Since the test files will reference the files in app/script/ the compiler will recompile the referenced files and place them in test/.

There are two ways to deal with this. For both of them you will need to use a workflow management tool like Grunt to make them work sensibly.

Using Declarations

One way to go is, to avoid referencing .ts files that are not within a compilation target. Instead generate definition files (.d.ts) and reference them. In our example case we have two compilation targets – app/script/ and app/test/. In this case we avoid referencing the .ts files in app/script/ within the test files in app/test/. Instead we generate .d.ts files for all .ts files in app/script/ and then reference them in the test files in app/test/.

This can be done with the compiler switch --declaration when using tsc. For grunt-typescript task you can use declaration: true option to do the same. So your Grunt workflow would look like.

  1. When writing your test files in app/test/ make sure to add the references to the source files as a .d.ts (not yet available) instead of .ts.
  2. Compileapp/script/ with the --declaration option which will generate the .d.ts files in the same location as the .ts files.
  3. Compile app/test/  to test/ .

Using similar relative paths

You can use a single compilation command/step which will compile all the files into relative paths. This however alone is not going to solve our problem in the above example. Lets look at how this works.

This time we use a single compile step targeting app/ and everything in there to www/ which will create www/script/ and www/test. This method does not duplicate the .js files, but it puts the test/ in the wrong place. We can fix this by adding two more steps into the workflow. Lets look at how our workflow is going to be when we use this approach.

  1. Compile app/  to www/  which will create both the script and test folders in the www/
  2. Use the grunt copy task to copy the www/test/ back to the root of the project.
  3. Use the grunt clean task to delete the www/test/ .

Of course you can be done with the first step if your source path and destination path are both relatively same. If you are able to structure you project in such way life will be quite easy for you.


These workarounds don’t solve bigger problems such as the need to compile only the files that are changing. This becomes a nightmare in very large code bases where you have workflow configured to watch and compile only file that are changing.

Hopefully TypeScript team will put in a sensible solution for this in future releases. If you would like to add something to this please post it in the comments.


TypeScript with Ionic and Yeoman

I wanted to get TypeScript working on an Ionic project that I am starting, but couldn’t find a decent resource that helps you get TypeScript working with Yeoman generated Ionic project. So I thought i’d put down a few steps that will be useful for anyone who might need it.

Environment Requirement

This post is only going to work for you if you are using the following tools/frameworks for the given purposes.

  1. Yeoman for scaffolding and Grunt for workflow/build automation. Honestly if you haven’t heard of these or tried these, you definitely should give it a try before starting your Ionic/Angular project (or for that matter, any JS/HTML project).
  2. TypeScript as your language. There is so much hype around TypeScript and ES6 right about now. Angular 2 supposedly is going to support TypeScript strongly and if you are starting a Angular project with 1.x, you should consider going with TypeScript and structure your code in such way that it can be easily ported to Angular 2 in time to come. (Hopefully I will be writing a series of posts on this).
  3. Ionic as the mobile development framework.
  4. Angular 1.x 

This post doesn’t cover the details of setting up the above but here are a set of things you will need to install to get started.

  1. NodeJS needs to be installed along with NPM.
  2. Install Yeoman tools as per this page using NPM.
  3. Install Cordova and Ionic as per the Ionic Documentation.
  4. Install the TypeScript compiler as per this page using NPM.

Create the Ionic Project with Yo

Once you have all this in place you need to use the generator-ionic generator to bootstrap your project. So lets first install the generator using NPM.

npm install -g generator-ionic

Once you have the generator globally installed, you can bootstrap your project folder. Start by creating the project folder, navigating into it and then use the generator to create the project. There will be few steps to let you customize the project.

yo ionic [app-name]

The newly created project structure will have all the files necessary to get started with your Ionic project. You can use the Grunt CLI commands to run, emulate, test and do other things as specified in the generator-ionic page.

Include TypeScript into the Workflow

Now that we have the Ionic project structure, we need to include the TypeScript compilation step into the Grunt workflow. First you are going to need the grunt-typscript Grunt plugin to do this.

npm install grunt-typescript --save-dev

Next we need to make changes to the newly created Gruntfile.js to include and configure the typescript task. First include the plugin by placing the following line in the file. You can put this line somewhere before the grunt.registerTask  statements.


Once thats done we need to include the configuration for the typescript task. This needs to be added into the grunt.initConfig block.

  typescript: {
      base: {
        src: ['<%= %>/<%= yeoman.scripts %>/{,*/}*.ts'],
        dest: '<%= yeoman.dist %>/<%= yeoman.scripts %>/',
        options: {
          target: 'es5',
          sourceMap: true
      test: {
        src: ['<%= yeoman.test %>/spec/{,*/}*.ts'],
        options: {
          target: 'es5',
          sourceMap: true

The configuration contains two parts, one for the main code and one for the test code. As you can see the (defined in the same grunt.initConfig block) is accessed to get the correct paths for the source and distribution. This configuration will compile all .ts files in the source path (in this case the app folder) and move the resulting .js and .map.js files to the distribution path (in this case the www folder). You can do similar configuration for the test code (currently compiles into the same path). All other available configuration are defined in the grunt-typscript page.

Next we need to add few more lines into the watch configuration (again in grunt.initConfig) to ensure the .ts file changes will run the typescript compiler on those files.

  watch: {
      ts: {
        files: ['<%= %>/<%= yeoman.scripts %>/{,*/}*.ts'],
        tasks: ['typescript']
      tsTest: {
        files: ['<%= yeoman.test %>/spec/{,*/}*.ts'],
        tasks: ['typescript:test']

Now to the most important part – to include the typescript task into the workflow. You can simply do this by including it in the init task next to the clean step. This pretty much includes in all workflow commands defined in this particular Gruntfile.

  grunt.registerTask('init', [

Similarly you can include the test file compilation into the test task.

 grunt.registerTask('test', [

We are just not yet done though. In the original Gruntfile.js that was created, there is a task to copy all files from the source folder to the distribution folder. When we included the typescript task that moves the .js files, the copy task became redundant for the scripts folder. We need to fix this by excluding the scripts folder. Once you make the change your config should look like this.

  copy: {
      app: {
        expand: true,
        cwd: '<%= %>',
        dest: '<%= yeoman.dist %>/',
        src: [
          '!<%= yeoman.scripts %>/**',

As you can see we have also made sure that no .ts or .d.ts files are copied to the distribution folder as well.

Now you can go ahead and create .ts files in your scripts folder. However to compile them successfully we need to do one more thing.

TypeScript Definitions for JS libraries

Though we are writing our new code in TypeScript, most of the framework code such as Angular and Ionic are written in JavaScript. The TypeScript compiler wont be able to recognize the symbols and resources we use which are from the JS libraries. Don’t panic – we have bunch of awesome people who have created us DefinitelyTyped just for this reason. It’s a repository of TypeScript definition files for the popular JavaScript frameworks and libraries.

We need to include the TypeScript definitions for Angular, Ionic and Cordova for us to be able to use them. We don’t want to go ahead and include all DefinitelyTyped definitions, instead they themselves provide this handy tool TSD which will let you add definitions (just like NPM or Bower packages). Are we living in an awesome time or what?!

Lets first install TSD using NPM

npm install tsd -g

Now while you are in your project folder initialize TSD in your project by issuing the following command. This will create a tsd.json file where you can save all the definitions you install for later reinstall (just like NPM).

tsd init

The tsd.json file also contains the path you want to store the definition files. I would suggest putting them into your source scripts folder to fit our above configuration. In this example we have created a folder named typings.

  "path": "app/scripts/typings",
  "bundle": "app/scripts/typings/tsd.d.ts",

Now lets install the definitions we need for the ionic project by running the following commands.

tsd install angularjs --save
tsd install cordova --save
tsd install cordova-ionic --save

Once you run these you would notice that the typings folder we created now contains all the .d.ts files. Now all you need to do is create references to these files to get your project compiled.

For this purpose you can create a _references.ts declaration source file to include all references. Something like this.

/// <reference path='typings/angularjs/angular.d.ts' />
/// <reference path='typings/jquery/jquery.d.ts' />
/// <reference path='typings/cordova/cordova.d.ts' />
/// <reference path='typings/cordova-ionic/cordova-ionic.d.ts' />


Hope this helped and please let me know if you find anything that I have not covered here.

Using WDS to create a Wireless Bridge/Repeater

The term WDS (Wireless Distribution System) might be a familiar one if you have meddled with standard wifi routers/access points that are available nowadays. The concept is quite simple – the system enables the router/access point to act as a bridge or a repeater. Now as simple as it may sound, trying to get WDS working to extend your wifi network or to bridge your wifi to a wired network is not considered nearly as easy as it sounds.

It all started when I wanted to extend my home wifi network to the living room where I have my NAS and an Android based device running XBMC, both of which don’t have wifi capability. So I needed the wifi to be bridged to enable a wired network as well. Since the signal in the living room wasn’t great, extending the wifi made sense. What better than using one of the old routers I already had, to get this done right? So began the hunt for a hack. The more I looked on the internet I could not get a simple set of instructions which told me how to get this done. There were many articles elaborating on the concept like this one but nothing clearly said how to do it. Yet alone most of the discussions suggested the setting up WDS was most unlikely under many different conditions.

I had to give it a shot. So I took out three different models of the old routers I had and started messing with them. Changing the settings on them and trying different levels of changes to get them working. It didn’t take long before I could get a elaborate setup working that utilized WDS. However this was quite tricky and I picked up a few things on the way. So here it goes.

Following tips are based on the assumption that two routers/access points are used to extend and bridge a wireless network. Both devices are expected to have WDS capability.

1. Set the IP of both devices in the same subnet

Set static IP’s for both devices which belong to the same subnet. If you set the main device (lets call it AP1) to have the IP, you can set the secondary device (lets call it AP2) to have the IP or something similar. In this case we will setup AP2 to extend the network from AP1.

2. Setup only one DHCP server

If you require a DHCP server in your network it should ideally be setup on AP1. Disable the DHCP server on AP2. If AP2 supports DHCP relay, you may want to switch that on. Once you’re done with the full setup, one DHCP server should be able to assign and manage IP’s for all devices in the network.

3. Enable wifi and set the SSID

Enable wifi on both AP1 and AP2. The SSID of both AP1 and AP2 can be same or different. This doesn’t really affect the WDS setup since WDS uses your BSSID (the MAC address) to identify the devices. This decision depends on how you want to identify your network. If you want the wifi repeating to be smooth and you actually want to see your whole network with one SSID then you set the same SSID on both AP1 and AP2. If you want to identify AP1 and AP2 separately then you would want to assign two different SSIDs. What I did was have different SSID’s when setting up the network and then once I was done I switched both AP’s to the same SSID.

4. Set your wifi security to WEP

Set the wifi security on both AP1 and AP2 to use WEP. Also set the authentication to Open Authentication with a 128bit encryption. The authentication keys on both APs must be exactly the same. It’s essential that all settings be exactly the same on both APs.

5. Other wifi settings

Like I said, successfully setting up WDS to work means matching the settings on both AP’s to work the exact same way. If you have problems in getting WDS to work this is one area you can explore and tweak. As a thumb rule avoid having settings that are not absolute and can change. What I mean here is settings that are set to “Auto” or set to a range of values from which the AP can decide to choose such as “802.11b/g/n”. Following are a few of wifi settings you have to look into.

  • Wifi Mode – The mode has to be same on both APs and must be an exact value which is either 802.11g or 802.11n. If all your devices and both the APs fully support 802.11n, you can go ahead with that. However if you have difficulties getting it to work you can switch to 802.11g which has a better chance of working
  • Channel – The channel has to be the same. Having the channel set to Auto is not going to work. You can use a tool to check which channels have the minimum interference in your environment and pick the best channel. Set the channel to the same value on both AP’s.
  • Transmit Power – This shouldn’t ideally affect, however having this set to 100% on both AP’s will let you achieve the best range.

6. Set the WDS settings

Enable WDS on both APs. Depending on the device rest of the settings can vary. It essentially boils down to assigning the MAC address/BSSID of the devices to one another in the WDS settings. So in the WDS settings of AP1, you will need to assign the BSSID of AP2 and in the WDS settings of AP2, you will need to assign the BSSID of AP1. Different devices allow you to do this in different ways. You might see one of the following methods in each of you AP’s WDS settings.

  1. You may have to select the SSID of the other AP from a list (upon scanning for available networks).
  2. You may have to select the SSID of the other AP from a list which will reveal the BSSID.
  3. You may have to type in the SSID of the other AP
  4. You may have to type in the BSSID of the other AP

If either of your AP’s use method 1 or similar, you may have to have different SSID’s for AP1 and AP2 to ensure you can select them.

7. Set the correct security settings for WDS

Some devices require you to select the wifi security settings when setting up WDS. If this is the case you will need to put in the exact same settings you did in tip 4.

8. Don’t keep the APs too close to each other

When you are setting up the APs try and keep them away from each other. Keeping the APs too close to each other can cause interference which may not let either of the APs to perform.

There may be other factors that matter when it comes to setting up your WDS which I would love to know about as well. If you do find any other tips that may be useful please write them in comments section. Hope this helps someone save some time 🙂

Drawing network diagrams can be quite helpful when setting up even a simple network. Creately can be a very useful tool for drawing network diagrams. Give it a shot, its free to use.

Gmail is sending me other peoples mail!!

I have been receiving few emails from a guy about some book order. First time I saw it naturally my thought was SPAM. However today when I go a message from the same guy I had a proper look at it since it was showing up on my “Primary” mailbox again. It actually is a mail that is supposed to go to some guy/girl who has the address “”. Now I own an email address which is pretty much the same but without the dot (.) in the middle. I have the mail forwarded from that particular account to my current email address.

It seems like this particular person has mailed someone about a book on the classified site The seller however when replied to the mail saying its not available it landed in my inbox. Today I got another reply saying the book is available for $45. Now the craziest thing out of all this is that the to address of both of these mails show as “” which is not my email address.

I have just reported this to google and also forwarded the mail to the address that is supposed to receive it. Below is the email trail and the mail detail which shows the to address.

The mail trail:


The to address:


This is quite a scary thing to see! I sure hope my email is not lading in someone else’s mailbox!!


I think I was too soon to post this. As I searched I found the following article which clearly mentions that Gmail does not recognise dots(.). This clearly means that someone has misspelt their email address.

MySQL PDO for the default installation of PHP on Mac OSX

Quite a few times I have come across the problem of enabling the PDO drivers for MySQL on the Mac. I keep resolving this but every other time don’t remember how I did it. So I thought I’d write a about this so I can refer my own post when I need it 🙂

Initially the understanding that I had based on most of the posts and discussions around this topic is that the OSX does not contain the PDO drivers in it’s default PHP installation. Most solutions were talking about recompiling PHP with the PDO driver specifically for this purpose. But after much search I stumbled on this post which clearly mentions that the OSX Lion (10.7) ships with the PDO drivers by default. After playing around on Mountain Lion (10.8) I realised that this is the same case.

Initially when PHP is setup and working I was constantly getting the following PDO error

PDO::__construct(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock)

This lead me believe that the problem was actually with the PDO. However later I realised that the problem was lot simpler than it seemed. The actual sock file was missing as the error says and this can be found in your /tmp folder in the Mac (at least for the 10.7 and 10.8 versions of OSX). To resolve the issue all you have to do is

  1. Locate the php.ini file on your Mac (/etc/php.ini)
  2. Replace all instances of /var/mysql/mysql.sock to /tmp/mysql.sock
  3. Save the file and restart Apache.

Scaling BlazeDS with Servlet 3 (Concurrency)

One of the well known issues of BlazeDS is it’s limitation in scaling. To be more specific, if you are using BlazeDS for HTTP steaming using AMF, the number of concurrent streaming connections will be limited to 100s. The exact number would be dependent on multiple factors such as the capacity of the server and configuration settings on Tomcat or whatever the application server you are using. When it comes to streaming each connection would be opened and held until the client closes or the connection times out. In the case of BlazeDS this directly relates to the number of threads consumed due to how Servlets operate. Servlet consumes a thread per request and holds the thread until the request is committed. During streaming, a request is kept open throughout the streaming session which makes the servlet hold the thread through out. This particular problem cannot be solved with servlet 2.5 or before due to the limitation in Servlets itself. However Servlet 3.0 supports asynchronous requests which can be utilized efficiently to scale the same servers to support 1000s of concurrent connections.

Up to BlazeDS 4 there has not been support for endpoints that utilizes servlet 3.0. BlazeDS 4.0 turnkey ships with Tomcat 6 which uses servlet 2.5. There has been rumors that BlazeDS 4.5 will have endpoints that utilize the capability of Servlet 3.0. Still this is just a rumor and cannot be depended on. Given the current state of affairs and the growth of other frameworks and technologies I would not expect much. There have been solutions for the problem that uses various technologies and my picks are below.

  • MuleRTMP – A Google code project that uses the capabilities of Red5 streaming server and streams to AMF clients over RTMP.
  • A polling solution that uses Jetty 7 Continuations to provide an endpoint for BlazeDS
  • The Farata Systems’ solution which uses again Jetty 7 and Servelet 3 to provide a streaming endpoint for BlazeDS.
  • blazeds-servlet3-support – Another Google Code project that is a simple BlazeDS streaming endpoint that utilizes Servlet 3.

I have been personally working on the blazeds-servlet3-support project by contributing code. Right now the code looks quite messy but it works. I had to fix some of the issues and currently it is able to reliably stream messages on Tomcat 7 without causing any trouble. What this does is simply utilize the Async capability of Servlet 3 to isolate all the pushing functions into one single thread. Requests are handled and then immediately the Context of the request is handed to a the pushing thread, enabling the thread that handled the request to complete and return to the pool. This approach pretty much would allow your same server that was limited to 100s of connections to boost up to 1000s of connections. This is however not tested yet and will be done once I have completed work on the endpoint. I will run some load tests and post it up. If you wish to give this a test run here is what you need to do.

  1. Install Tomcat 7 and Blaze DS 4. The turnkey install of BlazeDS 4 is not going to work since it ships with Tomcat 6.
  2. Once you have Tomcat and BlazeDS working fine, change the Tomcat Connector configuration to use the NIO connector instead of the BIO conntector. The setting is in the server.xmland should be changed as follows.
    <!--<Connector port="8400" protocol="HTTP/1.1"
     connectionTimeout="20000" redirectPort="8443"/>-->
    <Connector connectionTimeout="20000" port="8400" 
     protocol="org.apache.coyote.http11.Http11NioProtocol" redirectPort="8443"/>
  3. In your Tomcat BlazeDS application context change the Servlet configuration to allow asynchronous capability for the MessageBrokerServlet. This should be done in the web.xml as follows.
  4. Copy the compiled blazeds-servlet3-support jar file to the WEB-INF/lib folder of the context.
  5. Change the WEB-INF/flex/service-config endpoint as follows.
    <channel-definition id="amf-stream" class="mx.messaging.channels.StreamingAMFChannel">
      <endpoint url="http://{}:{server.port}/{context.root}/messagebroker/streamingamf" 
  6. Restart Tomcat and you should be good to go!

Since I am continuing to work on this I would very much appreciate any feedback you might have. Please let me know your thoughts in the comments.

How to find the Curve Length in AS3

Recently when working on one of the features of Creately (an online collaborative diagram software) I had the need to calculate the curve length of a quadratic curve. The Flex/AS3 curves are quadratic (when you draw using the curveTo function of the Graphics class).The requirement I had was a pretty simple and straightforward one. However I didn’t find a simple straightforward piece of code that I could use to get this done. Of course there are frameworks such as Degrafa (an article on the topic) and Singularity libraries that allow you to achieve this very easily using those libraries itself. But if you are looking for just a function to get this done and not so worried about the accuracy of the calculation, the following should help. I’ve tried my best to explain this in the simplest for so that anyone can make use of it.

The most simple and naive method of calculating a curve length is to go through the curve in regular intervals and sum up the length of the line segments that are formed by the intervals. The accuracy of the curve length will vary by the frequency of the intervals. The higher the frequency the accurate and curve length would be, and the lower the frequency the more efficient your calculation will be. Depending on your requirement you can adjust the frequency when calculating the curve length. The following diagrams would further explain this (Please note that these diagrams are purely for the purpose of conceptualizing and are not accurate).

The above diagram explains the fundamental rule of a quadratic curve. Value t being a value between 0 and 1 can be used to find a point on the curve in relation to the full length of the curve. If t=0.5 (middle), the line interconnecting the middle point on line p1,cp and middle point of line cp,p2 will touch the the middle point of the curve at the middle of the formed line.

By deriving f number of regular intervals of t values (minimum being 1/f), we can form line segments along the curve that can be used to calculate the full length of  the curve. This can be done using the following two AS3 functions.

//Function that calculates the curve length
public function curveLength ( p1 : Point, p2 : Point, cp : Point,
	f : int ) : Number {

	var length : Number = 0;
	var step : Number = (1/f);
	var tx : Number;
	var lastPoint : Point;
	var curPoint : Point;

	for ( tx = step; tx < 1; tx += step ) {
		curPoint = interpolateCurve( p1, p2, cp, tx );
		if ( !lastPoint ) {
			length += Point.distance( p1, curPoint );
		} else {
			length += Point.distance( lastPoint, curPoint );
		lastPoint = curPoint;

	length += Point.distance( lastPoint, p2 );
	return length;

//Function to interpolate a curve on t
public function interpolateCurve ( p1 : Point, p2 : Point, cp : Point,
	t : Number ) : Point {

	var ret : Point;
	var x1 : Point = Point.interpolate( cp, p1, t );
	var x2 : Point = Point.interpolate( p2, cp, t );
	ret = Point.interpolate( x2, x1, t );

	return ret;

You can find a suitable f value for your purpose. To better understand this I have written a demo app that draws a given curve using both the above method and the Flex Graphics.curveTo method on top of each other. By setting different f values you can understand the difference between each curve visually. I have found 10-20 to be a decent value for f depending on the size of the curve. You can further play with this by downloading the below mxml file.

Download Curve Length Demo (Simply click on three points of the canvas to draw the curve )