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?

Providers

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

Service

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

 
Then the angular code

image

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

image

Factory

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

image

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

image

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.

image

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

image  
image

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

image

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).

image

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)

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

JSON

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

image

 


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

Directives

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

image

 

 


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.
image


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

ToArray()

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.

image

 

*IntelliJ

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).

image

Efficiency

I was presented with another use for yield.

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

image

 

 

 


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.

image

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.

Code

//Declaration
private enum ServerType {
        DEV("
https://server1:8001", "customservicesuser", "xzy"),
        TEST("
http://server2:8001", "customservicesuser", "xzy"),
        PROD("
http://server3:8001", "customservicesuser", "xzy"),
        LOCALHOST("
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");
        }

Enjoy!

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

Marking

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.

Deletion

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.

Generations

The Hotspot JDK is broken into the following generations.

  • Young
  • Old
  • Permanent

image

 

 

 

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)

image 

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

NewRelic

Another tool I recommend when instrumenting applications is NewRelic.com 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.

BOOM! Bye bye iPhone, again…

So I’ve splashed out the 600euro and got me a SIM free Samsung Galaxy S4 Android phone.

Why?

Well I find myself doing more and more JAVA these days (as if I wasn’t busy enough keeping up to speed on .NET and iOS too) and I’ll admit it’s starting to win a place in my heart, not the language as such as it’s IMO inferior to C#, but the framework has lots little gems, there are some pretty nice external frameworks e.g. Drools, JBPM etc, and the application servers are interesting (I'm focusing mainly on JBoss AS7 these days); what I’m trying to say is that I’m starting to feel that Android may be a home away from home.

Flirtations

Well I’ve previously two timed my iPhone with a Windows Phone 7, this lasted for about 10 months before I moved back to iPhone, I guess one of the biggest reasons for doing this was I’d invested in a few iOS apps like the very expensive TomTom Worldwide and I kept finding a need for it (I travel with work and don’t always have roaming data). Also the lack of apps was disappointing, even though I contributed to the ecosystem with a WP7 app for Grass Management. I know the app situation is improving especially with Microsoft buying them up but I see too many complaints on social feeds to make me think they are a little shaky (is it the fault of the developers? … maybe!). When I moved back from WP7 to iPhone I complained for a few days over little nuisances, but I stayed there. Until now….

Android a week on

I’ll admit I was a little apprehensive at first thinking I’d like only the big screen and the  ability to write and deploy some droid apps on a real device (i don’t include the Samsung Galaxy Y that’s lying about the office as a real device :-) )

The good

But I’ve been very surprised, the Android apps appear to be better, the experience appears to be better, notifications are better. Why do i think this is? well maybe because the API allows the developers to do more, iOS does really lock things down which has it merits (we’ve all heard about the apps that silently call premium numbers).

  • The screen is large and beautiful
  • Camera is fantastic
  • Have all the apps I had on iPhone (not yet paid for TomTom again but will)

The bad

  • I don’t have the ability to have widgets on the lock screen when I have a PIN active.
  • The screen is too large! Contradiction I know, but I’ve hands like shovels and I need two of them for this device, apple has a great argument but it won’t win out.

 

Am I going back

Well never say never, but apple needs to up it’s game with a bigger screen, I always thought it was fine until I look back on my iPhone now and think it’s tiny

C++ ACE

Overview

I’ve been looking at a c++ application that uses ACE library, now I’ve never used this library myself, I used to love BOOST when I was 100% c++ (way back in the day sniff sniff). C++ 11 has drastically improved life sure but it’s not got everything I need.

I decided to do a bit of googling to see what I’ll be dealing with and below was the first post I came across on StackOverflow…. oh dear! not a great start for my motivation :-(

Post

Do yourself a favor and steer clear of ACE. It's a horrible, horrible library that should never have been written, if you ask me. I've worked (or rather HAD to work with it) for 3 years and I tell you it's a poorly designed, poorly documented, poorly implemented piece of junk using archaic C++ and built on completely brain-dead design decisions ... calling ACE "C with classes" is actually doing it a favor. If you look into the internal implementations of some of its constructs you'll often have a hard time suppressing your gag reflex. Also, I can't stress the "poor documentation" aspect enough. Usually, ACE's notion of documenting a function consists of simply printing the function's signature. As to the meaning of its arguments, its return value and its general behavior, well you're usually left to figure that out on your own. I'm sick and tired of having to guess which exceptions a function may throw, which return value denotes success, which arguments I have to pass to make the function do what I need it to do or whether a function / class is thread-safe or not.

Boost on the other hand, is simple to use, modern C++, extremely well documented, and it just WORKS! Boost is the way to go, down with ACE!

Using MVC5 Owin Security with EF Code First

Good evening, I’d like to share my solution for using MVC5 Owin security with VS2013 Update 1.
I wanted to have my own DBContext contain both my own DBSets and also the security tables.

Now I could find zero documentation on this and I actually walked away from the bleeding edge last week and reverted to MVC4. Tonight I had some free time and like a dog with a bone I wanted to figure this out. I’m not saying I came up with the nicest or correct solution, but alas I came up with something that appears to be working for me.
Please feel free to give me any feedback I’d appreciate it.

The problem

I wanted one single database containing my own entities and also the security entities.
I wanted to use the latest MVC5 built on the OWIN (open web interface for .net).
I wanted to use code first migrations to keep my database up to date.
I could find no documentation..

The Solution

  • Create my own entity class
    image

 

 

  • Create my own DBContext and IdentityStoreContext (the secret sauce) 

image The SiteCertDbContext derives from the IdentityDbContext used by default in MVC5 Update1.

  • Tell the account controller use this new DbContext

image

 

That’s pretty much it,  hope it helps someone else out you can now open the Nuget package manager and Enable-Migrations.

Parameterized Unit Tests with JUnit

I’ve been shown a lovely little utility for testing with JUnit 4.11 whereby one can have a list of items performed as part of the single unit test.

First set add the annotations you see below and set your inputs and expected outputs. (Arrange and Assert)
image

 

 

 

 

 

Then create a constructor and some static variables to store each Tuple

image

 

 

 

 

Then define your single unit test (the business logic is your Action)

image

 

 

 

 

That’s it, a really nice way to have a single unit test that can be run multiple times with different parameters.

image

 

 

 

 

 

If you would like to do the same sort of testing in .net you have some choices to make.

you could use NUnit and use the TestCaseAttribute

image

 

 

 

 

Of if like me you prefer MSTest then you can opt for a data driven unit test.
See this vs2013 page (has worked at least since vs2010) :
http://msdn.microsoft.com/en-US/library/ms182527(v=vs.120)

image

Recent Tweets

Note: For Customization and Configuration, CheckOut Recent Tweets Documentation

Calendar

<<  July 2017  >>
MoTuWeThFrSaSu
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

View posts in large calendar

Month List