Archive

Posts Tagged ‘c#’

Handle all uncaught exceptions thrown when using Task Parallel Library (take 2)

May 7th, 2010 Buu Nguyen No comments

A couple of days ago I posted a solution to handle all uncaught exceptions when using TPL. I’ve found a better way to do that, making use of task continuation. The class ThreadFactory below exposes the Error event which can be subscribed by a top-level handler and provides methods to start a task attached with proper continuation.

internal class ThreadFactory
{
    public delegate void TaskError(Task task, Exception error);

    public static readonly ThreadFactory Instance = new ThreadFactory();

    private ThreadFactory() {}

    public event TaskError Error;

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

    public void Start(Action action)
    {
        var task = new Task(action);
        Start(task);
    }

    public void Start(Action action, TaskCreationOptions options)
    {
        var task = new Task(action, options);
        Start(task);
    }

    private void Start(Task task)
    {
        task.ContinueWith(t => InvokeError(t, t.Exception.InnerException),
                            TaskContinuationOptions.OnlyOnFaulted |
                            TaskContinuationOptions.ExecuteSynchronously);
        task.Start();
    }
}
  • Share/Bookmark
Categories: .NET 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!

  • Share/Bookmark

Speaking at the Visual Studio.NET 2010 Launch in Hanoi

April 19th, 2010 Buu Nguyen 6 comments

Last Tuesday, I spoke at the Visual Studio.NET 2010 launch in Hanoi. It was a big launch with about 400 attendees. I hosted 2 sessions, one about ASP.NET 4.0 (including web forms, MVC, AJAX and dynamic data) and another about C# 4.0 and PLINQ. On the following day, I spoke at Microsoft Vietnam’s office about building scalable .NET web applications to about 40 .NET architects and developers in Hanoi.

In general, it was a great trip to Hanoi and I had a lot of fun speaking and meeting many people there. The sessions by other speakers were really great. I was particular impressed with what Silverlight 4.0 and SharePoint 2010 had to offer.

You can find the slides and sample code I used for these sessions below.

Sample code can be downloaded here

Some pictures taken (click to view larger images)

VS.NET 2010 Launch Event

Tea Break during the VS.NET 2010 Launch

.NET Web Scalability Presentation at Microsoft Vietnam's Office

Tea Break during the Scalability Presentation

  • Share/Bookmark

Fasterflect 2.0 Release

March 21st, 2010 Buu Nguyen 4 comments

I am pleased to announce the release of Fasterflect 2.0. For those who are not aware of Fasterflect, it is a library that helps you get rid of the complexity and slow performance of .NET Reflection. Check out this Code Project article and a previous announcement for an introduction.

Fasterflect 2.0 comes with a great number of additions & changes, which are possible thanks to the fact that I am no longer the only developer of this project; instead, Morten Mertner (author of Gentle.NET) has joined me since the beginning of 2.0 and made huge contribution ever since. Let’s look at some highlights of this release.

The most exciting addition in this release is that Fasterflect now includes a Query API. Previously you can only use Fasterflect to construct objects or performs invocations (these 2 usages are now referred as Access API). With this release, you can query .NET reflection metadata with Fasterflect although much simpler than what you have to do with the built-in .NET reflection. You can even do more thing with this Query API than you can with .NET reflection out of the box. For example, you can choose to exclude backing members from a lookup or enable partial-name lookup. All you need to do in order to have these level of control is specifying a proper Fasterflect binding flag. The nice thing about Fasterflect binding flag is that it is also fully supported in the Access API.

Next, the Access API is now fully integrated with .NET reflection metadata classes, such as ConstructorInfo, MethodInfo, FieldInfo etc. This integration makes it able for you to mix & match the usages of Query API and Access API as well as allows you to use .NET reflection as it is while delegating the invocation to the fast CIL-generation engine of Fasterflect.

We have also built on top of the core Fasterflect engine some add-on services such as advanced object construction, deep cloning and object mapping. We expect to have more of these services in future releases and of course, you can send us your contributions too.

Users of previous versions of Fasterflect should be aware of the following breaking changes.

  • Many existing extension methods have their names changed as we went through the process of improving API’s consistency & usability. We hope these changes are for the better because now we have 2 developers vote on the conventions instead of 1 like previously :-) . You would have to make some code change when switching from 1.1 to 2.0, but the changes should be very straight-forward in most cases except for the other changes described below.
  • Fasterflect extension methods now don’t require a type parameter, which we have found to be inconvenient because people are forced to append <object> to the call even when they don’t care about the return value or its type. These methods now simply return result of type System.Object and you can cast to the correct type if you need to.
  • Batch fields/properties setting are gone. They are replaced by the object mapping add-on service which is more flexible, sophisticated and faster (CIL code generation is used behind the scene). Batch setting of static members is not supposed though because we think it’s not a common scenario. That said, do let us know if you have this need and we will add support for it in the next minor release.
  • The class Reflector and its methods are now gone. We instead employ a custom-built weak reference-based cache to assure that generated CIL can be garbage-collected when memory is low.

