So what is this – javascript

To the uninitiated this can be really confusing in JavaScript. Consider the following:


The code above logs this three times, but what is this?

The main source of confusion is a quirk of the language where depending on the invocation pattern this can be set to the global variable (e.g. window in a browser). But there are come other gotchas.

In the example above this is 3 different objects.

  • Window
  • ATest
  • Object

Function Invocation Patterns

In order to explain this we need to know what function invocation patterns are in JavaScript, of which there are 4.

  • method
  • function
  • constructor
  • apply/call

I’ve covered the first 3 above in my example


image In the method invocation patters, the method is called bare. Javascript assigns the global variable to this in this instance.


imageIn this constructor invocation pattern (i.e. new) this is assigned to the object getting created, ATest 


image In the function invocation pattern this is the enclosing type also, however this is just object in this case i.e. the object literal returned from ATest constructor.


I’m not covering this here but the Apply (and the call) invocation patterns basically let you set the value of this.

Note: Object Literal can be avoided in this example above as follows.
What we do is set the methods on this explicitly.



Angular.js .NET File Upload

In this post I’m going to show you how to upload a file using Angular.js on the client side and Asp WebApi on the back end.

Lets get started

Create you project in visual studio, and add your angular.js app controllers etc.

Interestingly enough I’ve already shown you how to do the server side over 2 years ago!
Crikey 2 years and I’m still writing about the same old stuff….. well not really, last time it was knockout, sliverlight and the likes, now it’s Angular.js’ turn.

Angular file upload, Nuget

In order to facilitate the process, we’re going to use a nuget package I like, see screenshot.


The beauty of this package is that its got shims for non html5 browsers (apparently there are a few hanging around still :-( )

To use this package you’ll need to include 2 scripts, file-upload-shim before angular.js and file-upload after.

Script Includes



Next add the input tag and add the ng-file-select directive





Add the upload module



Here i added the $upload factory to my controller

Controller function


Here I enumerate the files (should i wish to have multi select) then I upload each one by posting to my Web Api .net controller, I pass a little more information also as to the diff side, but that’s pretty much it.


Now even though I did show you the .net code before I’m going to show it again now, because as I mentioned I’m passing a little information as to the side the file I’m uploading represents.



Why Java Sucks ex colleague of mine sent me this link this morning.
Apparently I got associated with it, haha, yes at one time I used to shoot down java at every occurrence, this was most likely because I didn’t know it well enough at the time; now I just yawn a little and continue ;-)

Programming in C# after using Java


Enjoy the website! I did ;-)

To see the other side of the story have a look at some of the videos here

IDE’s and tools

I’ve gotten a few emails from last night’s post asking me why I’ve gone black (and will i go back?),, well you know what they say!

Btw: I’ve Visual Studio, IntelliJ and WebsStorm on black/dracula themes at the moment and a week on I’m kinda sold, the only big downside is when I switch to another app when in dark light (in bed for example) I hurt my eyes as they adjust.

Some people asked about the IDE as it wasn’t visual studio (nope, I’ve not written java in VS yet ;-) ) so I thought it would be interesting to share what tools and IDE’s I use.

As it happens I just rebuilt my OS last weekend so it’s all clear in my head, here goes:

Operating systems:

Windows 8.1 and Mac OS as the moment, I prefer Windows, but my Mac Book Air is by far my favourite hardware… conflict!! I am doing a project with a Raspberry Pi at the moment and between that and the Mac I’ve pretty much given up on DOS* in favour of powershell (simply because I can type linux commands)


  1. Visual Studio 2013 this is my favourite IDE, I’ve been using VS since the mid 90ies, mostly these days I use VS for C#, ASP, UML, Testing, Azure, most of my pet projects are Azure based.
  2. InetlliJ : I took me a while when I started learning Java to settle on IntelliJ, I went back and forth between that and eclipse for a while until I understood java and it’s eco system enough to set up my own projects. IntelliJ is just fantastic and the tooling is great (ideal for MSofties) and there is a certain degree of familiarity as Jetbrains the company behind is the company behind Resharper.
  3. WebStorm: This is another Ide from Jetbrains (they have a few good IDE’s js,java,php,objective-c, python etc, check them out), I use this mostly for non ASP web stuff (where I naturally use VS), it’s quite good.
  4. XCode: I’ve created a few iPhone app’s, I hit the curve learned objective-C and the libraries enough to get a few apps in the store and XCode was the vehicle, I’ve not used AppCode from jetbrains but I bet it’s good! The truth is I’ve not used XCode in about a year now I guess, the reason is that I’ve moved to Android myself and don’t have a iPhone any longer (and at least for the foreseeable future) so I’m not motivated enough to do any iOS coding on my free time.


