Tales from the Evil Empire

Bertrand Le Roy's blog

News

Ads Via DevMavens

ASP.NET AJAX UpdatePanel Control: Add Ajax interactivity to your ASP.NET 2.0 web pages


follow bleroy at http://twitter.com


Add to Technorati Favorites

Blogs I read

My other stuff

You can do the TODOs today too!

Don't just leave your junk lying around. (c) Bertrand Le Roy 2002 If you’re anything like me, you probably litter your code with TODO comments, postponing random tasks for the sake of moving the project forward. And there is of course a non-zero probability that you are going to ship with those comments still in.

So I want to propose the following call to action to all readers of this blog: open your current project and start implementing what’s in those TODOs today.

Finding the TODOs is easy. In Visual Studio, do CTRL+SHIFT+F (search in files), make sure you are searching across the whole solution and search for “TODO”. In the results window, you can click on each result to open the file at the TODO comment location.

While working on a file, you can open the task list window (CTRL+\, CTRL+T), open that drop-down menu and choose “Comments”:

TaskList Comments

Once you’ve done that, Visual Studio brings you a list of all those TODO comments in the currently open files, which is easier on the eyes than the search results window:

Task List

You can now go through those one by one (double-clicking on the TODO in the task list takes you there) and delete the comments once you’ve implemented the feature they describe.

UPDATE: some commenters pointed out that the todo list is limited in scope. I updated the post. Resharper also apparently has a greater feature around that.

Mocking indexer setters with Moq

(c) Bertrand Le Roy 2004 I quite like MoQ because it makes sense for me. Shamefully, I’ve always had some trouble understanding test code that was using mocks built with other frameworks. With MoQ, I can just grok it for some reason. It’s just super-clear to me. It doesn’t mean I have any idea how it really works but for now I’m just happy with the magic.

Anyway, yesterday I wanted to check that a controller action was setting some Application variable (let’s not get into the debate on whether or not it should do that at all). Something like this:

application["foo"] = new Foo();

Now how do I enable the object to be set by the tested code? Well, that one is easy, I can use SetupSet on indexers just fine:

var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.SetupSet(
c => c.Application["foo"] = It.IsAny<object>());

This call tells the mock that it can accept to run code that attempts to set the “Foo” application variable with any object.

But now, what if I want to get a reference to that object from my test code in order to check the value of some of its properties?

Well, MoQ has a Callback method that you can hook to the result of any Setup call. The action that you provide it will be run whenever the setup code is called. The problem with that callback method is that its signature must match that of the setter exactly. Unfortunately, that signature is implicit. If you get it wrong, the test will fail more or less silently (it will just tell you setup failed with little details). To get this right, you need to know what the setter syntactic sugar compiles to, which kinda sucks, but the good news is that you only have to figure it out once, which I just spent some time doing for you (and for myself too, let’s be honest):

var mockHttpContext = new Mock<HttpContextBase>();
Foo map = null;
mockHttpContext
.SetupSet(c => c.Application["foo"] = It.IsAny<object>()) .Callback((string name, object m) => { map = (Foo)m; });

Because this is an indexer setter, the compiled code actually takes a name and a value, which is reflected by the signature of the callback lambda. We can now call into the code to test, knowing that when it sets our “Foo” application variable, the local “map” variable of the test code will get set. The test code can then party on the object and assert whatever it wants.

I hope this saves some time whoever is trying to do the same thing.

Why is ASP.NET encoding &’s in script URLs? A tale of looking at entirely the wrong place for a cause to a non-existing bug.

(c) Bertrand Le Roy 2003 Several people have reported seeing errors in their logs that seem to be due to requests such as this:

/ScriptResource.axd?d=
[lots of junk]&amp;
t=ffffffffee24147c

The important part here is the HTML-encoded “&amp;” sequence, which stands for “&” of course. If this exact URL is sent to the server, the server won’t know what to do with the escape sequence (URLs are not supposed to be HTML-encoded on the wire) so the parameters won’t get separated as expected, potentially resulting in a server error. This bug in the toolkit is an example of that: http://ajaxcontroltoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=13134

