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

menu

Monday, May 11, 2015

12 Interesting facts about front end Web technologies

0 comments
1 . By typing this below you can use your browser window as text editor
data:text/html, <html contenteditable="">
</html>


2. By typing below you can quickly run your html without running html file
data:text/html,<h1>
hay, I am html</h1>


3. By typing below in your browser console you can make page editable
document.body.contentEditable='true';
document.designMode='on
4. In mordern browser if you define any element with some Id it create a JS global variable

 <div id="IAmaDiv"></div>
console.log(IAMaDiv); // <div id="IAmaDiv"></div>


5. You can pass multiple statement inside if statement without using curly braces

if (confirm("wanna see two alerts?"))
  alert("first"), alert("second");

6. If  you want to disable alert in a Html page ,you can type this in console

alert = console.log.bind(console);

7. If you wanna print an array in table form.You can use below in Chrome

var author = [{name: 'ashish', age: 24}, {name: 'Nautiyal', age: 23}];
console.table(author); 

8. console.log($0); returns the currently selected element in Chrome

9. monitorEvents(window,'click'); can monitor all the click event on page in google chrome

10. debug(debugThisFunction); will kick on debugger whenever control will execute debugThisFunction

11. Typing keys(window); in console will return an Array of global objects

12 . history.pushState({}, '', "changedurl"); by using this you can change your url bar in browser to something else
Read more ►

Saturday, May 9, 2015

Webview in PhoneGap/Cordova or Turn your website into mobile application Cordova/phonegap

0 comments
First of all you need to install Phonegap/Cordova in your system and if not installed you can refer to this link https://cordova.apache.org/docs/en/4.0.0/guide_cli_index.md.html .

I hope you are done with the Cordova/Phonegap thing and now you have a link which will open up a website and you want to convert it into an application.Making an application from a web link in just 10-15 minutes don't you think its amazing.So lets start with it.

If you are familiar with Cordova or Phonegap then you will definitely know about deviceready Event Listener in Cordova/Phonegap. But if not don't worry it a very basic thing you can set up the Cordova/Phonegap thing in your system from the link shared previously.It will guide you completely how to install Cordova in your system and it will also setup one basic project.In that project you will find deviceready Event Listener.In short deviceready is the event which is fired after the cordova file is completely loaded and your application is ready.

You can simply do like this and make your application from the link.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
 // Now safe to use the Codova API
 window.location="http://your.website";
 }
You also need to declare something like this in xml file to tell Cordova that it is safe.
<access origin="http://your.website" subdomains="true"/> 


Now in case if the internet connection in the mobile is not working and you run the above code it will not work.But there is also a solution for this.


In Cordova /PhoneGap we have a plugin for checking network connection just install the plugin from your command line window by running this command
cordova plugin add cordova-plugin-network-information

After this add some code to check your internet connection type
function checkConnectionType() {
      var networkState = navigator.network.connection.type;
      var states = {};
      states[Connection.UNKNOWN] = 'Unknown connection';
      states[Connection.ETHERNET] = 'Ethernet connection';
      states[Connection.WIFI]   = 'WiFi connection';
      states[Connection.CELL_2G] = 'Cell 2G connection';
      states[Connection.CELL_3G] = 'Cell 3G connection';
      states[Connection.CELL_4G] = 'Cell 4G connection';
      states[Connection.NONE]   = 'No network connection';
      return networkState;
    }
Now you can add logic to do something in case of no internet connection.
function onDeviceReady(){
   var networkState = checkConnectionType();
       /*load local files if there is not network connection */
    if (networkState == Connection.NONE) {
        window.location="open some other local file like sorry no internet connection";
       } else {
         window.location="http://your.website";
       }
    }
    
Or you can also open a native Cordova/Phonegap alert in case of no internet connection like this.
function onDeviceReady(){
    var networkState = checkConnectionType();
      /* load local files if there is not network connection */
        if (networkState == Connection.NONE) {
           navigator.notification.alert('Oops! Sorry No internet connection');
         } else {
           window.location="http://your.website";
          }
      }
 
This is my first one hope you will like it and fell free to ask any questions.
Read more ►

Wednesday, November 19, 2014

Cordova Contact API example with AngularJS and Onsen UI

0 comments
This tutorial is divide into three parts.

  1. Designing the template with onesen ui
  2. cordova contact plugin
  3. rendering the contact with angularl

First we will design the layout in onsen UI for the application.So first we will create a page holder. Onsen UI provides <ons-navigator> component to serve this purpose.As the page holder is created by <ons-navigator>.Now lets create a page by using <ons-page>.One thing i would like to clear before proceeding ahead <ons-page>  should be used as root element of the page. The whole page will be encapsulated within <ons-page>.We want to show the contact image  to right side and the contact information to left side.For doing this lets create a row by using <ons-row align="center">. Now devide this row into two columns by using <ons-col>.As we have now two equally devide layouts at the center.

Now lets create the placeholder for the contact information by using simple <div> component.Now lets add a button at the end to envoke some method. For creating a button in onen UI we need <ons-button> component. Lets add this component just before where page gets close i.e. before </ons-page>. So the final template of the app will be
<ons-navigator>
    <ons-page>
          <h3></h3>
          <ons-row align="center">
              <div class="Demo">
            <ons-col>                
               <div class="Demo">
              </div>               <hr />                
               <div class="Demo">
               </div>                <hr />                
              <div class="Demo">
              </div>             </ons-col>             <ons-col>
          <ons-button ng-click="pickAcontact()">Pick contact</ons-button>
                              </div>             </ons-col>           </ons-row>
</ons-navigator>
    </ons-page>
  Now our template is ready lets quickly add some css rules.
