References to good BYO PHP MVC Framework tutorials

When I first came across the term MVC (Model-View-Controller) few years back, the whole concept sounded so complex, especially for people with (old) ASP and PHP background. In those days, we were so used to mixing business logics inside the presentation layer. It was so logical and convenient, until the code got big and things got out of hand. We forgot where the codes were, and we risked stability even for small changes to the UI, because they were all intertwined with business logics.

Typical PHP-HTML mixed code:

  include "someFileContainsFunction.php";
  public function someLocalFunction( $param )
    return "Business logic in <b>$param</b>!";
  <title>HTML with PHP</title>
    <h1>My Example</h1>
      print someLocalFunction( "Inside body" );
    <b>Here is some more HTML</b>
      print functionFromExternalPHP();

Then I was introduced to MVC during a Microsoft .NET bootcamp in Singapore. I was quite fascinated with the idea. Separating the 3 components enable us to distribute the work to programmers and designers, allowable them to do their work without touching the fields they’re not familiar with. It is also an ideal solution to multinational collaboration.

Although the .NET MVC framework was great as a development tool, I couldn’t understand the fundamentals of building an MVC. We merely followed the coding style requirements by the framework, and work our way through to make the application work.

So I went in search of other languages, and found many other frameworks such as Ruby on Rails (for Ruby) and CakePHP (for PHP). They are also great MVC frameworks, but then again, they’re very established with quite stringent coding style requirements that I always got lost halfway down the development.

I thought the best way to learn about something is to start from the beginning, and keep on testing and failing until I understand it. The following 2 tutorials are great starting points. I managed to write my own MVC framework within a day (or maybe a few hours) by following the tutorial from Domagoj Salopek. I would recommend going through this tutorial first before going to the next one, which is slightly more complex but covers a little more for MVC.

Of course, there’re people who think that using MVC on a small project is an overkill. Trust me, it’ll help you in the long run. By writing a core MVC framework, you’ll be able to use it in all other projects in the future, regardless how big or small it is. Unless the client only wanted a “simple” website. I know clients always think their requirements are simple because they don’t understand the simpler it seems, the more work it takes. I’m referring to those instances where the project can be done just with HTML and JavaScript. In those cases, MVC is really too much.

Now, going back to fiddling the simple MVC framework that I have written.

Edited: After writing my own simple MVC framework, I went on to study other major PHP framework such as Symfony, CakePHP and CodeIgniter. I noticed that CodeIgniter uses a very similar approach to the simple framework introduced by Domagoj. So if you’re advancing to a more complex framework, take a look at CodeIgniter. You’ll be glad he had written something so fundamental to get us started.

MD5 Hashing password or text using Perl

Just a small tip I learned from work.

Obtain the MD5 hash of the password using Perl:

$ perl -MDigest::MD5=md5_hex -e"print uc(md5_hex(@ARGV[0]))" hellother3



The uc() means returning the upper case of the result.

print uc(md5_hex(@ARGV[0]))

To return the lower case of the result, use lc() instead:

print lc(md5_hex(@ARGV[0]))

Setting Aptana to read another file type as PHP

So recently I’ve been following this simple tutorial to learn about creating a simple MVC PHP framework:

It’s so simple that I got a MVC template in less than an hour. But it definitely took me some time to fully understand the code. Luckily I have some experience with WordPress and CakePHP so somehow it wasn’t too long for me. *Trigger proud-mode* 😛

As usual I was using my favorite IDE Aptana but something struck me: I don’t see the PHP color code for the *.tpl files that I have created for the MVC framework. It’s quite annoying and inconvenient.

Turns out it’s actually quite simple to “fix” it.

  1. Just go to Preference (Mac users check the “Aptana Studio 3” menu at the top panel, WIndows and Linux users should check the File or Tool menu)
  2.  Under General -> Editors -> File Associations
  3. Under File Types -> Choose Add, and enter: *.tpl
  4. After added, click on that file type
  5. At the bottom, click Add and choose “PHP Source Editor”.


Now when you reopen all the *.tpl files in Aptana, it will be recognized as PHP files.

Hope this is useful to you. 🙂

Windows 7 Auto Logon in Domain

1. Go to Start>Run (or press the windows key + r)

2. Type regedit and press the enter key or click on OK.

3. In the registry editor go to HKEY_LOCAL_MACHINE>SOFTWARE>Microsoft>Windows NT>CurrentVersion>Winlogon

4. On right side pane look for these values AutoAdminLogon, DefaultPassword and DefaultUsername. If they are there skip on to Step 6.

