Archive

Archive for the ‘Uncategorized’ Category

Paint War is released!!

December 22nd, 2011 Buu Nguyen 2 comments

This is the release month! After qTrace, another product I spent much mind and heart on for many months has just been released: Paint War, the super fun and addicted (shamelessly biased!) iPad game.  Visit Paint War’s website or iTunes App Store to learn more about Paint War.  And don’t forget to give it a try!

Paint War

PaintWar

PaintWar

PaintWar

PaintWar

On Becoming a Technical Lead

August 1st, 2011 Buu Nguyen 4 comments

Presentation I gave at the Success in IT Career event organized by KMS Technology last Saturday.

Categories: Uncategorized Tags: , , ,

ASP.NET jQuery Cookbook

May 9th, 2011 Buu Nguyen No comments

Another book of which I was the technical reviewer was published: ASP.NET jQuery Cookbook. Access to the link to find out more about the book.

aspnetjquerycookbook

Categories: Uncategorized Tags: , ,

Handle all uncaught exceptions thrown when using Task Parallel Library

May 4th, 2010 Buu Nguyen 2 comments

I’m using the TPL (Task Parallel Library) in .NET 4.0. I want to be able to centralize the handling logic of all unhandled exceptions by using the Thread.GetDomain().UnhandledException event. However, in my application, the event is never fired for threads started with TPL code, e.g. Task.Factory.StartNew(...). The event is indeed fired if I use something like new Thread(threadStart).Start().

This MSDN article suggests to use Task#Wait() to catch the AggregateException when working with TPL, but that is not I want because it is not “centralized” enough a mechanism.

I’ve posted the above issue (verbatim) in this StackOverflow question but didn’t receive any response. So, I had to roll out some custom code to do that. Below is the description of the solution for those who are interested.

The general idea is pretty simple. First, we need to know all the currently executed tasks. Since there’s no built-in way to know which tasks are being executed, we need to intercept the task addition. The class TaskFactoryWrapper below does just that.

static class TaskFactoryWrapper
{
    public static void Start(Action action)
    {
        var task = new Task(action);
        TaskErrorWatcher.Instance.AddTask(task);
        task.Start();
    }

    public static void Start(Action action, TaskCreationOptions options)
    {
        var task = new Task(action, options);
        TaskErrorWatcher.Instance.AddTask(task);
        task.Start();
    }
}

Inside the class TaskErrorWatcher, there’s a worker thread which periodically checks each task to see if the latter already finishes, is canceled or causes an error. If it causes an error, the worker thread trigger the error event.

class TaskErrorWatcher
{
    public delegate void TaskError(Task task, Exception error);
    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    private static readonly TaskErrorWatcher @Instance = new TaskErrorWatcher();

    public static TaskErrorWatcher Instance
    {
        get
        {
            return @Instance;
        }
    }

    private TaskErrorWatcher()
    {
        Task.Factory.StartNew(Monitor);
    }

    public event TaskError Error;

    public void InvokeError(Task task, Exception error)
    {
        TaskError handler = Error;
        if (handler != null) handler(task, error);
    }

    private readonly List<Task> tasks = new List<Task>();
    private readonly object syncLock = new object();

    public void AddTask(Task task)
    {
        lock (syncLock)
        {
            tasks.Add(task);
        }
    }

    private void Monitor()
    {
        Utils.Interval(3000, () =>
                                {
                                    lock (syncLock)
                                    {
                                        for (int i = tasks.Count - 1; i >= 0; i--)
                                        {
                                            var task = tasks[i];
                                            if (task.IsFaulted)
                                            {
                                                InvokeError(task, task.Exception);
                                            }
                                            if (task.IsCanceled || task.IsCompleted)
                                            {
                                                tasks.RemoveAt(i);
                                            }
                                        }
                                    }
                                },
                                ex => Log.Error(ex));
    }
}

Utils.Interval is simply a helper method which repeatedly executes an action when the specified interval has elapsed.

