Tuesday, October 20, 2009

When to use ASP.NET Web Forms and when to use ASP.NET MVC

Disclaimer: I don't work for Microsoft and I have no reason to push one technology over another. I just want to get my thoughts down in writing. With that said...

I've been building websites with ASP.NET web forms for 8 years now. Wow, has it really been that long? I still remember trying out the first ASP.NET public beta. As a performance enthusiast, the biggest thing that appealed to me was the way it was a compiled language unlike classic ASP. And there was indeed a large leap in performance across the board. But as I used it more I began to realize how much of a departure from ASP it really was.

The Magical ASP.NET Web Forms
The whole idea behind ASP.NET web forms was to simplify things for the web developer by almost mimicking the way Windows applications work. When an event is raised, an action is performed. So was born the concept of postbacks and ViewStates to make the modern web application stateful, so to speak. ViewState information is stored in your HTML page to track the state of an HTML form. And postbacks intercept this ViewState data behind the scenes to handle a lot of functionality you'd otherwise have to write yourself. This magical process allows a lot of the built-in web controls to do their thing. Perhaps the most profound of which are the built-in validator controls that automatically handle both client-side and server-side validation.

So this sounds so good, why mess with this system? Well, you may have noticed that I said that the ViewState data is stored in the HTML. The ViewState can sometimes become quite large, adding a lot of bulk to your pages. Not only can this slow down the experience for the user, but it potentially detracts from the SEO (search engine optimization) potential of your pages. One of the goals of SEO should be to achieve the best textual content to HTML ratio possible, so filling your HTML with a bunch of ViewState gibberish isn't going to help your cause.

Secondly, as useful as many of the web controls in ASP.NET web forms are, some of them have their faults. For example, pretty much everything requires a postback. Even the DataPager control used for paging in a DataGrid requires a postback. This is not a good thing for SEO or for the user. So the question remains, if some of these built-in controls have problems like this, then why bother with web forms?

Enter ASP.NET MVC
In some ways ASP.NET MVC is a step backwards. You don't have the dozens of web controls on your side to help you out. At first glance some of the MVC examples may even look like classic ASP to you. But it has some structure to it: models, views, and controllers. It's the whole idea of the separation of layers put into practice.

- Models are designed to to hold your business logic and data access.
- Views are your pages.
- Controllers are designed to tell your application what page to go to and when.


So the idea with all of this is to allow complete control of your rendered markup and application flow while encouraging some structure in your application. MVC doesn't generate or rely on ViewState (yay!), and it promotes this idea of writing URL's with folder names only. In other words, gone are the days of default.aspx. Once again, both of those little details are good for SEO.

So what should I use?
I recently rebuilt my site Regex Hero with ASP.NET MVC. I primarily did it because I wanted to rid my site of ViewState and get the best SEO possible. And I also did it for the learning experience. But I do still think there's a time for both.

If you're building a complicated site with a lot of HTML forms and form interactivity then you may want to stick with ASP.NET web forms. Some of its built-in controls can be a big time saver for the developer and can be worth their little quirks.

But if you're building a public-facing site then the full control of your markup that MVC gives you is a big thing. And if there's not a massive amount of forms to build then I'd strongly consider ASP.NET MVC for the full control of your HTML markup that you'll gain.

Monday, March 23, 2009

VB.NET 2008 - XML parser makes writing Javascript easy

Today I had the need to write some Javascript in an ASP.NET VB code-behind. I was about to do it the old way with quotes and ampersands and underscores.

And then I had a thought. VB in Visual Studio 2008 has a built-in XML parser. So all I have to do is start typing xml and the IDE will recognize it. So why not put the Javascript inside a CDATA tag in some XML and let VB take care of the rest?

It works! Here's an example...

Dim script = <xml>
<![CDATA[
alert("Hello World!");
]]>
</xml>

Response.Write(script.Value)


This makes it so easy to write Javascript in a code-behind, especially when you have a lot of Javascript to write.

Tuesday, December 9, 2008

Redirecting the Default Page (/default.aspx) to the Root (/)

The problem
Today I found that one of the sites I work on is being linked to from other sites in two different ways. Some links had default.aspx at the end, and some didn't. So what? Well, sure technically they both bring up the same page. But the search engines don't see it that way. This means that the link popularity for the home page was being split between two URL's. That's bad.

The search for a solution
So my search began for a solution. I knew that if I simply put the redirection code on default.aspx that I'd create an infinite loop. So I figured I'd put a statement in there to only redirect if "/default.aspx" is in the path. Unfortunately, I quickly found that ASP.NET sees both the "/" and the "/default.aspx" URL's as being the same and impossible to distinguish the difference. I heard some people say that it's possible to do this with an HTTPHandler in .NET, but without any examples I leaned more towards a solution on the IIS side of things. Now for all I know IIS 7 might be able to do what I want natively, but being stuck with IIS 6 it looked as though my only option was to install an ISAPI filter to take care of all this. So that's what I did.

