Wednesday, 27 February 2008

How to abort asynchronous ASP.Net Ajax method calls

This blog post is about ASP.Net Ajax calls (Update panel and such), if you are interested in aborting jQuery.ajax calls, just call abort() on the ajax return object.

Kamal Balwani asked for my help on the blog chat today and asked for the solution for a really annoying issue. He was opening a window when pressing a button on an ASP.Net page and that window used web services to request data from the server repeatedly. The problem was when the window was closed and FireFox (the error did not appear on Internet Explorer) showed a 'Sys is not defined' error on this javascript line: _this._webRequest.completed(Sys.EventArgs.Empty);.

It was a silly error, really. There was this javascript object Sys.Net.XMLHttpExecutor and it had a function defined called _onReadyStateChange where a completed function received Sys.EventArgs.Empty as an argument. At that time, though, the page was unloaded as well as any objects defined in it. I consider this a FireFox bug, as any javascript function should not try to access an object that was unloaded already.

Anyway, going through the Microsoft Ajax library is a nightmare. I am sure they had clear patterns in mind when they designed it this way but for me it was a long waste of time trying to get my head around it. Finally I've decided that the only solution here was to abort the last Ajax request and so I've reached these two posts:

Cancel a Web Service Call in Asp.net Ajax
How to cancel the call to web service.

Bottom line, you need to use the abort function on a WebRequestExecutor object which one can get from using the get_executor function on a WebRequest object which should be returned by a scriptmethod call.

But you see, when you execute TestService.MyMethod you get no return value. What you need to do is use TestService._staticInstance.MyMethod which returns the WebRequest object required! Good luck figuring that out without Googling for it.

From then on the ride was smooth: add an array of web requests and at the window.onbeforeunloading event, just abort them all.

Here is the code for the popup window:

<body onload = "runMethod();" onbeforeunload = "KillRequests();">

function runMethod() {
   if (!window._webRequests) window._webRequests = Array();
   _webRequests[_webRequests.length]
      = TestService._staticInstance
        .MyMethod(OnSuccess, OnTimeout);
   }


function OnSuccess(result) {
   //do something with the result
   setTimeout(runMethod, 500);
   }


function OnTimeout(result) {
   setTimeout(runMethod, 500);
   }


function KillRequests() {
   if (!window._webRequests) return;
   for (var c = 0; c < window._webRequests.length; c++) {
      if (window._webRequests[c]) {
         var executor = window._webRequests[c].get_executor();
         if (executor.get_started()) executor.abort();
         }
      }
   }

Tuesday, 26 February 2008

Making the AjaxToolKit TabContainer tabs vertical

A chat user asked me the other day of how does one put the tabs in the AjaxToolKit TabContainer vertically and I had no idea. I've decided to do it today and write this blog post, maybe he'll come back and he'd get the answer.

So, the request is simple: take a web site with a TabContainer in it and make it show the tabs vertically. I can only assume that the vertical tabs would go on the left and the content in the right. So I took the Internet Developer Toolbar and analysed the html output of a page with four static tabs. I added a <style> tag with CSS classes and started making changes until it worked. Unfortunately, the same setup would not work on Firefox, so I had to repeat the process using Firebug to analyse the page output. In the end this is the result:
<style>
.ajax__tab_header {
float:left;
}
.ajax__tab_body {
/*float:left;*/
margin-left:220px;
}
.ajax__tab_outer {
display:block !important;
}
.ajax__tab_tab{
/*min-width:200px;*/
width:200px;
height:auto !important;
}
</style>
.

Add this on top of your page or include it in your CSS and the tabs will appear vertically.

Now for a bit of explaining.
  • First of all this does not overwrite the CSS that the TabContainer loads because it is organized under a general ajax__tab_xp class like: .ajax__tab_xp .ajax__tab_header .
  • Then the width of 200px is arbitrary. I used it to keep the vertical tabs at the same width. I tried using min-width first, but it won't display right in Firefox.
  • Another point is about the ajax__tab_body class that I tried to set up first as float left, which would place the body div next to the tabs div, however this breaks if the body tab is wider and the content would appear underneath the tabs div. Thanks to my colleague Romeo I used the margin-left trick. 220px is enough to work in both IE and Firefox. It can be made smaller (closer to 200px)if the default IE body margin would be 0.
  • The !important keyword is placed to overwrite some settings that are already set up in the original TabContainer CSS.
  • Last issue: now the right panel will be truncated if it gets too large. You should control the overflow of that div, although, as far as I am concerned, my job is done


