Chorn Sokun’s Weblog

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

Archive for the ‘Tips & Tricks’ Category

MonoRail, IRescueController Handle Unexpected Exception

with one comment

By default you can intercept unexpected exceptional error occur in MonoRail you can opt to render a specific view from Views/Rescues folder or let MR pick standard one such as 404 page not found …

How how about you want to log the exception then you need to build a custom controller class that implement IRescueController interface just like this:

public class RuntimeExceptionController : SmartDispatcherController, IRescueController
{
  public void Rescue(Exception exception, IController controller, IControllerContext controllerContext)
  {
    // ... log via log4net ...
    // ... render & send error back home :) whatever you find helpful
  }
}

// usage: simple
[Rescue(typeof(RuntimeExceptionController))]
public class HomeController: SmartDispatcherController{
  public void Index(){
     throw new Exception("Boom !");
  }
}

Written by Chorn Sokun

October 1, 2009 at 10:38 am

Khmer Localization with .NET

without comments

Localization in .NET doesn’t seem to solve a lot of problem in theory but I get no luck to get it work, although I built a custom Culture and having the resource file embedded in the assembly it just WON’T WORK !

After look around for solution I decided to give up and cheat a bit building localization engine from scratch is not too difficult but I tend not to spend my time on this yet.

So here is my way to have bilingual UI (Khmer & English)
resource

by faking treat fr-FR == km-KH and that work !

Never die with your tool, exercise your brain ;)

Written by Chorn Sokun

October 1, 2009 at 9:10 am

Rediscover WinForm, landing Alien base?

without comments

Simple scenario each time a province change, district, commune & village will reset, not a big deal for me now a day to have this scenario on the web application but hey look it WinForm :( let see

I started from Form Load event cbProvince combobox get binded then wire cbProvince with SelectedIndexChanged event handler to load list of district into cbDistrict combobox and so on the code look more or less like this


public void Form_Load(object sender, System.EventArgs e){
  // binding cbProvince
}

public void cbProvince_SelectedIndexChanged(object sender, EventArgs e){
  //... binding the cbDistrict ComboBox using current selected value from cbProvince
}

public void cbDistrict_SelectedIndexChanged(object sender, EventArgs e){
  //... binding the cbCommune ComboBox using current selected value from cbDistrict
}

Sound good all event wired hit F5 to try out. Guess what happen? it slow & AND finally throw an exception !!! but how? years passed and this behavior didn’t change a bit

// flag state
private bool formReady = false;
public void Form_Load(object sender, System.EventArgs e){
  // binding cbProvince
  formReady = true;
}

public void cbProvince_SelectedIndexChanged(object sender, EventArgs e){
  if(!formReady) return; // this is the trick don't fire the event
  formReady = false;
  //... binding the cbDistrict ComboBox using current selected value from cbProvince
  formReady = true;
}
public void cbDistrict_SelectedIndexChanged(object sender, EventArgs e){
  if(!formReady) return; // this is the trick don't fire the event
  formReady = false;
  //... binding the cbCommune ComboBox using current selected value from cbDistrict
  formReady = true;
}

Written by Chorn Sokun

September 29, 2009 at 10:50 pm

jQuery.selectboxes removeOption()

without comments

Base on the doc page located here http://www.texotela.co.uk/code/jquery/select/ if I wanted to remove (clear) items from a select box all I need to do is call:

$('#select_box').removeOption(/./);

But in my case I had a select box like this:

<select name="select_box" id="select_box">
    <option value="">N/A</option>
    <option value="1">Low</option>
    <option value="2">Meduim</option>
    <option value="3">High</option>
</select>

and of cause the syntax specified above doesn’t do the trick; this is how I fix it:

$('#select_box').removeOption(/(.?)/);

Was that how it should be done? oh ! by the way the shorter way

$('#select_box').empty();

Written by Chorn Sokun

July 28, 2009 at 3:58 pm

Posted in Tips & Tricks

Tagged with

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

Myth of Cambodia Geography Identification Code

with one 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

MonoRail & jQuery

without comments

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

Brail Daily Use Macros #2

with 2 comments

Imagine you had to associate multiple skill to your “Profile”

Multiple skill

Suppose we have the following Profile & Skill class

class Profile {
  public virtual int Id { get; set; }
  public virtual string Name { get; set; }
  //.... other properties as necessary
  public virtual IList<Skill> Skills { get;set; }
}

// a lookup class per say
class Skill {
  public virtual int Id { get;set; }
  public virtual Profile { get; set; }
  public virtual string Title { get; set; }
}

Assume that we know how to apply AR attribute on these two class make it persist able to a database. The important thing is Profile has many Skills that all you have to concentrate on right now.

Ok ! today recipe is to generate UI with checkbox which allow user to tick and save the choices without any hassle. With the help of FormHelper method YES, WE CAN

<%
list = Form.CreateCheckboxFieldList("p.Skills", skills, {@text:'Title', @value:'Id'})
// we need a loop
for item in list:
%>
  ${list.Item()}  ${item.ToString()}
<%
end
%>

Don’t panic let me explain a bit ${list.Item()} will generate individual html checkbox where ${item.ToString()} will generate a label for each one.

Written by Chorn Sokun

March 16, 2009 at 5:00 pm

Brail Daily Use Macros

with one comment

If you are DRY then try these macros in your *.brail

<% OutputSubView("_list") %>

Passing some variable to sub-view

<% OutputSubView("_list", {@students: studentList}) %>

but if you work with *.brailjs then you would love

Page.ReplaceHtml("#domElementId", {@Partial: '_list'})

Why do I choose brail?

  • it compile => performance gain
  • easy to create additional template processing macros
  • it just Boo !

until next time.

Written by Chorn Sokun

March 10, 2009 at 10:22 am

Posted in Castle, Tips & Tricks

Tagged with