Saturday, June 28, 2014

Write Better jQuery Code for project

"JQuery is most powerful and rich tool for client side development. But improper use of jQuery might become nightmare for developer. In this article I have explained all about what developers are doing and what they should do with jQuery.”

This article aims to explain use of jQuery for rapid and more sophisticated manner. Now a days any website does not only focus on backend functionalities like user registration, adding new friends or validation like stuffs, but also focuses on how their web page will appear to user, how their page will behave in different - different situations. For example, slideshow on front page, onmouseover show beautiful animations, show properly formatted error message or show interactive hints to user for what to do on their site.


So, what is jQuery:
JQuery is very handy and more interactive, powerful and rich client side framework built on Javascript. JQuery is able to handle many powerful stuffs like HTML manipulation, events handling, beautiful animations. And its most attractive feature is it is cross browser. By using plain Javascript we need to make sure for many things like, the code we write is good as well as must be tends to more perfection. It should handle any exception if user enters any other invalid type of values and not just hangs script or show horrible behaviour. But in my career what I have seen is many junior developers are using plain Javascript solution instead of jQuery like rich frameworks and writes numbers of line of code for just doing some small stuffs.

For example, one wants to write code for showing datepicker selection on onclick event. If we are writing code using plain Javascript, what could be the flow is,

1) onclick event create one div element.
2) inside that div, add content for dates, month and year.
3) Add navigation for changing months and year.
4) Need to make sure that, on first client div should show and and on second client div must be hidden, and should not affect any other HTML elements. So, just creating datepicker is little more difficult task and if this needs to implement more times in same page, then it becomes more complex and if code is not properly implemented then doing modification can be a nightmare.

Instead of doing this type of complex things, jQuery comes to rescue in that nightmare. By using jQuery we can show datepicker like this:


 $(“#id”).datepicker();

That’s it, we can reuse same code multiple times by just changing id(s) and without any kind of collision we can show multiple datepickers in same page. That is the beautifulness of jQuery. In short, by using jQuery we can focus on more functionality of system, not just only small-small parts of system. Using jQuery we can write more complex code like rich text editor and many other stuffs. But writing jQuery code without proper guidance and proper methodology, we ends up writing code in horrible formation, and sometimes that kind of code becomes more panic for other team members to understand and modify for just small changes.

In my professional career, many times I have seen that, developers make silly mistakes during jQuery code implementation. So, based on some silly mistakes, here is some general guideline that every developer should keep in their mind during implementation of jQuery code.

General guideline for jQuery:

1) Try to use ‘this’ instead of just using id and class of DOM elements. I have seen that most of developers are happy with just using $('#id') or $('.class') every where.


//What developers are doing:
$('#id').click(function(){
    var oldValue = $('#id').val();
    var newValue = (oldValue * 10) / 2;
    $('#id').val(newValue);
});

//What should be done:  Try to use more $(this) in your code.
$('#id').click(function(){
    $(this).val(($(this).val() * 10) / 2);
});



2) Avoid Conflicts: When we are working with cms like wordpress or magento etc. they might have use other Javascript frameworks instead of jQuery. And if you needs to work with jQuery inside that cms or project. Then use noConflicts of jQuery.


var $abc = jQuery.noConflict();
$abc('#id').click(function(){
//do something
});



3) Make Sure for Absent Elements: Make sure that the element on which your jQuery code is working/manipulating is not absent. If the element on which your code will manipulate is adding dynamically then first find it, if that element is added on dom.


$('#divId').find('#someId').length;



This code returns 0 if there is not any element with 'someId' founded else it will return total numbers of elements which are inside 'divId'.



4) Use proper selectors and try to use more ‘find()’, because find can traverse DOM more faster. For example, we want to find content of #id3

//developer generally uses
var content = $(‘#id1 .divClass’).html();

//better way is  [This is more faster in execution]
var content = $(‘#id1’).find(‘div.divClass’).html();



5) Write functions wherever required. Generally developers write same code multiple times. What should he do is, first make a flow how that task is going to implement. Find the block that will repeat again and again. For example, on blur of any text box get validated value. If value is empty then return 0 else give values that user has entered. So, there are some way to implement that functionality.



//Javascript
function doValidation(elementId){
//get value using elementId
//check and return value
}

//simple jQuery
$(“input[type=’text’]”).blur(function(){
//get value using $(this)
//check and return value
});

//best way to implement
//now you can use this function easily with click event also
$.doValidation = function(){
//get value
//check and return value
};

$(“input[type=’text’]”).blur($.doValidation);


6) Object Organization: This is another thing that each developer needs to keep in mind. If some bunch of variables are related to one task and some bunch of variables are related to another task then make them more organized.


