Archive for the 'Programming' Category

Introducing instant domain search - 10xwhois

I have been working on a domain search utility for couple of days and it is ready for release. 10xwhois is an instant domain search tool built with ajax and java. If you are into domain name business, this is a must have tool.

Just type in your desired domain name and select the domain extensions you are interested in. Domain availability status will instantly appear below. For non available domains, whois service is also provided.

This tool is running on Java and is hosted on a dedicated server. Got any comments/suggestion? Let me know.

Installing tomcat 6.0 on MediaTemple dedicated server

In the last post, I looked at how Java can be configured on MediaTemple CentOS server. This post will show you how you can install Tomcat on your server.

1. Download and extract tomcat 6.0 binary distribution. Get the URL of the tar.gz file from http://tomcat.apache.org/download-60.cgi. From the ssh console download using wget.

wget http://apache.deathculture.net/tomcat/tomcat-6/v6.0.14/bin/apache-tomcat-6.0.14.tar.gz

Now use the following commands to extract the files.
gunzip -d apache-tomcat-6.0.14.tar.gz
tar -xvf apache-tomcat-6.0.14.tar

2. set JAVA_HOME variable to point to your Java installation.For this you need to login as root. Create or edit a java.sh inside /etc/profile.d. Add the following line in java.sh.

export JAVA_HOME=/usr/java/jdk1.6.0_04

3. Start tomcat from bin folder. Login again to SSH using your non root user id.  The startup script for tomcat is in [tomcatdir]/bin. Change to bin and then execute,

./startup.sh

Voila! You should see the tomcat server running at www.yourdomain.com:8080/

To shutdown you can use ./shutdown.sh, but for some reason I am not able to execute it. So currently the only way to stop is to kill the Java process from SSH. Update: I got shutdown.sh working by adding -Xmx4m as JVM parameter in catalina.sh for “stop” block of code.

Now my next task is to get Struts2 sample application running on this…

Installing Java 1.6 (JDK6.0) on MediaTemple dedicated virtual server (dv)

I recently bought a dedicated virtual hosting service on MediaTemple. The idea was to use this server for all my future projects in J2EE and Ruby on Rails. For $50/month, this service is not exactly cheap, but I am yet to find an alternative VPS host (I am planning to evaluate SliceHost sometime in future)

By default, the server comes with Ruby 1.8.5, but not Java compiler. My first task was to install latest JDK (1.6) on the VPS server.

All dedicated virtual servers hosted by MediaTemple comes with a CentOS installation. You can check that by running the following command on SSH terminal.

cat /etc/redhat-release

I got CentOS release 4.5 (Final) on the console.

Now before you can install Java, you need to know the password of “root” user in your server. For this, create a new support request and ask MediaTemple to set your root password of your choice.

Now comes the second problem. How do you download Java binaries onto your server? One option is to download JDK on to your machine and then upload it to server. Since the file size is more than 60MB, I didn’t want to use this method.

What you need is the ability to download J2SE 1.6 rpm binaries directly to your dedicated server. The Linux command “wget” is the ideal tool for this. But what is the URL to download?

The problem with Java download is that there is no direct link available for download. In order to force license display and acceptance, Sun uses a hidden redirect to the actual download. You need to find this URL.

For MediaTemple installation, select Java download which is “jdk-6u4-linux-i586-rpm.bin” from the list at http://developers.sun.com/downloads/. Using Firefox, start the download. Immediately pause the download and then righ click on the “resume” link to get the actual download link.

Paste the URL in a text editor and then quote it by adding double quotes at the beginning and at the end of the URL.

Now from the SSH terminal, type the following.

wget <quoted url from text editor> -O j.bin

This will download the Java binary as j.bin in the current folder. Now change to super user mode by typing sudo su.

Make the j.bin executable for using the command chmod a+x j.bin and execute it by ./j.bin. Accept license terms and continue. You will get the Java installed on the MediaTemple DV server.

But you are not there yet! Following is the error I got when I ran “java -version” on the command prompt.

Error occurred during initialization of VM
Could not reserve enough space for object heap
*** glibc detected *** free(): invalid pointer: 0xb7e71280 ***
Aborted

On CentOS you need to do something more to get Java installed. You need to set a link to Java. Execute the following from the root privileges. Change jdk1.6.0_04 to your version of JDK download.

/usr/sbin/alternatives –install /usr/bin/java java /usr/java/jdk1.6.0_04/bin/java 1

After this I was able to get a sample Java program running on the MediaTemple dedicated server. Now the next step is to install Tomcat App server. That is for another day….

