• We Code
  • We Design
  • We Develope
  • We Write
  • We Share

menu

Sunday, July 20, 2014

Promises in AngularJS: What are they and How to use them?

0 comments
Asynchrony is unavoidable in any platform these days. Asynchrony doesn’t just help the servers to serve their clients better but it also maximizes effective utilization of the resources. JavaScript is no exception.
In recent times, use of asynchronous programming became very important as the expectations out of the software systems that we are writing is went up drastically. And even some of the browser APIs like Indexed DB work on an asynchronous model.
Traditional way of handling asynchronous tasks is the callback model. As the asynchronous tasks are handled by a separate thread or a separate process in some cases, the main program using the asynchronous task doesn’t know when the operation is going to be finished. So, we attach a callback function to the asynchronous task and the attached method would be called when the task is done.Though this approach looks good for upto a chain of one or two asynchronous tasks, it makes the code less readable when we have 3 or more async operations that depend on the result of the previous
operation. Following is an example of such scenario:

Promises: What are they and How to use them?

firstAsyncOperation.onOperationCompleted = function(

if(operationObject.state == “success”){

var secondAsyncOperation = secondAsyncFunction(operation.resultData);

  secondAsyncOperation.onOperationCompleted = function(){

   if(secondAsyncOperation.state == “success”){

     var thirdAsyncOperation = thirdAsyncOperation();

      thirdAsyncOperation.onOperationCompleted = function(){

       if(thirdAsyncOperation.state == “success”){


       }


      };


    }

      };

}else {

//May be some other async operation to handle error case
}

};
That might look beautiful with nice switch between the curly braces and parentheses, but it becomes difficult to manage such code blocks. It becomes really painful when you have to write such blocks multiple times in your code. Promise is a pattern created to solve this issue. Rest of the article speaks about the pattern of promises and how to use them to address this kind of issue.

What is Promise ?
A promise is an object that holds an asynchronous operation. At any given point of time, the object is in one of the three states:

• Pending: When the asynchronous operation is still going on

• Success: When the async operation is successfully completed

• Failed: When the async operation is completed but failed

The promise specification doesn’t tell how to implement a promise, but it says what should be implemented. According to the specification, any promise implementation should have a then callback that accepts two callbacks: one for success and the other for failure. Some implementations (such as Q) also accept a third callback that is invoked when the operation is in progress.

A typical asynchronous operation handled by a Q promise looks like:



asyncOperationObject.then(successCallback, errorCallback, inProgressCallback);

function successCallback(data){
     //----------
     //----------

     //---------- 

    }

function failureCallback(error){

 //----------
 //----------
 //---------- 

 }


 function inProgressCallback(info){

 //----------
 //----------

 //---------- 
 }

 

In general, we pass in anonymous functions as callbacks to the then method. The syntax is shown below:




asyncOperationObject.then(function (data){
//--------
//--------
}, function (error){
//----------
//----------

}, function (info){
//----------
//----------

});


One can include or ignore the callbacks depending upon the need. In most of the scenarios, we ignore the in-progress callback. It can be used to show when there is a need to show a progress bar to indicate the current state.

Chaining Promises

The very first thing we saw in this article is, how dangerous the callback model is for chaining async operations. The best part about the promises is that, the then method also returns a promise object.
This means, we can return another then on the return object.




asyncOperationObject.then(function(data){

   return data;

  }, function(error){

    console.log(error);

  })

  .then(function(data){

    return data

  }, function(error){

    console.log(error);

  })

  .then(function(data){

   return data;

  }, function(error){

   console.log(error);

  });


Though the above operation is chained,it still looks flat. It is very easy to manage such operations as well. More than everything, it is easy to read the subsequent then blocks.

Conclusion:
Understanding promises is very crucial these days. It is an important pattern to be followed in every JavaScript heavy application. There are several implementations of promises, including Q, jQuery’s deferred API, Angular’s $q (inspired from Q), RSVP, when.js and so on. Promises got a place in the ES6 specification as well. It is already implemented in latest versions of many of the major browsers.

Happy promising!
Read more ►

Monday, June 2, 2014

AngularJs $apply $digest in Detail With Error Handeling

