Wednesday, 4 July 2007

How to Set the Maximum Length of a MultiLine TextBox

The MaxLength property of a TextBox control has no effect when the TextMode is set to MultiLine. The reason for this is that a MultiLine TextBox is rendered as a <textarea> tag, which does not have a maximum length attribute:

<textarea name="txtComments" rows="2" cols="20" id="txtComments">

In contrast, a TextBox with its TextMode set to SingleLine is rendered as an <input> tag, which has the maxlength attribute:

<input name="txtComments" type="text" maxlength="5" id="txtComments" />

If you wish to restrict the amount of text in a MultiLine TextBox, the workaround is to use a RegularExpressionValidator control. In the following example, the validation expression allows between 0 and 5 alphanumeric characters to be entered:

string strMaxLength = "5";

revComments.ValidationExpression = "\\w{0," + strMaxLength + "}$";

Sunday, 1 July 2007

Always Use Response.End() After FormsAuthentication.RedirectToLoginPage()

Here's something else that wasn't immediately apparent to me:

If you’re using FormsAuthentication.RedirectToLoginPage() to direct unauthenticated users to a login page, you must follow that statement with a Response.End() if the page would otherwise continue loading content. Although the code appears to branch, the redirect does not stop the execution of the rest of the page.

Redirects appear to work fine in a browser (and would pass all UI tests). They issue an “object moved” status, causing the browser to reload a new page. However, this reload relies on the client’s browser taking this action. If you inspect the response (eg. using telnet), you'll see that when browsing to a protected page, which has the redirect in the Page_Load handler, the “object moved” flag is correctly set, but the content following FormsAuthentication.RedirectToLoginPage() continues to be output, completely negating the purpose of log-in.

The solution is to add Response.End() after the redirect. The output is then correctly terminated as the following telnet session shows (click on the image to view it in full):

Screen shot of a command line telnet session

Do Not Use Underscores in Host Names

As part of a recent development task, I’d written some code to log users in to an extranet. It worked fine in Firefox, but when used in IE, it kept redirecting users back to the login screen. Debugging showed that users were being successfully authenticated, but that this was being lost as soon as the user tried to navigate to another page. After a long and painful process and the enlisting of help from colleagues, the problem was traced to an underscore in the host name (ie. the hosts file had an entry similar to “”). Is was only half chance that the culprit was discovered—we tried to add a host header in IIS and it complained about invalid characters.

It took about three days of project time and much hair-pulling to pin down this obscure issue. One to note!