5. If the above values aren’t there, then right click on empty area in the right pane select New>String Value and enter the value name such as AutoAdminLogon. Repeat this step for each value.

6. Once you’ve created these values double-click each value and enter the following value data for the particular value

Name : AutoAdminLogon Value : 1
Name : DefaultPassword Value : the pasword of the user profile
Name : DefaultUsername Value : the username of the account you want to log in to

7. Now you’re done!


C# .NET Entity Framework: How to insert record into database table with auto-increment primary ID?

Updated: 9 Sep 2016

Just got a comment asking me to take this post down because it’s outdated. Well, this was written in 2012 so it’s really VERY old. And I no longer use C# .NET Entity Framework. I’m leaving this post here for people who’re still using the old framework. All comments are closed now. I’ll no longer answer question relating to this topic. Please read it with caution.


I want to insert some records into the database table but it is giving an error which says “INDENTITY_INSERT is set to OFF”, something like that.

To resolve this, there’re 3 steps:

First, in Visual Studio 2010 and click on the .edmx file.
Look for the relevant and right click on the identity column (ID in most cases) and choose Properties.
In the properties window, look for StoreGeneratedPattern and change the value to “None”.
Save the changes.

In some cases (in my case), changing the value in step one is not enough. We still need to manually edit the .edmx file.
In Visual Studio 2010, right click the .edmx file -> “Open With…” -> Choose “XML (Text) Editor” to open the .edmx file
Look for the relevant table and change StoreGeneratedPattern=”Identity” to StoreGeneratedPattern=”None” for the identity column.
Save the changes.