The solution
I stumbled across Ionic's ISAPI Rewrite Filter (IIRF) which is completely free and powerful enough to do exactly what I needed. The information and download link is all found here:
http://www.codeplex.com/IIRF

Follow the instructions in the readme to install it on your IIS server and configure it for your website. You can use one of their sample "IsapiRewrite4.ini" files as a test and then go from there. But if you want to redirect default.aspx to the root of the site as I did, then read on.

I'll show you my ini file in my production environment first, and then explain how it works.

# IsapiRewrite4.ini
#
# ini file for the ISAPI rewriter.
#
# Tue, 9 Dec 2008 01:49
#

RewriteFilterPriority HIGH
RewriteLogLevel 0

# Any incoming URL that starts with /default.aspx will be redirected
# to the root directory while preserving any query strings.

RedirectRule ^/default\.aspx(.*) /$1 [I,R=301]

You can take the above and try it out for yourself and it may just work as is. But as always, I suggest testing thoroughly in a development environment before throwing this out on your live site.



Breaking it down
RewriteFilterPriority HIGH

In production I want IIRF to run as fast as possible since I'm essentially waiting on it to process the rules for every request. Albeit we're talking about imperceivable milliseconds but hey, I'm a speed freak.



RewriteLogLevel 0

This is actually the default setting. RewriteLogLevel 0 means there will be no logging at all done by IIRF. Again, this setting is for pure speed.



RedirectRule ^/default\.aspx(.*) /$1 [I,R=301]

There are a few things going on in this single line of code so allow me to break it down further.



RedirectRule

If you look through the IIRF examples you'll probably notice that they mostly use the RewriteRule command, while I'm using the RedirectRule command. Redirection is what we need here because we want IIRF to return a status code indicating that the page has moved (more on that later).



^/default\.aspx(.*)

This is the URL we're looking to redirect from. It's a parameterized regular expression that matches any URL starting with "/default.aspx"



/$1

This is the URL we're looking to redirect to (but only if the previous regular expression is satisfied). The "$1" part grabs the parameter from the regular expression and puts it into this URL. So in the event someone goes to "/default.aspx?animal=monkey" they will be redirected to "/?animal=monkey"



[I,R=301]

These are both modifiers documented in the IIRF readme. The "I" modifier specifies case-insensitive matching, which is what we want. And the "R=301" modifier specifies to use a 301 redirection, which is perfect for the search engines. The 301 status code specifies that a page has permanently moved. And that means that any link popularity from the old URL will be carried onto the new URL.



In effect, I've allowed the link popularity between "/" and "/default.aspx" to join forces, increasing the chances of the home page to place well in Google search results. At this point it's just a matter of time before Google re-indexes the site. I anticipate the PageRank and the traffic for the home page will go up so I'll be keeping an eye on it.

Monday, June 30, 2008

"Give and You Shall Receive" - A Guide to Improving Your Website

There's no doubt marketing companies have a tough job with websites. They're called upon to drive more traffic to your site and/or improve conversion rates or sales. These days there are marketing companies who specialize in all of this and even perform search engine optimization (SEO) services as well. And SEO has been a growing industry in recent years. The goal of an SEO company is to improve your placement in the search engines. Of course, Google has such an overwhelming presence that you could call the process "Google optimization," but I digress.

SEO involves following best practices with html page design. Google looks at many factors to determine relevance. But in no particular order the 4 major factors are:
1.) Page titles (anything inside the <title></title> tags)
2.) URL's
3.) Meta keywords and description
4.) Content

So you should use:
1.) unique titles for every page
2.) page names that are relevant to the page's content
3.) meta keywords and meta description that describe the page's content
4.) text and text links throughout the site (relying on text more than images)

The problem I've seen is that the approach towards SEO can sometimes get a little out of hand. I've seen examples where multiple pages are created on a site with very, very similar content with only slightly different wording. The whole reason for creating these near-duplicate pages is to saturate the site with keywords (what the users are searching for to find your site). The problem then is that these redundant pages seem strangely out of place to any human looking at the site. This is just one form of SEO "trickery" I've seen that can detract from the user's experience when they're actually trying to read the content on your site.

OK, let's say that you have good placement on the search engines but you want to improve your conversion rate. In the case of an e-commerce site, a sale can be synonomous with a conversion. Or in the case of a site for insurance, completing an online application could be defined as a conversion. In either case a user starts out looking through the site. Perhaps they'll read a few of your pages, or perhaps they won't. And then, if you have it your way, they eventually perform the action you're wanting them to. There's a science behind improving the conversion rate. Often times a marketing company will suggest A/B testing to test if a change shows in improvement in the statistics. The problem I've seen is we can sometimes become so obsessed with the conversion rate that we don't want to do anything to screw it up. We don't want to scare off users, and sometimes we'll even lie or we don't tell them the truth up front in effort to get the user to do what we want. And on top of that, some of the decisions around trying to optimize conversion rate can negatively influence the usability of the site.

