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

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(){
 console.log("custom Function is called")
 customFn.prototype.increment = function(){
 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.



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.



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


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 = "";

   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.


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


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:         {


   4:             String url = "";

   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());


  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.

Saas vs Software + Service

Before I start I hope you are well acquainted to the term Software as a Service.If not please check the previous post( on my blog.

Microsoft has named its architecture as a S+S (Software as a Services).The question is whether is it just a marketing gimmick or does it signify anything different?

Yes,though the basic principles remain same,there is a marked  difference.

Saas means the entire software is delivered as a service.The client machine does not need to do anything.The entire computing power remains with the browser.

S+S on the other hand believes clients aren’t useless 😉 .It is based on the theory that software resides on the client system and is heavily supplemented by internet and cloud applications.It does not however mean today’s antivirus,that gets its updates from the internet.

S+S architecture:For accessing cloud services you need to have a browser and an OS which is also a software.So Microsoft believes S+S and not SaaS is the future…

BING!…..Microsoft brings out a new decision engine….Bing vs Google!!!

Bing ! as we know it is the new search engine. Microsoft claims its much more than a search engine and it is a decision engine…

It was first designed as KUMO .KUMO was alpha tested by Microsoft guys and it was never opened to the public.I had seen KUMO in action at the Microsoft IDC.

Contrary to popular beliefs That windows life has been redesigned and renamed to BING!!…. actually KUMO has been renamed to BING

Bing is in beta stage I am going to talk about the features currently present and the features which are going to come…

First let me talk about the current features…

The UI is clean ,fast and beautiful to look at…

The core search is good almost similar to Windows Live with a no. of improvements.

Each celebrity is ranked by Bing xRank depending on its search popularity.On the day of writing this post Michael Jackson stands at no. 1 and SRK at 109.So xrank is a method developed by Bing to rank “notable” persons.So whenever you search for someone “famous” … Xrank will be displayed and you can also compare the xrank of celebrities.Clicking on the Xrank will show a summary of information on the celebrity ranging from “Search Volume” to biographies.This feature was also present in windows live but Bing has perfected this feature by structuring results and filtering it according to your needs.

Related searches are shown in the left pane.Type a name of place ,and related search appear relating to travel ,hotels etc.


Mouse hover preview is available….too..In some pages it shows the preview and in some pages it shows additional info that can be found on the site.

Image search is great with fully functional filters.filters

Try searching image of any celebrity and it will show you the various filters,through which you can filter the images and find what exactly you are looking for.


VIDEO search has mouse over preview with related videos and filters based on “LENGTH” …”SCREENSIZE” …”SOURCE” etc..


These were there from Windows Live Search…and is very helpful so I do not need to compare the image and video search with any other search engine…..







Now we come to the best part …

Bing vs Google a review




THE PICTURES ARE SELF EXPLANATORY…. you have filters,pictures host of related searches Bing to help you find and DECIDE exactly what you want.


Comparison based on name and place

…again do I need to say more…. If you depend on the Internet for your travel needs…then Bing automatically is the best choice….The filters are made keeping in mind the information the user may be looking for.

Related searches again help you along with recent searches if you want to go back to your previous search…


Last but not the least…searched “open source” ….here also Bing takes the cake….

Don’t get bogged down by the huge number of results shown by Google….you cannot access beyond the 100th page..

So what do we conclude…Is Bing better??

Well frankly..the time hasn’t yet come to pass a judgement…Google still has the major share and a large database.On the other side Bing is in BETA ,a lot more is to come in terms of Travel Search,’planning your journey…local search.

The travel Search and “Structured Results” are going to be the XFACTOR of Bing….Whenever you need to decide ..Bing is there to help you providing with local to international information.It categorises the results based on content so that you can access that “specific” information you are looking for within a short time.A lot more is to come and Microsoft is surely moving on the path to create a “better way to search” if not the best way to search!!….. till then keep saying BING! O!!! 

Cloud Computing….. A Basic idea…..


Cloud Computing

Wikipedia defines it as “internet based development of computer technology”

Until now we have been mainly using Internet for our needs for “information”. Now we are going to use the internet as a “Platform” on which we can run software.

Still now, we have seen software as a “product” which can be bought permanently. This article will change your perception towards “software”.

Imagine the business model of BSNL. You cannot buy the “telephone” one time and say that you have “bought” the whole Telephone Network (… I am not talking about Billionaires…!). You have to pay for the “service”. So, you basically use telephone as a “service” rather than an “object” which can be bought from a shop.

Look around you, and you will find a number of services you use daily like the Electricity, Water supply…etc

So this theory can also be applied to the “Software” world. Think about Microsoft word, suppose instead of buying the costly Office suite as a product, you only pay for the “amount of time” you use MS word and the “amount of Data” you process, through it.

This model is termed as SOFTWARE as a SERVICE (SaaS).

Well this is exactly what next generation software is going to be….

Sounds bad????

Think again!!!.The software does not need to be installed “in your local Hardware. The software does not use your computer as the “platform”; instead it uses the INTERNET as the platform. Technically, the application is said to run on the “Cloud” (Think about it as dozens of web server is running a single Microsoft word..though this is not the exact representation).So irrespective of the power of your computer, it can run application smoothly. So actually, your data and your application are sitting on servers that you control. There are no restrictions on moving data into or off your Cloud Infrastructure. These servers are for all practical purposes indistinguishable from servers in your physical data center.

The internet ensures platform independence but the full feature set can be utilised only when coupled with certain other software,APIs,etc example: Flash in Youtube…


Microsoft Live Workspace:

It is similar to the example I shared with you’ll. You can access the entire Microsoft Office suite along with its latest features through the Internet, irrespective of the configuration your computer. Your work is stored in online folders called SKYDRIVE so you don’t even need Pen drives to carry your work. You don’t need to have MS Office installed. All it requires is web browser (like Internet Explorer) and a decent internet bandwidth.

This is particularly useful for project works when different parts of a single document is being edited by a number of individuals simultaneously, so you have one final copy instead of ,merging individual copies.

All Microsoft Live services are based on the cloud computing Model.

The best part is that this service is absolutely free!!!

Orkut : It is also based on SaaS model. Social networking sites provide you a service in exchange of ads.

YouTube: This also is a classic example of SaaS. The video runs on your computer irrespective of whether you have any “media player”. But you still need flash player to run the video.

Cloud computing has also given rise to HaaS (Hardware as a Service)

Suppose instead of buying the entire processor, you only pay for the amount of processing power you need for processing your data, data storage and data transfer.

So this actually refers to the “purchasing of Processing Capacity” over the web. (Google has launched a similar service called the App Engine permitting developers to run web applications on Google’s Infrastructure)

Advantages of HaaS

  1. It allows users to change their online hardware at any point of time.
  2. Users can choose their own specifications.
  3. Cheaper than actual hardware.

So now we can see, individuals as well as organizations can connect to “Cloud” computing resources to fuel their information activities rather than having to having to install “software” on their hardware.

So these are the some aspects of Cloud computing….Hope the article was informative…

Abhik Mitra