Free Twitter Bootstrap Admin Template

Previously I had shared an admin template which was custom-made. Today I share an admin template based on popular Twitter’s Bootstrap CSS framework. It has a lot of benefits such as responsive design, response images, a host of ready-made styles and icons that you can use.  Take a look at some of the images in below given gallery, click to see in full view:

Go ahead and download it here and have fun :)

Download

My Local Development Workflow with WAMP/XAMPP, GIT and Google Drive

I like to share my local development workflow which has turned out to be extremely useful in that all my projects’ files are versioned and on the cloud. I use git to keep my files versioned and Google Drive so that I can access my projects anywhere. In this post, I will share really cool stuff that you definitely should consider implementing for your own projects.

If you don’t know about git and its benefits, there are numerous compelling reasons why it is useful, you might want to check out:

The benefits of keeping all my files and projects on the cloud like Google Drive should be obvious but if you are still not sure, check out:

Although there are many other cloud storage services such as Microsoft SkyDrive, Dropbox, Box, Bitcasa, etc but I chose Google Drive since it gives 10GB of free space which should be enough for my development needs. If that’s not enough for you, you can create another Gmail account and get another 10GB free. You might want to read their usage policies too if you want.  You may also consider using Bitcasa which gives you unlimited space but since it is new, I can’t personally trust it as yet.

Installing Google Drive

Step 1: Create a new Gmail account to be used with Google Drive client software. Although you can use your existing account but it is good idea to create a new one used for your projects’ backup only.

Step 2: Download Google Drive from here or here. During the installation, you would be asked to specify the folder path which will be synchronized with Google Drive. Make sure that you specify a folder present on any drive other than your OS drive so that even if your system crashes or corrupts, your projects remain intact. For example, I have that folder on path D:/Google Drive/

Step 3:  Once installed, run Google Drive software and specify the credentials of your newly created Gmail account.

Using Google Drive with WAMP/XAMPP

Now that we’ve setup google drive, it is time to setup document root to google drive folder and create virtual host. This would allow you to run your local projects through WAMP/XAMPP from google drive folder. The reason why we do this is that since google drive folder will be sync by google drive software, any project we put in that folder will automatically be uploaded in your google drive account.

Note: I am using XAMPP but if you are using WAMP, some settings or file paths might be different, you should consider reading its documentation.

Step 1: Inside your google drive folder, create a new folder named webroot making whole path X:\Google Drive\webroot where represents your drive letter.

Step 2: Assuming you have specified google drive folder to be  D:/Google Drive/, open httpd.conf (normally located at apache\conf folder) file in notepad or other text editor and find the line Include “conf/extra/httpd-vhosts.conf”. If there is a hash (#) before that line, remove it. Now find the line with <Directory /> and you should see something similar to:

<Directory />
 AllowOverride none
 Require all denied
</Directory>

Change Require all denied  to Require all granted

Or if you see something like:

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

Change it to:

<Directory />
    ........
    Allow from all
</Directory>

Now come to bottom of the file and add:

<Directory "D:\Google Drive\webroot">
  Options Indexes MultiViews
  Order Allow,Deny
  Allow from all
</Directory>

Save the file and close it.

Step 3: Open httpd-vhosts.conf (normally located at apache\conf\extra folder) and add these lines at the end of it:

<VirtualHost 127.0.0.1:80>
    DocumentRoot "D:/Google Drive/webroot"
    ServerName gdroot.loc
    ServerAlias gdroot.loc
    ErrorLog "D:/Google Drive/webroot/logs/error.log"
    CustomLog "D:/Google Drive/webroot/logs/access.log" combined
</VirtualHost>

Save the file and close it. Notice that we have specified gdroot.loc as address which actually means google drive root (.loc signals that it is local folder) which actually maps to your google drive webroot folder eg D:/Google Drive/webroot. Notice that you could name it anything you want like mycoolwebsite.com, yourname.com, etc but of course that is local folder running from your own computer.

Step 4: Open hosts file in notepad or other text editor located at X:\Windows\System32\drivers\etc where stands for drive letter where your OS is installed. At the end of that file add this line assuming you specified URL in above step as gdroot.loc:

127.0.0.1       gdroot.loc

Or if you also use port to access your LAMP/XAMPP URLs, specify that as well:

127.0.0.1:PORT_NUMBER_HERE       gdroot.loc
Note: If you can’t edit hosts file, you need to have file owner permission, search on google how to do that.

Restart apache and access the new url by typing gdroot.loc in your browser. You should see screen similar to when you go to http://localhost.

Congratulations ! you have a nice workflow now. You can now put all your existing our new projects inside your new document root which was assumed to be located at D:\Google Drive\webroot and now all your projects are sync with google drive and automatically uploaded to your google account which you can access anywhere. For example, you can now access your projects at office or any other computer by installing google drive client software  there and telling it sync/download your webroot folder. Your projects are now always there and backed up on the cloud :)

