Quick Tips For ASP.Net - Part One
Just about everyone has been to a session on ASP.Net best practices, read a book or 10 on the subject, and possibly even a couple of blog posts or MSDN articles. This post is NOT one of them. It is simply a quick list of tips and suggestions for making your ASP.Net application a little better.
I jotted down the tips below over the course of the morning. It is by no means exhaustive and I hope to publish another set of tips or two shortly. If you have any other suggestions/tips, please list them below. If you are not the kind of person who likes to comment on a blog, please drop me a line at scottwater@gmail.com. I will either add them below or create another post and list them. I am also working on a set of caching tips, so if you have any of them, there will be a specific post related to caching.
Tip: Do not use the AutoPostBack attribute on the DropDownList control to simply redirect to another page.
There are probably cases when this might make sense, but for the most part it is overkill. Using the autopostback for a redirect requires extra roundtrip to the server. First the autopostback returns to the server and processes everything up to the event handling the postback. Next a Response.Redirect is issued which goes back to the client requesting the client use another page. So you end up with two separate requests + processing just to get a user to another page.
Using the onchange event of the select element, we can do this all on the client. In the sample below, I am simply redirecting to the current page with an updated querystring element. Your logic will vary, but in the case below, I am avoiding the zero index.
<asp:DropDownList runat="Server" ID = "dropdown" onchange = "if(this.selectedIndex > 0) { window.location = window.location.pathname + '?t=' + this[this.selectedIndex].value;}" />
Tip: Never use the ASP.Net Label control.
Ever is a strong word, but except for some quick and dirty style hacks you should never ever use this control. Any text is rendered inside a span control which is usually unnecessary and complicates any CSS styling you may be trying to use. In most cases, you can replace the Label with a Literal and achieve the same results.
Tip: Use the ASP.Net Repeater instead of DataList, DataGrid, and DataView controls
The Repeater is the single most powerful control shipped in ASP.NET. It is versatile and lightweight. There are times (especially prototyping) when the other databound controls make sense to use, but they generate a lot of extra markup and generally complicate the page with all of their events and styling. Using the Repeater, you may write a little more code up front, but you will be rewarded in the long run.
Tip: Understand how to effectively use caching.
By now, most ASP.NET developers know about the Cache. Most examples show the virtue of caching for hours at a time. Very little data that is worth the effort to display on a web page requires caching for this long. The main reasons for caching are performance related. Memory in ASP.NET is still a very limited resource. Do not waste it by caching anything more than a couple of minutes unless it is very expensive to regenerate.
Tip: Always set a memory threshold for your AppPool.
A related tip would be to first understand the total memory available on your box: how many sites are there, is SQL running locally? Is there anything else on this box which will consistently use Memory?
In most cases, you should never set the available memory for an AppPool above 800mb's unless you can also set the 3/gb switch (then you can use about 1200mb). Allowing memory to go unchecked or set about 800mb can bring even a moderately sized site to it's knees once too much memory is used.
Tip: Use AppOffline.htm for updates
If you are making any changes to files in your bin directory, always use the AppOffline.htm file. It is very likely that while you uploading (or copy & pasting) your updates, users will see an error message. It is much better to show them one that you purposely created and can explain the situation vs. the built in ASP.NET error pages (or even your own customError page). In addition, this will help prevent the locking .dll issue that is not supposed to exist anyway.
Tip: Always check Page.IsValid in your button's EventHandler.
Just because you are using ASP.Net validation controls, do not assume the page could not be submitted with invalid data.
Also, just because you hide a control, do not assume buttons/textboxes/etc on it are not submit-able. It is perfectly fine to hide a control that a user should not access, but with very little code (or using a third party tool) users can easily make an HttpPost with any data they choose.
Tip: When redirects are permanent, use a 301 status code.
This use to be a little more manual, but with ASP.NET 2.0, it is even easier:
Response.RedirectLocation = "http://site.com/newlink.aspx";
Response.End();
Tip: To create fully qualified URLs, use the new VirtualPath class.
string relativePath = "~/somefolder/test/123.aspx"
Uri newUri = new Uri(Request.Url, VirtualPathUtility.ToAbsolute(relativePath));
Again, please add any other suggestions below. I am looking forward to reading them.
Update: It looks like there is a case for using the Label control as an html label element (for accessibility). I was unaware of this functionality and will call it out better in another tip installment. Thanks Phil and Dusty!
Similar Posts
-
I am going to start a new thing. Think of it as my Favorites List, but on my blog instead of my browser.
-
The web is inheritently stateless, however, ASP.Net provides you with a very comprehensive list of options
-
Ancora Imparo has a post on Caching in ASP.NET which is a very interesting and handy read. some interesting
-
Occasionally Scott Watermasysk will post about writing code, and when he does you need to read the post
-
Links regarding Tips and Tricks in ASP.NET - some articles from Scott Watermasysk Quick Tips For ASP.Net...
-
Links regarding Tips and Tricks in ASP.NET - some articles from Scott Watermasysk Quick Tips For ASP.Net
-
Filed under: aspnet , asp.net tips by Scott Watermasysk on February 27, 2007 The web is inheritently
-
About a week ago, I attended my first Philly .NET User Group meeting. I have known about them for awhile,
-
.NET Tips & Tricks Michael Nemtsev, Microsoft MVP Last update: June 13 , 2007 Document version 0