Once the EF settings are done, we can set the primary key at the EF side.
However, SQL Server does not allow the Identity column to be set unless IDENTITY_INSERT is ON. (
So we need to manually execute SQL command to turn on the IDENTITY_INSERT first before we insert new records.

using (TestDBEntities1 context = new TestDBEntities1())
	using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
		int i = context.ExecuteStoreCommand("SET IDENTITY_INSERT TestDB.dbo.Person ON");
		Person p = new Person();
		p.PersonID = 4;
		p.Name = "Michael";
		i = context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.Person OFF");

This is a workaround to let us manually set the identity column.
Warning: when IDENTITY_INSERT is set to ON, we need to manually assign the identity key (ID in most cases). You must ensure that it is unique and not null or empty. If you want to get the next available ID, you may add this:

Person p = context.Person.OrderByDescending( c => c.PersonID).FirstOrDefault();
int newId = (null == p ? 0 : p.Id) + 1;


New generation internet cafe: bring your own computer

Recently there are some emerging new ideas of small USB-drive size personal computers that are powered by Linux or Android. It may not be as powerful as a computer now, or even a smartphone. But this is the beginning of a new era, the era where we literally bring our lives (and data) with us to work and play.

Today in internet cafe, we always face the danger of privacy. More often than not, the computers in the internet cafe are not well protected against people from trying to steal our information. Be it password or browsing history.

Imagine a day where internet cafe provides only monitor (with built-in powerful graphics engine), keyboard and mouse. All you need to do is to plug in your USB-drive sized personal computer into the monitor and you can start working with all your personal data and whatever cookies you may have stored. You don’t have to remember to log out of your device because you’ll take everything with you when you leave the cafe. (And of course there’re still ways to steal your password through keystroke with some external devices, but let’s just forget about that for now. :P)

This could be applied to our office workstation too. No need to bring heavy laptops to and fro. Just a tiny personal computer, internet access and cloud storage.

People (such as Motorola) have also thought about using our phone as our personal computer. But the main problem is, because we have so many different phone manufacturers implementing different peripherals, it is still better to come up with a common device such as USB, for this new portable personal computer.

It’ll be very difficult for internet cafe owners to try to provide different peripherals for different phones. If so, I can foresee a shop with many sections and each section for different phone manufacturer.

One major disadvantage of many proposed USB personal computer is the graphics card. Due to its size, manufacturers cannot squeeze in high performance graphics card. So playing games with the device may not be ideal. Then why not put the graphics card in an external device such as the monitor? When we plug in our USB PC, it will automatically switch to this high-end graphics card and we can start shooting our enemies at the top of a high building.

Just some thought. And I really believe this will happen some day.

Retrieve Linux and Darwin version

There’re many ways to retrieve the linux version or distro information. Sadly, they are not standardized across all distros.

Below are some of what I have found working for myself. Feel free to suggest more.

Retrieve Linux version

You can use either of the followings:
# uname -a
# cat /etc/issue

Getting Kernel version on Mac and Unix/Linux machine

To get the full kernel information using command line

terminal?> uname -a

On Fedora 16, you’ll see

Linux computer-fedora-linux 3.1.0-7.fc16.i686 #1 SMP Tue Nov 1 21:00:16 UTC 2011 i686 i686 i386 GNU/Linux

On Ubuntu 12, you’ll see

Linux computer-VirtualBox 3.2.0-21-generic-pae #34-Ubuntu SMP Thu Mar 29 22:33:16 UTC 2012 i686 i686 i386 GNU/Linux

On Mac OSX Lion, you’ll see

Darwin iMac.local 11.3.0 Darwin Kernel Version 11.3.0: Thu Jan 12 18:47:41 PST 2012; root:xnu-1699.24.23~1/RELEASE_X86_64 x86_64

To just get the kernel name using command line

terminal?> uname -s

On Linux machines, you should see


On Mac machines, you should see


Mac osascript pass variable to bash shell

Just wanted to keep this solution found from several sites.

This scripts uses Mac’s osascript to call a simple dialog and asks user for an input. On return, the result will be passed to the bash variable $UserInput.

A very important note here is that the 2nd EOT line must not include any indent or space in front. It will return an error message saying “161:164: execution error: The variable EOT is not defined. (-2753)”. I was searching high and low for the problem and didn’t realize it is so stringent with indent/space.


# Created by Andrews Ang on 6/29/11.

function GetDialog(){

UserInput=`/usr/bin/osascript « EOT

    tell application “System Events”


    set myReply to text returned of (display dialog “Here is a question” default answer “Here is a reply”)

    end tell


    echo ”${UserInput}”



Raphael.js IE7 issue with innerHTML on elements other than div

I kept having this unknown error on IE7 (IE9 compatibility mode) when I use Raphaël JavaScript Library. On deeper research, this error points me to line 5178’s “span.innerHTML”.

I found this very interesting article about usage of .innerHTML in IE7:

…innerHTML can cause some problems, particularly in Internet Explorer. If you use innerHTML to add or update form elements, all sorts of screwiness can occur. Sometimes the data from the newly added elements won’t be included when the form is submitted to the server.

and it provided a useful fix:

First of all, use the DOM to create a block level element—such as a div—using createElement. Then update the innerHTML property of this newly-created element. Finally, insert the updated element into the document using a DOM method like appendChild or insertBefore…

I thought it was a perfect fix, so I searched for the .innerHTML implementation in raphael.js (line 5178):

res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/"));

and changed it to:

/*Resolve IE7 issue with innerHTML*/	
var newdiv = document.createElement("div");
res.textpath.string && (newdiv.innerHTML = Str(res.textpath.string).replace(/"));
/*end of resolution*/

Somehow it worked very well. I had forked and submitted a fix but still waiting for the main master to commit this change. You can find the fix at my fork:…patch-1

ASP.NET passing data between pages

Today I was working on a senario where I wanted to pass an ID to another page after a postback had occurred. Usually I would do this using a redirect with the ID appended behind the URL as query string, like this.

// In page2.aspx
protected void Button1_Click(object sender, EventArgs e)
    // Did something here
    string passinId = txtId.Text;
    Response.Redirect("/Page1.aspx?id=" + passinId);

And then in Page1.aspx, I do this to get the ID.

// In Page1.aspx
protected void Page_Load(object sender, EventArgs e)
    String s_id = Request.QueryString["id"];
    if(null != s_id)
        // do something

However, in this special case, I’m actually loading Page2.aspx using AJAX within a modal window in Page1.aspx. Page1.aspx has many links to load Page2.aspx (I’ll skip the long story), so having the ID in the address bar as a query string will make it look very confusing to the user.
I find Session quite useful here: it allows me to pass the ID between pages yet not showing it in the address bar. Of course, security is not of concern here since I’ve been showing it in the address bar anyway.
So in Page2.aspx, instead of appending the ID behind the URL, I do this.

// In Page2.aspx
protected void Button1_Click(object sender, EventArgs e)
    // Did something here
    string passinId = txtId.Text;
    Session["SpecialKeyName"] = passinId

Then in Page1.aspx, I get the ID like this.

// In Page1.aspx
protected void Page_Load(object sender, EventArgs e)
    if (Session["SpecialKeyName"] != null)
        //get the Session value
        string s_id = (string)(Session["SpecialKeyName"]);
        // Do something

I make it a point to delete the session after use since I only want to use it whenever it’s available. If it’s not available, I will show some default data.

This is not the only way, but it definitely helps me solve my problem.

Read up here on MSDN for more information on Session, different types of approaches as well as some tips and warnings of each approach.

Another good read about ASP.NET Session State on MSDN here.