Sergio and the sigil

JavaScript and its love for zeroes

Posted by Sergio on 2009-09-19
This post is part of a series called JavaScript Demystified.

Answer quick. Do you know what date is being created here?

var year = '2009', month = '09', day = '01';
var date = new Date( 
             parseInt(year),
			 parseInt(month),
			 parseInt(day)
			 );	

At first glance, it wouldn't surprising that someone guesseed September 1st 2009. However, I'd not be writing this post if that was the correct answer, right?

There's an interesting and tricky thing with the JavaScript parseInt function: it can parse strings with a numeric value in the decimal radix, but also in other radices. See the following examples.

//passing the radix explicitly
parseInt('1011', 10); // ==> 1011
parseInt('1011',  2); // ==> 11
parseInt('1011',  8); // ==> 521
parseInt('1011', 16); // ==> 4113

Maybe you thought that if you didn't pass the radix, then it would default to 10 because it's the obvious behavior. Well, no. In JavaScript the default behavior is to try to identify one of the literal formats and interpret that. So here's that in action:

//leaving JavaScript on its own
parseInt('1011'); // ==> 1011 (decimal literal)
parseInt('0x12'); // ==> 18   (hexadecimal literal)
parseInt('0511'); // ==> 329  (octal literal)
parseInt('0182'); // ==> 1    (whaaaa?!?!)

If you are familiar with the literal notation for integer numbers in JavaScript, and after I explained the default behavior of parseInt, then you probaly understood the results shown above. Well, maybe the last one deserves some comments.

When JavaScript is parsing the string, if it finds a digit (number or alpha) that is invalid in the chosen radix, it stops right there and parses only the portion of the string that comes before that digit. So, since we started '0182' with a leading zero, the octal radix is assumed. Then, because 8 is not a valid octal digit, only '01' will be parsed, which becomes 1.

Tip #1: If there's any chance the string value you plan to parse into an integer number has a leading zero (or a less likely 0x,) then be safe and pass the radix parameter to your parseInt call. If you're extra paranoid, then always pass the radix.

Back to our original question

Armed with the clarification made above, we can expand our example like this:

//given:
var year = '2009', month = '09', day = '01';
// then the following statement:
var date = new Date( 
         parseInt(year),
         parseInt(month),
         parseInt(day)
         );	
//...is equivalent to:
var date = new Date( 
         2009,
         0,  // ===> oopsie
         1
         );	

Hmmm, a zero in the month parameter. Will we have an error here? No, here comes the second potential surprise of this post.

Tip #2: When creating a new date using new Date(year, month, day), the month parameter, and only the month parameter is zero-based (0 to 11).

So, in case the tips and the picture in this text were not enough to help you guessing the date being created, here goes another completely gratuitous one with the answer.

Mozilla Add-Ons in Chicago

Posted by Sergio on 2009-09-17

Later this month I'll be attending the Mozilla Add-Ons Meetup in Chicago.

I'm continually impressed with the extensibility of Mozilla applications and the amazing things people are doing with it. I'm interested in both the extensibility model and in writing a few custom extensions myself, even if it's just for my own use. Given that it's mostly XML and JavaScript, it should be right up my alley.

After seeing a presentation about building Firefox extensions earlier this year I decided I had to look into that more seriously.

So if you're in the area and wants to see what this is all about, this meetup might be a good way to get some info to get going.

It's Generic, not Multipurpose

Posted by Sergio on 2009-09-09

There's something that has been bothering me with many .Net APIs that are Generics-based (or that at least try to be.) I might be totally off or just nitpicking but I could not find any reference agreeing or disagreeing with the opinion I'm about to give.

Generic parameters are not data

Well, that pretty much summarizes what I think and I could stop right here. On the other hand, doing that would make for a pretty lousy blog post. Let's elaborate on that statement a little more.

The way I like to see the generic parameters in a function declaration (those that go inside the < and >) is akin to modifiers. They modify the function's data parameters (the normal parameters) and/or return value's data type.

Here are some examples, loosely based on some APIs you may be familiar with but changed to avoid singling out anyone. Some of the examples are really popular.

The typeof hater

Take a look at this generic function call.

cachedData.DeleteAllInstances<Book>();
// or even
cachedData.DeleteAllInstancesOf<Book>();

I could almost bet that the generic methods above only use the Book generic parameter in a statement like typeof(T). So what they really need is the Type object not the type identifier, and that's exactly what the following non-generic version asks for.

cachedData.DeleteAllInstances( typeof(Book) );

