Combres – WebForm & MVC Client-side Resource Combine Library

November 4th, 2009 Buu Nguyen No comments

Combres (i.e. Combine-Resources), is a very easy-to-use library which can be used to automate many steps that you would have to do yourself when applying many performance optimization techniques in your MVC and Web Form ASP.NET applications. This library is formerly known as ASP.NET MVC Client-side Resource Combine Library until I decided to retire that boring and lengthy name. Combres is also a major upgraded over the previous version. In a nutshell, the following features are supported by Combres:

  • Organize resource files, including JavaScript and CSS, into separate resource sets, each may share the same or use different configuration settings.
    • ConfigConfiguration settings are specified in an XML file which is monitored by Combres so that changes get noticed and applied immediately.
    • Resource files can be static files in the web server, dynamically generated files, or remote files from external servers or web applications.
  • Allow files in resource sets to be combined, minified, and gzipped before sending to browser. All is done using 1 single HTTP request per resource set. (Refer to Yslow’s performance rules #1, #4 and #10 to know why this is useful.)
    • The minification part is performed by the great YUI Compressor library.
  • Generate proper ETag and Expires/Cache-Control headers for every response as well as support server-side caching. (Refer to Yslow’s performance rules #3 and #13 to know why this is useful.)
  • Integrated with ASP.NET routing engine and thus work equally well for both ASP.NET MVC and ASP.NET WebForm applications.
  • Support Debugging mode, which won’t cache or minify contents at all to facilitate debugging.
  • Extensibility via the filtering architecture. Anyone can easily add more functionality to the Combres engine by writing a custom filter. There are 2 built-in filters in the 1.0 beta release, which I will describe in this article.

I wrote about how to use and enhance this library in this Code Project article.

You can also get the binary, source code and sample from these links:

  • Share/Bookmark

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).

  • Share/Bookmark

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!

  • Share/Bookmark

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

June 26th, 2009 Buu Nguyen 1 comment

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.

  • Share/Bookmark
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.

  • 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

Common developers CV’s mistakes

January 21st, 2009 Buu Nguyen 2 comments

Being responsible for hiring developers in almost every position I landed, I’ve screened probably a few hundreds of developers CVs through out my career. Following is the list of mistakes I often found in CVs.

  • First and most common mistakes: the CV lists too many skills. In fact, I’ve seen many CVs with roughly a dozen lines mentioning about many dozens of technologies and tools. In many cases as the on-site interviews revealed, these developers just possessed superficial or absolutely no knowledge about the things they listed. One can only go so far (to the on-site interview) being untruthful. On the other hand, even if these developers really know about these things, among the too many things they list, I can hardly find the ones that should really stand out (i.e. the things that the candidates have expertise in.) Now, there are those of you who really have extensive set of skills under your belt and want to list them all, it’s still better if you can highlight the top skills that you master so that they can stand out from the rest. Most of the time, employers don’t care about the skills you are not really good at. Think about it, would I hire a top .NET developer to write Java code just because the guy happens to know a bit about Java?
  • Some candidates describe what they were supposed to do instead of what they actually did in their previous positions. If one implemented the security module of a software using Spring Security or used Struts 2.0 to implement a web module of another software then I would want to know about that. On the other hand, I don’t want to read a some general job description stating the obvious and of little interest (to me) such as “designed and implemented the application”, “worked with QA to resolve defects”, and “participated in code review” etc. (Guess what, if you’re not doing these things, you are not developers.) On the other hand, some candidates went so far quoting text from the job description while they have not actually carried out such responsibilities and that has resulted in quite a couple of embarrassing on-site interviews. Be very specific about the things that you did is the key to avoid this mistake.
  • Mention too much about the clients and products. As a matter of fact, I’ve seen some CVs in which every project is accompanied with a lengthy paragraph describing the product and its client. Much of this information is pulled out of the marketing information provided in the client’s or product’s website. Keep this in mind: most employers don’t care about the vision of your client organization and the greatness of the product. For the software that you built, only 2 things should be mentioned in the CV: what problem the software solves and what technologies it is built with. Anything other than that is noise and should go away. For the client, the name and a link to their website are more than enough. For the really rare case that I want to learn more about the client, I will find more information through the provided link (or Google, for heaven’s sake).
  • Some CVs mention too trivial projects. Don’t get me wrong, it’s good to demonstrate how much passionate you are about this software engineering by listing things like, say, personal projects but there’s no point mentioning some trivial toy or university projects in your CVs. Think about it, how much value the employer gains knowing that a developer can code a Tic Tac Toe game or a shopping cart? Absolutely nothing unless you expect us to say to ourselves “Look, that guy is really cool – he can code Tic Tac Toe.” Save the space for more valuable things instead. If there’s no such thing, better save us some reading time by removing them from the CV.
  • Spelling and grammar mistakes in CVs. I am constantly surprised that many developers don’t even care to do a quick check to make sure no grammatical and spelling mistakes in their CVs. After all, it only takes a few minutes for this check to be done with any word processing software. Without doing this, one risks leaving a bad impression to the recruiter; the impression that the author of this CV is either lazy, doesn’t care about getting the job, about doing the right things, or about going the last mile to get the work done. That might be a harsh conclusion one can come up with given just a few spelling mistakes, but given the sheer amount of CVs recruiters have to screen for any particular position, they are not supposed to be very patient and tolerant of poorly written ones.
  • A bonus tip: don’t be afraid to list your certifications if you have any. This is actually not a common mistake, but since there is a rising number of people who suggest that developers should not include certifications in their CVs, I think it’s worth setting an alarm. Anyone who have under their belt a few certifications know that it’s not the papers themselves that have a lot of value but the actual studying process that one usually gets through to get those papers is valuable. Plus, if one spends the time that would otherwise be spent on vacation or gaming to study and achieve some certifications relevant to her work, it means that she cares, if is not passionate, about her job. And that is never a bad thing. Finally, with all things being equal, some companies would prefer to hire developers with one or more certifications than others because that would help with the partnership process with vendors like, say, Microsoft (like it or not, there are obvious benefits to become partner of the big vendors).

That’s it, the top CV mistakes. Am I missing anything?

  • Share/Bookmark

The impassionate and NNPPs are not that destructive

January 8th, 2009 Buu Nguyen No comments

I’ve just read two interesting blog posts this week, Jeff Atwood’s Programming Love It or Leave It and Jay Fields’ The Cost of Net Negative Producing Programmers. Jeff Atwood basically thinks that people who don’t have passion for programming should not go into the field while Jay Fields thinks that poor programmers add significant cost to any project and should not be in the industry as well. If I were to read these a year ago, I would have wholeheartedly agreed with them. After all, I too had to maintain the very poor code written by incompetent programmers and couldn’t help but wishing they were never programmers in the first place. And I had strong opinion in passion being one of the top criteria for hiring programmers and felt bad about those who are not passionate enough to spend extra time learning stuff beyond the work at hand. But a year working exclusively in a managerial role has changed my view on that quite a lot. Don’t get me wrong, I still think passion and talent are important attributes of developers, it’s just that they are much less important than what I used to believe.

Indeed, when you are in a position to receive projects from clients and responsible for hiring people to accomplish those projects, you’ll quickly realize one thing: there are just not enough talented or passionate developers, much less those who are both passionate and talented. Truth be told, I was extremely selective in my hiring to the extent that I was infamously known among the HR department as a “candidate eliminator”. And yet, I think less than 5% of those I selected into onsite interview met both criteria. That said, if I had rigidly maintained my rules of placing passion and talent before any other, I would never have found enough people for all the projects. In such situation, there are 2 things one can do: give up and reject the client projects for not being able to find enough members to staff in, or staff the best you can and find ways of accomplishing the projects. Now, nobody in his or her right mind would go with the first option.

After spending more than a year working with impassionate and not talented people, I have come to realize that a team which has such developers can still deliver good result. Now, among those people, I have yet to find a person who is passionate but has poor programming skills, but the remaining categories (impassionate but talented and impassionate and not talented) turned out to add value to the team in one way or another. Specifically, I realized that impassionate developer can still be good developers. These developers would rather go home early and spend time taking care of their family or pursuing their real passions. They never write any blog or participate in any open source projects nor do they have any plan to do so. And they only learn things as they are needed instead of browsing through latest books and blogs to learn about the trendy things. But when they do something, they do it with utmost attention and most importantly, they write good code. That should not be a surprise. You just need to realize that good developers are, well, good developers regardless of whether they spent 8 or 16 hours per day programming. (Although the one spending more time may learn more.) As a matter of fact, two developers in one of the projects I worked on were not passionate about software development at all. They just realize that programming is something they are good at, so they do it to get the money to spend on the things they really love. One guy’s passion is photography, but he is smart enough to know that he can’t make as much money being a photographer. He loves it, but he simply has no talent for it.

I’ve been talking about good developers who are not passionate. How about those who are both impassionate and have bad programming skills? I worked with them too, and I have to say: such people are NNPPs mostly because they are mismanaged. A good manager will recognize the strengths and weaknesses of their members to put them into the right position. Before you laugh at the idea, think about all the work that need to be done for the projects to be successful. Are you sure that all of such work require really smart developers to do? Do you need good developers to maintain the project’s build scripts? Or setup a build system? Or evaluate a tool? How about writing project documentations? Or migrate one source control system to another? Simple bugs of well understood components (or even more complex bugs but have the new code reviewed by good developers, but that’s another story)? The point is, in just about any software development project, there are always some work which smart and passionate people hesitate to do (and may not do it well if they have to do it) but enthusiastically accepted by others. Let the latter do such work, they are neither passionate nor smart but they work for the pay in order to do things they really love. Therefore, they are willing to do so and even feel happy for not being asked to do more than what they are capable of doing. And you, the passionate and smart developer, can be happy too. The right-person-for-the-right-job is the name of the game.

Having said all these, sometimes some people just don’t fit to your project, then you have to let them go. But the point remains the same, things would be much easier if we can find all the top guns and put them into the team. But we simply can’t. Sometimes, we have to live with what we get and do the best about it. Just face it. And happy programming.

  • Share/Bookmark

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

  • Share/Bookmark
Categories: Uncategorized Tags: , ,

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