Let’s take cool stuff one step further by using git so that our projects file are also versioned. If you don’t know much about git and its benefits consider reading links posted above or below in the Git Resources section.

Using Git with a Central Repository

Creating and using central repository is especially useful in a team. If you just want to keep your projects versioned and are the only developer working on a project, the normal flow is (unless you track your project to remote host such as github):

  • modify files
  • commit your changes
  • repeat

So essentially you can skip this section if you just want to version your project files and are only developer working on a project.

Step 1: Download msysgit from here, choose first link from there. Install it with default settings.

Step 2: Go to your google drive folder (D:\Google Drive\) and create a new folder there named central.git

Step 3: Right click on newly created folder and choose Git Bash Here and type: git init –bare

Step 4: Create a test project folder named myproject inside your normal WAMP/XAMPP webroot/htdocs folder or google drive webroot folder mentioned above (Although you can git-manage any folder anywhere on the drive but naturally we want to git-manage projects that we run from webroot/htdocs folder).

Step 5: Right click on newly created folder, choose Git Bash Here and issue these commands one by one:

git init
git remote add central /e/Google\ Drive/central.git/
git push --all central
git push --set-upstream-to central master

Great! now we’ve setup central repository for all our git-managed projects and we can commit, push, fetch all changes from that central repository. For any new repository, you can now issue commands like:

git clone /e/Google\ Drive/central.git/
git fetch /e/Google\ Drive/central.git/
git push central
and so on

Hope you liked the post and have fun !

Git Resources

Happy New Year & 2012 in Review

I wish you all a very happy new year that brings a lot of happiness to you, your family and friends,

No much blogging this years but here is the summary of my blog :)

Here’s an excerpt:

19,000 people fit into the new Barclays Center to see Jay-Z perform. This blog was viewed about 77,000 times in 2012. If it were a concert at the Barclays Center, it would take about 4 sold-out performances for that many people to see it.

Click here to see the complete report.

PHPExecute – PHP Code Runner

Often times, you quickly need to test some PHP code. To do so, you create a file, put it in web root folder, write some code in it, open its URL and then you see its output. This is kind of lot of work and I often need a way to quickly test my PHP code. This requirement made me create my own code testing tool, PHPExecute.

PHPExecute is the fastest way to test PHP code. You write the code, hit the execute button, an ajax request is triggered and you see the output fast without page refresh. Here are some of the cool things about it:

  • Very fast way to test your code
  • Nice friendly interface
  • Code  Highlighting
  • Useful PHP, system information panel
  • Saving favorite code snippets
  • Adding useful classes
  • Easy to extend as per your needs

Screenshot

Extending PHPExecute

The good thing is that you can download (see below) it, see its source code and extend it however you like according to your needs. For example, you can add classes for testing, performance or any other purpose. One can even integrate bash commands (I am not going into details of that) to make it even more useful tool to work with.

Usage Notes

  • PHPExecute uses eval function to run the code. It is strongly recommended that you should use that tool for local testing only and not on production server due to security reasons. If you do, you use it on your own risk.
  • In order to save snippets, PHPExecute uses localStorage feature which is available in latest browsers (and IE9+) only and also it can be around 5MB in size. This isn’t that ideal if you are going to save a lot of snippets but you can always extend PHPExecute to add database support and save your snippets there.
  • The custom functions that can be used in PHPExecute can be found in includes/functions.php file. You can add any functions in that file that you want to use directly inside PHPExecute. The custom functions can also be seen in PHP Info > User Defined Functions.