Ruby - A programmer’s best friend?

Ruby Programming Language

I have been really busy for last few days. On the professional front, I am looking for some challenge. Couple of interviews,  but I am still to find a better job.

The other thing that kept me busy was the Ruby programming language. I had gone through python language couple of months back and wasn’t much impressed. So when I started on Ruby, I was very skeptical and it seemed like some Japanese propaganda.

But 2 days of Ruby programming had me fully excited. You can  say I am on the “programmer orgasm”. Ruby is a very compact language and you will be amazed at the code reduction when you convert something to Ruby.

I will soon be writing a quick reference on Ruby for a Java/C++ programmer like I did with PHP. After a month of programming in PHP, I think it is a very badly designed language. I think PHP became popular due to two major reasons; Almost all web hosting providers support it. Also for a novice Web programmer, PHP was an ideal choice.

If you were to develop a Java web application, you had to study the entire J2EE stack. Then after that you find out that not many Web hosting providers give Java or JSP support!

Now that is where Ruby shines. Ruby on Rails is a Web application framework built on top of Ruby. Interestingly, Dreamhost provides Ruby on Rails support. I am yet to dig deep into Ruby on Rails, but from a couple of simple tutorials it looks very promising.

Enabling single sign on - Web applications in WebSphere 6.0

Recently I came across a requirement to enable single sign on between two different Web applications running on different machines but on the same domain. WebSphere does provide out of the box support of single sign on, but figuring it out took a lot of time for me. So I have written this step by step guide so that you don’t have to go through the torture again!

All the screenshots in this guide are taking from Rational Application Developer (RAD). I could configure everything except “roles to groups mapping” directly from RAD’s console. For configuring “roles to group mapping” I had to export and deploy the application from an EAR file.

1. Enabling WebSphere security

Check out the following screenshot which shows the settings I have selected under Security->Global Security.

Global security settings

a) LTPA is required when the Web applications are on the different machines but on same domain.

b) I used a custom user registry which checked the users against a database. A more common approach is to use LDAP.

2. Click on the “custom” link under user registries in Security->Global Security. Following settings were selected on this page.

a) userid and password given is a valid user id in the database.

b) MyUserRegistry implements com.ibm.websphere.security.UserRegistry interface and is copied to the “classes” folder inside WAS home folder.

3. Click on “LTPA” under authentication mechanisms. Single sign on can be enabled by clicking on the “Single Sign On” link on the right.

The above three steps completes the “Global Security” setup on WAS. Now we will configure JAAS for applying this security at the Web application level.

1. Configure web.xml of the application. This involves protecting Web resources using security-constraint entry. Following is a sample entry,

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Protected Area</web-resource-name>
            <url-pattern>*.do</url-pattern>
            <http-method>DELETE</http-method>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>PUT</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>operator</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>CONFIDENTIAL</transport-guarantee>
        </user-data-constraint>
    </security-constraint>     
    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>MyApp</realm-name>
        <form-login-config>
            <form-login-page>/logon.jsp</form-login-page>
            <form-error-page>/logonError.jsp</form-error-page>
        </form-login-config>
    </login-config>

2. Implement a login page for application which conforms to WAS standards. Following is a sample page,

<html>
  <title>Login</title>
  <body>
  <form method=”post” action=”j_security_check”>
     Enter user ID and password:
     User ID: <input type=”text” size=”20″ name=”j_username”>
     Password: <input type=”password” size=”20″ name=”j_password”>
     <input type=”submit” name=”login” value=”Login”>
    </form>
</body>
</html>

3. While deploying bind web.xml roles with groups from UserRegistry. For simplicity you could also attach the entire role to “any authenticated user”.

Some common errors and their solution,

1. When I start RAD after enabling Global Security, it is in “starting” mode forever!

Open soap.client.props in base_v6\profiles\default\properties folder and add the userid and password fields as shown below. The userid/password must be the same as the one given on “custom user registry” page.

com.ibm.SOAP.loginUserid=test
com.ibm.SOAP.loginPassword=test

Run the following command on the command as shown. Replace the cell name and node name with the values on your machine. This reconfigures FileTransfer application with authentication.

D:\Rational\runtimes\base_v6\bin>wsadmin wsadmin.bat -profile redeployFileTransf
er.jacl -c “fileTransferAuthenticationOn machine97622Node01Cell machine97622Node01
 server1″ -user test -password test

2. I am getting the following error,

Authentication failed for user: com.ibm.ws.console.security.ConnectToRuntimeException: null nested exception is com.ibm.websphere.security.CustomRegistryException