Last but not least, the project wiki on CodePlex is fully populated with comprehensive documentation. While Fasterflect is still ridiculously easy to use, it now has a much bigger API and is more sophisticated than it used to be (e.g. with Fasterflect binding flags). Therefore, documentation should be of great help for those who want to understand everything about Fasterflect to use it effectively in even advanced scenarios without having to dig through the source code.

You can download the binary, source code and CHM API help file in the Fasterflect 2.0 release page in CodePlex. If you want to explore Fasterflect in details, surf through the project wiki. If you just want to jump right into the usages without any further introduction, check out the 2-minute-guide to Access API and this page about the Query API. Finally, the comprehensive unit test suite included in the code download can also serve as good reference for the API.

  • Share/Bookmark

Fasterflect vs. C# 4.0 Dynamic

December 31st, 2009 Buu Nguyen 4 comments

As .NET 4.0 final release will hit the market pretty soon, it’s worth discussing the value of Fasterflect in the face of C# 4.0’s dynamic keyword.  (If you aren’t familiar with C# 4.0 dynamic, you should read my article on C# 4.0 before continuing.)

To recall, Fasterflect was designed to address 2 key disadvantages of .NET Reflection: ease of use and performance.  As seen in my article about C# 4.0, the dynamic keyword nicely addresses the easy of use with a resulting syntax looking even nicer than Fasterflect.  How about performance?

I improved the benchmark application of Fasterflect to add some benchmark code comparing between the performance of C# 4.0 dynamic and Fasterflect.  Here is result of method invocation benchmark.

fasterflectbenchmark

While performing slower than Fasterflect’s cached API, C# dynamic performs much better than Fasterflect’s standard API.  (Not surprisingly, the C# dynamic binding doesn’t resort to the slow reflection mechanism internally.)

With this awareness in mind, together with the understanding about the features of C# dynamic and Fasterflect, let’s discuss about areas where Fasterflect shines even in the face of C# 4.0 dynamic:

  • C# dynamic doesn’t handle invocations performed based on dynamic information (i.e. field name read from XML file).
  • C# dynamic does handle certain types of dynamic invocations, including static method invocation, static property invocation and constructor invocation.
  • C# dynamic doesn’t handle non-public members.  So you’ll receive exception if trying to, say, invoke a private method.
  • When performance is more critical than readability then the Fasterflect’s cached API might be favored over C# dynamic.

Granted, there should be workarounds for the first 3 items.  For example, if you want to invoke static method dynamically with C# dynamic, you would have to workaround like the approach described in this article.  However, the approach uses reflection behind the scene so you would have the same performance issue to start with.

This doesn’t say that Fasterflect is better than C# dynamic though.  While both share a couple of features and maybe used interchangeably in some scenarios, they also have different problems of their own to address.  There are many things that you can do with C# dynamic that you couldn’t do with Fasterflect, e.g. implementing an interceptor to dynamically handle all method invocations (or missing methods) etc.  So, pick the right tool for your problem at hand.

  • Share/Bookmark
Categories: .NET Tags: , , , ,

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.

  • Share/Bookmark

ASP.NET MVC Validation Library

February 10th, 2009 Buu Nguyen 5 comments

Inspired by the work of Emad Ibrahim, I set out to develop a validation library for ASP.NET MVC. Besides trying to meet the same objectives as Emad Ibrahim’s library, i.e. model-based validation, integration with the jQuery validation plugin, and little or no duplication between client-side and server-side validation, these are the differences of my library:

  • Built for MS Validation Application Block. (Emad Ibrahim’s library targets Castle’s validation framework. Check out his library if you need this feature.)
  • Allow users to specify the properties to be included in a server-side validation. This is useful in situation in which you use part of the model in some pages (e.g. Change Password page only uses the Password field of the User entity).
  • Allow users to tell the client-side code generator to generate script to ignore missing DOM elements. This feature goes nicely with the above feature. The generator could have been implemented to receive a list of properties to generate client script for but I have not made up my mind yet whether this is a better approach or not.
  • Allow users to specify whether they want the validation initialization code to be generated or not. This is particular useful if you want to customize the validation initialization code differently for different pages.

How does it work?
The idea of the library is that one should be able to decorate an entity object with some validation attributes and then have that entity validated at both the server-side and client-side with the minimum amount of code. Let’s say you have a User entity in your application, you can annotate it as follows:

public class User
{
     [NotNullOrEmptyValidator(MessageTemplate = "Name is required")]
     [StringLengthValidator(6, 20, MessageTemplate = "Name must be between {3} and {5}")]
     public string Name { get; set; }

     [NotNullOrEmptyValidator(MessageTemplate = "Email is required")]
     [EmailValidator(MessageTemplate = "Invalid email address")]
     public string Email { get; set; }

