Leaky Abstractions? Try Asp.Net!
secretGeek .:dot Nuts about dot Net:.
home .: about .: sign up .: sitemap .: secretGeek RSS

Leaky Abstractions? Try Asp.Net!

First here's a code example:

Single line 'TextBox':

<asp:TextBox ID='dd1' runat='server' TextMode="SingleLine" MaxLength="10"> </asp:TextBox>
                                                                                    ^^^^This 'MaxLength' is respected!

Multi line 'TextBox':

<asp:TextBox ID='dd1' runat='server' TextMode="MultiLine" MaxLength="10"> </asp:TextBox>
                                                                                    ^^^^This 'MaxLength' gets ignored!

Now here it is in pictures:

max length ignored on multi-line TextBox

The single-line TextBox respects the maximum length property. The multi line textbox does not. We see other differences too: these two 'TextBoxen' differ from each other in far more than the number of rows.

The cause here is a classic 'Leaky Abstraction' - and asp.net is riddled with such leaks.

The 'abstraction' of "TextBox" is used to emit either one of three underlying html elements -- "TextArea", "Input type=text" or "input type=password" -- depending on the 'TextMode' property. The three controls are wildly different animals.

"Solutions" to this problem tend to use javascript to stop input once the maxlength is reached.

Edge cases are frequently missed, for example:

  • Once maxlength is reached, ignore input, but don't ignore: Arrow keys, Delete key and Backspace. Others?.
  • Pasting of text should truncate down to maxlength.
  • Disabling of javascript is always possible, so length validation needs to be applied on server side as well.
  • Now that javascript is in play, browser compatability becomes a bigger problem.

That's pretty nasty stuff to have to perform -- and worse, you're given no warning that you need to perform it.

The API tells you that there is a maxlength property you can use... but the API, in this case, is lying.

I'm not really concerned with this problem technically. And I think the asp.net abstraction is so extreme that it's admirable. I'd like to know how to patch this kind of leak.

Here's what I'm wondering:

Is there a way the text box class could have been implemented so that you get a compile error for setting the maxlength property when the textmode is multiline?

That would be enough to make it a safe abstraction in my books. It's more extreme than the static typing afforded by most static type systems.

I expect that such a constraint could be achieved with a language/tool like Spec#.

An alternative would be to throw an exception when setting the maxlength property if the textbox type is multi-line, and vice versa. But that seems like quite a faulty approach.

I'm just not happy about this at all. I think I will need to write a very stern letter to Scott Guthrie.





'Steve' on Mon, 26 May 2008 19:14:31 GMT, sez:

I too was stung by this particular "feature". To get around it I developed a control extender to perform the tasks you've highlighted in your article, which I then put up on codeplex (http://www.codeplex.com/ajaxcontrolextenders). Check it out, see if you find it handy and feel free to modify it if it's not quite what you wanted :)



'mike' on Mon, 26 May 2008 20:08:57 GMT, sez:

>Is there a way the text box class could have been implemented so that you get a compile error for setting the maxlength property when the textmode is multiline?

That doesn't seem to me like it would solve the problem. If the abstraction is that a single TextBox class renders the appropriate, you know, stuff, and if the maxlength property is available on that class, why should I end up with compile-time errors because I in all innocence set this property when textmode happens to be set to multiline mode? Understanding why maxlength doesn't work if the box is set to multiline is a big ol' leaky hole in the abstraction, no?

The correct solution (again, as it seems to me) is to have the TextBox class render the appropriate, you know, stuff to make it all happen correctly. Or to change the model so that the multiline text box inherits via a different path that ends up with that class not exposing a maxlength property.

But what do I know? I'm just a VB guy.



'lb' on Mon, 26 May 2008 20:39:53 GMT, sez:

@steve -- that is excellent work. It's quite a bunch of dependencies to take for getting around just this one problem. But there's a good chance the developer has already taken onboard the ajax control toolkit, so this is well mitigated.

Open sourcing your solution like that is also very good, as it means that any bugs/edge cases you've missed can be raised and addressed.

@mike

>have the TextBox class render the
>appropriate, you know, stuff

This would be pretty hard to do -- and it would still be leaky. (Would suddenly require javascript for example).

>change the model so that the multiline
>text box inherits via a different path

I thought about that... then you'd have <asp:TextBox and <asp:TextArea ....
this would be a good solution from my POV but wouldn't match with the Asp.net webforms (implied) goal of trying to make the web look like a big old VB6 application.

But more importantly Mike, did you like the use of the plural 'textboxen' ? I had you in mind when I wrote that one ;-)



'Dom' on Mon, 26 May 2008 20:50:19 GMT, sez:

Nasty business this. Here's a solution I've used in the past which utilises a behavior:

In your stylesheet, add:
TEXTAREA { behavior: url(maxlength.htc);}

Save the following into a file called 'maxlenth.htc':
<PUBLIC:COMPONENT id="bhvMaxlength" urn="maf:Maxlength">
<PUBLIC:PROPERTY name="maxLength" />
<PUBLIC:ATTACH event="onkeypress" handler="doKeypress" />
<PUBLIC:ATTACH event="onbeforepaste" handler="doBeforePaste" />
<PUBLIC:ATTACH event="onpaste" handler="doPaste" />

