Similarities between Services and Factories in Angular JS – Part 1


Most of the articles talk about differences.I will start with similarities and work our way to differences.

I will be using the code added https://github.com/abhikmitra/Service-vs-Factory/tree/master/app/scripts .

So firstly we have 3 pages with 3 separate controllers.

1.MainCtrl,

2.AnotherCtrl,

3.OnemoreCtrl

Claim 1 : Services and factory are both lazy loaded.

Proof : Move from “another page” to “main page” and only then you will see customFactory, Customservice getting instantiated.

Claim 2: Both of them are singleton and can be accessed in the same way
ServiceOrFactorName.somefunction();
Proof:

Our Service look like


angular.module('serviceVsFactoryApp')
 .service('Customservice', function Customservice() {
 console.log("CustomService has been Called");
 console.warn("Value of this inside a factory",this,"Notice the __proto__ by putting a break point")
 var localVariable = 1;
 this.thisVariable = 100;
 this.test = function () {

 return ++localVariable;
 }
 });

This allows us to call the service from controller with the following syntax.

</pre>
Customservice.test();
<pre>

So what does angular internally do ? It does a new of the contructor function Customservice() and caches it for it to be used as a singleton .If you put a breakpoint in the customservice and check the value of this you will see

this.__proto__ = Customservice

Now if we want the same functionality form the factory,this is what we will be doing.

</pre>
angular.module('serviceVsFactoryApp')
    .factory('customFactory', function () {

        console.log("CustomFactory has been Called")
        var localVariable = 1;
        console.warn("Value of this inside a factory",this,"Notice the $get")

        return {
            test: function () {
                console.warn("Value of this inside the object a factory",this,"Notice the __proto__")
                return ++localVariable;
            },
            thisVariable : 100
        };
    })
<pre>

So for the first time when the service is instantiated customFactory function is invoked once. and the returned object is cached for the lifetime of the app.Hence we can access the test function in the same was as previously.
Putting a break point in the code ,you will see that the this operator has a $get which basically means that the factory function is the function that we pass it to the provider using $get.

Another way to achieve the same goal is through this way

</pre>
angular.module('serviceVsFactoryApp')
    .factory('customFactoryThatInstantiatesAfunction', function () {

        console.log("CustomFactory has been Called")
        var localVariable = 1;
        console.warn("Value of this inside a factory",this,"Notice the $get")
        function Customservice() {
            console.log("CustomService has been Called");
            console.warn("Value of this inside a factory", this, "Notice the __proto__ by putting a break point")
            var localVariable = 1;
            this.thisVariable = 100;
            this.test = function () {

                return ++localVariable;
            }
        }
        return new Customservice();
    })
<pre>

This is exactly what a service does.So a service is a syntactic sugar on top of factory which itself is a syntactic sugar on providers

Some of the similarities.
Both the service and factory can have private variables in our case we call it local variables.
In your controller ,you can choose to do this

</pre>
<pre>customFactory.addingRandom="random text"; Customservice.addingRandom="random text";</pre>
<pre>

Which basically adds a prototype to the current instance.And since its a singleton,all the modules using this instance get access to the value.

So this brings the part 1 to close. In part 2 we will see more of differences than similarities.

Functions Expression vs Declaration


Declaring functions might seem to be trivial but in the world of Javascript,there are a lot of misconceptions around it .I will try and demistify about what exactly goes on .

1.We will start off with this code snippet.


var fn = function(){
exprFn();
declaredFn();
var exprFn = function(){
console.log("Expression Function ran");
}
function declaredFn(){
console.log("Declared Function ran")
}
}
fn();

Does this work ? No . It says exprFn is undefined.
Conclusion:The reason being even though the variable declaration is hoisted at the top.The expression assigning the function to exprFn did not and hence we are trying to invoke undefined() and hence it is throwing an error.Lets correct it,which will take us to our next point.


2.


var fn = function(){
declaredFn();
var exprFn = function(){
console.log("Expression Function ran");
};
exprFn();
function declaredFn(){
console.log("Declared Function ran")
}
}
fn();

The result is

Declared Function ran
Expression Function ran
declaredFn() apparently was invoked before it was even declared.
Conclusion:This is because function declarations like variable get hoisted.Hence the declaredFn’ s declaration statement was hoisted and hence declaredFn was already declared.function declarations are parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated foremost any other expressions contained in a scope


 

3.


var fn = function(){
declaredFn();
test();
var exprFn = function test(){
console.log("Expression Function ran");
};
exprFn();
function declaredFn(){
console.log("Declared Function ran")
}
}
fn();