public static void Interval(long interval, Action action, Action<Exception> errorHandler = null)
{
    var watch = Stopwatch.StartNew();
    while (true)
    {
        try
        {
            action();
            watch.Stop();
            Thread.Sleep((int)Math.Max(0, interval - watch.ElapsedMilliseconds));
            watch.Restart();
        }
        catch (Exception ex)
        {
            if (errorHandler == null)
                throw;
            errorHandler(ex);
        }
    }
}

Now, in the top level code (e.g. inside Main()), just subscribe to the Error event of TaskErrorWatcher and do whatever you want to do in case of error, e.g.

TaskErrorWatcher.Instance.Error += (_, error) => HandleError(error);

That’s it. Hope it helps!

Speaking at Barcamp Saigon 2009

December 16th, 2009 Buu Nguyen 4 comments

I spoke at Barcamp Saigon 2009 last Sunday. It was a fun event. Met a number of interesting people and learned some new things from other sessions. I talked about the two open-source libraries I developed, Fasterflect & Combres. Below are the slides I used for my presentations.

Fasterflect – a fast and simple API for Reflection invocation

August 10th, 2009 Buu Nguyen 2 comments

If you think the built-in Reflection API in the .NET framework is too verbose for many circumstances and has poor performance, you are not alone. I think that too. And yet, being able to write reflective code is an inevitable (technical) requirement in most of the applications I develop. This is why I have built Fasterflect (read either “Faster-flect” or “Fast-reflect”) as an alternative API to the .NET Reflection functionality.

The goal of this library is to make Reflection calls as straightforward as possible while offering better performance than normal Reflection calls. In this article, I’ll describe the approach chosen to build Fasterflect, its APIs, and measure its performance via some benchmarks.

You can refer to this Code Project page for the guide to the library. For latest development code & binary, refer to the project page in CodePlex.

Updated 8/19/2009: Version 1.0 is released and can be downloaded from the CodePlex project page. This release supports ref/out parameters for methods/constructors/indexers and structs. Implementing support for struct has been quite challenging (and thus interesting) due to its data-copy parameter passing semantic and my design goal of sharing the API for both structs & classes (instead of creating a bunch of overloads for structs).

ASP.NET MVC Client-side Resource Combine

June 26th, 2009 Buu Nguyen 5 comments

ASP.NET MVC Client-side Resource Combine is another spin-off library from one of my current development projects. (The other is ASP.NET MVC Validation Library.) While the name is “resource combine”, this library actually does more than just combining client side resources including JavaScript and CSS. It allows you to organize resources into groups which will be combined, minified, compressed, and cached (at both client and server sides) together. While the library comes bundled with some routing and link utility to help developers easily integrate it into their ASP.NET MVC applications, there’s no reason why the library cannot be used with ASP.NET WebForms applications.

Refer to the project CodePlex page for detailed usage and binary/code download. The library uses the great YUI Compressor library for the minification part.

Hopes it helps!

Lost of posts & comments from 1/9/2009 to June/2009

June 26th, 2009 Buu Nguyen 2 comments

Upon writing a new blog post today, I recognized an shocking truth: the provider hosting my blog during their database migration had somehow cleaned up all of my blog’s posts and comments dated after 1/8/2009. Since I trusted my provider in their infrastructure, I did not do the backup job well myself so I did not have anything to repopulate the database.

Luckily, Google’s cache made it possible for me to retrieve the text and posted them again with an adjusted timestamp. As for the comments, since there were many of them and yet not all of them could be found in Google’s cache, I had to leave them for now. Therefore, you won’t see any comments dated from 1/9/2009 to around June 2009 (when the migration occurred). My sincere apologies to those comments are lost due to this incidence. I myself feel very very bad about it. I will work with the host provider in a last attempt to find way to recover the comments. If that doesn’t turn out right, I will find a new provider. And I will surely backup my blog frequently in the future.

Categories: Uncategorized Tags: ,

Junior developers beware, SOLID principles and design patterns are indeed useful for you

February 13th, 2009 Buu Nguyen No comments

I have several times disagreed with Jeff. They are just rare occasions though, given the amount of blog posts he wrote and I read (and agreed with). However, given his popularity as a blogger, any misleading advice may be highly destructive to junior software developers who may turn to his blog for advices. This time around, Jeff bashes guidelines, rules, and checklist with SOLID principles being one of the targets.

