Wednesday, August 27, 2008

Using URL Rewriting For More Friendly Links

As part of an application we're developing at work, I recently did some research on whether it was possible to make the links to items, categories, etc., more friendly to search engines. The links we currently have are something like this: /website/productdetails.aspx?productid=123456. Basically, we pass in a product ID to the productdetails.aspx page. However, it would be nicer to have something more like /website/item/123456/rewritten-item-description.aspx.

I did some research and came up with some code that will work, and not be too intrusive to the rest of the code, or require any changes in IIS. First, we'll add a property to the items that returns a link in the correct format, so that we don't have to duplicate that code in the various places we show the link. To convert the item description to something that looks like a filename, I came up with the following method:

private string CreateLink(string prefix, string id, string description)
{
String format = "{0}/{1}/{2}.aspx";
String fixedDescription = "";
fixedDescription = description.Trim().Replace(" ", "-").Replace("&", "and").Replace("/", "-");

Regex nonWord = new Regex(@"[^\w\-]", RegexOptions.IgnoreCase);
fixedDescription = nonWord.Replace(fixedDescription, "");

fixedDescription = DeAccentCharacters(fixedDescription);

return String.Format(format, prefix, id, fixedDescription);
}

This strips out any non-word characters, replaces spaces and slashes with dashes, ampersands with the word "and" and converts accented characters to their non-accented counterparts (that part is done in DeAccentCharacters(), which I won't post, since it just uses a pre-made lookup table, and isn't that interesting). It then prefixes the name with the prefix and id, basically coming up with what I showed above.

Now that we have links in the correct format, we need to interpret them. Note that it looks like we have a couple of directories there ("item" and "123456") that don't actually exist. We need to intercept the request for this page before ASP.NET has a chance to complain about it not existing. To do that, we add some code in the Global.cs class in the App_Code directory. First, in the Application_Start() method, add this, anywhere in the method:

SetupRewriteRules();

This will set up a list of URL rewriting rules, using regular expressions. Then, in Application_BeginRequest(), add this as the first line, before anything else you may be doing:

RewriteURL();

This calls a new method that interprets the rules created in SetupRewriteRules() and rewrites the URL in the request accordingly.

Next, add this class to the file (at the end is preferable):

private class RewriteRule
{
private Regex rule;
private String rewrite;

public RewriteRule(String ruleRegex, String rewriteText)
{
rule = new Regex(ruleRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);
rewrite = rewriteText;
}

public String Process(String path)
{
Match match = rule.Match(path);

if (match.Success)
{
return rule.Replace(path, rewrite);
}

return string.Empty;
}
}

Next, add a static list to hold these and the SetupRewriteRules() method:

private static List<RewriteRule> rules = new List<RewriteRule>();

private void SetupRewriteRules()
{
rules.Add(new RewriteRule("Item/([^/]*)/(.*).aspx", "/ProductDetails.aspx?productID=$1"));
}

We have more rules, but I'll just show this one. Note that the first parameter is a regular expression that matches "Item/item ID/filename.aspx". The second parameter is what to replace that with. In this case, it takes the first match (the item ID, enclosed in the first set of parentheses), and puts it where the "$1" is in the URL.

Finally, add the RewriteURL() method:

private void RewriteURL()
{
foreach (RewriteRule rule in rules)
{
String subst = rule.Process(HttpContext.Current.Request.Path);
if (subst.Length > 0)
{
HttpContext.Current.RewritePath(subst);
break;
}
}
}

This code iterates through each rule, and if it finds one that matches, it calls RewritePath() using the rewritten URL. This is what actually translates the "friendly" URL into something that works with our application. The great part is that it is totally transparent to the user; they never see the rewritten URL. Postbacks still work fine as well.

I realize there are other ways to do this, like ASP.NET MVC, but our application is pretty much already written, and I'm not wild about going back and redoing it in a totally new technology. This can be retrofitted onto the app without too much pain, and could even be turned off or on with a config file setting if needed.

Wednesday, August 20, 2008

Red Gate Buys .NET Reflector

