jQuery Ajax Beats ASP.NET Ajax

ASP.NET Ajax is a good technology in theory, but the implementation in practice is anything but smooth. There are many little ‘quirks’ that ASP.NET Ajax does to your page; these quirks almost entirely revolve around the handling of viewstate during ajax calls.

ASP.NET Ajax passes the viewstate to the server and back during things like UpdatePanel updates. This is done to insure that the viewstate is always up to date, even if the page information changes during the Ajax call. Many Ajax calls, however, don’t require any changes to viewstate. Unfortunately, when the viewstate comes back, I’ve found many unpredictable results – things like page titles changing and breaks in back-button functionality in some scenarios. More importantly, these bugs are hard to track down and understand, in my experience. On top of this, viewstate is usually pretty large, which slows down ASP.NET Ajax requests and transfers more data across the wire, increasing bandwidth costs.

What have I chosen to do instead? Through Encosia, I’ve found that it’s fairly trivial to make jQuery Ajax calls into the codebehind, or even to local web services via JSON. These calls are small (they don’t send viewstate), transparent (they don’t change page information on return unless you explicitly ask to), cross-browser compatible, and rock-solid (like everything in jQuery).

Surely there are quite a few circumstances where ASP.NET Ajax beats out jQuery Ajax (for things like datagrid population, for example). From now on, though, I’ve decided that my default stance will be to write my Ajax calls in jQuery unless I can create a compelling case to do so in another technology.

C# Collapsible Properties

Here’s a sweet way to display properties. Basically, I had a bunch of generic properties that I was using shorthand notation for, and one that was a read-only property which served as an aggregate of a few other properties. I couldn’t shortcut it, but the implementation of it was trivial, so I hid it inside a region whose name looked exactly like a shorthand property. Tough to explain, but easy to understand:

Collapsed Property

Expanded Property

Expanded Property

HybridDictionaries – Careful!

I was refactoring some code the other day, and I noticed that at one point, there was code that created a foreach loop, but it was keeping track of an index inside, by manually incrementing at the end of the foreach loop. Something like this:

int index = 0;

foreach (Widget widget in WidgetBasket)

{

// Do stuff…

index += 1;

}

Well, being the foolhardy coder that I was, I said let’s just change that foreach loop to a for loop, so we can keep track of the index as a part of the loop construct. I’ve done this a thousand times, so I didn’t think much of it. I also didn’t take a minute to look at the data type of Widget, not that it would have helped at that point.

So, I threw my code into test, and lo and behold I started getting null reference exceptions. What the heck – all I did was change a little loop?!?

Well, I dove under the covers, and it only took me a few minutes to find the issue. The Widget object was of type HybridDictionary. If you’re not familiar with a HybridDictionary, it’s one of those built-for-speed collection types, behaving like aListDictionary when it’s small, and switching over to a HashTable when it gets larger. Like all collections I’m aware of, it has an array-style indexer, which enables it’s use in looping constructs.

The rub with HybridDictionaries is that they don’t behave like 0-based indexed array – a foreach will keep returning the next found item until it’s done, but a for loop doesn’t behave like that – the 0th element was null, and so was the 1st, and so on. So, obviously, it’s not a good idea to go with a for loop – they just don’t work.

Thankfully, there is a way to have the HybridDictionary behave normally, but it comes at a performance cost that probably destroys the value of this type of collection in many common uses. You’d just call the CopyTo method, which will copy the dictionary to a one-dimensional, zero-based Array. That’s not all that intuitive, and it’s a trap I bet a lot of people fall into when starting to work with the HybridDictionary.

Given all this mess, I’m not a big fan of the HybridDictionary – give me a generic list any day!

Smart Enumerations, Part II

I’ve made an update to my EnumerationHelpers code since the last release, which you can read about here. Previously, the only attribute that is supported for ‘get’ behavior is the Description attribute. This is all fine and good, but what about when you want to decorate your code with your own custom attributes, yet be able to get at them in a generic fashion?

Enter a brand new EnumerationHelpers method! This method is called GetCustomAttributes, and is written using generics for the best possible performance. Here’s an example of what it’s good for and how to use it:

enum Status
{

 [StatusColor("All is good", Color.Blue)]
 [StatusColor("Copacetic", Color.Pink)] Ok,
 [StatusColor("Uh oh..", Color.Orange)] Warning,
 [StatusColor("Holy Crap!", Color.Red)] Critical,
 [StatusColor("Rapture!!!", Color.Black)] Deadly

};

Status status = Status.Ok;

// Returns StatusColor Array containing the 'All is good' and 'Copacetic' StatusColor attributes.
StatusColor[] colorAttributes = EnumerationHelpers.GetCustomAttributes(status);