We have changed the function a bit .We basically have named the anonymous function assigned to exprFn to test.It is called a named function expression.But the above code doesn’t work.
ReferenceError: test is not defined
As named function expression are also not hoisted.


 

4.


var fn = function(){
var exprFn = function test(){
console.log("Expression Function ran");
console.log("inner:expression",typeof exprFn)
console.log("inner:function name",typeof test)
};
exprFn();
console.log("outer:expression",typeof exprFn);
console.log("outer:function name",typeof test);
}
fn();

If you run the above piece of code you will see
Expression Function ran
inner:expression function
inner:function name function
outer:expression function
outer:function name undefined
So you see ,the function identifier (name) is not accessible by the outer scope.The specs says that the identifier should not be available in the scope enclosing it.Hence “test” is undefined

Now that we know the difference between function expression and function declaration.The question we will try and answer is

why the following doesn’t work as an IIFE: function foo(){ }();.

It doesn’t work because brackets after a function declaration doesn’t invoke the function.The function can only be immediately invoked if its an expression.


1+function foo(){console.log("I got executed");}()

The result is
I got executed
NaN
The spec says that the plus operator expects 2 expression.Hence our function declaration is transformed into a function expression and the extra brackets at the end invoke them.Similarly the common practice of using IIFE is putting it within brackets.


(function (){console.log("I got executed");})()

The extra brackets just turns the function declaration into an expression and makes it invokable.You can transform your function declaration to an expression by putting it in an operator that expects expression.Js would do the rest for you 🙂

Instance Creation Part 3


The previous post we dealt with how “new” works. In this post we will talk about how Object.create works.


var constructorObj = { a:1};
var obj = Object.create(constructorObj)

If we print obj, we will see Object {a: 1}

Firstly, obj is of type Object and not constructorObj.Secondly lets go a little deeper and try


Object.getPrototypeOf(obj)

Object {a: 1}

So basically the constructorObj got attached to the prototype of the new object.That is all it does

Now lets change our constructorObj


constructorObj.a = 2

print obj
Object {a: 2} .So the prototype shares the same object.Any value you change on the object also reflects on the instances.And also obj.constructor points to the native Object

Lets see how it behaves with instances created with new


var constructorFn = function(){this.a=1};
constructorFn.prototype.field1 = "test";
var obj = new constructorFn()
var newObj = Object.create(obj);

Now if we print newObj.We will see

Object {a: 1, field1: “test”}

So the way this happens is newObj[[prototype]]==obj,obj[[prototype]] = constructorFn[[prototype]].

So now if we print Object.getPrototypeOf(Object.getPrototypeOf(newObj)); we will see exactly what we expect Object {field1: “test”} .

Lastly lets see what happens when we pass a function


var obj = Object.create(constructorFn)

If we print obj , we will see Function {}
typeof obj is “object”
obj instanceof Function //true

So what exactly happens ? Well the function gets attached to the prototype .
Object.getPrototypeOf(obj) gives us the original constructorFn. Unlike new there is no change of the this object and hence obj does not get a copy of the properties.

Introduction to the Windows Phone platform


Shared Windows Core

Windows 8 and Windows Phone 8 Share Many Components At The Operating System Level

Shared Core means

• OS components such as the kernel, networking, graphics support, file system and multimedia are the same on both Windows 8 and Windows Phone 8

• Hardware manufacturers work with the same driver model on both platforms

• Windows Phone gets the support for multi-core and other hardware features that Windows has had for years

• These solid, common foundations makes it easier to extend the Windows Phone platform into the future

It doesn’t mean

• Windows 8 and Windows Phone 8 developers work to exactly the same APIs

• (though you will see more commonality as new features are introduced to both platforms in the future)

Windows Phone 8 supports

• Managed app dev using the WP7.1, WP8.0 .NET and WinPRT APIs

• Native app dev using WinPRT and Win32

• Games dev using the WP7.1 XNA framework

• Games dev using Direct3D or DirectX

clip_image002

Since we are going to look at managed app dev , let me point you to the classes you can use for WP 8 development. There are basically two sets of API s

clip_image004

Now which one should you choose ?

Windows phone .NET API

This has full support windows phone 7.1 classes. So if you code using these supported classes, your app will run on WP 7 two. If you have existing app that runs for WP 7.1,you do not have to re-develop from scratch, you can reuse the existing code base. Contains classes and types from the System and Microsoft.Phone namespaces