//bad way
var disableTask1 = false;
var defaultTask1 = 5;
var pointerTask1 = 2;
var disableTask2 = true;
var defaultTask2 = 10;
var currentValueTask2 = 10;
//like that many other variables



//better way
var task1 = {
disable: false,
default: 5,
pointer: 2,
getNewValue: function(){
//do some thing
return task1.default + 5;
}
};

var task2 = {
disable: true,
default: 10,
currentValue: 10
};

//how to use them
if(task1.disable){
//do some thing…
return task1.default;
}


7) Use of Callbacks: When multiple functions are used in your code and if second function is dependent on effects of first output, at that time you need to write callbacks.

For example, task2 needs to be executed after completion of task1 or in other way, you need to halt execution of task2 until task1 is executed. I have seen many developers are not aware of callback functions. So, they either initializing one variable for checking [like mutex in operating system] or setting timeout for execution. Below I have explained how easily you can implement using callback.

 //Javascript way
task1(function(){
task2();
});


function task1(callback){
//do something
if (callback && typeof (callback) === "function") {
           callback();
    }
}

function task2(callback){
//do something
if (callback && typeof (callback) === "function") {
             callback();
}
}

//Better  jQuery way
$.task1 = function(){
//do something
};

$.task2 = function(){
//do something
};

var callbacks = $.Callbacks();
callbacks.add($.task1);
callbacks.add($.task2);
callbacks.fire();


8) Use of Each for iteration


var array;

//javascript way
var length = array.length;
for(var i =0; i < length; i++) {
var key = array[i].key;
// like wise fetching other values.
}

//jQuery way
$.each(array, function(key, value){
alert(key);
});


9) Never write any code again and again. If so, you are doing wrong holt your coding and read above described all 8 points again.

So, I think this is it for getting started with writing more manageable and reusable code. There are many things that needs to be taken care of during development. Next time I’ll explain how to write more effective plugin with some example.

Wednesday, August 14, 2013

Free online Linux Courses


Majority of free online Linux courses are not affiliated with universities but are intended for self-study and don’t offer any academic credit. Linux course materials comprise PDF, video and screenshots and content is normally intended for newbies of Linux systems. 

 Listed below are sites that offer free Linux courses online:

1) Back to Basics: Linux Fundamentals at Novell
This free tutorial is meant for individuals who want to learn Linux fundamentals by means of self-directed study. This course concentrates on various functions including restarting and shutting down the Open Enterprise Server, logging in and out and controlling the Linux desktop. You can also access a cheat sheet for most typical command terms used in Linux.       Visit Link

2) Building Dynamic Websites at Harvard University
This online OCW course provides knowledge required to make a website. The course has multiple video lectures and individuals are instructed on how to make a website using Linux, in addition to a range of other frameworks. You can learn how to set up domains, program with Java, design databases, and construct web pages using CSS and XHTML.     Visit Link 

3) Computational Physics at Universiti Teknologi Malaysia
The course focuses on teaching students how to do physics calculations using a computer as a calculator. You can also learn Java programming in a Linux environment. With the help of external website links, this online course instructs you about using algorithms and working within the Linux OS. Visit Link

4) The Embedded Linux Quick Start Guide through YouTube
This free tutorial lasts for less than an hour and offers learners with an introduction to the Linux environment. Explained by Chris Simmonds during a 2010 Embedded Linux Conference in Europe, this is the first video in a 3-part series on Linux. You can learn the four fundamental elements of Linux such as toolchain, boot loader, kernel and user space.   Visit Link

5) Introduction to Linux at the University of South Carolina
This is a simple preparatory tutorial of slides available in PDF format. The course material provides basic information about Linux, its different versions - or distributions, and how to use it. Some of the topics and tools covered in the course comprise files, folders, pages, commands and writing script.