This means that custom user registry is not loaded. Ensure that you restart RAD after copying custom user registry class. Also ensure that custom user registry class is under classes folder (base_v6\classes on RAD)

3. I have an error which is not listed above?

Check the trace.log inside base_v6\profiles\default\logs\server1 folder. This should give a lot of information about the underlying problem. If you are still unable to resolve the issue, contact me!

Pagination in DB2 database

Pagination is required when you develop a listing screen which has thousands of records. The best way to implement pagination is to leverage features available on the database. In an Oracle database you can use RANK() function. On a DB2 database you can use ROW_NUMBER() function. Following example shows how to implement pagination on a DB2 database,

SELECT * FROM
  (SELECT a.customer_name, ROW_NUMBER() OVER
    (ORDER BY a.customer_name) AS RN FROM customer a
    WHERE a.customer_status=’ACTIVE’
  )
X WHERE X.RN BETWEEN 0 AND 100

This method won’t work if you are using AS400. On AS400, the only way seems to be iterating through the entire result set and then picking up records needed for the screen. For example, if you want to show records 100 to 200, start from 0, ignore upto 100 and then populate records from 100 to 200 and then stop. Obviously this means that if the resultset is huge and if you navigate to the last page, it might take a lot of time.

Restarting my linux love - the debian way

I have dabbled in linux long time back but never took it seriously. But this week something triggered inside me and I have decided to give it another try. My cousin sunil is a linux guru and with his blessings I have restarted my linux love! :-)

But hey, I have no intention to chuck Windows out. After all I have paid over Rs.6000 for it! So instead I decided to use Vmware (which is a virtual pc server and is now free!) as my new machine and install Debian on it.  Check out the Debian social contract to see why I am interested in Debian.

Earlier when you run linux on Vmware it used to be slow. But not anymore! With my machine (amd64 with 2GB RAM) speed difference is hardly noticeable!  Another advantage is that with NAT networking on Vmware, your Wifi network will appear as an ethernet network for the virtual pc!  (Configuring WiFi on Debian business card ISO seems to be almost impossible).

So I downloaded business card version of Debian (33MB) and I am currently running the net-install from it.

Debian on Vmware

My first lesson in PHP/Wordpress plugin development

Recently I had released a WordPress plugin - Google Blog Search Preview. I had tested it over two webhosting providers and everything seemed perfect. But within a week of release, I was getting reports of this plugin failing on certain installations. Well, it turns out that I had coded my plugins in PHP5.

The error was,

Parse error: syntax error, unexpected T_STATIC, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /home/brodopr/public_html/brodo/wp-content/plugins/jj_gblogsearch.php on line 15

Unfortunately many sites still run WordPress on PHP4. The biggest problem is that object oriented features in PHP is very different between version 4 and 5. For example, the static keyword is not available in PHP 4 which I was using in my plugins!

So the first lesson in WordPress plugin development - Test your plugins in both PHP 4 and PHP 5 installations! WAMP server even has a plugin which allows you to switch between PHP4 and PHP5. So that was easy!

I have released version 1.1 of Google Blog Search Preview  which works on PHP4 and PHP5. You can download it here. Many thanks to Carlo and Len for reporting this problem.

Is there a perfect online polling system?

Perfect voting system?I wanted to create a poll on this blog and then I realized that there is no such thing as a perfect poll! The main problem is, how do you prevent bogus or duplicate votes?

Many existing polling systems use IP address to identify duplicate votes. But this eliminates a lot of valid votes! For example, 1000+ employees at my office use the same proxy server and hence to the polling system will appear as a single voter!

Also different IP addresses can never guarantee perfect polls. Methods used for internet anonymity such as Tor can be misused for bogus voting.

Other methods used are the cookie method and the email verification method. Both these are not fraud proof. Cookies can be easily deleted and multiple email ids can be easily created.

What we need is an internet identity which probably links to something like a passport number!

During my search for a perfect polling system, I came across this link. It claims to build a fraud proof voting system. But in reality it is probably the worst voting system!

Releasing Google Page Rank plugin 1.0 for Wordpress

Google Page Rank Today I am releasing my second plugin for WordPress - The WP Google Page Rank Display 1.0.  You can use this to show off your Google Page Rank in the WordPress blog. This is superior to other plugins out there due to two major reasons,

1. Page Rank value is cached for 24 hours and hence means minimum load on Google servers and on your blog.

2. There are no external dependencies for this plugin.