In a post on his blog today, Lutz Roeder announced that he has sold .NET Reflector to Red Gate Software. This is an indispensible tool for any .NET developer (I can't believe I left it off my list earlier!). I hope Red Gate will continue to support it, especially the free version. We use several of their products at work, and they are a good company, so I have high hopes for it.

Tuesday, August 12, 2008

Favorite Computer Books

I believe all good developers should keep up to date with technology, and one good way to do this is to read technical books. I realize there is a lot of information available on the internet these days, and many people think they can get everything they need from there. However, for some topics, a well-written book is a much better option. With that, here's a list of books that have been useful and/or influential in my programming career:
Note that several of these books are not focused on a specific technology, and thus won't go out of date as soon as a lot of computer books will. I think that's important when deciding what books to buy, especially if you're on a budget. Try and find a book that will last more than the year or so that many tightly-focused books will.

Friday, August 1, 2008

Debugging ASP.Net AJAX Pages

If you've done any ASP.Net AJAX development, you've probably run into the following error message while debugging (Sys.WebForms.PageRequestManagerTimeoutException: The server request timed out):

This happens because the default timeout for asynchronous processing is 90 seconds. This is a reasonable default, and really, nothing in an asynchronous request should take that long. However, if you're stepping through code of any complexity, you can easily exceed that limit. You can fix this by setting the timeout on your script manager, like this:

<asp:ScriptManager ID="MainScriptManager" runat="server" EnablePartialRendering="true" AsyncPostBackTimeout="3600" />

However, you probably don't want that in production. There is also a way to set this in your code-behind, and do it conditionally, based on whether your pages are running in debug mode or not. If you've been doing ASP.Net development for any amount of time you are probably aware that you shouldn't run your production site in with debug enabled in the web.config file. So, how do you tell if that is enabled? In that link, Scott Guthrie mentions that you can use HttpContext.Current.IsDebuggingEnabled to tell. So, the code to set this would look like this:

// if we're running debug mode, increase the async timeout to 1 hour.
// this allows stepping through code without timing out on the front end.
if (HttpContext.Current.IsDebuggingEnabled)
{
MainScriptManager.AsyncPostBackTimeout = 3600;
}

This only increases the timeout if you're running in debug mode. I've implemented this in one of our products, and it has worked great.

Wednesday, July 30, 2008

Too Slow or Too Fast

I had a conversation with a co-worker recently that got me thinking. He had been at a local .Net users' group, and had mentioned that we hadn't upgraded to .Net 3.5 yet. Everyone else was amazed that we weren't taking advantage of this yet.

As I read various blogs, I see lots of companies working on the cutting edge, using things like .Net 3.5, LINQ, the new MVC framework, etc. Sometimes I wonder how they are able to justify moving to these new technologies so quickly. I'm very much in favor of learning new things, and using them where it makes sense, but I think it is also wise to sometimes wait a bit before rushing to upgrade.

We have a product (actually several products, but we consider them one system) with around a million lines of C# code. It currently supports around 400 internal users, as well as 50,000 external users. Our main focus has to be to keep it running, while adding new features and fixing bugs as needed. Without being able to show a tangible benefit of upgrading, we would have a difficult time telling the business that we needed several weeks to convert this system to the latest and greatest offering.

When we made the move to .Net 2.0, we were able to sell them on the fact that it gave us a new web deployment model that would allow us to react to their demands more quickly, as well as the possibility of moving to 64-bit code eventually. At the start of this year, I was given tentative approval to upgrade to .Net 3.5, but since then, we've been so busy that I haven't had a chance. At this point, I'm not sure I would be able to convince anyone that it was worth our time and effort.

Maybe some of the other companies I see adopting the latest thing do so with smaller applications, or with totally new products. Unfortunately, we don't often have the opportunity to do that, since my group's main focus is the large system I mentioned earlier. It does disappoint me somewhat, since I would love to be learning the new technologies, in case I need to find a new job.

Still, it has made me wonder if we are the ones moving too slowly or everyone else is moving too quickly. I know I really don't want to be the one debugging Microsoft's latest code. I've been involved in that before with other products, and it was no fun. We had a product that was delayed over a year while we worked with a vendor to squash all the memory leaks in their DLL.

So, the way I see it, we can either stay with what works until we see a pressing reason to upgrade, or jump in with both feet and deal with the consequences. One is good for business, the other one may be better for my career options.

Wednesday, July 23, 2008

Working From Home

A few months ago, my company made the decision to allow people in the IT department to choose to work from home at least a few days each week. This was partly to help with rising gas prices, and partly to help retain employees, since we've had a hard time filling vacancies recently. I gladly took them up on this, even though I only live about 4 miles from work.

In the time I've been telecommuting, I've learned a few things about how to make it work, at least for me.
  • Have somewhere private. If you have a spouse and/or kids at home, you must have someplace you can go to be totally isolated from them. Having them interrupt you just doesn't work. I'm lucky in that we just finished our basement, and I have a nice office to work from.
  • Have a comfortable chair and a good desk. Before I got my new office, both my chair and my desk were over 10 years old, and would not have made a good environment to to real work in. They were fine for casual use, but not 8 hours a day. I bough an all new desk and chair, and have been happy with that ever since.
  • Have the right equipment. I already had a company-supplied laptop, and I supplement it at home by plugging in a keyboard and mouse, and attaching to my personal monitor, so I can have dual screens. I've had dual screens at work for several years now, and I don't think I could live without it anymore, so that was a must for me. (Some people may be lucky and have their company buy these, but part of the conditions for this was that no extra equipment, beyond a USB headset, would be purchased).
  • Treat going to work just like you would on a normal day where you actually leave home. I still get up at my normal time, shower, get dressed, have breakfast, etc. Then, when 8:00 comes around, I say goodbye to my wife and kids and retreat into my office. I do come out occasionally for breaks, and for lunch, but I try to keep that to a minimum. I know for some people, the attraction of telecommuting is that they can dress like a slob or not shower, but for me, that is part of getting into the right mindset to go to work.
  • Keep track of what you do each day. My manager requires a quick email at the end of the day listing what we accomplished that day. I think that's a good idea, because it keeps me focused on getting as much done as I can so I can show that I've been productive, even though nobody can see me.
  • Keep in touch with your co-workers. We have IP phones and a corporate instant message program in addition to email that helps us all communicate even when nobody's in the office. This is key, since you can't just holler over the cube wall when you need to talk to someone.
Telecommuting has worked out great for me. There are usually fewer distractions, and when I have something intense to work on, I can really focus and get it done. It isn't for everyone; some people may miss the daily interaction with co-workers. But if you can handle it, it can be a real productivity booster. I'm really grateful that my company has allowed us to do this.

Monday, July 21, 2008

Basics: No Warnings

Does your code compile with no warnings? Most developers wouldn't dream of checking in code that didn't compiler without errors, but what about warnings? At other companies I've worked at, the code has been full of warning messages. Some of them were relatively harmless (I was working in legacy C code at the time, and as the compiler go better, more warnings were shown). Others were more critical, and really should have been addressed.

In my current job, the main product I work on has around 1 million lines of code, and I'm proud to say that we keep it warning-free. This is no small feat, since we use XML comments, and have the option turned on that generates a warning whenever one is missing from a public or protected member.

Some people would argue that a warning is just that: a warning. If it isn't an error, why bother fixing it? For one, it clutters up the output window and the error list in Visual Studio. It's no fun having to page through several dozen warnings just to find the error(s) you're looking for.

The most important reason, though, is that often, those warnings may be pointing to something more critical that could be wrong with your code. For example, every time we've upgraded the Infragistics library we use, we've had a number of warnings appear because they are planning on deprecating some methods or properties in a future build, and have marked them as such in the current build. Sure, the code still compiles and runs, but maybe it won't in the next build. Infragistics is giving us advance warning that our code may break. We always make it a point to fix those as part of the upgrade process.

Another warning that I've seen a few times is when a developer declares a method in a class with the same signature as one in the base class without realizing it. The compiler warns that you have hidden the base method, and you should either rename it or use the "new" keyword. If you don't clear up this warning, you may be breaking something without even realizing it.

The next time you build the product you're working on, take a look at the build results. If you're getting warning messages, figure out why and get rid of them.