Back to my developer life

Spring Boot

I’m familiar with .NET Framework and ASP.NET MVC, I did love ASP.NET MVC over Spring 2 because of its simplicity, and it was the reason that I chose .NET and ASP.NET MVC for my first startup company in the year of 2009.

Now, I’m not an entrepreneur, I’m just an employee, a technical architect in an outsourcing company and I’ve lost my habit of programming like a developer.

And when thinking of a create anything related to community, ASP.NET MVC is not my 1st choice anymore, although ASP.NET MVC is open source and free, but IIS and Windows Server is not free, and I had to pay a lot when running the Jou Developers community (a community for Vietnamese developer).

I turned to PHP and Java, but my feeling about PHP is that it’s not the language I love the best, Laravel is great, NginX is great, but I’m not in love with PHP anyway. Java is something different, I like Java, but I’m afraid of XML stuff, and I hate to configure everything by myself for a small web application. This is also the reason why I do not like Android very much, when I have to touch XML files every time.

New Spring, Spring Web MVC, Spring Boot, thymeleaf and Gradle really wake me up. I can write web application or console Java application without fear. They save my time. Especially Spring Boot, with it, we can simple call a java command to run a website without any pre-install webserver. ASP.NET is changing with OWIN and Katana, but it doesn’t mean that we will have a light weight web server instead of IIS to host a website. XPS server of Mono is good but not up-to-date, it’s very hard to configure and I give up using XPS. Why I have to waste my time when I have Apache, Tomcat, Nginx, and Jetty.

I’m a .NET technical architect, and I’m still a .NET developer. But by now, most of my personal projects will be developed by using something that are more open like Java, Scala, JavaScript and PHP.

This blog has been idle for a long time, now it’s the time to make it rise again. Back to my hobbies, I will reading-coding-writing night and day. Saigon, 24/02/2014

Getting started with Spring MVC and Gradle

Today, I would like to share an article that can help to get started with Spring MVC and Gradle.

What is Gradle?

I never use Gradle before, however, it’s easy to know what Gradle is, due to

“Gradle is a project automation tool that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based DSL instead of the more traditional XML form of declaring the project configuration.”

I don’t know about Groovy, however, we can learn a lot about Gradle by visiting

Install Gradle on Windows

Download the latest Gradle distributed package at Current version of Gradle is 1.9.

I extract Gradle distribution to folder c:\gradle-1.9 and also add gradle root folder to system PATH variable.

To see as if Gradle is working, open command line application and try to call gradle.bat, the you see the result like below, you can now using Gradle.

I choose NetBeans 7.3 to be my IDE, but NetBeans doesn’t support Gradle officially, so we need to install a plugin named Gradle by follow the instruction from the web page

After installing Gradle, you need to configure Gradle plugin by open menu Tools->Options. We need to set the Gradle Installation Directory for the plugin.

Then, use NetBeans to create new Gradle project:

After choosing project type, now we have to input project name and the main class:

After clicking finish, then a project will be created with its structure like below:

You can see the build.gradle file and settings.gradle file. The build.gradle file is the most important one. You don’t need to use NetBeans to create the project, you just need create a new folder and create the two files build.gradle and settings.gradle.

The settings.gradle just contains the project name: = 'gradle-simple-mvc'

The build.gradle stores all configuration needed for our project:

apply plugin: 'java'

sourceCompatibility = '1.7'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