0 comments
The best practice to change the value of bindings is $apply . What $apply actually does ? it update the bindings of the page and notify the value has changes . it calls $digest internally and return the promise. Almost whole angular binding run inside $digest.
 $scope.$apply('foo = "bar"');

//or
 $scope.$apply(function(scope) {
scope.foo = 'bar';
});

//or
 $scope.$apply(function(){
$scope.foo = 'bar';
 });


I was trying to change the scope value with ng-click . And i kept getting a error . Error: $apply already in progress.
If you are also facing the same error I found two solution for it
First Solution : you can put the putAsafeApply method , which wil check the status of the $apply .

$scope.putAsafeApply = function(fn) {
var status = this.$root.$$phase;
if(status == '$apply' || status == '$digest') {
 if(fn && (typeof(fn) === 'function')) {
 fn();
 }
 } else {
this.$apply(fn);
}
};


$scope.$$phase or $scope.$root.$$phase will return "$digest" or "$apply" if a $digest or $apply is in progress. I believe the difference between these states is that $digest will process the watches of the current scope and it's children, and $apply will process the watchers of all scopes.

So now we have putAsafeApply method and we can use it where ever we want to use instead of $apply.


$scope.putAsafeApply(function() {
 $scope.foo = 'bar';
});



Second Solution : It is simpler then the first one .You can use the $apply inside the $timeout function without delay.

$timeout(function(){
$scope.foo = 'bar';
})


 $timeout(callback) will wait until the current digest cycle (if any) is done, then execute your code, then run at the end a full $apply which will call $digest internally as explained earlier .



Read more ►

Thursday, May 29, 2014

PhoneGap / Cordova Unzip Plugin for android

0 comments


While developing A phoneGap application i faced a problem in unzipping a folder. I downloaded a folder in zip from server using FileTransfer API.
I searched a lot for UnZIP plugin of phone gap but did not find any one the net . Than i started writing a fresh cordova plugin for unzipping

There is few prerequisite before using this plugin
Node.js and Cordova CLI or PhoneGap's CLI


Installation : 1 . Open Your terminal and go to your project directory
2 . Enter this command
phonegap  plugin add https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin.git
  
or If you using cordova
cordova  plugin add https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin.git
or you can download the plugin from Git repo Manually

https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin.git



3 .I Assume you downloaded the plugin manually from git repo

Copy the com folder inside the src folder under your android project

4 .Copy ExtractZipFile.js file inside your www folder and make its reference in index.html

5 . Open res/xml/config.xml file from your project and paste the line
   <feature name="ExtractZipFile">
                        <param name="android-package" value="com.phonegap.plugin.ExtractZipFile.ExtractZipFilePlugin"/>
                </feature>

or 
 <plugin name="ExtractZipFile" value="com.phonegap.plugin.ExtractZipFile.ExtractZipFilePlugin" />


or Usage :
function extractOK(status)
{
    console.log("extractOK");
}

function extractError(error)
{ 
    console.log("extractError "+error);
}


function extractFile(zipfile)
{
    console.log("Extracting "+ zipfile);
    extractZipFile.unzip(zipfile, extractOK, extractError);
}


Get the file reference and pass as parameter in function extractFile(zipfile) . And you are done with extractFile


Git Repo Link : https://github.com/ashishanautiyal/Unzip-PhoneGap--Plugin
Read more ►

Friday, May 23, 2014

Knowledge Optimization and Knowledge Sharing in Java Technology

0 comments
Information is crucial to the organizations and individuals as it helps them to protect their data, wealth as well as assets but often there has been the challenge of sharing this data with others for them to exploit it to their advantage and any other intended purpose. As a result of this therefore, there is need to allocate more resources and time to the sharing of this information by the different people. Governments, individuals as well as corporate and organizations therefore have set out to come up with better ways of enhancing the sharing of their data in the information systems. One better way of doing this is through the sharing of the knowledge through the Java Technology and software.

