Monthly Archives: February 2011

IE9, compatibility mode and the META tag

Note: This post describes how to use the Compatibility META tag correctly in order to force IE9 to switch to an older browser mode. If you’d rather skip the explanation and get to the technical stuff, simply scroll down to the last paragraph.

There are many posts addressing IE compatibility issues. This post from the IE team, back in 2008, also demonstrated how META tags or Http Headers can be used to control Compatibility View in IE8 (now also in IE9). This was supposed to help us developers to overcome compatibility problems without having the user to do anything (well, this was the intention…)

In short, older IE browsers support quite a few “IE only features”. If these were used in your website, they could break if your users upgrade their browser to a newer IE. This might happen because IE is becoming more and more compatible with world-wide standards. In other words, Microsoft is taking out stuff which wasn’t supposed to be there in the first place, and are also making sure that stuff which was supposed to work is actually working the way it was supposed to work in the first place (mainly CSS and rendering issues).

While this is a good and promising direction from Microsoft, this could be bad for your website. For example, if you’re using 3rd party controls which are a year or more older on your web application, these may break as their code was probably written prior to IE9 betas which allowed tests. Upgrading to the latest version of these controls is not always an option as some of these may no longer be supported. Even upgrading your own code may be costly.

Fortunately, the IE team thought of these issues and have provided us with a solution. Those meta tags/headers previously mentioned. According to their blogs and documentation, a developer could specify a meta tag instructing the browser to use a more compatible mode, so that the website will not break. Following the instructions here, you should be able to place the following meta tag in your head section (you can replace the EmulateIE8 with supported values as listed here or here):

 <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >

While this should have solved the now-breaking website – it didn’t. IE9’s Developer Tools (F12) Script tab displayed the following error:

HTML1115: X-UA-Compatible META tag (‘IE=EmulateIE8’) ignored because document mode is already finalized.

Needless to say, this was frustrating. In order to try and figure this out, I have downloaded the IE9 Platform Preview. Basically this is an IE9 browser, which provides two great benefits:

1) It runs side by side to the existing IE browser and does not replace it, as a regular installation would have. So it saves you the trouble of installing a VM machine to test things or simply installing a non-released IE9 instead of your current IE.

2) On the Status Bar of the Platform Preview is easily visible the running Document Mode. While this info is available also in the Developer Tools of IE9 Beta/RC if you do choose to install it, having the status bar display the Document Mode constantly is just plain comfort.

After debugging and creating a new website to test why IE9 fails to switch to IE8, the problem seemed to be the position of the meta tag. It seems like the X-UA-Compatible tag has to be the first tag in the <head> section. If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the <head> forced IE9 to switch to IE8 mode successfully, and the website started working again.


Posted by on 25/02/2011 in Software Development


Tags: , , , , , , , ,

.NET Reflector no longer free

It seems like Red Gate decided to commercialize .NET Reflector as of March. A noticeable warning is displayed on the Reflector‘s download page.

After searching a little on the web, I found an interview by Ed Burnette, in which a Red Gate  employee explained that their “initial assumptions” regarding supporting freeware and premium versions based on the developers who’ll pay for the premium version “were wrong”. To be honest, ever since Lutz Roeder sold this tool to Red Gate, I was afraid that something like this would happen. I’ve been using .NET Reflector for years, sometimes on daily basis, and it’s a real shame that Red Gate aren’t holding on to their statements, about keeping Reflector free.

It’s true that Red Gate is a commercial company, so basically they don’t have to provide Reflector for free. BUT, there are several things I’m puzzled over:

  1. If Lutz Roeder created Reflector, and did this amazing work for free, for about 8 years or so prior to selling it to Red Gate – how come Red Gate can’t support a free version? I mean, Lutz Roeder is probably a great developer doing all this by himself, but I’m quite sure Red Gate could have pulled it off.
  2. More over, if the Premium version is the real reason why Red Gate is having problems to finance this activity – either close this operation (the premium, not the free version – after all, Lutz did provide the “lite” version for free…), or charge the extra money from the premium users.
  3. According to the interview, it seems that developers would have to pay 35$ and they will get Reflector 7 forever (“perpetual license”). So the discussion in the interview regarding the “6 months expiration date” is not really an issue. In other words – you could provide the community with one, last, free non-expiring version of Reflector as it is today. After all, you simply have to compile a version which won’t expire, just like you plan to do in version 7. Developers that will choose to pay will be able to download newer versions. At least you could leave us with the current free version. In short, please do not insult us with the “well, Lutz planned the 6 month expiration so developers will have to update, and that’s why developers can’t keep their current free version” explanation.