• There have been new classes added for Windows Phone 8.0, for example

• Microsoft.Phone.Wallet

• Microsoft.Phone.Tasks.ShareMediaTask

• Microsoft.Phone.Tasks.MapsTask

• Microsoft.Phone.Storage.ExternalStorage

• Microsoft.Phone.Networking.Voip

Windows Phone Runtime API

Windows Phone Runtime is a subset of the full WinRT, plus some phone-specific additions. Windows (Phone) Runtime is implemented in C++ and projected into C#, VB.NET, and C++.

You would be using this library typically if you are developing for Windows Phone 8 and Windows RT since the Windows PRT API and the Win RT API has a lot of shared codes.clip_image006

So, it is mostly a matter of choice which class you choose since equivalent classes exist in both the APIs

.NET API

Windows Phone Runtime API

System.IO.IsolatedStorage

Windows.Storage

System.NET.Sockets

Windows.Networking.Sockets

System.Threading.ThreadPool

Windows.System.Threading.ThreadPool

Microsoft.Devices.Sensors

Windows.Devices.Sensors

System.Device.Location

Windows.Devices.GeoLocation

Just to let you know, unlike Windows 8HTML/JS app development isn’t possible for WP 8.But we can use HTML 5 hosted in webview to make cross platform apps.

Best Alarm Apps in Windows Store.


Windows store like the android app store is populated by a lot of junk apps that don’t work. For the past few days, I was searching for a decent alarm application and I found that very few of the alarm application actually work. The main problem is that the alarm apps stop running the moment you visit another app.

So here I am going to document the best Alarm Apps in Windows 8 and the various pros and cons.

1. Smart Metro Alarm

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Snoozing, repeating and alarms that repeat on specific days are supported

3. Night Mode to be used as a night stand clock.

4. Stopwatch that works even if the app is closed.

5. Snapped View works properly.

Pros: All the above features actually work. I have bought this alarm and the developer keeps updating this app every week. Alarms ring properly and stopwatch works fine. .The biggest feature is that the alarms actually work even if the lock screen is on or the app isn’t running.

Cons: Overtly simplistic UI.UI could be improved

Rating 8/10

Link

2. Sunrise Clock

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Night mode.

3. Choice of 5 beautiful background picture.

4. Very attractive UI

5. Works in snapped mode.

Pros: Very nice UI. Has the concept of sunrise, so if you keep the alarm app on and go to sleep it will simulate a sunrise with time but, if you are like me you will be too sleepy to notice. Over all the app works great as long as you keep it open. You can choose from 5 different sounds

Cons: The app doesn’t work, when the lock screen is on or you are seeing another app. The alarm unfortunately doesn’t ring when any other app is open. So if you by chance fall asleep without opening the app then your alarms won’t ring. A very serious problem. And also no option of snoozing.

Rating 5/10

Link

3. HD Alarm Clock

A bit pricey alarm clock with heavily customizable features.

Key features:

1. Multiple Alarms can be set and stored forever. No limit on alarms stored

2. Choose your own alarm tone.

3. Very nice UI

4. Obstacles for deep sleeper.

5. News are shown in one screen.

6. Beautiful themes and work well.

Pros: All the features work as expected. One cool thing is obstacles that are put in place during an alarm

Con: The alarm stops working if the app isn’t running or the lock screen is on. The only problem that seriously impairs the functionality.

Rating: 7/10

Overall winner: Metro Smart Alarm

Exception Handling in Task Based Parallel programming.


As you had learnt in the previous posts, Tasks are executed asynchronously and parallel. Now what happens when there is an exception? How and where is it thrown?

This blog post answers all the above questions

1. What happens when an exception occurs?

When a task causes an exception, it first terminates the Task .E is caught,saved as a part of an AggregateException ae and stored in object’s Exception property

.Now, we know, that I synchronous programming, the exception propagates upward to the caller from the callee.

But in synchronous programming, the scenario is different. Here if the exception is unhandled, it is re thrown at a later time.

2. What do you mean by ‘Later Time’?

The exception AE is rethrown when it encounters .result,.Wait or WaitAll Task functions.The exception if not handled or touched, is rethrown when the task object is garbage collected.

3. What is the proper way to handle exceptions ?

   1: Task<int> T_1 = Task<int>.Factory.StartNew(() => { 

   2:                 //throw new ArithmeticException();

   3:                 //do something awesome that generates an exception

   4:                 return 1;

   5:             });

   6:             try

   7:             {

   8:  

   9:                     int a=    T_1.Result;

  10:             }

  11:             catch (AggregateException AE)

  12:             {

  13:                 AE = AE.Flatten();

  14:                 foreach (Exception ae in AE.InnerExceptions)

  15:                 {

  16:                     //handle each Exception ae

  17:                 }

  18:  

  19:             }