File management

Total Commander by, I’ve been using this since 2001, I was previously using norton commander but when I changed company I no longer had access to that software so I found my beloved TotalCommander, this is without doubt one of the major reasons I prefer windows. (I must get off my bum and find a corresponding program for Mac as Finder is dreadful IMO.

XML and it’s cousins

Stylus studio: great for formatting xml and editing xml in tree and grid formats, generating xsd, debugging xlst etc, nice xpath support.

Idiot’s guide to Angular service vs factory

You won’t believe the amount on questions I’ve come across regarding the confusion between angular services factories and providers. This blog post attempts to help clarify same and get you started.

Which should I use?

Factory* if you don’t know this this is a good place to start.

Which is most powerful?


What’s the difference?

I’m not going to cover providers here so lets see the difference between services and factories.

The rhetoric

Service gets passed a function that’s considered to be a constructor, so you get back a new-ed constructor.
Factory gets passed a function which it invokes and returns the result.
A service is often used when you have 3rd party constructor function and want to use this.

Example1 – Same end result both ways


First lets show the view in all it’s glory, it’s quite simple just will display whatever x is.

Then the angular code


You can see that we don’t return anything! so think of this as a constructor function, so effectively angular will give us a new TestService and we can call the doSomething method on it, the output looks like this



Now let’s look at the same thing as a factory


What’s the difference? Well in this instance we are returning something! Angular will call new on the returned object and return it.

Ok I get it but

Show me a reason to prefer one over the other? Well lets say we want to pass some information to the service or factory, well given we have no control over angular creating our service we cannot pass any additional information! it just creates the function.

Factories on the other hand we get to return what we want! So we can return a function! Lets look at some code to make this easier to see


So now if we don’t change our controller we have a problem, because angular has just created f for us! Let’s see this in a debugger, we can clearly see that TestService is not an object but rather a function.


Now we need to modify our code to work, let’s do that.


So hopefully that’s helped you a little understand the difference.

Example 2

I’m working on a project at the moment and I’ve just created a backend REST webservice to manage user properties


as you can see I've got the basic REST HTTP verbs, GET,POST,PUT,DELETE, it’s done in Java, but could just as well be in .NET, node, php etc, it doesn’t matter, the basic premise of REST is that it just used what HTTP already gives us.

Now I want to be able to use this information in JavaScript, Angular itself exposes a $resource exactly for this scenario (read the docs there’s one or two simple steps needed to use it).


The important thing to notice is that we are returning something from our function, and we are passing parameters, therefore we cannot use a service in this scenario.

I hope this has clarified this situation for you, if so please drop me a line and let me know and I might cover providers also.
(comments are disabled until i get a better recapcha for all this spam I get when enabled).

Recursive Directives Angular.js

Another day, another post with me talking about something I barely know about. Today I’m going to show you my first second stab at a recursive Angular.js directive.

Let’s first have a look at the end goal (forgive the as of yet unfinished css and bad contrasting colors)

Basically we have a list of objects in the dependency tree, each of these in turn can contain a list of children.


Lets have a look at the JSON we are trying to represent



It’s pretty simple, each dependency can have children that are in fact themselves the very same object literal types.


I created two directives, one for the dependency and one for it’s children.




As seen from the screen clipping the directives are pretty simple, however I’d like to draw your attentions to the link function of the curve directive. The reason I had to do this is because on my first attempt I tried to just call the <dependencies  in the template itself with an angular ng-if, however angular.js just kept going into an infinite loop, so I added the children <ul> on the fly and $compiled them in (note: $compile is injected).

The templates for these widgets are pretty trivial (i could have in-lined with “template” but choose to use templateUrl as I much prefer this approach.

This template just creates a <ul> and then calls the other directive that creates the <li> entries.image

This template shows the <li> entries, remember that I $compile in any children in the directive, it also adds a good or bad class if necessary for styling.

I hope this helps someone should they also encounter the same problem I did with the infinite loop, I’m definitely not saying what is presented above is best practise as I’m relatively new to angular.js after hanging up my knockout.js belt (it was good while it lasted but angular is much more in line what what I need for SPA apps).

Be careful of deferred execution

Take the following code, if you have ReSharper installed you’ll be warned that there is possible multiple enumeration of your IEnumerable, this means that  Select will be repeated twice for everything in the array.image


One solution is to Enumerate one and immediately after the select by calling .ToArrayimage



Guava / Java

It’s not just C# that you need to be careful with, take the google java library Guava

image We don’t get the same nice warning in IntelliJ* yet the solution in this case is much the same.




If you’re from a MS background like me and doing any Java, then do yourself a favour and use IntelliJ, it’s much easier to use.

Efficiency Yield

Talking to an ex colleague of mine this evening about some use cases for yield, it’s quite a handy little keyword, i often use it for splitting a large collection into smaller ones (Chunk).



I was presented with another use for yield.

Take a third party API that takes an IEnumerable of objects that are expensive to create,





we can see that there is an early imageexit strategy so we may not need all items in the enumeration.





Now lets say we have 3 implementations of this interfaceimage

trivial i know, but assume we don’t know if they return null or not at compile time.



Now here’s a nice way of passing all of the above to a third party API and only incur the construction hit as and if when they get enumerated.


Using the trivial logic outlined here, ExpensiveFactoryC will never get constructed.

Enum on steroids – java

Hi was reviewing some java code this week and came across this wonderful way of establishing structured enums.


private enum ServerType {
https://server1:8001", "customservicesuser", "xzy"),
http://server2:8001", "customservicesuser", "xzy"),
http://server3:8001", "customservicesuser", "xzy"),
http://localhost:8001", "customservicesuser", "xzy");

        private String serverUrl;
        private String username;
        private String password;

        ServerType(String serverUrl, String username, String password) {
            this.serverUrl = serverUrl;
            this.username = username;
            this.password = password;

// Usage
        try {
            serverType = ServerType.valueOf(server);
        } catch (Exception e) {
            System.out.println("Unable to get the server info, options are: 
                DEV, TEST, PROD, LOCALHOST");


Garbage Collection in the JVM (1.6)

Hi guys,

I’ve found myself discussing garbage collecting in the JVM a few times this week and though I’d share this information with everyone that ever wondered how all this works.

Automatic Garbage Collection

Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and deleting the unused objects. An in-use object, means that some part of your program still maintains a pointer to that object. An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

In a programming language like C++, allocating and deallocating memory is a manual process. In other languages e.g. .net and Java, the process of deallocating memory is handled automatically by the garbage collector.

Basic Process


The first step in the process is called marking. This is the activity of marking what parts of memory have references and which have not.


The second part is removing unreferenced objects, The deletion can be normal or can also include compacting.

Stop the world

When a gc happens all the threads in the application are stopped in what is referenced to as a “Stop the world” event.

JVM Generations

Having to mark and compact all objects in the JVM is inefficient, as more and more objects are allocated the list of objects grows and grows leading to a longer GC time. Empirical analysis of applications has shown that most objects are short lived.


The Hotspot JDK is broken into the following generations.

  • Young
  • Old
  • Permanent





Note not all JDK’s have the same structureimage

In this post I’m referring the the SUN JDK6 only. I’ve not really used the JDK7 that much except for personal projects, but even that is different with the G1 (Garbage First) and JDK8 will be a game changer again…

Sun Hotspot

The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. Minor collections can be optimized assuming a high object mortality rate. A young generation full of dead objects is collected very quickly. Some surviving objects are aged and eventually move to the old generation.

The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection.

The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.

Classes may get collected (unloaded) if the JVM finds they are no longer needed and space may be needed for other classes. The permanent generation is included in a full garbage collection.

GC Process

In the simplest of terms:

  • New objects are allocated into the eden section of the heap. after the first GC if they are still referenced they are aged and moved to the S0.
  • On the next GC, any referenced objects in eden are moved into S1, also the objects in S0 if still referenced are aged and also moved to S1.
  • The process repeats alternating between S0 and S1 until the objects are aged enough to become eligible for the old age pension and are promoted into the tentured generation.


Show me the memory!

So enough talking, show me the money as Cuba Gooding once said ;-)

The simplest way to visualize the GC in operation is to open the %JAVA_HOME%\bin\jvisualvm

When you run it for the first time it will ask you to click OK to calibrate so do this.

You will need to go to Tools/Plugins/Available Plugins and choose VisualGC (i’ve it already installed hence you see in a different tab)


You can then double click on the java application you wish to profile (I chose Weblogic Application Server) and you can see the GC minor collections in progress.

Shows the WLS server starting up and the Eden space starting to fill.image

Shows the Survivorimage 1 getting the first aged references

Simagehows the minor GC’s and the alternating between S0 and S1

Shows aged survivors getting their old age pensionimage

You can look at the monitor tab to get some more diagnostics,
Number of threads / Classes etc

image You can see what types of objects are holding memoryimage


Another tool I recommend when instrumenting applications is not only will you get JVM stats, but you’ll get so, so, so, sooo much more, you just have to use it to believe it.