6) The Linux Effect: 20th Anniversary at The Open University
Introduced as an online podcast training, the Linux Effect provides information on the Linux OS and how it's progressed through over the years. The course provides information pertaining to the origin of Linux, how it can be used in our daily lives and the link between Linux and cloud computing. You need to have a PDF viewer, such as Adobe Reader, to finish this course.      Visit Link

7) LPI Exam 201 Prep: Linux Kernel at IBM
This is a free tutorial series that prepares the students for the Linux Professional Institute Intermediate Level Administration (LPIC-2) Exam 201. While the first tutorial students are explained components, compiling, patching and customization of a Linux kernel. Other topics include system maintenance, hardware, web services, and troubleshooting.      Visit Link

5 Great Free Tools For Your Invoicing Needs


Sending invoices and quotes to multiple clients is an everyday task in the life of a web designer. You will fall into hundreds of paid invoice applications while searching for the free one, each ranging from 5$/m to 30$/m and so on. Paid apps can be good for large corporations who earn a lot of money but they are simply a monthly expense for an average freelancer. That’s why we have prepared an article having 5 best free invoicing apps for your business.

Billing Boss
      Billing Boss is a totally free invoicing application with pretty features. The user can easily keep track of billings and payments. Account at Billing Boss can be integrated with Sage Payment Services, Beanstream, or PayPal. In result, customers can pay your invoice online immediately. User interface of Billing Boss has been adapted in different languages. Further, the mobile version of web interface is also available to interact with application on iPhone or G1.


During the Sign Up, the user fills up the required information like Name, Address, Logo, and Tax Information of business. The account can also be linked with some merchant services if required.

In next step, you need to create customers, which is simple enough. Then you can make a quote or invoice. Once you fill the invoice and save it, a preview of invoice will appear. In this preview, you can apply available styles, send or print it, or save as pdf. Below are the screenshots for the above mentioned two steps.






Intuit Billing Manager
        Intuit Billing Manager is also a free and intuitive online invoicing application. You can easily create and send invoices. The application gives you a review of what is overdue and what has been paid. The user can send reminders to customers if there is an outstanding payment.



After filling login details, the user can create invoice immediately. I would recommend going on settings tab and modifying your details accordingly. You can alter business information like address and logo, default messages attached in outgoing email, payment methods and some other default invoicing parameters.



In the left side bar of the application, you can see “My Address Book” which is used to manage your customers. You can add manually or import CSV file of your business contacts at once. Also, there is a section in the sidebar titled as “Products & Services”. In this section, you can add what you are offering to avoid manual entry whenever you create an invoice.

If you create invoices infrequently, above mentioned steps can be skipped. The invoice creation process is straight. You can apply one of the invoice templates available. After filling the information, the invoice can be saved, previewed, printed, or sent by email. In print mode, the invoice can also be saved as pdf.





Invoice Journal
           Another Great and Free invoicing application is invoice journal which lets you create invoices for your clients. After signup, invoice journal give you a unique sub domain which can be used for login to your account. The process is very simple. You can create clients and after that start sending invoices for no fee. The application has a nice and very simple user interface which makes it great to use.



BambooInvoice
            BambooInvoice is a free and open source application to send and manage professional invoices. One has to install it on its own servers before using it. It is one of my favorite invoicing application as my point of view is that invoicing and your personal finances are sensitive case and you should not leave them to some one else.


The open source software needs php5 and mysql 4.1 databases to work efficiently. It is build using code igniter and really have great user interface. BabmooInvoice is a very active project and you can also get support if you run into any trouble by accessing its forums here. Give it a try and you will love it.





Simple Invoices
         Simple invoices is another free and open source invoicing system which you can use to get money from different clients. Like BambooInvoice, you have to install in on your own server to use. The open source application has been translated in to many languages and some developers have also built extensions for it. You can also email your prepared invoice as pdf. Simple invoices has comprehensive documentation so you can install it easily.

Have a look at the user interface of simple invoices. It has been enhanced with Ajax and java script.



I've covered some awesome free web apps that are best alternatives of expensive invoicing apps. Feel free to share your invoicing systems and let us know if we have missed something important.


Monday, July 15, 2013

Create new controller on ZF

In this tutorial I'll explain how to create new controller and do more interesting stuffs. As I explained in previous post, for most important of controller, that requires directory with same name of controller and inside that, view pages with same name of all actions of controllers. But, this is automatically managed by ZF command line tool. And in Netbeans IDE there is more good interface for executing commands