.item {
padding: 10px;
line-height: 1;
}
background-color: #ccc;
.item-thum {
height: 50px;
width: 50px;
.item-title {
border-radius: 4px; }
font-weight: 500;
font-size: 15px; } .item-desc {
line-height: 1.3;
font-size: 14px; color: #666; margin: 4px 0 0 0;
font-size: 12px;
padding: 0 30px 0 0; } .item-label { color: #999; float: right;
overflow: hidden;
} .col { border: 1px solid #ccc; background: #fff; padding: 4px;
padding: 8px;
color: #999; } .page__content { background-color: #f6f6f6; } h3 {
color: #666;
font-size: 17px;
}

  Now lets jump to the contact plugin of the cordova.First add the plugin by using "cordova plugin add org.apache.cordova.contacts" command. once the plugin is added into the application we can move ahead with this plugin . Lets quickly check whether plugin installed correctly by using cordova plugin ls.it will list the all installed plugin.
  Cordova provide navigator.contacts.pickContact api to access the contact from contact list. navigator.contacts.pickContact  takes two arguments first a success callback or a error callback.
   navigator.contacts.pickContact(function(contact){
    // contact can accessed here
   }).
   },function (err){
    //error callcback
   So  now lets play with angularJS.First of all define app ,module. Now create a controller. I have created a controller "AppController".Now create a method pickAcontact and bind this to button we created while designing the layouts by using ng-click directive.Now inside this methode call the pickContact api and on the success callback of the api add the result to $scope.contact. which we will use in the template. Now come cak to template and make data binding.The final html will be.

<ons-navigator>
    <ons-page>
          <h3></h3>
          <ons-row align="center">
              <div class="Demo">
            <ons-col>
              </div>
                {{ contact.name.formatted }}               <hr />
                {{ contact.emails[0].value }}            
               <div class="Demo">                 {{ contact.phoneNumbers[0].value }}
                {{ contact.addresses[0].postalCode }} <br />
               </div>                <hr />                <div class="Demo">
                {{ contact.addresses[0].streetAddress }} <br />
                {{ contact.addresses[0].locality }} <br />                 {{ contact.addresses[0].region }} <br />
              <div class="Demo">
                {{ contact.addresses[0].country }}               </div>             </ons-col>             <ons-col>
          <ons-button ng-click="pickAcontact()">Pick contact</ons-button>
                <img ng-src = "{{contact.photos[0].value}}" />               </div>             </ons-col>           </ons-row>     </ons-page>
  </ons-navigator>
  Come back to controller , after assigning the contact value to $scope.contact call the  $scope.$apply() ,  $scope.$apply(); will let the angular know there has been some changes made in values.

Read more ►

Monday, September 1, 2014

AngularJS ui-router tutorial from scratch - Part 1

0 comments
AngularJS is very powerful framework and provide the solution for almost every challenge without integrating any outside libraries. Angular UI library is broken in many parts so you can pick the feature and include only that in your angularJS application.
But still we can add libraries and make the angular application more powerful.
ui-router is one of most powerful ui library of the angularJS . Instead for just providing the url route it plays with the state. ui-router provide many extra and more powerful feature. We can have nested views , multiple views on one page or the multiple view wich have common controller .

INSTALLATION : For installing ui-router in your application you can install it through the bower
$ bower install angular-ui-router --save 



and then include the it in your HTML file
<script src="phoneCatApp/bower_components/angular-ui-router/release/angular-ui-router.js" type="text/javascript"></script>   
or

you can save the source code  from the GITHUB .



For using the ui-route you need to ui-router as a dependency in your module



<html ng-app="phoneCatApp">

<head>

<script src="script/angular.js"></script>

<!-- Include the ui-router script -->

<script src="script/angular-ui-router.min.js"></script>

<script>

    // ...and add 'ui.router' as a dependency

    var phoneCatApp= angular.module('phoneCatApp', ['ui.router']);

  </script>

</head>

<body>

</body>

</html>


If you used ng -router  then you most probably came across the ng-view directive . So here instead of using the ng-view we use ui-view ,the  views will get change inside this ui-view

<div ng-controller="mainController">

<div ui-view="">

</div>

</div>


Now we will write the config of the app for routing . It is very simmiler to the ng-route but instead of playing upon $routeProvider we deal with $stateProvider.

.config(function($stateProvider, $urlRouterProvider) {

$stateProvider

.state('first', {

url: '/first',

templateUrl: 'template/first.html',

controller :firstController

})

});


template  templateUrl and  templateProvider 

 These three are used  for setting the views .You can use any of them according to your needs .

  1. template - template is a  string of HTML content or a function that returns HTML
  2. templateUrl - templateUrl is a  string of a URL path to a template or a function that returns a URL path string
  3. templateProvider - templateProvider is a  function that returns an HTML content string

Controller 

 controller is used to bind the controller to the view. Which can operate over the view 

url 

 This work very simmiler to the ng-route  but have many upgrades in it .Which we will discuss in future.



How to route ?

1 . ui-sref 

 ui-sref work smiler to the href but it have more capability . It takes the stateName as the the parameter .


<a  ui-sref="first">First</a> 

2 . $state.go

  If you want to change the view from controller then you need to use $state.go . The syntax is

go(to, params, options)

  • $state.go('first') will take it to first state.
  • $state.go('^') - will take it to a parent state
  • $state.go('^.sibling') - will take it to a sibling state
  • $state.go('.child.grandchild') - will take it to grandchild state



This is the first part of ui-router. I will discuss many other parts in next series of it.
Read more ►

Sunday, July 20, 2014

Promises in JavaScript: 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!



About Author : 
Name :S Ravi 
Twitter : https://twitter.com/SRavi_Kiran
Bio: Software Professional, Passionate about Microsoft technologies, Blogger, Love to pass time with Music and Cricket
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 ►