My Way or the Highway
So here's my proposition, and it's simple: Give and you shall receive. In other words, often times what is best for the user is also best for you. By this point, the article may read as if I'm saying that SEO and marketing services are evil. And I certainly don't mean that, but this is a reminder that your priority should always be to make your customer happy. And you may have to remind your marketing division of this too.

Write Compelling Content
My advice is to write lots of useful content or articles related to your website's goals. If you sell cookbooks, write up some free recipes to bring people to your site. If you're selling some sort of fitness program, write a detailed synopsis and free advice that your audience can benefit from. This will give your company credibility and provide a good service to the public.

Design Carefully for Good Usability
Also focus on usability patterns and apply them to your site. It should be easy to find information on your site, easy to find products, and especially easy to buy a product or complete an application. Use your common sense in all of this, but also try user testing and as simple as it seems try basing your design on proven formulas in some of the hugely popular websites out there. For example, users are accustomed to using sites like amazon.com, buy.com, hrblock.com, etc. So you can take elements or ideas from their design and implement them in a similar fashion for your own site.

The Benefits
Never underestimate the power of a happy customer. One of the big benefits of my suggestions is that users tend to link to "good" websites. And the more links you have from other sites, the better link popularity you'll have. Link popularity is the other major factor in search engine placement. If your site is linked to from hundreds of other websites, then your chance of showing up on the first page of the search results can become far better. In the user's mind a "good" website may be one with good products, good prices, good information, good service, or maybe all of the above. But if you give your users a good overall experience at your website, you will receive more traffic and higher conversion rates. So that is what we as website owners should strive for.

Below are a couple of valuable resources to help you get started:

Website Optimization ( www.websiteoptimization.com ) - This site is packed with good information on optimizing your website for speed, but also information regarding SEO and usability.

Jakob Nielsen's website ( www.useit.com ) - Jakob is an authority in the web world when it comes to usability studies.

Tuesday, February 5, 2008

NSIS: Another Gem from Nullsoft

I figure I'll follow a bad review with a good one.

NSIS is a scriptable installation system designed to create Windows installers. It's open-source, free, and becoming more and more popular as time goes on. Google uses it for many of their software applications, as does Yahoo, McAfee, Amazon, etc, etc. You can find a list of more companies using it here.

I used NSIS to create the installer for a certain VB.NET software application I've been developing and supporting since 2004. But NSIS wasn't my first choice. In fact my first choice was InstallShield because that's what the consulting company I was working for at the time had used in the past. I wrote about 20 different installers with it, and they worked pretty well, some of the time. But eventually I got fed up with InstallShield's awful support for what I considered simple custom tasks. When I eventually figured out how to do some of what I wanted, I still faced problems with InstallShield's flaky behavior.

I was determined to find a replacement for InstallShield, so I looked at WISE. It was also a disappointing experience for me as the IDE itself liked to crash on me from time to time as many others have reported. So WISE was out.

I tried a few other installers and eventually I came to NSIS. At first I was skeptical since it was free, open-source, and I hadn't heard of it before. I figured that a free open-source installer like this couldn't possibly compete with the likes of InstallShield and WISE which seem to be regarded as industry standards for some reason.

The thing is, using NSIS is a COMPLETELY different experience from InstallShield and WISE because absolutely everything is done through scripting which can seem like a daunting task at first. But I used the HM NIS Edit tool to build my first NSIS installer. The wizard took me through the basic steps of creating my first installer, and it wrote the code I needed to get started. The code was a little weird at first but I'm a programmer so I got the hang of it eventually. Furthermore, I found the user-submitted code examples and tutorials on their sourceforge site to be very helpful.

I was able to do EVERYTHING I wanted with NSIS. I've been using it on a fairly large scale now for the past 3 years. And I've had absolutely no complaints with flaky behavior from thousands of users now. In the latest release of our completely rewritten software I made the installer first automatically detect if Windows Installer 3.1 is installed, and then download & install it if necessary. Then it'll check if .NET 2.0 (or later) is installed on the machine and download it from Microsoft if it's not. It will also perform a CRC check to ensure the installer itself is not corrupt, assign appropriate file associations for the software, and check if the logged in user has administrative privileges. All of this works perfectly.

On top of that, the final executable NSIS produces is much smaller than an equivalent InstallShield exe. And an NSIS installer performs the installation MUCH faster than InstallShield as well.

So for me it was a no brainer. Once I got over the initial learning curve of NSIS I never looked back. I highly recommend it for any programmer who wants to build good Windows Installer packages for their software.