Comments
Dusty on on 2.15.2007 at 9:37 AM
Nice set of tips. And I mostly agree, except for on the label. It is incredibly useful in cases where it's a label for an input field. If you set the AssociatedControlID property of the Label to a textbox, for instance, it will render as a LABEL in the html, with the FOR attribute set to the textbox. This is the generally preferred method for accessibility.
Scott Watermasysk on on 2.15.2007 at 9:41 AM
Hi Dusty,
Great tip! I never knew that. We actually have a custom label control in CS which does exactly that behavior. It is a big framework.
I will definitely add it to the next list.
Thanks,
Scott
Colin Bowern on on 2.15.2007 at 10:28 AM
The problem with memory consumption is that there still are few good (and by good I mean easy-to-use) tools to understand where memory is consumed inside an application. Sure I can get a user mode dump and find out I've got 300,000 strings allocated. But where did they come from? Not so obvious for most ASP.NET developers. I'm curious if anyone has come across a tool that has been easy to work with and relatively inexpensive on this front.
Erik Lane on on 2.15.2007 at 10:34 AM
Keep the tips coming...it helps make the Community a little better everyday.
Phil Haack on on 2.15.2007 at 12:53 PM
Great tips Scott! Looks like Dusty beat me to the punch as I was going to say the same thing. Instead, I wrote up a blog post with a visual demonstration.
http://haacked.com/archive/2007/02/15/ASP.NET_Tip_-_Use_The_Label_Control_Correctly.aspx
Rob Dixon on on 2.15.2007 at 1:28 PM
I would also like to point out that the label control is great for localized application. In ASP 2 and in DotNetNuke versions 3 and 4, simply specifying a resource key to a server control will automatically hook up the resource.
Of course it doesn't have to be a label control, but often times that is what makes sense- and when working with DotNetNuke's localization, it has to be a control that runs on the server and has a property for the text, because resource keys are referenced in a format like: "firstname.text". Again, the property doesn't have to be called "text" but the control has to be able to reference the rendered text as a property of the control.
Scott Watermasysk on on 2.15.2007 at 1:43 PM
Hi Rob,
That is why the Literal control exists.
<asp:Literal runat="Server" Text="<%$ Resources: Comments, NoMessage %>" />
Or you could even skip the control all together and do something like <%= Resources.Comments.NoMessage %>
Thanks
Barry on on 2.15.2007 at 2:50 PM
Ah but asp.label is schizophrenic.
In < 2.0 it was just the text surrounded by <span>
In 2.0+ once you set the AssociatedControlId property it outputs the HTML <label>.
So being a link whore like Phil, I wrote that up as well :)
http://idunno.org/archive/2007/02/15/ltasplabelgt-the-schizophrenic-control.aspx
Vikram on on 2.15.2007 at 8:23 PM
Another good tip would be to use the stringbuilder class insted of the string variable while working with large string.
Daniel Fisher(lennybacon) on on 2.16.2007 at 12:58 AM
The stringbuilder only makes sense with dynamixc strings which consist of more than 7 strings that are connected to one. If less use string.Concat().
steve f on on 2.16.2007 at 2:57 AM
stringbuilder not really an asp tip, more a general framework performance tip, and yes only with dynamic string with > 7 concats
DuncanS on on 2.16.2007 at 11:37 AM
"..you should never set the available memory for an AppPool above 800mb's unless you can also set the 3/gb switch (then you can use about 1200mb)."
Where are you plucking these figures from?
Scott Watermasysk on on 2.16.2007 at 11:54 AM
Hi Duncan,
Mostly experience. :)
When memory is set about 800mb, it is very easy to get OutofMemory exceptions.
Googleing a bit:
http://msdn2.microsoft.com/en-us/library/ms972959.aspx
http://codebetter.com/blogs/jeffrey.palermo/archive/2006/06/13/146389.aspx
Of course, things will vary but my recommendation for the last 2+ years has been to set memory at 800mb or less with 2gig of ram on the server and about 1.2 gig when you can flip the 3/gb switch.
HTH,
Scott
Bill Robertson on on 2.16.2007 at 12:00 PM
I have a Ajax control that helps with wiring up labels to their associated input elements, but without all the messy <% = syntax or using server side controls to get the client ID set correctly.
http://billrob.com/archive/2007/02/16/my-way-to-assign-for-attribute-on-labels.aspx
Marcin on on 2.19.2007 at 4:28 AM
Use HyperLinks not LinkButtons