Consistency in publishing of the blog posts
Although patterns of publishing of blog posts with regards to the regularity with which they are done are determined by the nature of the content and the idea of the blog site, it should be done as often as possible. Often the successful way to attract and maintain visitors to a site could be through regular publishing of quality content for the blog site which will not only appeal to the visitors but also keep them coming back to the site. Attracting more people will widen the scope of the search of the website on the search engines as well as improve the rank of the website in the search engines and this will improve the visitors to the website as well.
Maintaining the visitor numbers high to the website can also achieved through other strategies such as inclusion of survey or polls done on a frequent regular basis like daily or weekly. This could also be done alongside inclusion of a visitor’s book in the website as a strategy to improve and notice the guest frequency.
Keep the visitors interested by asking questions related to the blog post
The development of questions relevant to the particular blog post will always keep the visitors asking more about the topic of discussion. This will also ensure their involvement as they will attempt to respond to the question in the comments section. Their contribution not only improves the content of the website but may also highlight the challenges especially with regards to products or services for a business, advertisement or sales promoting or related website.
Networking
This is especially relevant when done with other blogs which are directly related to the area of interest of the website. It provides users of other sites a direct link to your website from the other site. Inclusion of links to the website in comment sections of other blogs which are dealing with related fields could also be a good strategy to improve visitor frequency in the site.
Inclusion of sharing button or option in the site also allows the users as well as visitors to share information that they find useful or relevant to the site. This will also allow them to spread the links of the bog by sharing them on social media as well as through their personal emails. Use of handles such as twitter, Facebook which allow for instant feedback is also good for the promotion of the site as well as attracting more users.
Quality content
Successful implementation of the java technology as a tool of sharing information will heavily hinge on the content that is being shared. When the content is short, precise and to the point then it is likely to appeal to many people rather than a redundant, long and boring content that is discouraging to read. Sharing of information that is useful and healthy for people will ensure that they read and want to read more the content associated or being passed through the Java technology. However much any content is shared and optimized across the different mediums and channels for consumption by the users, it will not be able to do much or achieve much with regards to impact if the content is not acceptable by the readers.
Avoid duplication of content
When the content being shared is one that has been duplicated and lack originality, it tends not to appeal to the readers and this may perhaps affect the consumption of the content and the general perception of the contents with regards to the reliability of the java technology as a source of information. It is therefore critical to avoid the duplication of content that is especially to be passed on to the people through the java technology.
Avoid issues of copyright
Any content that is to be passed on through the java technology should be able to be shared without any challenges especially with regards to issues of copyright. Most of the copyright issues have to do with the plagiarism of content without the author’s knowledge or permission or even acknowledging the author. Hence therefore there is need to prevent the issues of plagiarism or any other issues that may lead to copyright law suits and such.
Content should be content specific
When content is said to be specific this implies that is should be precise so that it only highlight the key point and remains within the scope of the subject of interest. Redundancy tends to arise because of the inclusion of irrelevant content which does not even relate or touch on the subject of interest in any way.
Avoid promotional content
Such technology is supposed to pass knowledge and not be used as forums to do promotion of other products and services. Therefore this should be avoided at all cost as it may lead to disregard of the content being shared even if it is relevant and worth reading.
Create links and addition share buttons
Inclusion of links and share buttons are necessary to allow for further sharing of the knowledge especially through the social sites. This could also be extended and done on the email so that the information can be channeled out as much as possible.


Author’s Bio: He is a writer by profession. He contributes articles and blogs on travelling, education, technology, fashion and shopping. He has good knowledge in all writing field. He helps the student’s any papers to buy from custom essay writers.
Google+ profile

Read more ►

Thursday, February 13, 2014

Show loading screen in Phonegap app over inAppBrowser

0 comments
The trick is very simple for showing the loading screen in phonegap application.You Just need to call activityStart function of the notification.


For hiding the loading screen in phonegap just call activityStop function.

The loading screen is very helpful while making Ajax call or while using the inappbrowser.It is really useful when loading the external link in inappbrowser.It is useful because you can not create a loading screen through your HTML in client side if you are loading the external link.Because inappbrowser overlay on the application.You can show the loading screen when loadstart events fire in Inappbrowser hide it when loadstop events fire.
Here is an example of loading screen with inappbrowser.




This phonegap loading screen only works with the android .And if you will touch the screen The loading screen will get hide.
Read more ►

Monday, January 27, 2014

FaceBook Login Logout using cordova 3.3.0 cli.

0 comments


In recent past i faced a lot problem in setting up the cordova facebook plugin with cli 3.3.0.After a lot of search i found it is typo from cordova.I am here sharing the easiest steps to setting up cordova facenook plugin using cordova cli 3.3.0 .