Google Page Rank indicates the value of your site assigned by Google search engine. It varies from 0 to 10. For example, http://www.google.com has a Page Rank of 10. Higher page rank means higher traffic from Google search engine.

For more details on the Google Page Rank Plugin and for downloads please visit the plugin page. If you have any comments, suggestions or bug reports please contact me.

Programmer’s challenge 2007 video

If you get excited about anything remotely related to programming (like me), then you will surely love this video. This video is of the Programmer’s challenge quiz competition where 6 of the leading game programmers take part. Most of the questions are game related and you will find a lot of funny answers!

The video is long (45 minutes). If you are on a slow connection like me, start the video and then pause it.  This ensures that the entire video is downloaded before you watch it!

Wordpress Plugin - Google Blog Search Preview

I do most of my programming during weekends. This weekend I decided to write a WordPress plugin. I also wanted to improve my recently acquired PHP skills.

WordPress dashboard displays incoming links from Technorati. This is very useful since it lets you know who are discussing about your blog (not all have trackbacks enabled). But sometimes not all links are visible on Technorati. So I supplement it by doing a “link search” on Google Blog Search.

What if I display the Google Blog Search incoming links also on the WordPress dashboard? Hence this plugin! This plugin uses rss library of WordPress. I wanted to do Ajax, but there isn’t any “native” support for Ajax in WordPress :(

Do checkout Google Blog Search Preview Plugin!

Software developers are idiots when it comes to usability - the SSL saga

I have 3 broadband networks at home. I use BSNL 900+UL, Asianet WOW 199 and Reliance Netconnect. My main network is BSNL which is quite stable at 256kbps. Asianet is the backup which gives speeds upto 2MBPS. Reliance netconnect using USB modem is the final backup and I use it whenever I am on train or bus or on the beach thinking about hot babes like maria sharapova (don’t worry, it is a gimmick to get more traffic!).

As I have posted earlier, I recently upgraded IE 6.0 to IE 7.0. Also Firefox was upgraded to 2.0.0.3. Everything looked smooth until today.

Today being the last day of the month, I wanted to check the Asianet WOW 199 usage. The maximum I can use is 700MB/month and I just wanted to see what is left and download something (paris hilton photos perhaps?)

So I switched my Wifi connection to Asianet and clicked on the account usage link. The login screen came and I typed in user/password and clicked go. Following is the screen I got on IE 7.0.

IE 7.0 SSL error screen

As you can see the error is quite informative. It is as useful as a britney spears album is to a seminary (oops I did it again, the traffic bait!).

The error looked suspicious since login page and account page were served from the same server. Anyway I called up customer care and they sweared that the server is infact working!

Ok, probably IE 7.0 has some bug. So I tried the Firefox 2.0 to login, and here is what I got,

SSL error on Firefox 2

Thank god! Atleast it says there is something wrong with SSL! This error is much more useful than the IE 7.0 error. But still I have no clue what is happening. The idiots who coded this error decided that I don’t want to know how to access the site.

But I want to. Otherwise I have no other way of getting my account info. So turned to the ultimate saviour of tech problems. The Google!

Ok. Here is the true picture. IE 7.0 and Firefox 2.0 decided to support only SSL version 3.0 onwards since previous versions of SSL (1.0 and 2.0) are insecure. But luckily in IE 7.0 there is an easy way to enable SSL 2.0 (which Asianet account page is using).

1. Click on Internet Options -> Advanced.

2. Under security, check the use SSL 2.0 checkbox.

The firefox 2.0 hack to enable SSL 2.0 is bit complicated. If you are itching to know about it, search in Google!

Now this incident clearly demonstrates why many Software developers are idiots when it comes to usability. Be it microsoft or the open source community, there are many who fail to understand simple user interface/communication principles.

I guess this also explains why geeks are incapable of getting girl friends like aishwarya rai!

PHP notes for Java programmer (4) - classes

Here is the last set of PHP notes which cover object oriented programming in PHP. The notes conclude with a set of supplementary notes. The entire list of PHP notes are available here.

PHP Notes - Object oriented programming

1. To call class methods without an instance, use scope resolution operator(::) else use (->). Check the following example,

class test {
 function f1() {
  echo “hello”;
 }
}

test::f1();

$t1 = new test();
$t1->f1();

2. In PHP, __autoload function (automatically called) can be used to simulate “import” functionality. This is very handy if you store your classes in separate PHP files. For example,

<?php
function __autoload($class_name) {
    require_once $class_name . ‘.php’;
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

3. PHP has constructors (__construct()) and destructors (__destruct()). There is no chaining of constructor or destructor calls. Use parent::__construct() for the same.

4. Method and properties can have “public”, “private” or “protected” visibility.

5. Use const keyword to define constants inside classes.

6. PHP has the standard class constructs - abstract, extends, interface, implements etc.

7. It is possible to overload method calls and member access using __call, __get and __set. This will be triggered only if the accessed attribute or method doesn’t exist! isset() and unset() can also be overridden using __isset() and __unset().

8. For serialization methods __sleep and __wakeup. All methods starting with __ are reserved as magic methods in PHP!

9. To perform shallow copy, use clone directive. It is also possible to define a __clone() method.

10. PHP supports reflection paradigm. For more details, checkout http://www.php.net/manual/en/language.oop5.reflection.php

11. PHP supports type hinting for object and array types. For example, function f1(array $a) { }

12. A typical PHP class declaration is shown below,

class Test extends T1 implements T2 {

 public $a;
 
 public function testmethod($value) {
  $this->a = $value;
 }
}

13. PHP exception handling is similar to Java. It is also possible to extend the base “Exception” class. Here is a sample use of exception,

try {
    $error = ‘error message’;
    throw new Exception($error);
} catch (Exception $e) {
    echo ‘Caught exception: ‘,  $e->getMessage(), “\n”;
}

PHP supplementary notes

1. For maximum security always validate user input. You don’t want to be a victim of SQL injection attack!

2. For database access, provide least access rights needed by the application.

3. On a production system it is better to disable error reporting.

PHP notes for Java programmer (3) - control structures and functions

Here is the 3rd set of PHP notes. With this all the core PHP language features are covered. The only thing left is the OOP support in PHP - classes and interfaces. For classes, I will cover only the PHP 5 features (PHP 4 has a different model). Stay tuned for the final set.

PHP Language Reference Notes - control structures and functions

1. There are two equality operators in PHP. == is for “equals” and === is for “identical”. “===” return true only if both operands are of the same type!

2. @ is an error control operator in PHP. This works only on expressions and will suppress error messages. Handy if you don’t want to expose errors to the page being displayed.

3. Backticks (“) can be used as the execution operator in PHP. for example $output = `ls`; will contain the directory listing in linux.

4. There are two types of logical operators - “and”,”&&” , “or”, “||”. The “or” operator has less precedance than “||”.

5. In arrays, “+” operator indicates union. “==” checks whether same key/pair value exist in arrays, while “===” also checks for their order (identical).

6. Following are the control structures in PHP,

if ($a > $b) {
   echo “a is bigger than b”;
} elseif ($a == $b) {
   echo “a is equal to b”;
} else {
   echo “a is smaller than b”;
}

while ($i <= 10) {
   echo $i++;
}

do {
   echo $i;
} while ($i > 0);

for ($i = 1; $i <= 10; $i++) {
   echo $i;
}

switch ($i) { // switch can work on strings!
case “apple”:
   echo “i is apple”;
   break;
case “bar”:
   echo “i is bar”;
   break;
case “cake”:
   echo “i is cake”;
   break;
}

7. There are two forms of else if in if blocks. It can be “else if” or “elseif”.

8. All control structures has an alternate form which uses colon(:) and end<type>; For example, if($a): endif;

9. PHP has a shortcut form of for, the foreach. Consider the following example,

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
   echo $value;
}
?>

10. The break statement takes an optional parameter indicating how many levels needs to be skipped. For example, break 2;

11. The continue statement takes an optional parameter indicating how many levels needs to be skipped when going to the next iteration. For example, continue 2; Also note that continue applies to switch statement as well!

12. The declare construct can be used for profiling. For example, declare(ticks=1) { //code here }. This works along with register_tick_function(). The registered function will be called for every n low level instructions, where n is the number of ticks.

13. To include another PHP file use either include() or require() construct. require() will cause a fatal error if the required file is missing. To avoid multiple includes of the same file, use include_once() or require_once().

14. In PHP, it is possible to define functions inside functions! Function visibility is global but the outer function must be called before you can call the inner function!

15. There is no function overriding or overloading in PHP.

16. Function arguments can be passed by value or reference. To pass by reference prefix variable with &. PHP also supports variable function arguments.

17. Default function argument values are possible and they should be ordered from right to left. For example,

function test($a, $b=”value”) {
}

18. PHP also has variable functions. This can be used for implementing function callbacks!

function f1() {
 echo “hello”;
}
$functionvar = “f1″;
$functionvar();

PHP notes for Java programmer (2) - types and variables

PHP Language Reference Notes - Types, Variables and Constants

1. It is not possible to mix XHTML declaration with PHP. Once way to solve this is to use <?php echo(”<?xml version=”1.0″ encoding=”UTF-8″?>\n”); ?>

2. A PHP instruction is terminated by a semicolon (except for code blocks such as an if block).

3. Three types of comments are possible - /*comment*/, //comment and #comment. Be careful when you mix them!

4. PHP supports eight basic types. They are boolean, integer, float, string, array, object, resource and NULL.

5. PHP types are weak and are dynamically typed. PHP variables are prefixed by dollar sign($).

6. Type conversion is easy! You can cast types or use settype() method. For example $intvar = (int)”100″ is a valid statement in PHP!. This is equivalent to   $v1 = “100″; settype($v1,”integer”);

7. Boolean literals true and false are case insensitive.

8. Integer overflow causes a variable change its type to float!

9. PHP has no native support for unicode strings.

10. String literals can be expressed in 3 forms - single quoted, double quoted and using heredoc syntax.

11. Single quote strings don’t evaluate the string content. Hence if variables are inside strings, they are not interpreted.

12. Double quote strings are evaluated. Hence if there are variable or special characters, the corresponding value is output. For example echo “hello $val” will print “hello world” if $val=”world”.

13. String characters can be accessed using index operation. For example, $v1[4];

14. Use complex syntax in double quoted strings for evaluating complex expressions!. For example,  $v1 = “hell”; echo “{$v1}o”; - The output is hello.

15. For string concatenation using dot(.) operator. For example “Hello”.” World”

16. By default arrays in PHP are associative in nature. Hence array(”0″,”1″,”2″) and array(”0″ => “0″, “1″ => “1″, “2″ => “2″) are identical.

17. $v1[] = “100″; extends an array by adding the element “100″ to it. The key will be maxkey + 1;

18. PHP supports callback functions.

19. PHP variable scope rules are a bit strange. A globally declared variable is not visible inside a function snippet. For example following won’t print “hello” since $a inside test() is a different variable!

<?php
$a = “hello”;
function test() {
  echo $a;
}
test();
?>

20. Keyword global can be used to refer global variables in functions. For example,

<?php
$a = “hello”;
function test() {
  global $a
  echo $a;  // prints hello
}
test();
?>

21. Another alternative is to use $GLOBALS superglobal! In the above example,  $GLOBALS[’a'] returns the value of $a.

22. Another interesting PHP variable property is that variables declared in a code block is visible below the code block! Consider the following example,

<?php
$check = true;
if($check) {
  $a = “hello”;
}
echo $a; // prints hello
?>
23. PHP has something called variable of variable. For example,  $a = “hello”; $$a = “world”; echo “$a $hello”; // This prints “hello world”.

24. In PHP, constants are declared using define. There is no need for a dollar sign to refer a constant. For example,  define(”PI”,3.14);echo PI;

25. PHP has a large number of magic constants. Values of some these depend on the context they are used. For example, echo __LINE__; will give you the current line number!

PHP notes for Java/C# programmer - set 1

Are you a Java/C# programmer looking for a crash course on PHP? Here is an easy way. In the next 5 days I will be going through the entire PHP documentation and will be taking notes which are relevant and unique to PHP.

I am a hardcore Java programmer and hence by following me you can quickly learn PHP! My notes will be mainly based on the online PHP manual. Here is the first set of PHP notes.

General PHP Notes

1. PHP - PHP:Hypertext Preprocessor is an open source general purpose scripting language.

2. PHP can be used for server side scripting, command line processing and as a GUI application (PHP-GTK).

3. PHP is changed to a proper object oriented language from version 5 onwards and allows OOP paradigm.

4. First sample program, the famous “Hello World”,

<html>
<head><title>Hello World</title></head>
<body>
<?php echo “Hello World” ?>
</body>
</html>

5. PHP exposes a set of superglobal variables accessible from anywhere. For example, $_POST superglobal can be used to extract http post parameters. $_POST is an associative array.

6. If the HTML form field name contains a dot(.), it is converted to an underscore(_) automatically by PHP. For example, if the text field name is “user.name”, you should use $_POST[”user_name”] to retrieve its value!

7. There are a couple of mailing lists available for PHP. It is at http://www.php.net/mailing-lists.php. So far I have only subscribed to “Announcements”.

Next set of PHP notes on the language features will be published tommorrow.

Starting PHP development

I have recently started on PHP programming (been postponing it for years!).  The official PHP manual seems to be the only source needed to learn PHP. It is pretty big and I think it will take a week for me to cover it.

An interesting feature of the online PHP manual is the inclusion of “User Contributed Notes”. Sometimes these notes are more informative than the manual entry :). But sometimes they can be misleading as well.

For testing out the scripts, I am using XAMPP Lite - An all in one Windows installer which contains  Apache 2.2.4 + PHP 5.2.1 + MySQL 5.0.33 + phpMyAdmin 2.9.2 + Openssl 0.9.8d + SQLite 2.8.15. Download, extract and run setup_xampp.bat and you have everything running in 5 minutes!

Also I am looking for a good PHP book which can be used as a single offline reference. PHP 5 Unleashed by John Coggeshall appears to be good, but I am yet to make a decision.

Top 10 traits of a good programmer

As I have written in one of my earlier posts, this is the 9th year of professional programming for me. In this post I will summarize my thoughts on what makes a good programmer (master programmer or chief programmer as called by some). I wouldn’t call myself a master programmer yet, but I am pretty sure I know the traits that define a good programmer.

Now before I go into the details, let me first clarify what the term “programmer” means to me. A programmer is not someone who blindly implements whatever design is given to them. Many software service companies in India are under this impression. This myth is purposefully floated around mainly because 90% of the programmers in these companies have less than a year of programming experience. So  coding/programming has to be projected as a mechanical activity!

So who is a programmer? A programmer is someone who has fairly good understanding of computer systems, can write good code, is intelligent and can visualize a software solution for a particular software requirement. He looks at the software requirement and starts thinking - How do I build this thing? How I can design the interface so that it is most user friendly? What happens when there is huge data volume? How do I ensure that no one hacks into my program (especially for Web applications)? How do I reduce coding effort? How do I ensure future additions have minimum overhead?

So as you can see it is much more than just mechanical coding.

Ok no more preaching! Here is my top 10 traits for a good programmer.

1. Think! -  This is the most important trait of a good programmer. He never jumps into anything. Given a problem, he first thinks over it. The more he thinks, the more ideas, questions and alternate solutions come to his mind. I see the lack of thinking as the primary source of all problems a novice programmer face. When he comes across a problem, he doesn’t think. Instead he bangs his head on it or asks for help from another guy. Sometimes you need to ask for help, but think on the problem or bug before you run across to your technical lead!

I will give an example of the importance of this “Think” factor. Sometime back we had a requirement to build around 40 interfaces. This basically required scripts to be written to transform data from a set of tables in one database to another. The estimates were done like this,

1 interface = 5 days and hence 40 interfaces = 40×5 = 200 days of build effort.

When I started on the project, everything was in place. The team, the effort of 200 days and the schedule. Then I thought over it. I saw that if a generic framework is written for the transformation, I could externalize the transformation rules into an XML file. The generic framework took me about 10 days to build. Then for all the 40 interfaces, the time taken was 5 days (since only tranformation rules were to be written). So my team got a lot of free time! :)

2. Learn! - Learn Baby, learn! A good programmer has a burning desire to learn new things every day. It is almost 15 years since I started programming. And even today, I spent a lot of time learning new things. When it comes to programming, every program you write teaches you something. I have fairly good knowledge of Java, C, C++, C# and Qbasic (yes qbasic is my first love!). Just recently I have started learning PHP.

Nowadays learning trait is something which I see less and less in my professional life. The learning itself is so formalized and force fed that people are bored with it.

By learning, I am not talking about taking professional certification. Sorry to say this, but I have nothing but contempt for many of the professional certifications (for example the Sun certifications). In India, it is very easy to manipulate the system and there is a lot of fraud happening on the certification front.

3. Help others! - This to me is the golden rule of programming. “Help other as you would want others to help you”. In my case, I think much of the programming wisdom I possess has come from helping others solve their problems! I used to sit till late hours and help others solve their programming problems or bugs. The advantage was,
 a) Immense experience in solving programming problems.
 b) Various ways people see a particular problem. Also you come across interesting/weird/strange ideas!
 c) Empathy towards programmers. The difficulty they face in their day to day job.