Download

Download PHPExecute at Github

I hope PHPExecute turns out to be a useful tool for you. Please do share if you add anything to it via comments so that we could know it and integrate ourselves too :)

JavaScript Best Practices

JavaScript is not only amazing language but also very tricky language. To make correct use of it, you need to follow some best practices to avoid any problems that might come about otherwise. I share some of the best practices you really should be following when writing JavaScript code. Of course this is not an exhaustive list but at the most fundamental level, every programmer should know and adhere to it.

1 -NEVER FORGET VAR KEYWORD

Most of the developers know about this but yet I wanted to mention this because it may not be clear to some or newbies or people having other programming language background that come to JavaScript.

Consider the following piece of code:

function myFunc(){
var firstName = 'sarfraz';
lastName = 'ahmed';
}

It should be noted that in JS, variables have function-level scope which means a variable declared inside a function can not be accessed outside of it. So let’s test above two variables:

myFunc();
console.log(lastName); // ahmed
console.log(firstName); // undefined

As you will notice, we are still able to access lastName variable. The reason is that it does not have function-level scope because we forgot to put var keyword before it unlike firstName variable. Hence, lastName variable went into global scope and became part of window (while inside browser) object eg window.lastName will output the last name too.

It is therefore always required to put var keyword before variables so that they do not become part of global scope. It has following benefits:

  • You save the memory and improve performance
  • You don’t pollute the global scope
  • You mistakenly don’t overwrite a global variable that might have the same variable name

This is a very important concept and JS developers have always been finding solutions to avoid this problem. One of the most popular solution is Singleton or Module Pattern you should check out. By the way, if you want to see other patterns also, take a look at:

Essential JavaScript Design Patterns For Beginners

2 - DECLARE VARIABLES ON TOP

Another thing that should be followed is that variables should be declared on top of each function because of what is known as JavaScript Hoisting. Here is an example:

var name = 'sarfraz';

(function(){
console.log(name); // undefined
     var name = 'nawaz';
     console.log(name); // nawaz
})();

Notice that even though name variable is outside the scope of function but on the very fist line it gives back undefined rather than actual name. The reason for this is that interpreter hoists or moves variables on top of the function, here is how interpreter sees or re-arranges it:

var name = 'sarfraz';

(function(){
     var name;
     console.log(name); // undefined
     name = 'nawaz';
     console.log(name); // nawaz
})();

As can be seen, name variable has been hoisted to top and declared there and also var keyword has been stripped from it where we assigned the value of ‘nawaz‘.

The same is issue is not only with variables but also function declarations but NOT with function expressions. You can learn more about the difference between function declaration and function expression here:

Named Functions Demystified

The solution to this problem is to always declare variables and function declarations on top of container function:

function myFunc(){
     var foo;
     var bar;
     var baz;

     // do something foo, bar, baz
}

The preferred and recommended syntax though that you must follow is to declare all variables in one go by separating them with a comma:

function myFunc(){
     var foo, bar, baz;

     // do something foo, bar, baz
}

3 – INITIALIZING MULTIPLE VARIABLES

Declaring variables on top is good practice but not multiple initialization. Consider:

function myFunc(){
var lang = encoding = 'en';
}

This is a very common mistake even amongst experienced JS developers where they think they have quickly assigned two variables same scope and same value. Though value for both lang and encoding variable is some but not the scope. Try it out:

myFunc();
console.log(encoding); // en
console.log(lang); // undefined

Here again, variable encoding has gone into global scope. Since var keyword is only appears before lang variable, that is the one which gets correct functional scope. In short, you should avoid that shorthand initialization unfortunately.

4 – STARTING CURLY BRACE ON THE SAME LINE