How to set up the Facebook plugin With cordova 3.3.0 cli for android ?
before Setting Facebook plugin with cordova 3.3.0 you have to setup these
Prerequisite :
  1. JdK
  2. Apache Ant
  3. Node.js and NPM
  4. Git
  5. Cordova 3.3.0 CLI


Once you installed all the above properly.Open your command prompt and go to your project directory and run this command




you will see the  screen like above after running the command . You have created a cordova project.Change your directory to facebookTutorial 

Now you are inside cordova project which you just created .Run the below command.



>

Now you installed facebook plugin in your cordova project. But if you will run the command  cordova plateform add android it will get failed and ask you to putt appid and appname.
For removing this error locate the folder \plugins\com.phonegap.plugins.facebookconnect inside your projectfolder.
Open The plugin.xml file from \plugins\com.phonegap.plugins.facebookconnect folder and find the lines




Modify it to


Where value is your app id and your app name.
 Run the command cordova platform add android . The screen similar to below will appear.
 Now you have installed facebook plugin and created android project.
Now we will see how to get login to facebook through cordova facebook plugin ?
 Now open the index.html file from your projectfolder/www in your favorite editor. And delete everything from this .
 You have a Blank index.html file.Write some dom elements inside your body Tag 



Your Dom structure is ready . Now Make reference of cordova.js ,cdv-plugin-fb-connect.js and facebook-js-sdk.js



Now come to your <script></script> portion and check the cordova facebook and cdv agent are included properly inside your project




Write  event handler function for login logout and status change.


Its time to initialize FB sdk now. Here i am initializing it with device ready event


Once the fb is initialize we can  make login to facebook through our application.Here the function for log in

For the Logging out

For getting the login status here is the code snipet






Once all this done run the command 



Your Application will be launch in your emulator.Here are few screenshots of emulator.


















Hope you enjoyed reading this.If any doubt i am open to answer .Feel free to ask and do't forget to share with your friends
Read more ►

Tuesday, January 21, 2014

Offline App Capability In HTML5

0 comments
HTML5 Offline Apps
Html5 Offline Apps
Offline app capability in HTML5 bought all the power to store data offline .When we talks about offline people ask offline means without internet ? First take the term ONLINE first . online and Web are kind of synonyms.
So why the term Offline is getting use for web technology . The offline here means run the webpage from file:// uri. But hang on it does not mean the web page will never get connected to server.The term offline will make more sense if we will take it like the web page could survive at the server downtime.There are various apps who connects the cloud server and survives at downtime. Gmail Mobile app and gmail offline are examples
.
In the Older time devs used the technique like cookies,Plugin Based Storage for storage. But the era of HTML5 bought more power to the client side for storage.
 . You can check the application for online/offline using navigator.onLine(). And it works everywhere in latest browser even in IE also.
You can also listen the events for it using.

document.body.addEventListener("online", function () {console.log("Now you are online !!!")}
document.body.addEventListener("offline", function () {console.log("Now you are offline !!!!")}

HTML5 bought many features to make application offline .Few Technique to make app offline
1.Application Cache : CACHE MANIFEST file make you able to store the resourse files locally for offline usage.Make a reference of manifest file inside <html> tag.
<html manifest="MyManifest.appcache">.

</html>
The mime type of the manifest must be text/cache-manifest.Manifest file is a simple text file . It looks like this

CACHE MANIFEST
index.html
index.css
index.js

2.Web Storage : Web storage have two sub category. One is persistent called local storage . In local storage we can set a value to a key using localstorage.key="value"
And we can retrieve it later . The other category of web storage is session storage we use it similar but the data gets lost once the browser gets closed .
We can just match the strings using the web storage.Simplicity is for calling the API is good part of this and bad performance is bad part of it.

3.Web SQL Database : Web sql database is a relational database .It has all the power of storing the complex relational database. it is well supported in all mobile browser the performance is really good .It has robustness. And the best part it is really easy to maintain.One have good command over sql can play with it with lot of ease.

4.Indexed database : Indexed Database is a collection of  stores of objects . Where you can keep the objects for future use.In indexed Db you don't need to define a schema before like  web sql database . In Index db you can have multiple databases and in each database you can have multiple stores.Indexed Database have good search performance and have robustness

Read more ►