New Blog.


Its been some time since I updated this blog. A much has changed since I last wrote here. From working on Open CV to Javascript to Android to Distributed Systems , I have gained more perspective and some skills 🙂 .

Hence forth I will not be maintaining this blog here .

You can visit my blog here – https://abhikmitra.github.io/blog/

If you want to know more about what I am doing , you can visit my website – http://abhikmitra.github.io/

 

Similarities between Services and factories in AngularJS – part2


In our previous post we looked at how to write service and factory and use it similarly by a uniform notation

<serviceOrFatoryName>.customFunction([arguments])
I also showed how factory is a syntactic sugar on provider and service is a syntactic sugar on Factory.Once again all the code is hosted in this github repo

In our next section we will look at some other patterns.

1. We want a class based approach and we should be getting new instances from service/factory.Basically our requirement are objects that are unique to a constructor and which wont be shared like a singleton across the app .


factory('customFactoryThatReturnsAFunction', function () {


 var staticVariable = 1;


 function customFn(){
 this.value=1;
 console.log("custom Function is called")
 }
 customFn.prototype.increment = function(){
 staticVariable++;
 return ++this.value;
 }
 return customFn
 });

The factory returns a constructor function .The proper way to use this would be


var obj = new customFactoryThatReturnsAFunction();
 console.log("Increment value",obj.increment());

This above code is the best feature of a factory . the staticVariable behaves like a static variable and is shared across.This is the  exact reason you would want to user factory.

 

Can this be done using services ?

Yes it can be done ,but it will make the syntax messy and takes away the benefit of using services.

 

Conclusion:

When should Services be used ?

  • When you have an constructor function,the instance of which needs to be single ton across the app.

When should factory be used ?

  • When you want to return an object that needs to be treated like a singleton
  • When you want to return a constructor function which will be used to construct new objects everytime.

 

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.

Instance creation part 2


My previous post shows how instance creation works with new operator.So in this post we will try to deduce what really goes on.
We will start with the basic and try and go deep


var constructorFn = function(){this.a=1};
var obj = new constructorFn();
obj instanceof constructorFn // true

Nothing unusual here.When the new keyword is encountered ,the “this” is said to the current object itself and the key value pair is set on the object.

Lets now modify our code a bit


var constructorFn = function(){
this.a =1 ;
}
constructorFn.prototype.key1 ="value1";
constructorFn.prototype.key2 ="value2";

on printing obj we see

constructorFn {a: 1, key1: "value1", key2: "value2"}

So what exactly did happen ? We already understand how a came into the picture.
To understand how the other 2 property came in ,look at the below piece of code

Object.getPrototypeOf(obj);
//displays
Object {key1: "value1", key2: "value2"}

So the algorithm of obj = new fn() goes as follows
1.Execute fn.
2.If “this” is encountered,set its value to the current object
3.If a primitive value is returned then ignore that and set obj to point to the current object
4.If a complex object is returned then obj should ignore the current object and instead be set to the returned value.
5.obj[[prototype]] should now point to fn[[prototype]]

An important thing to understand is that __proto__ and prototype is not same.In the above example


( new Foo ).__proto__ === Foo.prototype ;//true
( new Foo ).prototype === undefined ;//true

__proto__ is the actual object that is used in the lookup chain to resolve methods, etc.Prototype is a property belonging only to functions. Used in case the function happens to be used as a constructor

PS:__proto__ is deprecated and Object.getPrototypeOf should be used.

So the last question remains as to what is the “constructor”.constructor is nothing but the function that constructed the object.

obj.__proto__ === obj.constructor.prototype //returns true
Object.getPrototypeOf(obj) === obj.constructor.prototype //returns true

Why was the last line necessary ? So that we understand that “prototype” is for functions and Object.getPrototypeOf() is for instances.

PPS: Object.getPrototypeOf(obj) === Object.getPrototypeOf(obj.constructor)//returns false .

The reason being getPrototypeOf internally checks the __proto__ property as that is how the chain is traversed and not prototype and hence constructorFn.key1 will be undefined.

Instance creation in Javascript


There is a lot of confusion about instance creation in javascript .It is a common interview question.hence my attempt at providing some clarity .


var constructorFn = function(){
this.variable = "Hello World"
}
var obj = new constructorFn();

If you print obj in the console,you will see something like this


constructorFn {variable: "Hello World"}

This basically means that the obj is of type constructorFn . And the obj has 1 property.The “this” object is set to the new object itself