Red Gate – thanks for keeping Reflector free for 2.5 years since you bought it. .NET Reflector is (was?) an awesome tool. However, maybe it’s time for the community to start developing a new free alternative? If this call will be answered, then I think that Red Gate will discover that the choice they made was poor, even if for a short term they gained some cash from it.

BTW: Ed Burnette also provided a link to a video, where Red Gate guys attempt to explain their decision.

UPDATE: I was happy to learn that other alternatives already exist by now. There’s a free alternative from SharpDevelop called ILSpy, where they announce that “Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.” – Thanks guys.

Telerik also released a free decompiler: JustDecompile, with a cool “May The Source Be with You” slogan.


Posted by on 21/02/2011 in Software Development


Tags: ,

jQuery numeric textbox with range (well, none or zero to max)

I’ve been looking for a jQuery plugin which will allow me to turn a textbox into a numeric, ranged textbox. After searching a little around the web, experimenting with some of the alternatives without satisfaction, I found some code samples which were partially adequate and I decided on writing specific code for my own purposes.

It’s designed for something quite specific, so it lacks many options which more “generic” plugins have, but it could be of use for developers who require a simple numeric textbox limited by a certain “max number”. There’s no min number involved, but basically you can’t enter characters other than numeric, so it’ll either accept empty, zero or a positive number up to the max specified.

This is my first jQuery plugin ever. My steps were basically:

  1. Write jQuery-based code in my main document which performed what I wanted.
  2. Look up at the documentation for authoring jQuery plugins, and then I copy-pasted one of the examples which I thought suitable.
  3. Copy-pasted the code from step 1 onto the example’s template copied in step 2.
  4. Test and debug.

Here it is:

