Chorn Sokun’s Weblog

try { divide and conquer; } catch { keep it simple!; } finally { nothing is impossible; }

PHP date diff

with 2 comments

I call out for an excuse for not practicing PHP enough recent year; with just a simple date_diff could knock me out :) not to open my complain of having different version of PHP to check before using a function(s) I got a request from a friend to help workout how many days from two given date.

Now if I have two date string (it is what we get from form post right?)


// fixed format as I don't want to deal with complicate of different world format :(
$day1 = "26/03/2009";
$day2 = "28/03/2009";
// now I need to know how many days does it take from day1 to day2
// PHP 4.x; ignore my out of date PHP skill this is how I did it
$break_day1_apart = explode('/', $day1);
$break_day2_apart = explode('/', $day2);
$day1_number_form = $break_day1_apart[2].$break_day1_apart[1].$break_day1_apart[0];
$day2_number_form = $break_day2_apart[2].$break_day2_apart[1].$break_day2_apart[0];

$day_diff = abs((int)$day2_number_form - (int)$day1_number_form);

// and it should work by theory
echo $day_diff; 

Suck ! what would you do instead?

Written by Chorn Sokun

July 4, 2009 at 11:37 am

(N)How simple could that be?

with 2 comments

projection-skill-in-action

Wonder how this report get produced from model above it? If you guess was

  • NHibernate
  • MR (did you say <table>?)

You right and I must say I finally master the NH Projection skill or in another word (stealling from JXII) level up!.

What I did by taking AreaCode as primitive data connect it through and transform set of progress records into columns pretty cool trick, no NH hack is required it all natural.

Happy Projections day

Written by Chorn Sokun

May 29, 2009 at 12:19 pm

5,000 riels for a life

with one comment

I was deeply sad to witness an accident on my way back to work around 1:20 PM I am not sure I could express my emotion or be able to give you the image of the scense but I’ll do my best.

On a stop light turn blue a young man driving his motor on direction of Olympic stadium to Royal Palace shuddenly he saw the polices waiting on the otherside of the street (Monivong) wanted to stop him (his motor didn’t wear glasses) he began to speed up when on the opposite side there was a motor drive by a school girl and her female friend. The girl was tried to pass a car on the right hand side.

In just a second both motors positioned in the middle of the street where the accident occured where all passengers fall down on the street; about the card that the girl passed was immediately hit the break and it right wheel stop an inch from the girl’s motor back wheel I am not quiet sure if it front light was destroy or not as I changed my focus to the result of the accident.

What left on the scense? the man and the girl drivers was lightly injured BUT there was a body of the girl seating behind her friend still laid down on the street; her leg and hand was shocked. She was in a fatal condition as her head was hit hardly on the street.

usb-crash-helmet-optical-computer-mouse

Protection both motor drivers got their helmet on; but the girl seat behind was not although she did wear a mask to protect her health; but helmet should have been use instead.

I’m so sad really reallysad all of this could have not happen if the young man accepted penalty from the police then the lost is just 5,000 Riels (max) instead of the life of an innocense.

Written by Chorn Sokun

May 21, 2009 at 2:06 pm

Save the world

with one comment

It all about us saving the world let make it happen print a copy or more and stick it to a wall.

Cover your Cough Poster

Cover your Cough Poster

For a better print resolution download PDF file bellow:

Good health, bright future !

Written by Chorn Sokun

May 1, 2009 at 2:25 pm

Posted in Community, Socialize

Tagged with , ,

Myth of Cambodia Geography Identification Code

leave a comment »

How many of you are familiar with Cambodia Geography Identification code. Do you know the myth behind it code assignment? Well, it’s all started like this:

  • There are 4 levels of administration
    • Province
      • District
        • Commune
          • Village
  • Each level add up 2 digits begin with Province 2 digits
  • Identification code are stored in numberic form (Integer)

That mean valid village code length bewteen 7 and 8 for example code 24020406 would identified as:

  • Village Name = Ou Ressey Loeu (24020406)
  • In Commune  = Ou Andoung (240204)
  • In District = Sala Krau (2402)
  • In Province = Pailin (24)