As a kind of disclaimer, I am not a CSS expert. If you know of a better way of doing this, please let me know.

Monday, 25 February 2008

Templated Controls / Add UpdatePanels programatically

I named this post so because I started researching something that a chat user asked me: how do you add UpdatePanels programatically to a page. You see, the actual problem was that he couldn't add controls to the UpdatePanel after adding it to the page and that was because the UpdatePanel is a templated control, in other words it contains one or more objects that inherit from ITemplate and all the control's children are part of these templates.

So, the required application is like this: A page that has a button that does nothing but a regular postback and another button that adds an UpdatePanel. Each update panel must contain a textbox and a button. When the button is pressed, the textbox must fill with the current time only in that particular UpdatePanel. If the regular postback button is pressed, the UpdatePanels must remain on the page.

What are the possible issues?
First of all, the UpdatePanels must survive postbacks. That means that you have to actually create them every time the page loads, therefore inside Page_Load. Note: we could add them in Page_Init and in fact that's where they are added when getting the controls from the aspx file of a page, but during Init, the ViewState is not accessable!
Then, there is the adding of the UpdatePanels. It is done in a Click event from a button, one that is done AFTER the Page_Load, therefore adding of an UpdatePanel must also be done there. Note: we could put the CreatePanels method in Page_LoadComplete, but then the controls in the update panel will not respond to any events, since the Load phase is already complete.
There is the matter of how we add the TextBox and the Button in each UpdatePanel. The most elegant solution is to use a Web User Control. This way one can visually control the content and layout of each UpdatePanel and also (most important for our application) add code to it!
Now there is the matter of the ITemplate object that each UpdatePanel must have as a ContentTemplate. This is done via the Page.LoadTemplate method! We you give it the virtual path to the ascx file and it returns an ITemplate. It's that easy!

Update:if you by any chance want to add controls programatically to the UpdatePanel, use the ContentTemplateContainer property of the UpdatePanel like this:
updatePanel.ContentTemplateContainer.Controls.Add(new TextBox());


Enough chit-chat. Here is the complete code for the application, the DynamicUpdatePanels page and the ucUpdatePanelTemplate web user control:
DynamicUpdatePanels.aspx.cs
using System;
using System.Web.UI;

public partial class DynamicUpdatePanels : Page
{
private int? _nrPanels;

public int NrPanels
{
get
{
if (_nrPanels == null)
{
if (ViewState["NrPanels"] == null)
NrPanels = 0;
else
NrPanels = (int) ViewState["NrPanels"];
}
return _nrPanels.Value;
}
set
{
_nrPanels = value;
ViewState["NrPanels"] = value;
}
}

protected void Page_Load(object sender, EventArgs e)
{
CreatePanels();
}

private void CreatePanels()
{
for (int i = 0; i < NrPanels; i++)
{
AddPanel();
}
}

private void AddPanel()
{
UpdatePanel up = new UpdatePanel();
up.UpdateMode = UpdatePanelUpdateMode.Conditional;
up.ContentTemplate = Page.LoadTemplate("~/ucUpdatePanelTemplate.ascx");
pnlTest.Controls.Add(up);
}

protected void btnAdd_Click(object sender, EventArgs e)
{
NrPanels++;
AddPanel();
}
}


DynamicUpdatePanels.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicUpdatePanels.aspx.cs"
Inherits="DynamicUpdatePanels" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Panel ID="pnlTest" runat="server">
</asp:Panel>
<asp:Button ID="btnAdd" runat="server" Text="Add Panel" OnClick="btnAdd_Click" />
<asp:Button ID="btnPostBack" runat="server" Text="Postback" />
</form>
</body>
</html>


ucUpdatePanelTemplate.ascx.cs
using System;
using System.Web.UI;

public partial class ucUpdatePanelTemplate : UserControl
{
protected void btnAjax_Click(object sender, EventArgs e)
{
tbSomething.Text = DateTime.Now.ToString();
}
}