1: (function ($) {
3:     $.fn.numeric = function (options) {
5:         return this.each(function () {
6:             var  $this = $(this);
8:             $this.keypress(options, function (e) {
9:                 // allow backspace and delete 
10:                 if  (e.which == 8 || e.which == 0)
11:                     return  true;
13:                 //if the letter is not digit 
14:                 if  (e.which < 48 || e.which > 57)
15:                     return  false;
17:                 // check max range 
18:                 var dest = e.which - 48;
19:                 var result = this.value + dest.toString();
20:                 if  (result > {
21:                     return  false;
22:                 }
23:             });
24:         });
25:     };
26: })(jQuery);


1: $( '#myTextbox' ).numeric({max: 99999});

As I’m aware that this plugin lacks lots of functionality, and probably will have it’s own share of bugs, it’ll be great to receive recommendations for other plugins which support numeric and ranged input. I was hoping that jStepper would be my preferred solution as it seemed to have all that I wanted and more, but for some reason it ignores my option settings for not allowing decimals.

If you wish, you can download the code from here: jquery.numeric.js. Just make sure that you rename to js instead of doc.

Leave a comment

Posted by on 19/02/2011 in Software Development


Tags: , , , , , , ,

First attempt with jQuery UI

Its been quite some time that I’ve wanted to try out jQuery UI. I admit I did not bother to check if jQuery UI is the “official” library for jQuery, but the demonstrated theme-able widgets looked so amazing, plus the fact that this was based on jQuery – I really wanted to give it a shot. I know, i know – there are many libraries out there. I usually use AjaxControlToolkit, for the past several years actually, alongside other 3rd party controls (which were usually a necessary compromise), alongside jQuery and custom plug-ins.

BTW: At the current time, jQuery UI (1.8.9) has less than ten widgets available, lots of themes and other impressive effects. I only wish it had more widgets available.

In order to quick start with jQuery UI, you simple have to download a jQuery UI + theme, and follow the simple instructions here. The download page consists of many options, so I’ll simply recommend using the box on the right (labeled “Theme”), select a theme and hit the “Download” button. This will download a zip file with the complete package + the selected theme.

Of the different widgets I usually use, having a Modal Dialog is one of my preferred ones. Following the documentation and samples, simply displaying a Modal dialog message is quite simple. If you need a fill-out form, you’ll require a little more help from the documentation (or samples which are embedded within the downloaded file). What I did was a simple copy-paste of the HTML+JavaScript of the Modal Form sample, and started to change them according to my specific needs. I required a single textarea field with a simple validation, so I made the appropriate changes and the dialog worked without any problems. I was quite amazed how easy it is to add buttons to the dialog, with their callback functions.

1: <div  id="dlgNickName"  title="Nickname"  style='display:none;'
2:     <p> 
3:         Creating a nickname makes it easy to ....</p> 
4:     <br /> 
5:     <p class="validateTips"> 
6:         Enter a nickname</p> 
7:     <p> 
8:         <textarea rows="1"  style='width: 450px' name="name" id="name"
                        class="text ui-widget-content ui-corner-all"></textarea></p> 
9: </div>
1: $("#dlgNickName" ).dialog({
2:    height: 240,
3:     width: 500,
4:    modal: true ,
5:     autoOpen: false ,
6:     resizable: false ,
7:     buttons: {
8: 		"Apply" : function () {
9: 			$( "#nickname" ).text(name.val()); 
10: 			$( this ).dialog( "close" );
11: 		},
12: 		Cancel: function () {
13: 			$( this ).dialog( "close" );
14: 		}
15: 	},
16: 	close: function () {
17: 		allFields.val( "" ).removeClass( "ui-state-error" );
18: 	}
19: });

Finally, and without having anything to do with jQuery UI, I used the “what seems to be fantastic” TEXTAREA jQuery Textarea Counter Plugin (which also optionally limits the text and not only counts). This was the better plugin I found for this purpose. Other plugins I’ve looked at did either limit or either count, and those who combined both features didn’t looks as good as this one. It is also very customizable and simple to use.

The result looks like this (I used jQuery UI’s “sunny” theme):

In short, the jQuery UI Dialog Modal Form proved successful, at least for now. jQuery has other powerful widgets I’ll probably use later on. I’m already looking forward to using the ToolTip widget in the oncoming 1.9 release.

Leave a comment

Posted by on 15/02/2011 in Software Development


Tags: , ,

ASP.NET MVC Razor Code nuggets vs. Code blocks

There’s a difference between Code Nuggets and Code blocks in Razor. A “Code Nugget” is simply the usage of the @ sign which indicates a server-side “self contained” code block. For example:

1:  @Model.Name

This will basically print out a string. Resembles ASP.NET’s somewhat cumbersome <%= %>, but a lot more tidy and clean. No doubt this is very convenient.

However, if you require a “server side” code block, Razor allows opening a server side code block using @{ }. For example, say you want to print out a Model’s property, only it contains data:

1:  @{
2:     if (!string.IsNullOrWhiteSpace(Model.Name))
3:     {
4:         Html.Raw(Model.Name);
5:     }
6:  }

Note line 4: Html.Raw( ) is a helper method which simply outputs a text. Interesting enough, as opposed to the previous sample code, this code renders nothing to the browser, despite the fact that Mode.Name is not empty.

I went on and tried the following:

1:  @Html.Raw(Model.NickName)
2:  @{ Html.Raw(Model.NickName); }

As you might have guessed, line 1 provided the desired output while line 2 rendered nothing. Puzzled, I went to the Reflector and found out the following:

Code Nugget vs Code Block

Line 1 compiled into a this.Write(…) method, and line 2 resulted in a simple base.Html.Raw(…) call. This explained several things which in retrospect became obvious:

  1. A Razor code block is, basically, well, just a code block. This means that it will not output the text just because Html.Raw(…) is being called.
  2. Moreover, Html.Raw(…) does not render anything to the output stream by itself.
  3. A Code Nugget is compiled as a this.Write(…) method call.
  4. If we want to render something to the output stream from a code block, we should explicitly mention it, either by calling Write(…)/WriteLiteral(…), or simply by specifying a Code Nugget from within the code block itself. In other words, the following examples work well (note the @ signs emphasized in red):
1:  @{ @Html.Raw(Model.Name); }

And so does this:

1:  @{
2:     if  (!string.IsNullOrWhiteSpace(Model.Name))
3:     {
4:         @Html.Raw(Model.Name);
5:     }
6:  }

One final word about this topic. Re-examining Scott Gu’s blog, specifically the examples in the “Identifying Nested Content”, demonstrates the above “conclusion” explicitly. Nevertheless, apparently it was easy to miss, forget, or maybe it was just confusing till I experienced this myself. At least it resulted in a better understanding of the compiled Razor output.


Posted by on 14/02/2011 in Software Development


Tags: , , , , ,

Rendering JavaScript using Razor, including non-escaped characters

NOTE: This post uses a variant of the LocalResX extension method written and described in an earlier post, only suited for usage with HtmlHelper:

I wanted to render a JavaScript array, which was built of several server side resources. Similar to Classic ASP, MVC easily supports embedding client and server side code. This looks something like this:

1: var myArray = [ @for(int i = 1; i <= 10; i++)
2:                  {
3:                     @string.Format("'{0}'", Html.LocalResX("Item" + i.ToString()));
4:                  } ];

However, there were two problems:

  1. I needed a comma in between the client array items.
  2. The apostrophe (and eventually the comma too) are rendered as encoded escaped characters.

The thing is, I had no idea how to render simple text (i.e. a “comma”) to the client from a Razor block. When HTML elements are involved, you just write the HTML. When non-html is involved (such as JavaScript, as in this case), this is different. You can’t just write a comma in the middle of a Razor block and expect it to be rendered (this results in a “ CS1525: Invalid expression term ‘,’“).

One solution was specified in Scott Gu’s blog, about using <text> for rendering simple code from Razor blocks. This looks like this:

1:var myArray = [ @for (int i = 1; i <= 10; i++)
2:                 {
3:                     @string.Format("'{0}'", Html.LocalResX("Item" + i.ToString()));
4:                     if (i < 10){
5:                          <text>,</text>
6:                     }
7:                 } ];

Although an acceptable solution, the result seems to be rendered with extraneous newline characters, which was not the desired result. Besides, it did not solve the escaped characters of the string itself. I looked some more and found out that there are other alternatives to do this, such as to use HtmlHelper’s Raw method, which does not encode the characters and simply renders the text “as is”. The result is as follows:

1:var myArray = [ @for (int i = 1; i <= 10; i++)
2:                 {
3:                     @Html.Raw(string.Format("'{0}'", Html.LocalResX("Item" + i.ToString())));
4:                     if (i < 10){
5:                         @Html.Raw(", ");
6:                     }
7:                 } ];

This solved both problems.

Regardless, one thing which I find weird in Razor, is that once you open a Razor code block, you have to familiarize yourself with when you should or shouldn’t specify the @ sign. For example, if I omit the @ prior to Html.Raw (line 3), no compilation error would occur, but the server will render nothing. That is, it’ll completely ignore the entire code statement. On the other hand, if I specify @ prior to the if { … } block (line 4), a compilation error will occur upon render, claiming that: “ Unexpected “if” keyword after “@” character.  Once inside code, you do not need to prefix constructs like “if” with “@”“. Basically, this is understandable at times, but inconsistent: In Scott Gu’s “Introducing Razor” he demonstrates ‘if’ blocks using the @ sign. True, these code blocks are not nested within other Razor code blocks, but this shows the inconsistency.

Leave a comment

Posted by on 13/02/2011 in Software Development


Tags: , , , ,

ASP.NET MVC Resources

Implementing a multilingual web application is something I see as crucial, in order to address a larger crowd of people. In ASP.NET Web Forms, this was very easy to accomplish using the ‘$’ or meta:resourceKey, and the code behind relevant methods. In ASP.NET MVC I’m uncertain if this is inherently supported so I was searching for a way how to accomplish this. Global resources behave the same: ASP.NET infrastructure auto-generates a Resource class which can be used in exactly the same manner as in Web Forms. For example, if I have a GlobalResources.resx file, a GlobalResources class will be auto-generated containing static properties, which can be used as follows:

1: <li>@Html.ActionLink(Resources.GlobalResources.Home, "Index", "Home")</li>

Local resources, however, are not auto-generated classes. Looking around the web I came across an interesting post on how to use Local Resources using an extension method. This was great, but I was looking for some implementation that will: 1) Use a single “resource key” as an argument, and 2) Will be “context aware”, so that if the context is a layout (“Master page”), it’ll use local layout resources, and if the context is a page, it’ll use local page resources. After performing some experiments and debugging, I learned two interesting things using the excellent .NET Reflector (see pic below):

  1. Layouts and Pages are both considered as “pages” as they inherit from “WebViewPage”, making them both “pages” (Web Form’s MasterPage does not inherit from Page class, but from UserControl).
  2. Despite that, layouts seem to be compiled to a different assembly than pages.