Of course, when people see 500 errors popping up in their server logs, they immediately assume the application is failing for some users. Or that some idiot at Microsoft did something incredibly stupid (that’s what we idiots at Microsoft do after all).

Case in point, a quick peek into the source code of the application’s pages immediately reveals that the script tags generated by ScriptManager do indeed generate these URLs:

<script src="/ScriptResource.axd?d=[lots of junk]&amp;t=ffffffff8824ac28" type="text/javascript"></script>

So that’s where it came from! See? When I copy this URL into the browser’s URL bar, I do get the same error!

Then ensue various more or less rational reactions such as:

  • Correlate the user agent to the faulty requests (which correlates more or less with normal browser usage, i.e. lots of IE and then lots of Firefox, when there is a large enough sample).
  • Blame IE6 (lots of these requests come from IE6, hence it must be responsible: IE6 sucks).
  • “Fix” ScriptManager and remove the HTML encoding.

Well, by copying the URL from the source view into the URL bar, you did indeed reproduce the problem. A little too well. Better than you realize.

This is why. All of the errors in your server logs come from people doing precisely what you just did: copy the URL from the source view into the browser’s URL bar. They do it for various reasons: look at the source code for the scripts, understand what these weird URLs are, who knows?

But the point is, you will never be able to reproduce these errors during normal use of the application. There is nothing to fix here. The value that gets sent to the server never has the “&amp;” sequence. You can verify it in IE6, you can verify it in any browser on any OS, it will just work.

When putting a URL in an HTML attribute, you should *always* HTML-encode it. It’s the standard, and for good reason (it enables the browser to tell between “&”, “&amp;” and “&amp;amp;”, it enables quotes to be embedded into attributes, etc.).

A consequence of that is that if you’re going to copy the value of one of these attributes from the source view, you should do what the browser does when parsing the HTML: decode the value first (in other words, replace “&amp;” with “&”).

So yes, people do fail to do that and copy the URL without decoding. Well, they are not supposed to do that, nor do they need to do it. The error is normal, it results from a bad URL having been entered manually. Nobody would be surprised to get an error when querying foo.aspx?somenumber=thisisnotanumber for example. Same thing here. Pretty much.

Of course, this is not entirely trivial to figure out and I did pull my remaining hair a bit trying to understand what was going on, and you tend to trust people when they tell you there is a problem, especially when the description seems to make sense. There is some sort of confirmation bias going on there. But the more I looked at the different pieces of evidence, the more this explanation looked like the most likely, by far.

But of course, I may be missing something…

Survey: Ajax usage among .NET developers

(c) Bertrand Le Roy 2003 If you haven’t already and you are a .NET developer, please take a couple minutes and answer this survey, whether you use Ajax or not. There are a number of Ajax surveys around, but Simone’s is the only one that focuses on .NET developers.

The survey:
http://www.zoomerang.com/Survey/?p=WEB22973CYKW2H

Simone’s post:
http://codeclimber.net.nz/archive/2009/05/21/ajax-usage-among-.net-developers-in-2009.aspx

Twitter contest: what can you code in 130 characters?

I just posted the following snippet on Twitter. The exercise is to write meaningful and preferably cool code that fits in a Twitter message along with the #twitcode keyword, which leaves 130 characters.

private static readonly byte[] _blankGif =
  Convert.FromBase64String(
"R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAEBMgA7");

I can’t wait to see what people come up with.

Monitor the results from here:
http://search.twitter.com/search?q=%23twitcode

setInterval is (moderately) evil

bleroy05 JavaScript has two ways of delaying execution of code: setInterval and setTimeout. Both take a function or a string as the first parameter, and a number of milliseconds as the second parameter. The only difference is that the code provided to setInterval will run every n milliseconds whereas the code in setTimeout will run only once.