Consider the following code block where starting curly brace “{” is on a new line, this works fine in most situations.

function myFunc()
{
// some code
}

However, same convention will not yield expected results if you happen to write:

function myFunc()
{
     return
     {
         name: 'sarfraz'
     };
}

var f = myFunc();
console.log(f);

The result will be undefined because behind the scenes, interpreter puts a semicolon ‘;‘ after the return keyword making it:

function myFunc()
{
     return; // <----------------
     {
         name: 'sarfraz'
     };
}

To remedy such hard-to-debug issues, it is good practice to always put starting curly brace on the same line, this would work fine though:

function myFunc() {
     return {
         name: 'sarfraz'
     };
}

var f = myFunc();
console.log(f.name); // sarfraz

And that’s a reason why Douglas Crockford in his book “JavaScript: The Good Parts“, advocates this syntax for JS:

function () {
     // some code
}

if (expression) {
     // do something
}

Go ahead and check out JavaScript Coding Style to learn more as well as naming conventions.

Notice that it is not the return keyword affected by automatic semi-colon insertion but all these too:

  • var statement
  • empty statement
  • expression statement
  • do-while statement
  • continue statement
  • break statement
  • throw statement

Experienced JavaScript developers know pretty well about JavaScript’s automatic semi-colon insertion problem and avoid it. The benefit of above coding style however is that you avoid this problem without knowing that this problem exists just by following that coding style.

5 – USE ARRAY LITERAL INSTEAD OF NEW ARRAY()

There are two ways you can create arrays in JS:

var arr1 = new Array(); // array constructor
var arr2 = []; // array literal

Though both serve the purpose of creating arrays but there is important difference between the two.

In JS, even an array is an object. With first constructor method above, you are telling interpreter to call constructor of the Array and generate an object. The interpreter looks up into the execution context to find the constructor and once found, it calls it and creates the Array object. It seems that it has performance hit too as compared to latter array literal method. With the array literal method, interpreter just creates the array on run-time with no extra processing done.

Other than that, Array constructor is mis-guiding the way it handles its parameters. Consider:

console.log(new Array(5)); // [,,,,]
console.log(new Array('5')); // ["5"]

When one argument is passed to Array and that happens to be a number, a new array is returned with its length property equal to that number passed. The important thing to note here is that Array will be initialized from what number you specified to it, for example:

// Array constructor
var arr = new Array(2);
console.log(arr.length); // 2
console.log(arr[0]); // undefined

// Array literal
var arr = [2];
console.log(arr.length); // 1
console.log(arr[0]); // 2

So the conclusion is to always use array literal notation rather than Array constructor.

6 – USE PROTOTYPE TO SHARE ACROSS

The concept of prototypes or prototypal inheritance is rather confusing. I have seen people especially inexperienced JS developers adding class members to parent function which needs to be shared across child classes. Consider the following code:

function Person(name){
this.name = name;
}

Now let’s assume we want to have child classes the ability to display the names some how, one of doing it is putting method directly inside Person class:

function Person(name){
     this.name = name;

     this.display = function(){
         alert(this.name);
     }
}

Other way is to use prototype:

function Person(name){
     this.name = name;
}

Person.prototype.display = function(){
     alert(this.name);
}

With both ways, all child classes will be able to use the display method but there is important difference between the two. When you attach any methods or properties via this (first way above) to a class then all instances of inheriting child classes will also have these properties or methods within them or their signature. On the other hand, when you use prototype to add members (properties and methods) to parent class, children classes will still inherit all members but it won’t be present inside their own functionality or signature, rather they will be borrowing that functionality from their parent class thereby saving memory. For this reason, later approach seems good to follow in most situations.

7 – PUT COMMA BEFORE PROPERTIES

When working with objects or arrays, it is always a good idea to put a comma before the variable or object property eg:

// jQuery - create a new div with some css
$('</pre></pre></pre>
<div>').attr({</div>
<pre>
<pre>
<pre>
 "id" : "myId"
 , "class" : "myClass"
 , "class" : "myClass"
 , "color" : "green"
 , "fontWeight" : "bold"
});

In this way, we never add an extra comma or forget one from the last property. The reason why this is good practice is that, in IE, with extra comma at the last property, we do not get expected results sometimes (ExtJS developers must have learned this). I do the same with multiple variable declarations or arguments of function. It also makes the code look pretty too as far as I see it.

8 – DON’T MIX JS AND HTML