Unfortunately as I grew older and came in touch with extremely process centric enviornments, I realized that “Help others” is not something officially appreciated.

4. Lead by example! - Another important trait if you are a senior programmer or architect. Many times I have come across senior technical architects who say - “It is simple, you just do this and do that”. I am 100% sure that many of them can’t code what they so confidently say as “simple”!

If you are a technical lead or a lead programmer, lead by example. Write code in front of your team members. You will get more trust, respect and support from your team!

5. Know everything! - Ok, that doesn’t sound right. I will rewrite it - Know a bit about everything. For example, If you are a core Java programmer, you should also know about SQL programming. It also helps if you know a bit of regular expressions or a scripting language. For example, I have recently gone through XML specification twice even though I have no professional need right now. But someday I will need it.

6. Know basics of computer science! - There are many programmers out there who doesn’t have the basic knowledge of computers or their inner workings. This is very essential. Many of the programming difficulties that people face is due to the lack of knowledge of how computers work! If needed take a computer science course.

7. Perfect it as much as you can! - Nobody is perfect. You can’t write perfect code in the first iteration. Refactoring is the mantra. Analyse your code, find code fragments that can be reused and refactored.

8. Use tools! - Many programming tasks can simplied if you use appropriate tools. For example, in all my projects I use Ant to automate build and deployment process. You will be surprized at the time you save!