obj instanceof constructorFn

The above statement returns true .

Next Part:


var constructorFn = function(){
this.variable = "Hello World";
return "returned value";
}
var obj = new constructorFn();

On printing obj we see.

constructorFn {variable: "Hello World"}

So our function now has a return value.If a constructor function returns nothing, null, or any atomic / non-object value then said value is ignored and the newly created object reference is given back to the caller. So u see the constructor of your object in console

More modification


var constructorFn = function(){
this.variable = "Hello World";
return {"value":"hello inner world"}
}
var obj = new constructorFn();

On printing obj, we now see

Object {value: "hello inner world"}
obj instanceof constructorFn

The result is FALSE.

when you start returning explicit, complex objects and arrays in a constructor function, you completely override the reference that is returned to the calling context.

A-synchronism in Windows 8 App Development


This will be the last of our series Asynchronous programming.Now since we have a strong background of tasks,this will be very easy to grasp since from C# 5.0,asynchronous has been heavily simplified to represent closely its synchronous counter part.

We have two new keywords called async and await which we will be using.I will be referring to my previous posts .

Our demo app looks like this .The third column having textblocks for comments

image

Scenario 1 : Heavy work without using await .

So lets see the code for the No Await button

   1: start2.Text = System.Environment.TickCount.ToString() ;

   2:            AsyncDownloadFeed();

   3:            stop2.Text = System.Environment.TickCount.ToString();

AsyncDownloadFeed downloads news off the BBC website and also runs a synchronous piece of loop

Lets look at the code behind AsyncDownloadFeed.

   1: public async void AsyncDownloadFeed()

   2:         {

   3:             String url = "http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#";

   4:             HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

   5:             Task<WebResponse> response =  WebRequestObject.GetResponseAsync();

   6:             resp = await response;

   7:             comments_Copy.Text = "Loop Starting";

   8:            insaneSynchronousLongLoop();

   9:            comments_Copy.Text = "Loop Finished";

  10:             processNews();

  11:         }

yes I know I have used await here but bear with me.Treat this function as a blackbox.Next is the synchronous loop

   1: private  async void  insaneSynchronousLongLoop()

   2:         {

   3:             // comments.Text = "I am in the loop";

   4:             comments.Text = "I am in the loop";

   5:             int i = 0;

   6:             for (i = 0; i < 1000000000; i++) ;

   7:             comments.Text = "loop finished";

   8:         }

Click on the No await button and we will see, the difference between start time and end time is only 20 miliseconds apart.As expected,the textblocks populates even before the function AsyncDownloadFeed is completed.

image

If we wait a few seconds, we will finally see the result.

image

We already know this phenomenon as its not waiting for the function call to finish.

1.Why does it not wait for the function? It should have been synchronously waiting.?

Answer: Using the “async” keyword isnt the what causing the asynchronous behaviour.The async keyword single handedly cannot be used to transform any synchronous code into non asynchronous one.Async keyword just informs the compiler that there may be code which would need to be run asynchronously. So what is the cause ? Lets examine the AsyncDownloadFeed function by providing two outputs.

   1: public async void AsyncDownloadFeed()

   2:         {

   3:

   4:             String url = "http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#";

   5:             HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(url);

   6:             Task<WebResponse> response =  WebRequestObject.GetResponseAsync();

   7:             Debug.WriteLine("Started Awaiting");

   8:             var start = System.Environment.TickCount;

   9:             resp = await response;

  10:             var stop = System.Environment.TickCount;

  11:             Debug.WriteLine("End Await Duration="+(stop-start).ToString());

  12:

  13:             Debug.WriteLine("Loop Starting");

  14:             insaneSynchronousLongLoop();

  15:             Debug.WriteLine("Loop Ending");

  16:             processNews();

  17:         }

Task<WebResponse> response =  WebRequestObject.GetResponseAsync(); is familiar since we already are acquainted with TPL.

resp = await response; is the place where the magic occurs.This tells the compiler that it needs to wait for the response but in such a way,so that it does not block the UI.But this is not similar to “wait” as not only does it not block the UI,the compiler moves on to the next statement .Which means,the insaneSynchronousLongLoop() runs even before the webresponse is returned.Moreover in the insaneSynchronousLongLoop does not block the UI since its running on a different thread.

Another thing is ,we can manipulate the UI within the insaneSynchronousLongLoop () since the compiler takes care of that updating the UI only when the threads return to the main UI.

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