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.

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.

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.

Asynchronous Programming doesn’t imply multithreading!


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.

Few days ago,while talking to some of my friends,I realized a lot of people harbor a misconception that implementing asynchronous models makes their program multithreaded and parallel .I will try and debunk this myth in this post.

People often think asynchronous work equal multithreading. Which is absolutely not true?

In this post we are going to differentiate asynchronousness and parallelism.

Now let’s take an example, say we are consuming a web service or using the web Client which involves a call over the network and significant waiting time. The first thing that comes to our mind when we do such a work is that we must keep the UI responsive while our program waits. A lot of people think that to keep the UI responsive there HAS to be a separate thread which is running and taking care of our web request.

But the truth is different. The request only needs two threads at a specific point. It’s also possible to do the work in ONE thread without blocking the thread or freezing up the UI.

I will back up my claims logically

1. Most of the time is spent waiting for a response from the server. When a client machine sends a request, it has to wait for the reply. So what would a thread do when the request is in progress? If we use synchronous programming model, it will put the thread to sleep as there is no work for the thread to do.

2. Even while the client computer, is sending or receiving data /request to the server we do not need a different thread as this is taken care of by the network hardware. The network hardware inside the computer is quite capable to handle stuffs related to such tasks. When we actually send the data, the device driver for the NIC, programs the hardware pointing it to the data to send. The network hardware in most cases is quite capable of fetching the actual data to be sent directly from the main memory. So the driver only needs to inform the location of the data in the memory. So the work of CPU is only limited to telling the NIC where to fetch data from and where to send the data. The time taken to do that is quite negligible compared to the time taken to send the data.

3. The above case is true for most Input/output tasks. It’s the same with disk access. The CPU just needs to tell the disk controller as to which data needs to be accessed. The time is miniscule compared to the time disk controller takes to move its parts and access the data. The time the CPU takes to issue the instruction is very small compared to the above.

Practically most windows applications spend a lot of time waiting .Multithreading won’t make the “waiting” faster. It’s the asynchronous ness that would keep the program responsive. Multithreading is important when there is a specialized background that is running. That is when a multicore benefit will be more pronounced.

The main point of asynchronous code is mostly to reduce the number of threads we are using. It does that by taking away threads from code that may have blocked it. It will only be allowed to consume threads at only those moments when it actually has constructive work (useful CPU work) to do. This is what leaves the UI thread free to respond to the user input

Asynchronous programming Deep Dive part 2


 

Picking up from where I left off , I had promised to show you the code behind “both” button .The initial code is

   1: WebResponse Response = getResponse("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#");

   2:             int bbc =Int32.Parse( processBBCNews(Response).ToString());

   3:      

   4:  WebResponse Response1 = getResponse("https://news.google.com/news/feeds?ned=in&topic=h&output=rss");

   5:             int gn =Int32.Parse(  processGoogleNews(Response1).ToString());

   6:                      

   7:             int time_stop = System.Environment.TickCount;

   8:             //Computing the difference between the number of posts

   9:             textBox3.Text = (Math.Abs(bbc - gn)).ToString();

Now, the reduction in time can be felt the most in this part. Because we will designate 2 different threads to work on the 2 services.

Now to do this,if we blindly follow the previous method, we will end up with this .

   1: int time_start = System.Environment.TickCount;

   2:             Task<WebResponse> T1 = Task<WebResponse>.Factory.StartNew(()=>{

   3:             WebResponse Response = getResponse("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#");

   4:                 return Response;

   5:                 });

   6:            

   7:             Task<WebResponse> T2 = Task<WebResponse>.Factory.StartNew(()=>{

   8:             WebResponse Response = getResponse("https://news.google.com/news/feeds?ned=in&topic=h&output=rss");

   9:             

  10:             return Response;

  11:              });

  12:            Task<int> T1_next = T1.ContinueWith((antecedent) =>

  13:             {

  14:                 int gn = Int32.Parse(processGoogleNews(antecedent.Result).ToString());

  15:                 return gn;

  16:             },

  17:             TaskScheduler.FromCurrentSynchronizationContext());

  18:            Task<int> T2_next = T2.ContinueWith((antecedent) =>

  19:             {

  20:                 int bbc = Int32.Parse(processBBCNews(antecedent.Result).ToString());

  21:                 return bbc;

  22:             },

  23:                 TaskScheduler.FromCurrentSynchronizationContext()

  24:             );

  25:            

  26:               //Computing the difference between the number of posts

  27:             textBox3.Text = (Math.Abs(T1_next.Result - T2_next.Result)).ToString();

  28:           

  29:             int time_stop = System.Environment.TickCount;

  30:             label3.Text = (time_stop - time_start).ToString(); 

But this will not run. Infact this will freeze your application indefinitely? Why so?

The reason being, T1_next.Result executes before , T1 is actually finished . Now this is straight forward as we know that <task_name>.Result implicitly calls Task.Wait() and hence, it will freeze the UI thread and wait for the results.

