mercoledì 13 giugno 2007

Preventing double postback

Today I had to make sure a certain button could not be pressed twice, to avoid processing errors. Initially I just set the disabled property to true, but that would not work since postback from disabled controls is inhibited. I invoked manually the postback, and it worked, but broke when validators prevented the postback. After a little bit of wondering, I crafted this small routine, to be placed in a Page-derived class for simplicity.

/// <summary>
/// Makes a certain button one-shot only,
/// preserving validator functionality
/// </summary>
/// <param name="btn">The button that can't be clicked twice</param>
protected void RegisterSinglePostButton(Button btn)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("if (typeof(Page_ClientValidate) == 'function') { ");
sb.Append("if (Page_ClientValidate() == false) { return false; }} ");
sb.Append("this.disabled = true;");
sb.Append(ClientScript.GetPostBackEventReference(btn, ""));
sb.Append(";");
btn.Attributes.Add("onclick", sb.ToString());
}

It can be easily transformed in a control if needed, for further clarity.

sabato 9 giugno 2007

A small step for a man

Just a small accomplishment, yet I'm very happy. In the last days I was having a lot of 404 reports for a no-longer existing page on SkakkiNostri. The referrer page was null, so I had to find the source myself. I grep'd the source code, queried nearly every table in the database, but there was no link to that page there. So chances were a) some search engine b) some user.
Looking at the UserAgent/IP address, I quickly found it wasn't a search engine. So probably it had a user that dumbily had bookmarked that page, and now used my 404 error page to come back to the site. I have been thinking about what I could do to avoid this error, then I had a sudden realization: I could just track down the user using the cookies collection and send him a private message. Guess what? It worked. The user wasn't understanding what a 404 error was, but could access the site, so he was happy. Nonetheless explaining the situation to him we have been to fix the wrong link in the Favorites, and I'm no longer receiving emails. Well, not for that error :)