Chorn Sokun’s Weblog

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

Archive for the ‘Programming’ Category

Storm the Castle in Action

without comments

felt bore today and decided to tune into studio and record some stuff :D hope you enjoy it.

I know, I know the quality is bad but I don’t know I am not do much with youtube so it the luck I get :) BUT as always orginal video can be download here.

Source code: http://storm-the-castle.googlecode.com/svn/tags/barcamppp

Written by Chorn Sokun

October 23, 2009 at 5:50 pm

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

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

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

Storm The Castle

with one comment

I hope Ayende won’t mind if I steal the name :D well, he did used that name for one of his sample project. Anyway let me throw some good news out to all of my blog trackers “who loves coding :D” I just check-in a sample project using Castle minutes ago.

As I am not sure how many of you understand what I am blogging about or even had trouble try to replicate my trip. Now I make it simpler if you want to catch-up or debate with me on my future Castle posts you got a chance to start it  now just go grab a stick and stone from http://code.google.com/p/storm-the-castle/

If you have any question/suggestion/request you can post it on the project site I am happy to help it out as time allow ;)

Oh by the way this is my 100 posts :))

Happy Chinese New Year everyone.

Written by Chorn Sokun

January 24, 2009 at 11:59 am

AR, Wrap-up

with 7 comments

Castle ActiveRecord (AR) – is a .NET implementation of ActiveRecord pattern. The ActiveRecord pattern consists on instance methods and properties representing rows in the database, and static methods acting on all rows.

Knew how AR is capable of and read through available document I say it far more effort need to put on making the features more accessible; but still it present form (document) are just good enough to attract new comer with some basic scenario. Saying all thses mean I am not gonna repeat what is already there. What I am trying to do now is to give you a quick overview on what AR can do for you and why you should love it.

How to setup an AR class?

  1. Setting class attributes: [ActiveRecord] on class, at less on [PrimaryKey] attribute apply on class property and the rest simply [Property]
  2. Derive your class from one of these AR base classes: ActiveRecordBase<T>, ActiveRecordValidationBase<T>

Notice that non generic version is also available but I simply ignore it, or pretend it doesn’t exist :P

How to perform Create, Read, Update & Delete with AR?

Alright, depend on how your PrimaryKeyType is configured you may or may not call instance.Save() method. However once you set value for all required properties you can call instance.Create(). To read/retrieve data back you can call a static method of the class ARClass.Get(id) which will return an instance of ARClass. Once you got an instance you can make change to the properties value and then call instance.Update() to persist the change; or you can call instance.Delete() to delete the record off your table.

** Note that you might need to call SessionScope.Flush() in some scenario, but again it depend on how your session was configure as well.

How to filtering result?

Beyond basic data retrieval via static method such as Find, FindAll, FindOne. AR came with a varieties of query API namely

  • SimpleQuery<T>
  • ScalarQuery<T>
  • CountQuery
  • ScalarProjectionQuery<ARType, TResult>
  • ProjectionQuery<ARType>
  • ProjectionQuery<ARType, TResultItem>
  • or you can say NHibernate is the limited

These API are very handing when it comes to extracting data for reporting purposes. Last but not least, MultiCriteria is your best train for moving data back & forth between AppDomain to DBMS.

Conclusion

With such a great tool available off the shelf it shame for Microsoft not acquiring this stuff or even promote it but keep invest their money on new tool set which happen fail time & time again; but that is a political issue which I am not in a position to discuss :D How about you? what are your favorite AR query APIs?

 

Written by Chorn Sokun

November 4, 2008 at 8:10 am

Surprise !

with 5 comments

It amazes to see how people taking their value time and energy try to make the different, somehow I was not expected this phenomenon to growth that much in Cambodia but the truth is Cambodian make a different.

Ladies & Gentlemen, Boys & Girls watch out !

Programming Localization

Syntax Localization

At the movement of posting I am not clear who behind this project… but, you guy made something that turn my morning into

Congratulation! now let open our discussion will this thing change Cambodian development climate what are your pros & cons?

Written by Chorn Sokun

October 11, 2008 at 9:35 am

Raising the Dark Army

with 5 comments

I never regret to step my feet into programming world back in 1997. My first experience using notepad to script out (HTML) website. I don’t remember how many times I skew up my brother’s computer just to figure out a thing no matter how hard he try to avoid me. 

Rewind for the last 10 years I keep pushing myself up step by step no matter how hard, stressful I got I never give up. 10 years? Yeah I know my brain deserved a major upgrade perhap replacement of RAM, CPU Squad Core or something :) But see it took me so long to get to this stage where I legendary programmers abroad take much shorter time to advance their skills.

You may compare my learning experience to a single pig raising in a big farm, the lack of physical interaction, challenge and guiding is the main source preventing it from fast growth. But that are all history today I am so happy, because I am no fall into those mind set and I am not alone, ladies & gentlemen the dark army is rising. 

Dark Army

Dark Army, taking on TDD & DDD

This is the 5th session that they all come together and learn .NET programming C# and I glad to become their instructor as much as I enjoy walking them through the learning curve. Although it is a programming course we don’t talk much about syntax sugar or debate about how it was designed because it doesn’t give much value in real world once it’s time to get down to business so what they need to learn are concepts and tool set for rapid application development.

I want to see some new face as well but it doesn’t seem to work out just yet :) but again we please to invite you to join our journey anytime just keep you eyes on our public calendar.

Let the spirit of sharing growth among Cambodian, let us all create an opportunity for our young generation to extend what we had discovered.

Written by Chorn Sokun

September 27, 2008 at 10:34 pm