9. Explore code! - If you want to improve your coding skills quickly, one thing I recommend is exploring code written by others. If I would have said this 10 years back, you would ask me- “Where can I find good code?”  But now the scene is completely different. Open source movement has revolutionized everything.  There is so much good open source code out there that I feel overwhelmed by it!

10. Be Humble! - Humility is the last of the top 10 traits a good programmer should have. But it is not the least! As you get more and more experience, it is very natural to feel arrogant. The moment you become arrogant, you loose the trust and respect of your fellow programmers.

I have come across many who are intelligent and technically quite good. But again I have no respect for them simply because they are arrogant. Being arrogant also shows how ignorant you are!

Remember, no one is perfect. You can also make mistakes. If someone points it out, thank him and accept his valid comments.

Closing thoughts

Now you might be thinking - Why is this guy not talking about “design patterns”? Why is he not talking about “Ruby on Rails”? What about extreme programming? What about open source contribution? Linux? and so on.

My dear friends, In my opinion talking about design patterns or practising pair programming(as in XP) etc. are not one of the top 10 traits. Being aware of design patterns definitely helps, but I think you will anyway come across it yourself if you are a regular programmer or if you explore code written by others!

Again I want to stress my first point. A good programmer is someone who can build a “good” software system given a software requirement. The “good” here means - correct, optimized, reusable, extensible and elegant. Everything else (tools, language, methodology) are just tools to achieve it.