But at the same time after T1 finishes, T1_next will be invoked, which is waiting at the local queue to be run on the UI thread. While the UI thread isn’t finished because it’s waiting for T1_next. Thus we have a deadlock. Always watch out for such deadlock, when you are dealing with synchronization contexts. So we need to do away with the waiting .

We need to change our code a bit

 

   1: int time_start = System.Environment.TickCount;

   2:             Task<ListBox> T1 = Task<ListBox>.Factory.StartNew(()=>{

   3:             WebResponse Response = getResponse("http://feeds.bbci.co.uk/news/world/rss.xml?edition=uk#");

   4:                 //Instead of returning the response we send the response to another processing function which does not update the UI thread

   5:             ListBox bbc = processBBCNews_new(Response);

   6:             Thread.Sleep(2000);

   7:             //The processing function returns a listbox 

   8:                 return bbc;

   9:                 });

  10:            

  11:             Task<ListBox> T2 = Task<ListBox>.Factory.StartNew(()=>{

  12:             WebResponse Response = getResponse("https://news.google.com/news/feeds?ned=in&topic=h&output=rss");

  13:  

  14:             ListBox gn = processGoogleNews_new(Response);

  15:             return gn;

  16:              });

  17:             //The trick is to wait for both T1 and T2 without blocking the UI thread                      

  18:             Task[] arr = { T1, T2 };

  19:             TaskFactory tf = new TaskFactory();

  20:             //Continue when all acts like a call back ,and does not fire wait on the UI thread,hence the UI is still responsive

  21:             tf.ContinueWhenAll(arr, (a) => {

  22:                 int count = 0, count1 = 0;

  23:                 

  24:                 foreach (string item in T1.Result.Items)

  25:                 {

  26:                     //The listbox returned is iterated to add those values to the UI listbox 

  27:                     count++;

  28:                     listBox1.Items.Add(item);

  29:                 }

  30:                 foreach (string item in T2.Result.Items)

  31:                 {

  32:                     count1++;

  33:                     listBox2.Items.Add(item);

  34:                 }

  35:                 //Computing the difference between the number of posts

  36:                 textBox3.Text = (Math.Abs(count1 - count)).ToString();

  37:                 int time_stop = System.Environment.TickCount;

  38:                 label3.Text = (time_stop - time_start).ToString();

  39:             

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

If you go through the code,you would see I have used a continueWhenAll method.I have explained the reason.If you want to know more visit .

As I had promised, I have uploaded the entire app code here.

Optimizing Selectors in JQuery.


jQuery uses a selector engine called Sizzle.Sizzle has various ways of selecting elements. Selecting elements is one of the fundamental part of jQuery, hence it’s important we learn how to optimize our selectors. jQuery selector Engine runs from right to left. Being specific on the left hand side has a lot less value than being specific on the right hand side.

$(“.parent .child”)//This is how the selector engine works.

A common misconception is that being accurate makes the selector works faster as it knows where to find the DOM element. But that is not the case. jQuery has a very different way in which it handles selecting by id or selecting by class.

<ul class=”listing”>

<li class=”bullet”>

<h3 class=”mainelement”> This is a test<h3>

</li>

<ul>

 

$(‘ul.listing li.bullet h3.mainelement’) //though is the most specific is not the fastest.

The fastest selector is simply the class name by itself.

$(.parent child)//Fastest

Anything else is telling jQuery to do more work than necessary. Starting from the right that is all that we need to get the set of elements.

<ul class=”listing”>

<li id=”bullet”>

<h3 class=”mainelement”> This is a test<h3>

</li>

<ul>

Now since we have an id. We can further bring down the time required by selecting with ID.

$(‘#bullet .mainelement’)//Sizzle operates differently when the first selector is ID

But to really speed things up, we can use

$(‘#bullet’).children(‘.mainelement’) or $(‘#bullet’).find(‘.mainelement’)

The latter being the fastest. To understand the discrepancy we must look into the jQuery Source. When the only part of the selector is an ID jQuery uses document.getElementById(id) which drastically reduces the time taken.

$(‘p#randomid’) //jQuery will use getElementsByTagName(), then iterate though the array of elements for the above selector.

var div = $(‘#randomId’);ßjQuery will use getElementById() for the above selector

From the source code we can see, the fastest selector is

$(‘ ‘)//Returns an empty jQuery object.

$(‘body’)//Next in line, jQuery converts this to document.body

$(‘#id’)//Third fastest, jQuery converts this to document.getElementById(‘id’)

 

Now to distinguish between children() and find(), Children only looks at the immediate children of the node, while find traverses the entire DOM below the node. But in general cases find is faster. children () internally makes calls to sibling(), filter(), and goes through a few more regexes than find() does. find () and children() fulfill different needs, but in the cases where find() and children() would output the same result, it’s better to use find().