Welcome to part four of ASP.NET Secrets!
I’m Karl Moore and once again, we’re going wild with Web application tricks. Adapted from the full-length versions in my new book, VB.NET and ASP.NET Secrets, here’s what we’ll be covering today:
- Create Super Fast ASP.NET Applications, with Caching
- Hiding Error Code from Your Clients
- Forget 404: Customizing Your Page Not Found
- Ten Steps to Successful Debugging
Don’t forget that you can contribute to this series, yourself! Simply mail me—[email protected]—with your favourite .NET tips and tricks. I’ll publish the best, with full credit given.
But enough chatting. Ready to get started? Let’s go!
Create Super Fast ASP.NET Applications, with Caching
Some pages on your Web site will be awfully “expensive” to generate. By this, I mean they take time for your server to put together. Perhaps your page grabs the latest stock figures from an external site, perhaps it performs a long company calculation, perhaps it simply delves into your database and retrieves a news story.
Either way, it all takes expensive processor time, and it would be seriously useful if you could just “cache” those pages once they’ve been generated and automatically serve that same page back up for a certain period of time. When the period is up, the page can then run its code once again and “refresh.”
Sounds like a great method of optimizing your site—but perhaps not completely easy to implement. Well, actually, it is. In fact, to set the most popular form of ASP.NET caching into action, you’ll need only one line of code. Here’s how…
If you want to cache your page for, say, ten minutes, first open your .ASPX page in Design mode. Next, click the HTML button (or from the menu, select View, HTML Source). Just above the <%@ Page Language=”vb” … > directive, add the following line of code:
<%@ OutputCache Duration="600" VaryByParam="None" %>
This tells ASP.NET to cache the page after its first request for ten minutes (600 seconds). You can test caching by creating a page that simply displays the time as it loads, whilst incorporating an OutputCache directive with a short Duration attribute. Then, keep refreshing the page in your browser; only after the set Duration will the time update itself.
You may be wondering what the VaryByParam attribute is all about. Well, it tells ASP.NET whether it should cache all requests for this page, or cache separate versions, depending on whether the query string changes (in other words, the “parameters” to the page change).
For example, if you want two versions of a page cached when someone requests “article.aspx?id=10” and “article.aspx?id=11”, then you’ll want to change your OutputCache directive to:
<%@ OutputCache Duration="600" VaryByParam="id" %>
Alternatively, if you want a version of the page cached whenever any parameter alters, simply use a wildcard, as so:
<%@ OutputCache Duration="600" VaryByParam="*" %>
Here, no matter whether you request “article.aspx?id=12” or “article.aspx?tag=loveshack”, a different version of the page will be cached and re-served whenever requested again within the specified duration.
If you’re interested in caching just portions of your page, it’s interesting to note that you also can use this technique in user controls (see the “The Secret Behind User Controls” tip earlier in this chapter). This could perhaps allow you to have certain parts of the page updated with every request, whilst other, more common elements, simply refresh every hour or so.
A quick word of warning: Be careful not to overuse caching. Used wisely, it can greatly increase the performance of your Web applications. Used in a crazed, insane fashion—say, on a free text search page—it’ll bring your server to a grinding halt.
You can learn more about ASP.NET caching by looking up ‘ASP.NET caching’ in the Help Index. Surprising, that.
Hiding Error Code from Your Clients
One of the most beautiful features of ASP.NET is its rich error reporting. When something goes wrong, it highlights the exact lines of offending code, provides an explanation of the problem, and if it’s feeling merry, even suggests a solution from time to time.
The problem is: You really don’t want your visitors viewing code behind your applications. For a start, it may breach your site security. For seconds, it’s just not pretty. So, how do you stop it from happening?
First off, stop telling VS.NET to create the debug file, containing a copy of your code. You can do this by altering the application mode from ‘Debug’ to ‘Release’. Use either the drop-down box on the standard VS.NET menu for this, or select Build, Configuration Manager and edit through the dialog box. Next, turn off debugging by editing the Web.config file so the <compilation> element reads <compilation debug=”false” />.
Well, that may stop your code from appearing, but it won’t get rid of those awful generic error pages. You can, however, replace them with your own, slightly more elegant apologies. Simply alter the <customErrors> element in Web.config to something like <customErrors mode=”On” defaultRedirect=”genericerror.aspx” />. No problem!
Top Tip: With a defaultRedirect, ASP.NET automatically passes the filename of the page that generated the error in the query string, as a parameter called “aspxerrorpath”. You may wish to use this in your error page, perhaps to suggest a user solution or log to an errors file.
Caption: Our edited Web.config file
Forget 404: Customising Your Page Not Found
In the last tip, we discovered how to stop your code being displayed when an error occurs. We also found out how to redirect the user to a certain page when such problems arise. Well, this also kicks in with such irritations as the dreaded “404, Page Not Found” error message.
In those situations where a requested page is not found on the Web server, you might want to display your own custom message rather than a generic error message. You can do that easily, just by expanding the <customErrors> element of your Web.config file.
The following snippet shows part of an edited Web.config file that redirects to genericerror.aspx when regular errors occur, or 404.html when a file not found occurs, or 403.html when a permission denied server error occurs.
<configuration> <system.web> ... <customErrors mode="On" defaultRedirect="genericerror.aspx"> <error statusCode="404" redirect="404.html" /> <error statusCode="403" redirect="403.html" /> </customErrors> ... </system.web> </configuration>
Caption: Error 404 redirection kicking in when I access a non-existent page
Ten Steps to Successful Debugging
It’s terrible when it happens—but rest assured, it will happen. You see, debugging Windows programs is a pretty simple process and one not prone to failure. But debugging Web applications is much more fallible.
So, what should you do if you attempt to start debugging a Web application and get the dreaded “Unable to start debugging on the Web Server” error? Here’s your one-stop checklist…
- Are you working offline in Internet Explorer? Launch Internet Explorer and look in the File menu. If “Work Offline” is checked, click it to unselect this option, restart Visual Studio .NET, then try again.
- Are there syntax errors in Web.config? If there are, you won’t be able to start debugging. To check this, click Debug, Start Without Debugging and see whether your browser reports back an error. If it does, fix it and try again.
- Are you running Windows 2000 or Windows XP? If so, continue to step four. If you’re debugging a remote ASP.NET application under Windows NT 4, you’ll need to launch the application without debugging, then manually attach to it. Look up “debugging ASP.NET Web applications, system requirements” in the Help Index for more information. Word of advice: upgrade.
- Are you a member of the Debuggers Users group? You may be logged on as Administrator, but it’s still worth checking. If you’re not in the group, you may be denied your debugging rights.
- Does your Web.config file have its “debug” attribute set to “true”? If not, you’re going nowhere. You might also want to check that the Configuration Manager lists your project as ‘Debug’, not ‘Release’ (use the drop-down box on the standard menu to alter, or choose Build, Configuration Manager).
- When you created the project, did you specify an IP address rather than a machine name? If so, launch Internet Explorer, choose Internet Options, select the Security tab and add the IP address to the list of trusted sites—then try again.
- Did you install IIS after Visual Studio .NET? If so, you’ll need to do a little fixing. Use the Help Index to look up “installing Internet Information Server”. Midway through the software requirements, you’ll find instructions telling you how to install IIS. It also provides advice on configuring and repairing IIS after installing Visual Studio .NET: Follow the guidelines.
- Are the IIS security settings set up properly? You can check this by launching the Internet Services Manager in Windows 2000, or Internet Information Services in Windows XP (found under the Administrative Tools option on the Programs menu). Navigate to your Web server, locate the Default Web Site node, right-click and select Properties, choose the Directory Security tab, and select Edit. Ensure Anonymous Access and Integrated Windows Authentication are checked, then OK on all open dialog boxes.
- Is the Web application virtual folder set up correctly? You can check this by launching the Internet Services Manager in Windows 2000, or Internet Information Services in Windows XP (found under the Administrative Tools option on the Programs menu). Navigate to your Web server, expand the Default Web Site node, and then find your application folder in the list. If it looks like regular Windows Explorer, it hasn’t been set up correctly. To resolve, right-click on the folder, select Properties, click the Create button, and then hit OK to save.
- And finally, the most obvious of them all: Is the URL for the project correct? Ensure both directory and extensions are accurate—and attempt to browse the list of available files, where appropriate.
Coming Up in Part Five of Windows Secrets:
- Using .IsClientConnected for Long Processes
- What to Do When Session_End Doesn’t Work
- Spy on Your Web Host: Checking Uptime in .NET
- Can It Cope?—Stress Testing Your Web Apps
See you then!
About the Author
Karl Moore is a technology author living in Yorkshire, England. He runs his own consultancy group, White Cliff Computing Ltd, and is author of two best-selling books exposing the secrets behind Visual Basic .NET. When he’s not writing for magazines, speaking at conferences, or making embarrassing mistakes on live radio, Karl enjoys a complete lack of a social life. Check out Karl’s newest book, Ultimate VB .NET and ASP.NET Code Book.
# # #