ucUpdatePanelTemplate.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ucUpdatePanelTemplate.ascx.cs"
Inherits="ucUpdatePanelTemplate" %>

<asp:TextBox ID="tbSomething" runat="server"></asp:TextBox>
<asp:Button ID="btnAjax" runat="server" OnClick="btnAjax_Click" />


That's it, folks!

Thursday, 21 February 2008

Agile Development, another misunderstood buzzword

Agile development is something of a growing software culture. Every dev team is trying to become agile. Programmers I know working like that are all happy and evangelizing the concept as the best thing since the fire simulation algorithm. The word is that Agile gives control back to the developer.

So, what does a code monkey have do to become agile? (and no tree algorithm jokes here, please!). As experience dictates, Google for "become Agile in 11 seconds" and see what tools one can download and integrate in the personal toolbox! Surprise! There are tools, but they only help you when you are already agile. WTF? It was supposed to be a developer empowering thing!

Actually, this has an only marginal connection to the developer. Agile development is actually a management strategy. No programmer can become agile without the support of their manager. Management in itself is the application of scientific methods to achieve business goals, which are, almost every time, to maximize profits. You see, managers have noticed that they could hardly quantify programmer work. Software development was becoming more artsy and less scientific as technology grew ever faster and more complex.

The typical development cycle of a piece of software is to plan it (sort of) do stuff to it depending on the planning (which always results in changing the original plan or ignoring it altogether), then show it to the customer. They will, almost every time, just applaud and ask you "ok, this is nice (albeit full of bugs), but where is what I wanted?". The manager then gets scolded for not doing their job. But how could one possibly know what the client dreamed of when they said something completely different at the start?

So, what does a manager do when they have a big problem they can't get their hands on? They split it in smaller problems! Divide et Impera! said the Latin managers of old. So the Agile solution was to copy the development process in its entirety, make it as small as possible, then repeat it until it reaches the original size. It's like when you kill the monster at the boss level and he splits in many small bosses (let's call them middle managers) that you have to kill individually to continue the game. Hopefully I have explained this in a way most code monkeys would understand :).

What about empowering the developer? It was a really nice side effect, one that was taken into consideration at the beginning, of course, but I am sure exceeded the expectations of the designers of the process. You see, at the end of each iteration the application should work, somehow, and also be tested, documented, code reviewed and client approved. The client will undoubtedly notice a discrepancy between what he wanted and what was produced, but he can give feedback a lot sooner than at the end of the project. The developer doesn't have to work their ass off to finish the product, sometimes ignoring the most basic testing or documenting techniques in favour of speed, and then be forced to start work almost from scratch because the client either changed his mind or was not understood properly. Therefore there is an increase in motivation and thus productivity and a decrease in unnecessary work. This is also incorporated in one the agile principles YAGNI, which is actually a really buzzy and ugly acronym for "you aren't gonna need it" - in other words, do the least work to achieve the exact desired result.

But most importantly, this is a managerial process, one that is now easy to analyse and even quantify (since the idea to do as much automated testing as possible). If the bugs are too numerous, then testing must be improved. If code is too obscure, code review and refactoring must be done. If nobody knows how to use the product, documentation is needed. But only for the last small bit that was done. Even more cool, the documentation, code review and even refactoring can be done on the code from the previous iteration, while coders are working on the current one!

So, to summarize: to be agile means that your management has decided on a new strategy and you understand the principles enough to get the tools that would make it easier to work under them as well as design your applications to neatly mold to the concept. It does NOT mean you get some library or development tool and it does things for you. There is not an agilizer application (yet? :) take a look at Pex) and the different software patterns like MVC or MVP are used to facilitate the technical solution found to solve the managerial problem of quantifying results (in this case quality) which is Unit Testing.

It's not that Agile Development is not a good idea. Managers don't really see eye to eye with programmers because they have completely different goals - managers see things from the business perspective while developers see it from the beauty and functionality of code. It's like physicists and mathematicians all over again - but both are (or should be) scientific types that try to solve problems in the best possible way. Agile is a happy intersection of their goals, but as it happens, must be implemented in both worlds simultaneously.

Urban subculture for children sucks!

You thought the World Sucks series had ended? No, it is just in the process of gathering data for cool new posts! This one is about moronic shows on children TV! Do their parents know what "children-centric" stuff their kids watch?