- in Netbeans project panel --Right Click on project > Zend > Run Command... and interface will be open.


  • First parameter is "Filter": That similar to search particular command from all command list.
  • Matching Tasks: This will show you commands matching your query entered in Filter textbox. Select proper command from list. There is text area below list of commands, it'll show you description.
  • Enter required parameters in "Parameters" textbox.
  • At very bottom, there is "commad", it'll show you final output command. 
  • and press Run to execute command.
  • For example, I've created controller named "info".










[controller]

[view]


As Shown above both images, you can see new created controller: "InfoController.php" and for that controller there is "info" directory with .phtml files of actions of controller.

Now, let's modify Info Controller:
- Remove content of index.phhtml and edit indexAction in Controller.








In any controller there is init() and indexAction() as by default. You can create as many functions you want. When any controller executes init() method always executes first, no matter which action you are executing from that controller.

Now, Lets create another action in info controller with its view:


and add some message in anotherAction() function...

and execute...


That's it. This is enough to get started with ZF Controllers.

Controller understanding in ZF

When we create new ZF project, it creates two controllers [ IndexController.php & ErrorController.php ] by default. Controller as also called as Action Controller, because it controls all actions. Controllers are located in the application/controllers  directory. The action controller is concerned with out application's control logic and is part of the 3-tier separation the Model-View-Controller offers.

Default Example of controller:

class IndexController extends Zend_Controller_Action                                                                    
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }


}



Most Important:


Once one controller is created, then there is some thing you must care about. For example, for IndexController.php, with controller its view file is also created. As shown in image, there is naming conversation for that also. Views directory stores all view files of application. Inside views/scripts,  there must be directory with the same name of controller.
So, in this example there must be index directory. And based on action method in controller there should be view file. So, one view file for one action. So, here in this example, there is indexAction in IndexContoller.php, so, in views/scripts/index there is index.phtml


How controller executes:

We can directly call controller from addressbar. example: 
http://zf2-local.com executes indexAction() of indexController.php.
so, if you execute http://zf2-local.com/index/ then also output will be same. as like that, 
http://zf2-local.com/index/index will also give same output.






In next tutorial we'll modify controllers.

Understanding Directory Structure in ZF

When we create new project in Zend, it creates directory structure for us. On right side image, full directory structure of ZF application is shown.

This structure has four main area, application, library, public, and tests.

Application Directory: Is responsible for holding our application-specific files such as configs, controllers, models, and views. These are basic in any zend framework application,  in some zf application there is modules directory, holds different modules required for application. So, This application directory contains main MVC files.

Library directory: Is responsible for holding our supporting classes that not come into the scope of model. Inside library, we have the zend directory that contains the ZF source files.

Test directory: Stores our tests for our application.

Public directory: Is responsible for holding all of our publicly accessible assets such as images,CSS, and JavaScript.


Bootstraping [Bootstrap.php]:  This refers to the process of application initialization where we configure, and startup, the MVC process when someone requests a page.

The Index file [index.php]: This file is created under public directory, which is the main entry point for all of the requests to our application. This file points to application, library directory and application environment of application.

.htaccess file: This is important file in application, that rewrites rules for routing.

Application Configuration [application.ini]: This is most important for zf application. This is heart of application. Because, it contains all configurations about our application like php_errors, database connection, & path application, controller, library directory and all routing mechanisms are written here.



Zend Tutorials

Starting New Zend Framework Project

Hello, I'm back with new Zend Framework Tutorials. Go through these given links before directly starting from this tutorial:


In, this tutorial I'll explain how to create new Zend Project on your server with NetBeans IDE. Follow the steps as show in image below:
    [Image 1]

    [Image 2]



















[Image 3]

    [Image 4]


    


























[Image 5]


If you see directory structure like image 5, then congratulations...!!! your  Zend Project is ready to start.

Other ways to create project:
Zend Framework having powerful command line interface for doing work more easily. In Zend framework library you downloaded, there is "bin" folder contains zf.sh and zf.bat files.
- First go to the directory where you want to create your project.
- path-to-bin/zf.bat  create  project  project-name

Now, I created virtual-host named http://zf2-local.com.  This virtual host points to my public folder not root folder of project.




That's it, if you are able to see this type of page, then your created project works very well.