MVC page inheritance
Knowing that this is the same class hierarchy, I used a single method to accomplish the local resource handling. This resulted in the following extension method:

1: public static string LocalResX(this WebViewPage page, string key)
2: {
3:     var  value = page.ViewContext.HttpContext.GetLocalResourceObject(page.VirtualPath, key) as string;
4: #if  DEBUG
5:     if  (string.IsNullOrWhiteSpace(value))
6:         value = string.Format("*{0}*" , key.ToLowerInvariant());
7: #endif 
8:     return value;
9: }

Line 3 performs the two relevant things:

  1. Using the WebViewPage base class we have access to the ViewContext->HttpContext->GetLocalResourceObject, which is what retrieves the resource.
  2. the page.VirtualPath is what “differentiates” the Layout from the Page “resource context wise” . So when we’re in layout context, this will return the layout’s path. When in page context, this will return the page’s path. This is what ASP.NET needs in order to return the correct resource file.

Lines 4-7 are not really essential. They simply help in pointing out resource keys which do not exist in the resource file yet. This can also be logged to a log file.

The resulting code:

1:<li>@Html.ActionLink(Resources.GlobalResources.Home, "Index", "Home")</li> 
2:<li>@Html.ActionLink(this.LocalResX("Blog"), "Blog", "Home")</li>

Line 1 demonstrates a GlobalResource usage.

Line 2 shows the Local Resources implementation.


Posted by on 05/02/2011 in Software Development


Tags: , , , ,