One of the most important best practices is to always separate JS code from HTML and go unobtrusive. One would often see code like this:

<a href="#" onclick="doSomething()">Some Action</a>
<input type="button" onclick="doSomething()" value="Do Something" />
<form onsubmit="doSomething();">...

That’s a very bad practice in that it is hard to manage and maintain. HTML and JS should not be mixed ever. You could do the same thing like this:

<a href="#" id="link">Some Action</a>
<input type="button" id="button" value="Do Something" />
<form id="frm">...

<script type="text/javascript">
var link = document.getElementById('link'),
 btn = document.getElementById('button'),
 frm = document.getElementById('link');

link.onclick = function(){
 // do something
};

btn.onclick = function(){
 // do something
};

frm.onsubmit = function(){
 // validate form
};

</script>

This way it becomes easy to manage, maintain or enhance both HTML and JavaScript.

9 – PUT SCRIPTS AT BOTTOM

Normally scripts are put in <head></head> tags but this should be avoided. The reason for this is that browser loads your scripts sequentially and by the time they are loading, nothing else is done and website load times slow down (or at least that’s how visitors will perceive it) and you see actual output only after those scripts have been loaded by the browser.

The best practice is that scripts should be put on bottom of page just before closing body tag eg </body>. This way browser will instantly display page and page load time will be better for users who view that page.

By the way, always put CSS on top in <head></head> tags because that’s something browser reads first and renders page’s layout accordingly.

Read more about this at famous Yahoo’s performance article.

I would also suggest you to use Yahoo’s YSlow or Google’s PageSpeed add-on (add-ons of Firebug) which suggest you a lot of things on how to improve the performance of the page.

10 – NEVER FORGET SEMI-COLON

Always end statements and function expressions with a semi-colon:

var name = 'some name'; // <-------------

var myFunc = function(){
// some doe

}; // <------------

This is useful when you want to compress the code (for faster load times). If at any place, semi-colon isn’t present, you won’t be able to compress the code or wouldn’t get expected results most likely code-wise. You should always, always use semi-colons.

BONUS

The good news is that you can solve most of above problems by using JSHint or JSLint code quality tool. It will tell you about best-practices and any errors that might exist in your code. Having said that, it is good to improve your JS skills and avoid the need to go to such tools.

Introducing WebNote Chrome Extension

I like to read and research and as such I always bookmark interesting articles both locally and online eg Google Bookmarks or some other service. Since we do not always have the time to read an article of our interest the time we come across it, we use online bookmarking services to save and read them later and that’s good.