First of all I must explain what "manele" is. It is a kind of music with Arabic and Romanian folk music influences that has become a symbol of a type of Romanian urban subculture inspired from tribalism. You know the type, they are never original: members call themselves a family, they call each other brother, they dress and behave in a "manly" fashion, with speech inflexions that are supposed to show how tough and superior they are. It's like the US "African-American" street culture and in many ways it is a local clone of it.

Ok, now for the actual topic of this post. Yesterday I was watching TV (why, you ask? because I haven't bought yet the second computer and my wife commandeered the only one) and I was given the ultimate proof that it makes people dumb. It was a children TV show that involved teenagers from our own time having superpowers in some mystical realm.

So far so good, but then I noticed how their super powers came from a cell phone! To invoke the magical mana they actually typed some number on the phone pad. Then they transformed into colored knights that were heavily inspired from Japanese shows of the same persuasion, basically a guy in a colourful spandex suit and a motorcycle helmet with a silly sword in hand. The colors of the knights were a bright green, a bright cyan, pink, bright magenta, red and yellow! But what shocked me the most was that they spoke in "manele" style, calling each other "brother" and basically street talk! When they actually combined into a big mechanical knight on a big mechanical flying dragon and fought against what looked like a monster hydra with special effects from the old Japanese Godzilla versus [enter stupid monster name here] movies I was laughing my ass off.

No, really, I am not kidding! This was on TV, on a children's channel! Yeah, bro, that's coo'! Gimme five (gay porn looking knights that "couple" with each other to form a really stupid looking toy like fighting machine)! TV sucks, that was obvious, but to actually show this kind of scatological aberration is even beyond my pessimistic expectations.

Thursday, 14 February 2008

Synchronize the IIS log with your own loggers.

Sometimes you need an information like the time taken for a web page to actually reach the client. It is different from the time it takes to create the rendered content as it includes some web server overhead and the actual network transfer. IIS doesn't know anything about your code, so you can't tell it to log everything you need. How do you synchronize the information in the IIS log with the one in your own logging system?

Use the Response.AppendToLog method that will add a custom string to the end of the IIS logged cs-uri-query field. That doesn't help you much, but since you can add any string you want, you can add a key that would help synchronize the two informations.

Quick example:
string key=Guid.NewGuid().ToString();
Response.AppendToLog(" key=["+key+"]");
MyLogger.Write(myInformation,key);


Now you will only have to Regex the cs-uri-query field to find the key, then search the corresponding line in your own log. Simple! Sort of...

Wednesday, 13 February 2008

Bandwidth Throttle for ASP.Net

We were working on a project for a company that suddenly started complaining of slow ASP.Net pages. I optimised what I could, but it seemed to me that it ran pretty fast. Then I find out that some of the customers use a slow Internet connection. The only way to test this was to simulate a slow connection.

But how can one do that on IIS 5.1, the Windows XP web server? After a while of searching I realised that it was the wrong question. I don't need this for other projects and if I did I certainly wouldn't want to slow the entire web server to check it out. Because yes, changing the metadata of the server can, supposedly, change the maximum speed the pages are delivered. But it was simply too much hassle and it wasn't a reusable solution.

My way was to create a Filter for the Response of all pages. Response.Filter is supposed to be a Stream that receives as parameter the previous Response.Filter (which at the very start is Response.OutputStream) and does something to the output of the page. So I've created a BandwidthThrottleFilter object and added it in the MasterPage Page_Load:
Response.Filter=new BandwidthThrottleFilter(Response.Fitler,10000);
. It worked.

Now for the code. Follow these steps:
  1. Create a BandwidthThrottleFilter class that inherits from the abstract class Stream
  2. Add a constructor that receives as parameters a Stream and an integer
  3. Add fields that will get instantiated from these two parameters
  4. Implement all abstract methods of the Stream object and use the same methods from the Stream field
  5. Change the Write method to also call a Delay method that receives as parameter the count parameter of the Write method


That's it. You need only create the Delay method which will do a Thread.Sleep for the duration of time it normally should take to transfer that amount of bytes. Of course, that assumes that the normal speed of transfer is negligeable.

Click to see the whole class code