4. What is AggregateException ?

.NET throws all the exception wrapped in a single Exception called Aggregate Exception. Now as we know, that each task can create many subtasks, which again can lead to exceptions. So an aggregate Exception returned by a task, contains all the exception returned by the subtasks.

Consider this scenario, Task A creates Task B and Task C, and in doing so Task A is considered the parent of both Task B and Task C. These relationships come into play primarily in regard to lifetimes. A Task isn’t considered completed until all its children have completed, so if you used Wait on Task A, that instance of Wait wouldn’t return until both B and C had also completed.  So what happens if both throws an exception. Then both the exceptions are wrapped in an aggregate Exception and rethrown.

5 .How do we access the individual exceptions ?

We access it through the Aggregrate Exceptions class. But it might happen that the child of the parent’s task, spawns more child tasks which throws exception. Hence we can see a tree forming,whose leaves are exceptions.

By default, AggregateExceptions retains this hierarchical structure, which can be helpful when debugging because the hierarchical structure of the contained aggregates will likely correspond to the structure of the code that threw those exceptions. However, this can also make aggregates more difficult to work with in some cases. To account for that, the Flatten method removes the layers of contained aggregates by creating a new AggregateException that contains the non-AggregateExceptions from the whole hierarchy.

6. What is observing Exceptions ?

Now, as we said unhandled Exceptions will be rethrown during garbage collection. To avoid that ,there are 4 methods you can “observe” the exceptions or in other words allow the exceptions to be rethrown so that you can handle it.

Calling .Wait, .Result or .WaitAll on tasks will allow the task to re throw the exceptions. [task.waitany does not throw any exceptions)

Access tasks’ Exception property after completion of task.

Subscribe to TaskScheduler.UnobservedTaskException

Accessing the exception property after completion of the task will not re throw the exception. If the exception property is not null, then you would know that an exception was generated. Even if you don’t handle it, the compiler won’t rethrow during garbage collection as you have observed the exception

Difference between continuewhenAll and WaitAll


This is a part of the blog series , “Asynchronous Programming Using DotNet” .Please visit this page to see the “index” of all the posts I wrote on this series.

So what exactly is the difference between continuewhenAll and WaitAll method ? When and where should you use them?

Consider the following piece of code

   1: int start = Environment.TickCount;

   2:

   3: Task T1 = Task.Factory.StartNew(() =>

   4:

   5: {

   6:

   7: Thread.Sleep(3000);

   8:

   9: });

  10:

  11: Task T2 = Task.Factory.StartNew(() =>

  12:

  13: {

  14:

  15: Thread.Sleep(3000);

  16:

  17: });

  18:

  19: Task T3 = Task.Factory.StartNew(() =>

  20:

  21: {

  22:

  23: Thread.Sleep(3000);

  24:

  25: });

  26:

  27: Task[] T_Arr = { T1, T2,T3 };

  28:

  29: Task.WaitAll(T_Arr);

  30:

  31: int stop = Environment.TickCount;

  32:

  33: textBox1.Text =( stop - start).ToString();

The time of run is a little over 3000 miliseconds.

clip_image002

As you can see, Task.waitAll takes an array as an argument and waits till all the tasks are complete. The tasks itself are asynchronous in nature. So the period of waiting is roughly equal to the maximum of (Time taken by T1, Time Taken by T2, and Time Taken by T3).During the waiting period the UI freezes ,as the UI thread is busy waiting!! So basically even though the tasks are done asynchronously, the waiting is synchronous.

So what is the solution ?

The new code is

   1: TaskFactory tf = new TaskFactory();

   2:

   3: tf.ContinueWhenAll(T_Arr, (a) =>

   4:

   5: {

   6:

   7: int stop = Environment.TickCount;

   8:

   9: textBox1.Text = (stop - start).ToString();

  10:

  11: }, new CancellationToken(), TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

Continuewhen all typically starts a new thread.Continuewhenall delegate will be called once the tasks are finished and the contents of the continuewhen all will run on a new thread.So there is synchronous waiting.Here in our case ,since we are updating the UI, the task will run on the UI thread,but while waiting for the output it won’t be blocking the UI thread, Hence your application remains responsive, even if your tasks are not complete.