Now suppose these Geography represent in 4 separate tables (SQL Server for ghost shack!) 

geography

By knowing a village code (eg:  24020406) I want to extract province code and I want the quickest way possible any thought? Oh ! there will be a reward for best answer.

Written by Chorn Sokun

April 28, 2009 at 5:27 pm

Rhino-Tools a smarter Guard

with 4 comments

When Ayende typed Guard.Against(condition, error_message) it clicked in my brain. I thought wow that was nice and easy to use what it does was check if the condition is true it will throw and exception with error message specify. I had an idea using this litle beast for business validation, since it doesn’t required any special configuration all you have to do is adding reference to Rhino.Common.Clr.dll.

However the original Guard API only has only two static method Guard.Against() it was limited for web application. In web application we might want to report back all problems so user can make the correction before they re-submit the form again, but using Guard.Against() we only catch one problem at a time, if we have multiple codition to check you can imagine how annoy for web experience.

Ayende is kindly enough accepting my patch for two additional method for the Guard bellow:

  • Guard.Check(condition, error_message) – same behavior as Guard.Against() but it won’t throw and exception instead keeping records of problems
  • Guard.Report() – until .Report() get call and exception known as GuardSpotException will be throw.

Let see how I can improve my usage experience with these methods


try{
  new Guard()
    .Check(pay.Date.Equals(DateTime.MinValue), "Invalid payment date.")
    .Check(pay.Amount == 0, "Invalid amount, should it be something other than zero?")
    .Report();

  // persist pay instance to the database
}
catch(GuardSpotException ex)
{
  // list of errors message
  PropertyBag["errors"] = ex.GetErrorSummary();
}

First I instantiate a new Guard object and start checking conditions (business rules) finally I call Guard.Report() if there is any true condition (= business rule voilated) and exception known as GuardSpotException will be throw you then can catch and examin all problems.

Isn’t that cool?

Written by Chorn Sokun

April 10, 2009 at 10:37 am

MonoRail & jQuery

leave a comment »

Last year I blog about using jQuery.ajaxForm() to send http post request to MonoRail action and finally it depend on JSGenerator to produce javascript and send it back to client.

But overtime I find it pretty scary using that approach:

  • It give too much control to the server – the server can generate a bunch of javascript and send off to the client sort of invade client responsibility.
  • In some scenario I even specify from the server which div element I want to render my data table in

  page.ReplaceHtml('#divId', "content_to_be_replace_from_server")
  • using approach in previous post I was not be able to ensure 100% that if I send piece of jquery script that it combine into the main DOM properly for instance I did have a form & a jQuery to confirm the form into ajaxForm but that behavior is not always reliable.

So what the deal now? well, I happen to change the strategy a while ago just haven’t got time to blog about it the solution is pretty simple “Don’t make JSGenerator your new hammer.”, Let see my simplify approach:


<div id='dlist'>
  <!-- I am going to render list of data in this div --></div>
<input type="button" value="Show data" onclick="showData();" />
<input type="button" value="Add more" onclick="addData();" />
<div id='dform' style='display: none;'>
  <!-- I am going to load form into this div --></div>

That pretty normal HTML markup right? 2 div one for display list of data second one for display form for adding more data and I also have 2 buttons to invoke client script (jQuery).


<script>
function showData(){
   $('#dlist').load( '/task/list.rails', {'status': 'incomplete'} );
}

function addData(){
   $('#dform').load( '/task/add.rails', {}, function(){
      $('#dform').show();
    });
}
</script>