status = Status.Deadly;

// Returns StatusColor Array containing the 'Rapture!!!' attribute.
colorAttributes = EnumerationHelpers.GetCustomAttributes(status);

So, now tagging enumerations with information (and functionality) became even easier. There are very valid reasons to use enumerations to store application data, as opposed to say in a file or a database. The reason that I use enums often is that they are fast (since 99% of my enumerations are of type int under the covers) and they offer stronger typing than keeping values externally in data files or databases since the enum values are defined at compile time instead of run time (so less error handling code, too). They are also exceedingly simple to implement and very readable. There are obviously times when enumerations are not appropriate – typically when the data is volatile or when there is a large amount of data that needs to be maintained (the need for recompilation kills value in these situations).

Using this EnumerationHelpers class and some good programming, I’ve been able to implement finite state machines using a single enumeration and a single custom attribute. In this case the enumeration value would represent the current state, and the attribute would be used to hold state-transition information, including the next state. Well, anyway, the code is here, all zipped up for you. Everything is unit tested pretty well, so take a look at that to get a better idea of how to use it.

Hacker Email Address Parsing

It’s pretty common nowadays to see any type of email addresses that are publicly posted on the web to be formatted so that they are hard to spot by spambots that just rip through pages, parsing addresses out and adding them to various nefarious mailing lists. Such addresses often look a lot like “myaddress @ mysite . com” or a variation of such.

One thing that’s always struck me as funny is that a halfway decent programmer can pretty easily use Regular Expressions to parse through text and still be able to grab ‘hidden’ addresses. The idea is that even though these addresses are not traditionally formatted, they must still follow a pattern to be readable/understandable. If there’s a pattern you should be able to model it to some degree of accuracy using regular expressions – that’s exactly what the purpose of regex is. To that end, I decided to see how much effort would be entailed in writing said regular expressions, and how accurate I could make them. It’s important to note that I didn’t spend a lot of time optimizing my regex or getting the kinks out – this was just a toy project. All the regex that follows is C# flavored regex too, so if you use the Perl/JavaScript/whatever other flavor, you’ll have to rewrite them to suit your needs.

Here’s a good regex string that validates email addresses, which I used as a base for my modifications:

w+(?:[-+.]w+)*@w+(?:[-.]w+)*.w+(?:[-.]w+)*

Here was my first address to validate:

webaddress @ somesite . com

I modified my regex as such to allow spaces in an email address:

w+s*(?:[-+.]s*w+)*s*@s*w+s*(?:[-.]s*w+)*.s*w+(?:s*[-.]s*w+)*

Sweet, that worked! The above regex just allows whitespace in the address, and it works remarkably well. Next task:

webaddress dot somethingelse @ blah dot something . com

This address substitutes ‘.’ with the word ‘dot’, but it should still be pretty easy to overcome:

w+s*(?:[-+.'dot']s*w+)*s*@s*w+s*(?:[-.'dot']s*w+)*[.'dot']s*w+(?:s*[-.'dot']s*w+)*

Again, easy as pie. All you have to do is look for ‘dot’. It is trivial to extend this to include things like ‘dash’ and ‘plus’ and ‘period’. Now, let’s throw some illegal characters in there too:

<webaddress>@somesite.com dot au

Here’s the regex I created to solve this one:

w+[sW]*(?:[-+.'dot'][s]*w+)*[sW]*@[sW]*w+[sW]*(?:[-.'dot'][sW]*w+)*[.'dot'][sW]*w+(?:[sW]*[-.'dot'][sW]*w+)*

Hmmm… that regex is getting kind of ugly, but it does what I asked of it (for now). I assume that since I used W, which matches any non-word character, I’m opening myself up for some false positives. Next one up:

webaddress dot blah at findme dotcom

Here’s the regex for that one:

w+[sW]*(?:[-+.'dot'][s]*w+)*[sW]*(?:@|at)[sW]*w+[sW]*(?:[-.'dot'][sW]*w+)*[.'dot'][sW]*w+(?:[sW]*[-.'dot'][sW]*w+)*

There’s only one minor, seemingly trivial difference between this one and the last – it just adds the word ‘at’, much like when I added ‘dot’ earlier. No big deal, right? Well, if I think I may have had some false positives before, let me tell you, it’s really starting to break down now! The word ‘at’ is so ubiquitous in the english language that I ended up with so many false positives when this regex was embedded in random text that the results became almost meaningless. An example of text that would show a false positive now is ‘I met my brother at nine. He was…’, which would find the email address ‘brother@nine.He’ At this point I called it a day – that was a lot of regex to work through!