Before I explain why I think setInterval is evil, allow me to rant on a related subject for a paragraph: you should never pass a string into any of those functions and instead always pass a function reference (unless you really, really know what you’re doing). If you pass a string, it will have to be evaluated on the fly, and eval is quite evil itself (unless you really, really know what you’re doing). It might seem tempting to generate code this way to inject dynamic parameters, but there are better ways of doing that, using currying. In Microsoft Ajax, for example, we provide the handy Function.createCallback and Function.createDelegate for exactly that usage.

Anyways now let’s get back to the issue at hand: setInterval is evil. To better compare, let’s assume you have a reason to use setInterval (why else would you be reading this?). Here’s the code you might write:

<!DOCTYPE html>
<html>
<head>
    <title>setInterval</title>
    <script type="text/javascript">
        var interval = setInterval(appendDateToBody, 5000);

function
appendDateToBody() { document.body.appendChild( document.createTextNode(new Date() + " ")); } function stopInterval() { clearInterval(interval); } </script> </head> <body> <input type="button" value="Stop" onclick="stopInterval();" /> </body> </html>

Both APIs have a corresponding clear API that enables the developer to cancel the interval or timeout. To identify what interval or timeout you’re cancelling, you pass into the API a token that is whatever value the call to setInterval or setTimeout returned. And that’s a first reason why setInterval is (mildly) evil: if you lose that token, there is no way you can ever stop that code from running every five seconds until you navigate away from the page. But that is a minor inconvenience, it just means you need to carefully manage your own stuff, right? Well, actually if code that you don’t know or don’t control created that interval, you’re probably in trouble even if you kept your own house real nice and tidy…

But the real reason why I dislike setInterval is that it is quite hard to debug, in particular if you have more than one running simultaneously. For example, if you have two intervals, one running every 100 milliseconds, the other every five seconds, and if you want to debug the second one, the first one will constantly get triggered and will get in the way.

So what, you might say, is the alternative? Well, here is code that is quasi-equivalent to the code above, but that uses the much less evil setTimeout:

var interval = setTimeout(appendDateToBody, 5000);

function appendDateToBody() {
    document.body.appendChild(
        document.createTextNode(new Date() + " "));
    interval = setTimeout(appendDateToBody, 5000);
}

function stopInterval() {
    clearTimeout(interval);
}

Here, instead of taking a subscription for life, we’re just renewing the lease as we go. The big advantage of this code is that to stop the interval, you don’t need the token. Actually, I rarely even bother to keep hold of it. All you have to do is skip the line of code that renews the timeout for the next iteration. So no housekeeping to do, and if during a debugging session you need to get one of the interval functions out of the way, just drag your debugger’s current execution pointer to the end of the function, hit F5 and you’ll never see that function run ever again, boom, it’s out of the way and you can focus on your own debugging.

So to summarize, replacing setInterval with setTimeout is easy, pain-free and removes the inconveniences of setInterval. So while the setInterval evil is about at the level of not replacing the cap of the toothpaste, the non-evil alternative is so easy that I can’t see a reason not to forget about setInterval for good.

New release of the Ajax Control Toolkit

A new version of the AJAX Control Toolkit is now available for download from the CodePlex website. It contains three new controls:

HtmlEditor HTMLEditor - allows you to easily create and edit HTML content. You can edit in WYSIWYG mode or in HTML source mode. The control exists as a server-side extender but can also be instantiated purely on the client-side with a single line of code. Many thanks to Obout for building this.


ComboBox ComboBox - provides a DropDownList of items, combined with TextBox. Different modes determine the interplay between the text entry and the list of items. this control behaves very much like a Windows combo. Many thanks to Dan Ludwig for building this.


ColorPicker ColorPicker - can be attached to any ASP.NET TextBox control to provide client-side color-picking functionality from a popup. Many thanks to Alexander Turlov for building this.


The ASP.NET website has been updated with new videos and tutorials for these controls.

This new release also includes fixes for over 20 of the most voted bugs in existing AJAX Control Toolkit controls and now features minimized release versions of the script files.

The release can be downloaded as a server dll or as a set of files for use with pure client-side applications.

http://ajaxcontroltoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27326

Creating jQuery plug-ins from MicrosoftAjax components