The Stringophobic

It always feels weird when I find something like this:

var list = container.FindInterfacesInNamespace<IOneOfThose>();
// or even
var list = container.FindInterfacesInNamespaceOfType<IOneOfThose>();

That function call feels like someone is desperately trying to avoid passing the namespace string as a data parameter, possibly thinking that could hurt automated refactoring. I'd just go with this:

string interfacesNamespace = typeof(IOneOfThose).Namespace;
var list = container.FindInterfacesInNamespace(interfacesNamespace);

The thumb buster

Sometimes I think API designers are just trying too hard to use generics. I mean, if there's a way to get the data they need by way of a type identifier, no matter how unnatural that be, a generic function will be born. Paraphrasing what someone already said: When a new language feature is your hammer, everything starts to look like your thumb.

var list = container.
    FindAllImplementationsOfTypeAinTheAssemblyOfTypeB<IDoStuff, ConcreteDoer>();

You see, the first generic parameter in this example is fine (assuming the function returns something like IEnumerable<IDoStuff> ). The problem is the second one. If all you really need is an Assembly object, just ask for it, I'd say.

var asm = typeof(ConcreteDoer).Assembly;
var list = container.FindAllImplementationsInAssembly<IDoStuff>(asm);

How to avoid that

Here are some symptoms of function declarations that may be suffering from generic parameter over-excitement.

  • There's no way to skip explicit generic parameter passing, i.e. it's impossible for the compiler to infer the generic parameter from the data parameters.
  • The only usages of the generic parameter in the function implementation involve the typeof operator.
  • The generic parameter in question doesn't have any constraints (the where keyword in C#) in its declaration. Or maybe it does have but it's not being leveraged at all in the implementation and can be safely removed (maybe there's a Resharper code inspection suggestion for that.)
  • Because the generic parameters are being used in an unnatural way, the function name and/or the generic parameter name become much longer than the usual, in an attempt to explain the unexcusable.

As I said, I may just be too sensitive or completely missing the point, neither of which would be their first time. Worst case someone chimes in with clever remarks and I learn something new, which again would not be the first time.

Taming Firebug with Profiles

Posted by Sergio on 2009-09-01

This is a tip for anyone using Firefox and Firebug for web development that is not leveraging the Profiles feature of that browser.

Recent versions of Firebug (after v1.3 I think) removed the ability to enable Firebug panes on a per-domain basis. Now it's kind of all or nothing. And you know that you don't want to have Firebug enabled when using Ajax-intensive applications like GMail, for example.

The end result is that you are stuck in this annoying dance of of enabling/disabling, open/close Firebug when switching tabs.

There are some workarounds for that but I think the best solution for this problem is through Profiles, which is also a very nice approach for web development overall.

Firefox Profiles

Firefox stores all your preferences (add-ons, state, saved passwords, history, etc) inside profile directories. It installs a default profile and that's perfectly enough for the casual browser user. Web developers, add-on developers, and power users in general, on the other hand, can find handy uses for extra profiles.

You can see your profile directories in %APPDATA%\Mozilla\Firefox\Profiles (or, on the Mac, ~/Library/Application Support/Firefox/Profiles).

Development profile

The suggestion I'm giving is to create a separate profile just to be used during web development work. That way you can exclude some of the add-ons (like ad blockers, bookmarking extensions like Delicious, and any other non development-related extensions.) The opposite applies to your default profile — you can now remove all the development stuff from that profile and keep your browser a little lighter. In addition to that I use a different skin/theme in each profile, just to make it screaming obvious which one I'm looking at.

Here's how we create a new profile. First close all your Firefox windows and make sure there's no Firefox process running in the background. Now go to the command line and enter this:

(on Windows)
%ProgramFiles%\Mozilla Firefox\firefox.exe -ProfileManager
(or on the Mac)
/Applications/Firefox.app/Contents/MacOS/firefox -ProfileManager

This will bring up the Profile Manager, where you can easily create a new profile. Create one named Development and start it.

Once started, you'll notice that Firefox will open looking just like it did the first time you installed it. You can now install your favorite extensions for web development (like Firebug, YSlow, Web Developer Toolbar, User Agent Switcher, etc)

To launch Firefox using the the Development profile you can create a shortcut that passes some arguments to Firefox, like firefox.exe -P Development -no-remote. For example, I added that shortcut to my Desktop, Quick Launch, and Launchy. (Firefox will remember which profile you started last using the Profile Manager, and use that one next time you start Firefox without explicitly choosing a profile. You may want to leave the default profile selected in the Profile Manager.)

More uses for Profiles

Besides creating a profile dedicated to web development work, I can very well see myself eventually creating extra ones for different activities, like a Presentation profile and a NoAddons profile, for example.

ASP.NET MVC with jQuery SuperLoad

Posted by Sergio on 2009-08-23
The other day I wrote about the jQuery SuperLoad plugin but I couldn't offer any real working sample of an application using it. Today I'm here to rectify that and talk about the new sample code I've recently added to the project repository.

Adding products to your shopping cart

The application has a single page, which lists a few books that you can add to your shopping cart. The cart is initially empty and when we add items to it, both the cart item list and the total price (at the top of the page) get updated from a single Ajax call.

The client side

Here's sample of what each of the products' HTML looks like. They each are inside a div which's id contains the product's id.
<div id="product_8" class="product">
	<img src="../../Content/images/prod_8.jpg" align="left" />

	<div class="title">Product 8</div>
	<div class="prodPrice" >$8.88</div>
	Qty: <input type="text" size="2"  maxlength="3" 
				class="quantity" value="1"/>
	<input type="button" value="Add to cart" class="addButton" />
</div>
We just need to fire one Ajax call whenever one of those "Add to cart" buttons is clicked. Here's the code that does that.
$('.addButton').click(function() {
	var prod = $(this).parent('.product');
	var prodId = prod.attr('id').split('_')[1];
	var qty = prod.find('.quantity').val();

	$.superLoad({
		url: '/Shopping/AddItem',
		type: 'POST',
		data: { product: prodId, quantity: qty },
		success: function() { $('#empty').remove(); }
	});
	
});
As you can see, we are making a superLoad() call to the AddItem action in the ShoppingController. Since this is a data modification call, we chose to use an HTTP POST request. The posted data goes in the data option. To tidy up things, we delete the empty text from the cart (if it's still there) once the call completes successfully.

Multiple results from a single action

The challenge on the server side is to come up with a sustainable method of reusing existing actions and combine them in a single action result, formatted to SuperLoad's liking and returned to the browser. To address that issue the sample comes with an implementation of a composite action result class specifically built for the response format we are trying to create. That class is the SuperLoadResult, listed below.
public class SuperLoadResult : ActionResult
{
	public IEnumerable<SuperLoadAjaxContent> ContentItems { get; private set; }

	public SuperLoadResult(params SuperLoadAjaxContent[] contentItems)
	{
		ContentItems = new List<SuperLoadAjaxContent>();
		((List<SuperLoadAjaxContent>)ContentItems).AddRange(contentItems);
	}

	public override void ExecuteResult(ControllerContext context)
	{
		context.HttpContext.Response.ContentType = MediaTypeNames.Text.Html;

		context.HttpContext.Response.Write("<div class=\"ajax-response\">");
		foreach (var item in ContentItems)
		{
			context.HttpContext.Response.Write(
				string.Format("<div class=\"ajax-content\" title=\"{0} {1}\">",
			                  item.Command.CommandText, item.Selector));
			item.GetResult().ExecuteResult(context);
			context.HttpContext.Response.Write("</div>");
		}
		context.HttpContext.Response.Write( "</div>");
	}
}
I bet things will become clearer once I show it being used from the AddItem action. So here it goes.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddItem(int product, int quantity)
{
	var sku = GetProduct(product);
	var item = new CartItem(sku, quantity);
	var cart = GetCurrentCart();
	cart.Items.Add(item);

	//add all the separate action results that we want into 
	// a SuperLoad result, mapping each one to the right 
	// selector and update type.
	return new SuperLoadResult(
		new SuperLoadAjaxContent("#cartTotal", 
		                  SuperLoadCommand.Update, 
						  () => CartTotal(cart)),

		new SuperLoadAjaxContent("#cart", 
		                  SuperLoadCommand.Append, 
						  () => CartItem(item))
		);
}
That last parameter to the SuperLoadAjaxContent's constructor is what will be invoked to provide an ActionResult-derived object, which will be executed and injected in the right place of the combined response. If I needed to update more elements, I could simply pass more instances of SuperLoadAjaxContent to my SuperLoadResult. Both CartTotal and CartItem are regular action methods that return a partial view from an .ascx template. Here's how simple the CartItem action is.
public ActionResult CartItem(CartItem item)
{
	return PartialView("CartItem", item);
}
Again, the entire sample is available for browsing, forking, or downloading at the repository page.