if (!hasProperty('mainClass')) {
    ext.mainClass = 'com.tumivn.mvcsample.Main'

repositories {

dependencies {
    // TODO: Add dependencies here ...
    // You can read more about how to add dependency here:
    testCompile group: 'junit', name: 'junit', version: '4.10'

To enable java in the project, we need to enable java plugin:

apply plugin: 'java'

The main repository we use for loading dependencies (java libraries) is Maven so we need to declare it:

repositories {

Netbeans also declare a dependency for the project, which is JUnit, for unit testing:

dependencies {
    // TODO: Add dependencies here ...
    // You can read more about how to add dependency here:
    testCompile group: 'junit', name: 'junit', version: '4.10'

However, we need to change the the content of the build.grade so it will be a Spring MVC application other than a Java SE application:

apply plugin: 'war'
apply plugin: 'jetty'

repositories {

dependencies {
    providedCompile 'javax.servlet:servlet-api:2.5'
    compile 'org.springframework:spring-webmvc:3.2.5.RELEASE'
    testCompile 'junit:junit:[4,)'
    runtime 'javax.servlet:jstl:1.2'

/* Change context path (base url). otherwise defaults to name of project */
jettyRunWar.contextPath = ''

We need 'war' plugin to enable web development and when building the application a war file will be created for deployment; 'jetty' plugin for running jetty web server and deploy our website for testing. And the project need more dependencies:

dependencies {
    providedCompile 'javax.servlet:servlet-api:2.5'
    compile 'org.springframework:spring-webmvc:3.2.5.RELEASE'
    testCompile 'junit:junit:[4,)'
    runtime 'javax.servlet:jstl:1.2'

We need javax.servlet:servlet-api version 2.5 and spring web MVC framework version 3.2.5 for develop our website.

Then, we need add more folders to create web application structure:

You can see the web.xml file, it's the web configuration file, below is its content:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns=""




in this file we need to declare an org.springframework.web.servlet.DispatcherServletDispatcherServlet instance to processing work flow. Its name is dispatcher and the configuration file will be stored at [application root]/src/webapp/WEB-INF/spring/dispatcher-servlet.xml.

The dispatcher-servlet.xml content:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

  <context:component-scan base-package="com.tumivn.mvcsample.controller" />  
  <mvc:annotation-driven />

  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/"/>
    <property name="suffix" value=".jsp"/>


We declare to use annotation to configure routing instead of using XML by a declaration:

  <mvc:annotation-driven />

Beside, we have a declaration to allow dispatcher-servlet to scan through com.tumivn.mvcsample.controller package to get controllers appropriate for each request.

Now it's the time to write the first controller named HomeController:

package com.tumivn.mvcsample.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

public class HomeController {

    public String loadIndexPage(Model model) {
        model.addAttribute("title", "Hello Spring MVC!");
        return "index";

The loadIndexPage method is configured to response to the "/" request, and it will send the model with "title" message inside and the view "index" (WEF-INF/view/index.jsp) to front controller to merge view and model and return the result to browser. Below is the implementation of index.jsp


Now, it's the time to build the application. You can easily right click at the project root and choose build menu to build. Or open command line and go to the project root folder and then call "gladle.bat build" command and see build successes.

Now, it's time to run the web application by using the jettyRun task of gradle.

The Jetty server will be run and the website will be available at address http://localhost:8080/gradle-simple-mvc. Open a browser and browse the url and you will see a message "Hello Spring MVC!" on the browse. Congratulation!

To reference, source code is available at GitHub.

This is the first time I touch Java for 5 years. Many things new, and many things I almost forgot. But Java, Gradle and Spring MVC make me excited. I love to learn more about Java and PHP for my personal projects. And still use .NET and ASP.NET MVC for daily jobs.

Happy coding!

The beginning of a software scraftsman


When I’m as the 1st year of university, it took me 6 months to read a Visual Basic book.

After graduated, I realize that I can read a technical books in just a week.

At 22 years old, I became a lecture.

Then, when I was 24, I realized that reading book only can’t make me a pro, I needed more practicing

I became a Java developer for a software company at Hue city.

When I was 26, after a year of building my first framework for ASP.NET MVC, I realized that I need more experiences from real-world software company. At the same time, I realize the value of knowledge sharing, I wrote articles, celebrated code camps, trained the students about new technologies.

In 2010, when I was 28, I became a Microsoft Most Valuable Professional. At the same time, I went to Ho Chi Minh city and start my career as training manager, and after a year working as a training manager, I realized that couldn’t be a good trainer without more experiences.

At the beginning of 2012, I became an technical architect for a start-up company. Building development team, delivering proposal, a half-project manager.

In the middle of 2012, when bidding a big enterprise project, I realized that I didn’t know anything about enterprise. Self-practicing and reading didn’t make me a real software architect.

In the end of 2012, I joined a big software outsourcing company as Technical Architect.

At this time, at the age of 30, I realize that, to be a Technical Architect / Software Architect, I need to read and practice more and more. Broad technical view, hands-on experience, best practices, domain knowledge and the ability to learn and apply every technical with light speed is the key words for my next success.

But don’t forget to learn about data structure and algorithms, strengthen OOP design skills, learn more about database design and programming, the heart of software is data.

Don’t forget to write more articles, tutorials, and build more open source.

Don’t forget to respect people that share their knowledge to you.

Don’t forget to optimize your way of learning and practicing.

Now, it’s just a beginning of a road, the beginning of a software developer!

Tumi learns PHP – 02 – Apply unit testing to Harmonic series calculation

It’s been a while when I write the first article of Tumi learn PHP series. Today, I will refactor it a little bit by applying OOP and Unit Testing to make sure Harmonic calculation is more accurate and easier to maintain.

First thing first, I will change the website folder structure:

  • “app” folder is for storing application code
  • “public” folder is for storing web page, HTML and CSS, they are visible to end users
  • “tests” folder is for storing unit tests
  • “vendor” is for storing 3rd party libraries, e.g. PHP Unit

The virtual host points to “public” folder.

Now, we will use composer, a package manager for PHP project. We will go to to visit Composer home page and go to download page to download composer.phar archive and put to any folder that you want on your local machine. For me, I will put the composer.phar to application root folder.

At the root folder of our application we will create a composer.json file to declare what 3rd party libraries that we will use and then use composer to get them for our project.

    "require-dev": {
        "phpunit/phpunit": "3.7.*"

Open command line and navigate to our project root folder and call:

php composer.phar install

You will see something like the below screen shot:

Composer install

And the folder structure is:

Website folder structure

I use NetBeans as an IDE for this project so there will be a nbproject folder inside the application folder, but you can use any editor you want. And we will see that composer download phpunit and some symphony class for us. Because phpunit is dependent on some symphony classes, so composer will download the dependencies as well.

Now, we create a class Harmonic.class.php inside ~\app folder, it is for store the maximum number of Harmonic series and have a total() method to calculate the total of its series.


class Harmonic {
    private $maxNumber;

    function __construct($n) {
        $this->maxNumber = $n;

    function total() {
        throw new Exception('Not implemented');

The total method is not defined yet. We will implement it by following the TDD (Test Driven Development) process, it means that we will follow the red – green – refactor process. We will create test first, run it and see it fail, modify our class to pass the test, refactor it, then write another unit test and continue to test to see it fail…

Create a PHP file called HarmonicTest.php inside “tests” folder:


include_once '../app/Harmonic.class.php';

class HarmonicTest extends PHPUnit_Framework_TestCase

The Harmonic Test class will store all unit tests for Harmonic class and it’s derived from PHPUnit_Framework_TestCase class.

Now we implement the first unit test as a method of Harmonic test class to test the simplest case; the Harmonic class can calculate the series with max value is 1.

public function testTotalIsCorrectWithMaxValue1()
    $harmonic = new Harmonic(1);
    $total = $harmonic->total();
    $this->assertEquals(1, $total);

Now, we will try to run the test by invoking phpunit.php class like below:

First unit test

Yes, the test failed, because we didn’t implement the source code. To simply pass the test, I modify the total method to return maximum value:

function total() {
    return $this->maxNumber;;

Run the unit test again and see it passes. Now, we write unit test for another test case (maximum = 3):

public function testToalIsCorrectWithMaxValue3(){
    $harmonic = new Harmonic(3);
    $total = $harmonic->total();
    $this->assertEquals(1 + 1/2 +1/3, $total);  

Run unit tests and we will see the above unit test fails:

Second unit test

Now we have to modify the total() method of Harmonic class:

function total() {
    $result = 0;
    for ($i = 1; $i <= $this->maxNumber; $i++) {
        $result += 1 / $i;
    return $result;

Run unit tests again, we will see all test pass.

Are we done? No, not yet. Please don’t forget the sad paths. When the parameter is not as we want, e.g. $maxNumber is not a number, or $maxNumber is less than 1. When $maxNumber is less than 1 we simple return a null value.

When $maxNumber is not an integer, we expect that an InvalidArgumentException is throwed:

    * @expectedException InvalidArgumentException
    public function testTotalWhenConstructorParameterIsNotInt(){
        $harmonic = new Harmonic("Is String");

We need to learn more about PHPUnit to use it well. After Red status, we should implement Hamornic constructor as below:

function __construct($n) {
        throw new InvalidArgumentException(
                'Only accepts integer');
    $this->maxNumber = $n;

Maybe this will be enough and now we update our code to use Harmonic class. As mentioned above, the harmonicseries.php will be stored at public folder so end user can access:


And the harmonicseries.php is modified:

include_once "../app/Harmonic.class.php";
/* Write a PHP app that, which sums the terms of the harmonic series 
(1 + 1/2 + 1/3 + 1/4...) up to a limit supplied by the user.
$message = '';
$hasTotal = false;

if('POST' == $method)
        $limitNumberString = $_POST['limitNumber'];     
            $limitNumber = intval($limitNumberString);
            $harmonic = new Harmonic($limitNumber);
            $total = $harmonic->total();
            $message = "Total (with n = " . $limitNumber . " ): " . $total;
            $hasTotal = true;
            $message = "Error! You didn't input a number!";


        <title>Harmonic series sum</title>
        <style type="text/css">
            display: none;
        <div <?php  echo($hasTotal?'class="hide"':""); ?>>
            <form method="POST">
                <p><label>Enter N to evaluate 1 + 1/1 + 1/2 + 1/3 + ... + 1/(n-1) + 1/n: </label></p>
                <p><input type="text" id="limitNumber" name="limitNumber" /></p>
                <p><input type="submit" value="Submit" /></p>
            <h3><?php echo $message; ?></h3>
            <?php  echo($hasTotal?'<a href="">Calculate with another value of N..</a>':""); ?>

Yes, it work well, but again, it now well tested. The harmonicseries.php still contain logic, and it is tested. We need to apply a pattern like MVC to apply more unit test for our code. In the next article I will introduce a MVC Framework called Laravel and we will try to implement a website with CRUD features and access to a database (MySQL / SQLite).

You can find the source code on GitHub.

Happy coding!

Which JavaScript MVC Framework should i use?

Popular JavaScript MVC Frameworks

Which JavaScript MVC library should we use?

It’s hard to make decision because a lot of JavaScript MVC framework out there. For outsourcing business, it depends on what customer want. For personal usage, we can think read comparison articles and choose what we want.

Here’re two great links for your reference:

Back to Java world

Back to Java world

I remember of the day I gave up my job as a teacher at College of sciences and I had been interviewed to be a Java developer. The interviewer asked me many things about Java and HTTP, and I didn’t know anything at all. But, luckily, I passed and became an Java Developer.

In just nine months, I’d learned a lot about Java, JSP, EJB, Hibernate and many things more. But the company went to trouble with finance, and all developers lost their job including mine. The time being a Java developer is quite short, but It changed me from the one who didn’t know anything about how to make a real software became the real developer, who can build his own software, who can learn any technology for development without fear.

I’ve learnt .NET, JavaScript, PHP.. by myself and founded a small IT company that build softwares and websites by using .NET and ASP.NET MVC. And by now, I’m a .NET Architect, and has a programming blog, a .NET community for Vietnamese founded and programmed by me myself.

I decided to learn more about programming world by learning PHP, NodeJS… However, in the last two days, I’d lived alone and thinking about all the stuffs that I did before. I realize that Java bring me the passion of a programmer. Programming Java make me know about MVC, ORM, DDD and more. Java is pure OOP like C#, and Java world is huge (with/without Android). I’m eager to learn more about Java, Java EE, Apache Open Source and Linux.

I’ve learned PHP, and I keep on using it. But for my career a path, as a Software Architect, I need to a more powerful tool like Java and .NET. So it is the time to push the Reset button and re-build my knowledge to make it solid and make me more ready for enterprise world.

That means, I will not write a lot of articles for Vietnamese developers as usual. I will find a new administrator and a small team that will work on Jou Developers source code to enhance it.

I need to train myself and step up to a new level. I want me to be more ready as an Technical Architect. And have strong software development skill with Java and .NET.

I still love to learn more and more programming languages in my free time but from now I will focus more on enterprise software development.

Tumi learns PHP – 01 – Calculate the Harmonic series

I’ve spent a lot of my time to learn PHP without coding. It’s a shame. I believed that I can remember PHP syntax easily because I have 7+ years of C#. I also learned C++, VB6, VB.NET, ActionScript, Java and JavaScript before. But, the truth is, I can’t remember anything about PHP after learning it.

A friend of mine replied of Twitter when I said “Read programming books everyday”, he said “don’t forget to code as well”. Yes, you can’t be a senior guy without practicing. You can tell everyone what PHP has, what is Zend, what is Laravel, how they’re compared together, but when you try do real thing, you will be confused. So, I decide change my way in learning PHP, and I will share to you.

This is the first article of the series “Tumi learns PHP”. But please consider:

  • You can’t learn everything about PHP by reading my article. It’s just my way in practicing PHP.
  • You should skim through some PHP fundamentals book to learn PHP syntax or visit to learn.
  • I’m Vietnamese, English is my 2nd language, and it means that I can have a lot of typo/grammar mistakes. So please correct me if anything wrong.
  • And the most important one, I’m just a PHP newbie, please help to make me a better PHP programmer.


Write a web app which sums the terms of the harmonic series 1 + 1/2 + 1/3 + 1/4… + 1/(n-1) + 1/n  up to a limit supplied by the user. (n > 0, n is an integer)

My Questions

Currently I do not have any idea at all. But I have questions:

  • What is PHP, anyway?
  • Yes, I know PHP is a language for web development, I need an editor for writing PHP code, and which editor should I use?
  • I know that code can run by itself, it need to be compiled, how to compile PHP code and deploy it so that we can use it?
  • Environment for PHP development? How we setup that?

What is PHP? define: “PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language.” and “PHP code is interpreted by a web server with a PHP processor module, which generates the resulting web page: PHP commands can be embedded directly into an HTML source document rather than calling an external file to process data. It has also evolved to include a command-line interface capability and can be used in standalone graphical applications.”

PHP is a server-side scripting language and it’s also an interpreted language. It means that, PHP doesn’t need to be compiled before like Java, C# or C++, it is parsed and performed directly by an interpreter at runtime.

How can I develop web app with PHP?

It’s quite easy to getting started with PHP. I will introduce of how to install PHP on Windows first. At the moment, I just want to have PHP install on my computer, and can write some PHP code as soon as possible. I have heard about:

  • WAMP (Windows – Apache – MySQL – PHP)
  • LAMP (Linux – Apache – MySQL – PHP)
  • MAMP (Mac OS – Apache – MySQL – PHP)
  • Or NginX ( a web server that support PHP)

Apache is a well-known web server for PHP, it is open source like PHP and it’s free. MySQL is a database management system, is also an open source. We will learn about them in later articles.

Right now, we go to, my computer is a Windows 8 x64 one, so I choose PHP 5.5.3 VC11 x64 Non Thread Safe ( I download it and unzip it at E:\PHP\ (you can extract anywhere you want to).

Now open the Command Line (or PowerShell), and try to check PHP version:

Figure 1.1: Check PHP versionFigure 1.1: Check PHP version

On the above screenshot, I use the –V parameter to see installed PHP version, it is 5.5.3.

Ok, we already have PHP inside our computer, but how to start programming with it?

Don’t worry, first thing first you should add your PHP directory in to PATH variable of Windows, then you can call PHP everywhere you want. Follow this guide ( to add PHP to Windows PATH variable.

Now, we use PHP.exe command to print the result of 5 + 3:

Figure 1.2 – First PHP sentence Figure 1.2 – First PHP sentence

You can see the command and its result in figure 1.2. However, PHP is for web development, how can we do it without Apache or Nginx? Luckily, PHP has a built-in web server, and you can host your website for study purpose without installing Apache or NginX.

Create a folder that will contain you PHP files (I choose E:\_Websites\ex_01). Inside that folder, create hello.php, by call the below command:

Figure 1.3 – Create hello.php

Figure 1.3 – Create hello.php

Then type the content for hello.php using Notepad.

Listing 1.1 – Hello.php On the above code, the hello.php includes PHP code and HTML code, and PHP code is wrap inside <?php .. ?>. Now, back to the command line, and host the ex_01 folder as a website by using PHP built-in server: Figure 1.4 – Host a website using PHP built-in server Figure 1.4 – Host a website using PHP built-in server Now open your browse and navigate to http://localhost:8089/hello.php Figure 1.4 – My first PHP web page Figure 1.5 – My first PHP web page   So, we have our first PHP page, but writing PHP code with Notepad program is not a good idea. You need a more powerful editor that has PHP color syntax, code auto completion and much more. I prefer to choose Sublime Text, but Notepad++ is good as well. And there are many more powerful editor that support PHP like NetBeans, Eclipse…,  most of them are free.

Solving problem

Now we back to the problem that we write out in the beginning of the article “Write a web app which sums the terms of the harmonic series 1 + 1/2 + 1/3 + 1/4… + 1/(n-1) + 1/n  up to a limit supplied by the user. (n > 0, n is an integer)” In the root folder of the website, I create a PHP file called harmonicseries.php, we will implement our code to solve the problem inside it. Let consider the situation:

      • User will request the address http://localhost:8089/harmonicseries.php, and will get a web page that show a text box and a submit button; user will input the value of n and click submit button to send n value to web server.


  • The web server will calculate the harmonic series total and send back the result to end user.


Let start coding! Now we add some HTML code into the file:

Listing 1.2 – HTML form for inputting the value of N

When try to browse, we will get a web page like below:

Figure 1.5 – The harmonicseries.php UI

Figure 1.6 – The harmonicseries.php UI

You can click on Submit button, but nothing happen because there is no server side code for processing it.

When you try to browse http://localhost:8089/harmonicseries.php, you‘ve just created a GET request to server and web server parse PHP code and generate HTML content and return back to the browser. Then, you input the value of N to the textbox, and click Submit button. The browser will send a POST request to web server when Submit is clicked. This is because we set the method of HTML form to POST. When receiving the POST request, we need to have PHP code to retrieve the value of N and calculate the total number and then return the result back to client.

To determine if a request is POST or GET, you need to access a global variable $_SERVER like below:

Listing 1.3 – Detect request method

After thinking for a while, I decide to implement the entire code like below listing:
Listing 1.4 – Implement the harmonicseries.php

if you’re new to web development, you will have many questions for the above code. But I do not explain anything. You should try and to answer by yourself.

Now try to run the web page, and enter an invalid value to the textbox and click Submit:

Figure 1.6 – Try to add an invalid value

Figure 1.7 – Try to add an invalid value

You will receive the error message:

Figure 1.8 – Result when sending an invalid value to web server

Figure 1.8 – Result when sending an invalid value to web server

When you enter an valid value, you will receive the result:

Figure 1.9 : Result when sending a valid value to web server

Figure 1.9 : Result when sending a valid value to web server

Congratulation, you’ve done it.

Anyway, the above code is not good enough, and as an experience .NET developer, I ask myself how to improve the code, because:

  • This code is not easy for unit test, and how to unit test with PHP?
  • This code is not well designed, maybe we should apply some OOP principles.
  • Validation is not well enough, some invalid case is not checked, e.g. user enter decimal/negative value.

And I decide to learn how to make my code better by applying unit test and redesign the existing code in the next article.

September plan


I always have personal plans for improving my programming skills or for writing things like short stories, or programming articles for community, however, they’re almost failed. There are many reason that I can count on, but there is one truth, I failed in planning, that’s also mean I wasted my time.

To make my plans realicstic, I will write them on this blog each start of every month and write down the tasks status in the end of each week too.

So what is the plan for this month?

1. PHP The Right Way: read them all and then translate it to Vietnamese, Vietnamese IT students and developers need to read that before continuing on studying/programming using PHP.

2. Code bright (of Dayle Rees): I love this book, and I plan to re-write my website to PHP with Laravel framework, so I have to skim through this book within a week. (Deadline: September 14th)

3. A series of ASP.NET MVC (ver. 4+5) programming for Vietnamese developers, I will translate some of them into English to. (5 articles)

4. A simple blog using Laravel and MySQL and contrib it on GitHub or BitBucker

5. Learn “Building a Site with Bootstrap, AngularJS, ASP.NET, EF and Azure” of Shawn Wildermuth on Plural Sight

I think, they are not easy to finish but not very hard also.

Let wait and see what I can do within the next 3 weeks.


How to display time following client browser time zone on ASP.NET MVC or PHP

I have a site that have many users from different time zone, and I want the times on my web page will be displayed correctly due to the client browser time zone. How to do that?

First thing first, I need to store the create/update time for articles, comments… with GMT time zone. Then, when a user try to browse a page, I will try to get client time zone, and then convert the times to client time zone to display. For example, I’m at Vietnam (GMT+7), when I try to browse an article on my website, and the article create date is GMT 2013/06/24 10:00am, it should be displayed as 2013/06/24 05:00pm (GMT+7 time).

Secondly, we need to know that, we don’t have any function to get client time zone at server side, but we know how to get the time zone at client side by using JavaScript.

Please try run the below JavaScript on any browse:

var offset = new Date();
//result = 420 if client time zone is GMT+7, it means 7 hours or 420 minutes

OK, right now we know the time zone offset. But to get it on server side, we need to store the value into cookies. The JavaScript method below is to save a value to cookie:

function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays == null || nDays == 0) nDays = 1;
expire.setTime(today.getTime() + 3600000 * 24 * nDays);
document.cookie = cookieName + "=" + escape(cookieValue)
+ ";expires=" + expire.toGMTString() + "; path=/";

var offset = new Date(); 
setCookie("TimeOffset", offset.getTimezoneOffset(), 365);

But hold on a second, please see the last sentence of setCookie method:

document.cookie = cookieName + "=" + escape(cookieValue)
+ ";expires=" + expire.toGMTString() + "; path=/"; 

Why do we have “path=/”, what does it mean? Yes, it’s very important, you must know that cookies is an dictionary that will be send ford and back between client and server, so, the cookies size should be as small as possible. Let see an example below:

1) Using firebug, add a cookie by execute the document.cookie=”sample=420;” at “/” level.

When turn to Firebug Cookies tab, you will see:


Yes, the cookie sample is saved as expected, with Path equals to “/”.


2) Using Firebug again, and try to add cookie but with a deeper level page like, you will see that there are two cookie with the same name “sample” are stored:

03There’s no need to store a same cookie at many path, so we need to define the Path that we need to store the cookie by using “path” parameter like below:

document.cookie = "sample=420;path=/"

Now, with ASP.NET at server side, we can get the cookie easily like below:

    public int GetClientTimeOffset()
        var timeOffset = 0;
        var timeOffsetCookie = HttpContext.Current.Request.Cookies["TimeOffset"];
        if (timeOffsetCookie != null)
            timeOffset += Convert.ToInt32(timeOffsetCookie.Value);

        return timeOffset;

By using that above function, you can easily change the time value to follow the client time zone before, like:

item.CreatedDate = comment.CreatedDate.AddMinutes(-_cultureService.GetClientTimeOffset());

If you’re a PHP developer, it’s easy to get cookie value by get use $_COOKIE global variable like:

$timeOffset = $_COOKIE["timeOffset"];

But don’t forget to validate the cookie value before doing anything, because everyone can set the cookie by using a tool like FireBug. And sometime, the cookie is not set yet.

That all of my article today, the next article is about how to store multi-level comment system effectively to reduce the cost of querying data from SQL.

Happy coding!