However, I was looking for a solution which could allow me to save those articles locally on my computer and read them any time later, this is something useful in cases when you are not connected to internet and yet want to be able to have the access to articles you like. I came across Evernote which is pretty cool services you can use to save webpages, videos, voice and a lot more. My primary focus though was to save webpages/articles related to web development. Any page you save to Evernote (via their Web Clipper browser plugin), can be downloaded to your computer via Sync option of that software which is exactly what I was looking for. After using it for a while, it turned out that with FREE account only 60MB is allocated which I consumed within 15 days :(

As a developer, I thought of creating my own solution that could be used to save articles/pages locally rather than buying Evernote. So I went on to creating the Chrome extension named WebNote.

WebNote can be used to save webpages with all their content, images, css, etc locally. WebNote will prove useful for anyone who does research on a particular topic or reads a lot.

How It Works

Once extension is installed and you press its icon on the browser toolbar, it pops up with a window (screenshot below) which pre-fills the URL and Title of the page, allows you to select Folder you want to save the page in along with any optional Comments. The extension pre-fills folders field by reading them from the local database which means for the WebNote to work, you need to have WAMP setup locally. Once you press the Save button, the page’s information is saved in the very database. The page itself is saved on hard disk (folder where WebNote CMS will be installed) in MHT format and if you don’t know about MHT format, it is basically a format which saves all resources of a page including images, css in one single page. Internet Explorer supports this format which means saved pages will open in IE.

I won’t go into details of how I created Chrome extension (there are a lot of resources out there) or how pages are saved in MHT format with all their resources in single page or even the small CMS used to manage the pages saved via WebNote because everything can be downloaded (see Installation guide below) and source code can be viewed.

WebNote Screenshot


All the pages saved are accessed via little CMS that I wrote, here are some screenshots.

CMS Screenshots


Notice that from programming perspective, CMS’s code is ugly in that it does not separate PHP and HTML and CMS password is saved with no encryption (since it will run locally). There are some reasons behind that though:

  • I wanted to write application real quick – too lazy to separate php, html logic
  • It was only meant to be for personal use but today I decided to share it
  • It wasn’t meant to be a professional project in which I take all sorts of care

Anyways, it serves the purpose but you can still go ahead and modify the code however you like.

Installation

Installing Chrome Extension:

  • Download WebNote Chrome extension and extract contents somewhere
  • In Chrome, type “chrome://extensions/” (without quotes) in address bar, Extensions window will open
  • On the right side of Chrome Extension page, there will be a link “Developer mode“, click on that
  • Now click on the button “Load unpacked extension” and specify path where you extracted the WebNote extension
  • You will notice that a Notepad-like icon will be added to Chrome toolbar that is extension is installed

Installing CMS:

  • Download WebNote CMS and extract it in www/root folder of your WAMP installation folder
  • Open PHPMyAdmin or any other MySQL client of your choice and create a database named “webnote” (without quotes)
  • Import the sql file “webnote.sql” present in WebNote CMS folder in that newly created database
  • In the Webnote CMS folder, go to admin/includes/db.php and edit your database settings accordingly
  • Browse the CMS where you installed it in the browser like “http://localhost/foldername/admin“. You should see Admin login panel
  • Enter “admin” as username and “123123” as password without quotes.

Using WebNote

  • Once logged in, create some folders. You should see Add Folder link to the right of Navigation on the My Folders page.
  • To save a page, click the WebNote icon in the browser toolbar and hit the Save Now button
  • You will see ajax loading image, wait until page is saved. A notification will appear telling you that page is saved.
  • Go back to Admin panel, click on “My Folders” link and then click on the folder you saved the page in.
  • Click on the link title and it will open in Internet Explorer (because MHT is supported by it).

Notes & Tips

  • When you create a folder, it does not create a folder physically on your hard disk. Consider it kind of tag for each page.
  • All files are saved in “mht” folder inside CMS.
  • All other page information including title, folder, url, html is saved in database
  • To save pages, you obviously need to have internet connection to be able to save them locally and read them later
  • You can pre-populate “Comments” field by selecting some text on page and then hitting the WebNote icon in toolbar.

Have fun with your readings and research :)

Learning Javascript

JavaScript is cross-platform, cross-browser language; javascript is everywhere; web, RIA (rich internet applications), mobile, tablets, animations and even on server with the advent of node.js. Javascript is the language of the future.

I started off with jQuery without knowing anything much about javascript because by the time I didn’t find any reason to learn it due to fact that  javascript libraries did everything we needed putting complexities out of the way. Today I realize that I chose the wrong path, a good understanding of javascript language is crucial if you look at the reasons I have mentioned in the very beginning but it is never too late to start again, that’s exactly what I have decided, learning javascript seriously. I am not the only one who has started realizing the power and future of javascript, there are giants who have started learning it too. If you are also javascript-library-only developer, or even copy-paster programmer, you should really learn javascript !

Despite design flaws and bad reputation of the language as they say and probably rightly so, javascript is popular and language of the choice for those who have gone into deeper understating of it. Javascript language does have bad parts but its good parts over-weigh its bad parts and there is always room to avoid bad parts if you know the language right and use it effectively.

Javascript turns out to be extremely tricky language, consider:

// Comparison
'' == '0';    //false
0 == '';    // true
0 =='0';    // true

// Type checking
typeof null;    // object

// Scope
function myFunc() {
  return
  {
    name: 'sarfraz'
  };
}

var f = myFunc();
console.log(f);    // undefined

I did a lot of research to find best javascript learning resources. On the journey of my exploration, I came across some of the great resources with a lot of reviews and user feedback. By now, if you made your mind to take javascript seriously, here are the best resources out there you should check out.

Books

Online

Videos

Blogs to Subscribe

Tools

Let’s start… :)