<SCRIPT language="JScript">
// Keep user from entering more than maxLength characters
function doKeypress(){
if(maxLength && value.length > maxLength-1){
event.returnValue = false;
maxLength = parseInt(maxLength);
}
}
// Cancel default behavior
function doBeforePaste(){
if(maxLength)
event.returnValue = false;
}
// Cancel default behavior and create a new paste routine
function doPaste(){
if(maxLength){
event.returnValue = false;
maxLength = parseInt(maxLength);
var oTR = element.document.selection.createRange();
var iInsertLength = maxLength - value.length + oTR.text.length;
var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
oTR.text = sData;
}
}
</SCRIPT>
</PUBLIC:COMPONENT>

Now you're maxlength property on your textarea will be respected:
<TEXTAREA MAXLENGTH=50></TEXTAREA>

It uses Javascript of course. You should use a validator on the server side to ensure nothing is getting past, for example if JS is turned off in the browser.

The control extender solution is cool too.



'Dom' on Mon, 26 May 2008 21:00:25 GMT, sez:

Oh I forgot to mention, if you're not specifically targeting IE, you might want to convert this script to a standard JS file, rather than a JScript Behaviour.



'Doekman' on Tue, 27 May 2008 13:45:37 GMT, sez:

With compile time metaprogramming (or Template metaprogramming on wikipedia) you could do something. Someone at fogcreek wrote something about Wasabi and compile time metaprogramming.

Another edge case: a new line is in IE 2 characters, but in Firefox it's 1 character...




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. But the right to delete any post for any reason is reserved. Don't make me do it. Comments may be republished, emailed to your loved ones or printed and used as toilet paper. Who reads this legal bit anyhow?

TimeSnapper is a life analysis system that stores and plays-back your computer use. It makes timesheet recording a breeze, helps you recover lost work and shows you how to sharpen your act.

TimeSnapper won last year's Developer Competition at Larkware.com, and is used by over 10,000 people.

Articles

Alan Kay on 'The Camel has Two Humps' Alan Kay on 'The Camel has Two Humps'
is the music inside the piano? is the music inside the piano?
The Bluffer's Guide To Yegge: Business Requirements R Bullsh*t The Bluffer's Guide To Yegge: Business Requirements R Bullsh*t
Prototype Ready for Launch Prototype Ready for Launch
Idea: a poor man's eye-tracking heatmap for win forms Idea: a poor man's eye-tracking heatmap for win forms
'The Register' seems to have plagiarised Mary Jo Foley 'The Register' seems to have plagiarised Mary Jo Foley
A magic goal for software businesses A magic goal for software businesses
A to Z of Software Methodologies A to Z of Software Methodologies
TimeSnapper in Music! TimeSnapper in Music!
Fixing problems can give you a glimpse of something terrible Fixing problems can give you a glimpse of something terrible
Web Tablet: Toward Less Complexity Web Tablet: Toward Less Complexity
Do they store the code for TFS in TFS? Do they store the code for TFS in TFS?
Sudden TimeSnapper Discount! Sudden TimeSnapper Discount!
How Can Microsoft Beat Google? How Can Microsoft Beat Google?
TimeSnapper 3.1: Attack of the the Red/Green Stripes TimeSnapper 3.1: Attack of the the Red/Green Stripes
21 tools used in our MicroISV 21 tools used in our MicroISV
Lost Treasures of the DOS World: tree! Lost Treasures of the DOS World: tree!
The Virtual Machine Machine and the Virtual Virtual Machine The Virtual Machine Machine and the Virtual Virtual Machine
Should Linq To Sql Go Should Linq To Sql Go "Open Source"?
Redux: New Synchronisation Idea Overlooked By Microsoft Redux: New Synchronisation Idea Overlooked By Microsoft
New Synchronisation Idea Overlooked By Microsoft Live team New Synchronisation Idea Overlooked By Microsoft Live team
Visual Studio UX Taskforce, Office UX Taskforce... etc. Visual Studio UX Taskforce, Office UX Taskforce... etc.
How to be Jeff Atwood How to be Jeff Atwood

Archives .: secretGeek :: Complete Archives :.
25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Top 10 SecretGeek articles Top 10 SecretGeek articles

Downloads

TimeSnapper -- Automated Screenshot Journal TimeSnapper.com    
Version 3.1: instant productivity profiles

ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Next Action NextAction
Managing the top of your mind



[powered by Google] 


World's Simplest Code Generator (html edition) World's Simplest Code Generator
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker
How to be depressed How to be depressed
You are not inadequate.



Recommended Reading

The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Reginald Braithwaite
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Joel Pobar
Eric Sink
Joel Spolsky
Des Traynor

Aggregated Links

programming.reddit.com
dzone
dot net kicks

Human Link Machines

interesting finds
a continuous learner's weblog
arjan's world
n links today
new and notable
morning coffee
learning .net
weekly link post
(my del.icio.us account)

LinkedIn profile
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2006 .: privacy

home .: about .: sign up .: sitemap .: RSS .: © Leon Bambrick 2006 .: privacy