So, I know that my regex could be formatted much better, and that would help with false positives. If I was getting paid to write these, they would definitely be more polished. However, one thing that I did find is that if you’re really into using obfuscation to hide your email address, using ‘at’ instead of ‘@’ is probably one of the best obfuscation techniques. Take note so you can protect yourself from the evil spambots. Here is a copy of the text that I was working with, if you want to try these techniques on your own.

Disabling an Ajax Timer Control

I just got done fixing an issue that I was having with the ASP.NET AJAX Timer control, and I figured I’d write about it because there doesn’t seem to be like a ton of documentation out there right now as to exactly what is going on.

Here is the scenario: You have an Ajax enabled .aspx page which has an UpdatePanel set to update itself based upon a timed interval from a Timer control. You also have some type of submit button on the page that does a synchronous page submission. So, what happens when you click on the submit button, and before the page submit has run through it’s logic, the timer control trips and causes an asynchronous Ajax post? Well, what I was seeing was that the page would end up in an incongruous state – the submit works, but the page updates itself to show the results of the asynchronous update, not of the synchronous submit action.

This behavior is to be expected, to tell the truth. One of the actions has to win, and it may as well be the last one into the queue instead of the first. So, the real thing we want to do is disable the timer control based upon the submit button being clicked. No problem, I thought – I’ll just disable it in the event handler for the button click, like this:

private void SomeButton_Click(object sender, EventArgs e){

Timer1.Enabled = false();

// Do stuff here…

// Maybe reenable the timer here…

}

Hmmm… that doesn’t seem to work, and here’s why. Since the submit button click is handled server-side, the enabling-disabling action won’t be propagated back to the client until the postback is complete. The timer is a client-side javascript control, so it can (and will) keep working as the page is being posted.

So, what do you do? Well, you’re only really left with one option – disable the timer control on the client side. That means you’re going to be doing it via Javascript. Luckily, I found this post that details all about using Javascript to disable the timer control. Now, all you have to do is hook up a client side event to the timer control and programatically disable it. You can re-enable it in codebehind with the button click handler, too, so you don’t have to do that on the client side. Here’s what I ended up with:

<script language=”javascript” type=”text/javascript”>
<!–
function DisableTimerControl(){

// Disable the ajax timer control before elevating on the client side.
// It will be re-enabled on the server side.
var timerControl = $find(“AjaxUpdateTimer”);

if (timerControl != null){

timerControl._stopTimer();

}
return true;

}
–>
</script>

That wasn’t so bad, was it now? The long and the short of it is that you have to be careful about using Ajax controls, but it is still pretty easy to make them do what you want if you’re on top of things. Either way, Ajax is here to stay, so get used to it!

These are not the Same Thing

In C#, the following two pieces of try-catch code rethrowing are not equivalent. Don’t do the first one; the second one is where it’s at.

try{…}
catch (exception ex)
{

throw ex;

}

try{…}
catch
{

throw;

}

This is because when you rethrow the exception, you’re actually creating a new exception, and the stack trace will show your method as the originator of the exception that you caught and rethrew. The throw ex; syntax is just compiler shorthand and gets expanded into throw new exception(ex);, much like ? : turns into an if-then-else as it’s converted to IL.

Now, you might be tempted to use this technique to mask a call stack, so say an external customer doesn’t need to see the internals of your assembly in the form of a call stack. However, wouldn’t it be more prudent to create a new exception, one where you can customize the message to include your own text and additional information? Perhaps you could even a throw a custom exception of your own? Both are much better ideas, in my book.

OpenGL Aquarium

OpenGL Aquarium

So, in lieu of actually straining myself to come up with an interesting new post, here is a(nother) rehash of some content I created when I was in college (in 1999… ugh, too long ago!). I remember being very proud of this when I wrote it. Nowadays, I still find it a bit amusing, but it lacks a certain polish I like for my apps to have. That, and I bet that the code could use some cleaning up. Maybe, if I find suitable motivation, I will update it for today on the XNA framework or something. If you care to see it in action (the fish swim all over, but that’s about it) the link to download is here.

It’s funny – nowadays I’m a fish enthusiast and hobbyist. However, when I wrote this app in school, that definitely wasn’t the case. I guess I made a good choice. Oh, and expect to see a post soon with the new aquarium layout, as soon as I get around to getting it done. The tank’s going to look awesome!

.NET & Application Pools

[Note: I use the term web application in this post. This is not the Visual Studio 'Web Application' but rather refers to any .NET content that runs under IIS.]