Now that instead of using $.ajax I use $(’#elementId’).load() instead because load() will inject html render by MonoRail action in the DOM and it just as native element.

Note : line 07 dform had style apply so that without having form inside it don’t occupy space in the page however one content loaded we need to set visibility for it.

For your reference the final piece of the puzzle is purely view code like this (View\task\add.brail)


<form method='post' id='taskForm' action='/task/create.rail'>
  Name: <input type='text' name='t.Name' />
  <input type='submit' value='Create' />
</form>

<!-- not inject some jQuery script along make the form submit via ajax -->
<script>
   $(function(){
       $('#taskForm').ajaxForm ({
          success: function(response){
            $('#dlist').html(response);
          },
          error: function (xhr, status, error) {} // handle error if you wish
        });
   });
</script>

Notice on line #09 : need the form to submit using ajax and line #11 the client take control where it want to place the result (list of task).

It seem like we have to write a bit more code (jQuery) but after all that the fun part of being a programmer write code that :) Hope this would help.

Written by Chorn Sokun

March 26, 2009 at 9:13 pm

Posted in Castle, MonoRail, Tips & Tricks

Tagged with ,

MonoRail vs ASP.NET MVC Take #1 HTTP verbs

with 2 comments

Along came ASP.NET MVC although I am not the fan of ASP.NET MVC but it doens’t heard reading ASP.NET free chapter (nerddinner) and I did learn a few tricks, I will try my best to map concept between the two framework now let see

Why differentiate via HTTP verbs? read the book and find out, but here the deal

  • ASP.NET MVC [AcceptVerbs(HttpVerbs.Post)]
  • and [AccessibleThrough(Verb.Post)] in MonoRail

// GET: /Payroll/Delete/2
public void Delete([ARFetch("id"}] Payroll payroll){
   if (payroll == null)
   {
      RenderView("InvalidRequest");
   }
   else
   {
       PropertyBag["payroll"] = payroll;
       RenderView("DeleteConfirm");
   }
}

// POST: /Payroll/Delete/2
[AccessibleThrough(Verb.Post)]
public void Delete([ARFetch("id"}] Payroll payroll, bool confirm){
   if (payroll == null)
   {
      RenderView("InvalidRequest");
   }
   else
   {
      if(confirm){
     ..... // drop the record off the database
     ..... // do whatever you want.
      }
      else
      {
          RedirectToAction("Delete", "id"  + payroll.Id);
      }
   }
}

MonoRail Rock!

Written by Chorn Sokun

March 26, 2009 at 10:17 am

Posted in Castle, MonoRail, Tips & Tricks

Tagged with

Game? I’m suck! Help

with 9 comments

Last night while I went out to TnC for a reason I saw some friends Vannak & Ratha surprisingly they was having a good time in JXII world ;)

Talking about game when I was young (g! am I old) nah that time I was probably 12-15 years old and I love playing video game. My favorite was(is) “Street Fighter” but dear I hardly play those game anymore after my 2nd big brother punished me for always leaving home for game :( kids you know. Alright so what the deal? I moved my focus from game to computer and it end up with me being a computer programmer.

Suddenly in the late 2008 a friend who is a graphic designer Sambath persuaded me to play the game (JXII) well since I got a copy of the game during BarCamppp and consider the level of stress I had during working day I decided I should try something fun and there it started. But man, I may have been “’smarter” figure out how code work, but it seem like all the time when I try to be a gamer (computer game) I feel suck.

If you are my dear reader a JXer willing to help me becoming a better player please drop your suggestion base on the following spec:

Characters & skills Learnt

I am WuDang Sword sect, current lv 59, learn almost all available skill elements.
No school book went to HS a few times with deadly result :D even wounded.
Any tips, tricks … :) let play the game.

Written by Chorn Sokun

March 25, 2009 at 11:21 am

Posted in Geek, Socialize

4a friend in d’hospital

with one comment

Vithou this is for you man I hope you recovered and return home safely soon; we miss you and for the record bellow there is an award waiting for you well enough a drink and #$@ as usual ;)

for-a-friend-in-hospital

Ah! this app had Pheap’s finger print on it although he pretty young but he did a good job on this don’t worry you will not get suite for develop a lottery system :)) beware man.

Written by Chorn Sokun

March 19, 2009 at 3:14 pm

Posted in Castle, Geek, Joke, Rumor

Tagged with