     [NotNullOrEmptyValidator(MessageTemplate = "Location is required")]
     public string Location { get; set; }

     [NotNullOrEmptyValidator(MessageTemplate = "Password is required")]
     [StringLengthValidator(6, 50, MessageTemplate = "Password must be between {3} and {5}")]
     public string Password { get; set; }
}

Now, whenever this entity is populated with form posted values, you can perform server-side validation by invoking the Validate() extension method on the entity. Let’s do that in the action method.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditUser([Bind(Prefix="")]User user)
{
     try
     {
          user.Validate<User>();
     }
     catch (EntityValidationException ex)
     {
          ViewData.ModelState.PopulateWithErrors(ex);
     }
     return View();
}

The above code will perform validation on the entity given its validation attributes. If there’s any validation error, an EntityValidationException object is thrown and you can use it the populate the model state with error messages. The method PopulateWithErrors is another extension method provided by the library.

If you want to limit the properties to be validated (e.g. in a password change scenario), you can pass an array of property names into the Validate() method.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChangePassword([Bind(Prefix="")]User user)
{
     try
     {
          // Only validate the password property
          user.Validate<User>(new[] {"password"});
     }
     catch (EntityValidationException ex)
     {
          ViewData.ModelState.PopulateWithErrors(ex);
     }
     return View();
}

I could have added a custom model binder to the library so that validation happens at the model binding phase but I think that’s not a flexible approach since in many cases we would want to perform validation in the service layer instead so that the validation takes place consistently for any client of the service.

Let’s see the result of the server-side validation:

Okay, let’s move to client-side validation. The trick behind the client-side validation is that the view will invokes the HtmlHelper’s ClientSideValidation() extension method which will retrieve all validation attributes of the specified entity type (e.g. User) and generate equivalent client-side validation script for them.

Currently, while you can apply as many validation attributes to an entity as you like and the server-side validation will work perfectly fine, only a couple of validation rules are supported by the client-side code generator, namely required field validation, string length validation, and email validation. These3 rules are sufficient for my current need and I will add more on a needed basis (or you can download the code and implement more rules yourself.)

There are a couple of overloads of the ClientSideValidation() method:

// Generates validation script for the User type
Html.ClientSideValidation<User>();

// Generates validation script for the User type, including the code to initialize form validation
Html.ClientSideValidation<User>(string formName);

// Generates validation script for the User type and adds necessary code to avoid JavaScript error if one or
// more properties in the User type do not match with any DOM element.
Html.ClientSideValidation<User>(bool ignoreMissingElements);

// See the above 2 overloads
Html.ClientSideValidation<User>(string formName, bool ignoreMissingElements);

For example, the generated code for an invocation of the second overload will result in the following code:

<script language="JavaScript"><!--
$().ready(function() {

$("#edit-user-form").validate();
$("#name").rules("add", {
	minlength : "6", maxlength : "20",
	required : true,
	messages: {
		minlength : "Name must be between 6 and 20", maxlength : "Name must be between 6 and 20",
		required : "Name is required"

	}
});

$("#email").rules("add", {
	required : true,
	email : true,
	messages: {
		required : "Email is required",
		email : "Invalid email address"
	}
});

$("#location").rules("add", {
	required : true,
	messages: {
		required : "Location is required"

	}
});

$("#password").rules("add", {
	minlength : "6", maxlength : "50",
	required : true,
	messages: {
		minlength : "Password must be between 6 and 50", maxlength : "Password must be between 6 and 50",
		required : "Password is required"
	}
});

});
--></script>

That’s it, you don’t need to write a single line of JavaScript to have this nice client-side validation:

How can I download and use it?
The library is hosted at CodePlex. I have built it with ASP.NET MVC Beta, Enterprise Library 4.1, jQuery 1.2, and jQuery validation plug-in 1.5. You might need to make a couple of changes if you want it to work with a different version of those libraries. Any bug, please post on the project page instead of posting here. Thanks & hope you’ll find the library useful.

  • Share/Bookmark

Overview of C# 4.0

November 13th, 2008 Buu Nguyen 7 comments

Note: This article is also posted at The Code Project. Refer to this link. There are quite interesting discussions going on there.

The .NET framework 4.0 CTP has just been released and I think it’s a good time to explore the new features of C# 4.0. In this post, I will introduce about the following features: dynamic lookup, generics covariance and contravariance support, optional and named parameters.
Read more…

  • Share/Bookmark

Steve Yegge on the Next Big Language

February 13th, 2007 Buu Nguyen No comments

What Steve Yegge considers the Next Big Language.  Sound like

  • Ruby + (Java || C# 1.x/2.0)
  • (JRuby || Groovy || Ruby.NET) + good_tools (esp. IDE)
  • C# 3.0 && dynamic_typing (not just type inference) && more_syntactic_sugar (return multiple values, object-literal syntax for hashmap etc.)
  • Share/Bookmark