Application pools, on the surface, look to be a wonderful addition to IIS 6.0. However, unless you have a good understanding of how application pools work with regard the .NET framework, you could end up causing some serious damage. This is something that is usually explained in literature, but the impact of it is typically glossed over, so I’m here to help fill the gap.

Application pools are a way to allow web application isolation on a web server. An application pool is just a container for a worker process (w3wp.exe), which is in charge of serving requests for all the applications that it manages. A single application pools can have multiple worker processes running under it (termed a web garden), but a single worker process cannot run across multiple pools. An application pool can, theoretically, manage an infinite amount of applications, but you also have the ability to create more than one, and you can assign your application to any available pool using the IIS console (or programmatically).

iisconsole.jpg

Application pools create isolation in the sense that if there is a failure in one pool (the w3wp.exe process dies), it will not affect the other pools that are running. These failures occur at times, and in the case of web servers that serve multiple web sites, isolation is key – you don’t want your site to go down because someone else killed your worker process. Application pools also have the ability to run under different user credentials, which means you can manage access to certain resources using application pools. Application pools are also agnostic of .NET framework version – the virtual directory is the item that dictates both what
application pool manages it, and the version of the framework that it runs under. You assign an application to an application pool using IIS console.

One strange, and potentially dangerous, thing about application pools is that they can only run one version of the .NET framework at once. This
means that if you try serving an application that runs under .NET 1.1 and another under .NET 2.0 simultaneously, then they had better be under different application pools. What happens if you try running both at the same time? The first application that gets served will work, regardless of the framework version it runs under. The second will fail, and all subsequent requests for either application will fail. The worker process ends up dying an untimely death. How is this an issue? Well here are two very likely scenarios where this behavior can cause problems:

  • A user has just added a new virtual directory and has not been diligent on choosing the correct application pool
  • A web application has been upgraded to a newer version of the .NET framework, and the user updates the framework version on the virtual directory but fails to change to a more appropriate application pool.

So, how does one mitigate risk of application pool failure under this scenario? One of the most important things to do is to make sure you have
at least one application pool for every framework version that your web server supports. Typically, I do this by including the framework version in
the application pool name, for example naming two pools ‘ExamplePool 1.1′ and ‘ExamplePool 2.0.’ This greatly simplifies management. A good way to
see what version of an application pool that you are running under is to open the IIS console and expand the tree node that corresponds to the pool
you are interested in. This will allow you to see what applications are running under a given pool.

apppools.jpg

There are other options available to mitigate the risks of this issue hurting you, but all have significant drawbacks. First, you could create a
different application pool for every application you run. For a few applications this is fine. However, since each pool contains a w3wp.exe
process, a large number of active pools could slow down your server. Second, you could leverage a w3wp.exe process ping that will restart failed
processes. The drawback here is that this only works on one-off instances: a real issue will continuously kill the w3wp.exe process very quickly after
it is restarted. A third option is that you could make sure your application does not target a particular .NET framework version (they are supposedly pretty compatible, but there can be breaking changes from time to time). However, this means that you had the time to test your existing codebase before you introduce a new framework version. The only solution that I’ve found to work is pure diligence.

Describable, Smart Enumerations Helper Class (C# 2.0)

Update – Check out this article for the latest and greatest.

I’ve decided to post an EnumerationHelpers class written in C# 2.0. This class allows you to easily work with description tags on your enumeration values, and search them to pull the appropriate value out based on the description. This is great for times like when you want an enumeration to control a picklist but you don’t want to have to create a switch statement to match the displayed value with the enumeration value. In that respect, it also effectively isolates you from change (but, displayed values never change… right…). Here is an example of how to use it:

enum Status
{
 [Description("This is a new item")] New,
 [Description("This is an existing item")] Existing,
 [Description("This is an old item")] Old,
 DescriptionUnavailable
};

Status s = Status.New;

// Returns "This is a new item"
string strDescription = EnumerationHelpers.GetEnumDescription(s);

// Returns Status.Existing
s = EnumerationHelpers.GetEnumValueFromDescription("This is an existing item");

// Returns Status.Old
s = EnumerationHelpers.GetEnumValueFromDescription("Old");

// Returns "DescriptionUnavailable"
strDescription = EnumerationHelpers.GetEnumDescription(Status.DescriptionUnavailable);

As you can see, it becomes a fairly trivial task to implement describable enumerations. You can also see that it relies on the power of generics, and is type-safe. Feel free to take a look under the hood, and to use it for whatever needs you have. All I ask is that you leave in the copyright on the top of the code. Included in the package is a .csproj which includes the helper class and a set of NUnit tests that can help show you the ropes with the class. It’s available here!