Now, young developers, before you start throwing away all the books about design patterns, agile, OO principles etc., let me tell you one thing: if Jeff Atwood is a better developer at all today, it’s because he has learned from the rules preached by more knowledgeable people. Don’t believe? Read this. There you go, Jeff Atwood as a fan of Code Complete, a 900-page book full of coding rules, was so much interested in the book that he even named his blog after one of the book’s symbol. He just seems to forget about where he came from when he wrote:

While I do believe every software development team should endeavor to follow the instructions on the paint can, there’s a limit to what you can fit on a paint can. It’s the most basic, most critical information you need to proceed and not make a giant mess of the process. As brief as the instructions on a paint can are, they do represent the upper limit of what most people will realistically read, comprehend, and derive immediate benefit from.

It’s normal for a very experienced developer to rely mostly on his judgment instead of a set of rules and principles to do thing. But it’s just uncool for such an experienced developer to advise the newbies to do the same thing, i.e. they’d better use their judgment first before resorting to the distilled and valuable knowledge taught by others.

…I’ve found less and less use for rules in my career. Not because I’m a self-made genius who plays by my own rules, mind you, but because I value the skills, experience, and judgment of my team far more than any static set of rules… Rules, guidelines, and principles are gems of distilled experience that should be studied and respected. But they’re never a substute for thinking critically about your work.

The thing is people are not born making good judgment. And one of the best ways to sharpen one’s judgment is to learn from the knowledge of those people who have made good judgment. Only after one has practiced these teachings long enough, making a lot of right and wrong decisions based on these teachings, one will for the first time, really understand about them and don’t have to think about them any longer as they have become part of one’s instinct. That should be the thing experienced developers teach junior developers, not this:

The types of developers who could benefit from SOLID a) aren’t thoughtful enough about their work to care and b) won’t read much of anything

Don’t get me wrong, I respect many of Jeff’s opinions, but I think he should feel more responsible for his influence on those developers who are new to the industry and seek for advices from his writings. Obviously no one man is perfect and Jeff, like any other, doesn’t necessarily always have great things to say. But at least he should acknowledge that he’s wrong when he’s wrong.

Appendum 2/14
On the contrary to what I think Jeff Atwood should do in the previous paragraph given the large amount of thoughtful comments from many of his readers, he seems to dig himself deeper into the hole with his follow-up post.

GUI Mockups Made Easy

December 8th, 2008 Buu Nguyen 1 comment

I have been using Visio a lot to design GUI mockups. Visio is a pretty powerful and flexible software except for a few drawbacks and most notably the mockups produced by Visio have the Windows XP looks-and-feel. This is fine if these are mockups for a Windows desktop application but pretty awkward for other types of applications. Lately, I came across a nice alternative called Balsamiq Mockups. Mockups produced by this tool are platform-neutral and thus can be used to sketch GUIs for virtually any kind of applications. Besides, the control-set provided out of the box include many controls that Visio doesn’t have like tag cloud, map, browser window etc. There are a couple of nice features like JIRA and Confluence integration, but the thing I find most notable about Balsamiq is its agility: one can be a lot more productive building most of their GUI mockups with Balsamiq than with Visio.

For example, if I want to sketch a grid populated with some existing data all I need to do is dragging the grid component out of the toolbar and fill in some CSV-formatted text. (Anyone experiencing drawing data-grids with Visio will know the process is not that straight-forward.) Or if I want to create a tag cloud, I just simply enter some words and Balsamiq will weight the words randomly and display them in a nice tag cloud picture. For more complex components like tree or menu, a wiki-like syntax is available to fill in the data and decorate the output (e.g. menu item separator, checked menu item etc.) This simple process of entering some plain text repeats for all kind of GUI components which need input data.

Although I am happy with what Balsamiq has to offer, I wish the software has features to allow users to draw arbitrary shapes and add custom images into the mockups. For now, users are limited to whatever GUI components and icon images provided out of the box. Regardless, I think these requirements not necessary for a majority of GUI mockups and for most of the rest I think I can resort to my modest photo-editing skills :-) .

Below is a sample mockup created with Balsamiq. See more here.

mockup

Categories: Uncategorized Tags: , ,