(c) Bertrand Le Roy We had an interesting discussion recently on the ASP Insiders mailing list and ended up talking about what cool stuff we could build on top of jQuery. Many interesting things were mentioned and it was a very useful discussion but one suggestion in particular struck my curiosity as it was something I had investigated before and that could be improved on with very little code.

I had already written a little plugin to enable instantiation of Microsoft Ajax components on the results of a jQuery selector:

jQuery.fn.create = function(type, properties) {
    return this.each(function() {
        Sys.Component.create(type, properties, {}, {}, this);
    });
};

I have another version that is a little more elaborate and takes a bag of properties and events instead of just properties (get it from the attached sample) but you get the idea. This makes it fairly easy to instantiate components based on a selector:

$(":text.nomorethanfive")
    .create(Bleroy.Sample.CharCount, { maxLength: 5 });

But if this were a native jQuery plugin instead of a Microsoft Ajax component, as Rick Strahl suggested, chances are you’d do something like this instead:

$(":text.nomorethanfive").charCount({ maxLength: 5 });

We can actually get that exact result fairly easily by writing a plugin that is specific to this component, but we can’t expect every Microsoft Ajax component author to also write a jQuery plugin, can we? We can do better than that. Here is a second small piece of code that is still generic but is in the business of creating jQuery plugins:

Sys.Component.exposeTojQuery = function(type, pluginName) {
    return jQuery.fn[pluginName] = function(properties) {
        return this.each(function() {
            Sys.Component.create(type, properties, {}, {}, this);
        });
    }
}

Like above, the version in the sample is better than that in that it supports events in addition to properties but again you get the idea. Thanks to this function, we can create a jQuery plugin for any existing Microsoft Ajax component with a single line of code:

Sys.Component.exposeTojQuery(Bleroy.Sample.CharCount, "charCount");

After this call, we can write exactly the code we wrote before, but without having had to write a specific plugin. We can then use charCount like a native jQuery plugin:

$(":text.nomorethanfive").charCount({ maxLength: 5 });

This is really easy to use, and I quite like it. We could for example add the following line of code to the new MicrosoftAjaxTemplates.js:

if (jQuery)
Sys.Component.exposeTojQuery(Sys.UI.DataView, "dataView");

This would enable us to instantiate DataView controls as simply as this:

<ul class="dv">
    <li>{{ $dataItem }}</li>
</ul>
<script type="text/javascript">
    $(".dv").dataView({ data: ["foo", "bar", "baz"] });
</script>

Get the code from here (you need to include jquery-1.3.2.js to the script folder):
http://weblogs.asp.net/blogs/bleroy/Samples/jQueryCreate.zip

Five gems of XBLA
  1. The Maw is a charming and seriously fun game that is going to make you smile from start to finish.
  2. Puzzle Quest is one of those “just one more” time sinks. The improbable mix of puzzle gaming and RPG is just awesome. The sequel, Galactrix, is pretty good too (but quite buggy, you might want to wait for a patch or at least regularly copy your game save).
  3. Portal is simply the best game ever, at least for me. Portal proves once more that the simplest ideas can be the deepest and does so with amazing grace and mastery of the art of video games.
  4. Banjo Kazooie and Banjo Tooie were two of the best N64 games, maybe on par with Super Mario but with that unique Rare sense of humour.
  5. Cloning Clyde: smart and funny.

What are your favorite XBLA games?

Posted: May 03 2009, 12:20 AM by Bertrand Le Roy | with 5 comment(s)
Filed under:
Glimmer: visually build jQuery animations and stuff

glim4sIf you’re still intimidated by jQuery or DOM manipulation in general, if you need to quickly build web animations, if you’re more a designer guy, if you think tooling makes sense, or a combination of the above, you should probably check out Glimmer.

In a nutshell, Glimmer is a visual tool that builds HTML animations, menus, tooltips on jQuery. It builds all the code you need (HTML, CSS and JavaScript with jQuery) at the click of a button.

Check it out!
http://visitmix.com/Articles/Glimmer-a-jQuery-Interactive-Design-Tool

More Posts Next page »