Programming is not for everyone. If you don’t have the passion for it, quit and find another job. If your company doesn’t recognize your talent, quit the company.

Further Reading

Here are a couple of good books for exploring further on this subject. If you know a good one do let me know by commenting below.

The Mythical Man-Month: Essays on Software Engineering, 20th Anniversary Edition - The good old classic by Frederick P. Brooks.

Code Complete, Second Edition by Steve Mcconnell - A must read.

The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt and David Thomas - I endorse the apprentice method

Expert One-on-One J2EE Design and Development (Programmer to Programmer) by Rod Johnson - A must read if you are a J2EE guy.

Your thoughts are welcome!

Programmer for 8 years - and still enjoying it

Just last week I realized that it is over 8 years since I started my programming career (In India guys are ashamed to call themselves programmers, they would rather say “software engineer” or “senior software engineer” or “consultant” etc.). Last time I counted my experience as 5 years and obviously that was 3 years ago!

In Indian software industry, any guy who completes 3 to 5 years of programming career automatically becomes a manager. So essentially no programming/design after 3 or 5 years. Instead the guys start to do what is called “project management”. Something which terrifies me. It is a sheer waste of human talent and experience.

After 8 years of programming I realized an interesting fact. My ability to design software systems or code a software component reached its peak only after 6 years of programming. Ok, it may not be same for all, but it seems that you need to have atleast 5 years of solid programming experience to become a master programmer.

Another ability I acquired recently is the ability to troubleshoot a programming problem instantly. Also during code reviews, a glance at the code gives you lot of design/code improvements even when it is written by an experienced coder!

In most of the software organizations, human resources team(HR)  has no idea about the different types of talent employees possess. There cannot be any exceptions. Everyone has to have the same talent and same aptitude. So that means they cannot imagine a guy with 8 years of experience as a programmer. HR thinks, this guy must be either a lunatic or a total looser to remain as a programmer even after 8 years!

Following is a hypothetical conversation. But it could happen anytime :)

Tech support : You have all tools needed on your system - Microsoft Word, Excel and Outlook Express.

Me: I need Java compiler.

Tech support : I don’t believe you. You are too old for that. Get a written approval from the CEO.