ASPAlliance.com : The #1 Active Server Pages .NET Community The #1 ASP.NET Community
Search   Search

Subscribe   Subscribe

Powered by ORCSWeb Hosting


Site Stats


Powered By ASP.NET
 
Featured Sponsor

Featured Columnist


Featured Book
ASP.NET Developer's Cookbook
ASP.NET Developer's Cookbook

Find Prices


New! asp.netPRO

We publish our articles in the standard RSS format.

Powerful .NET Email Component

Code Sharing Software
Click here to return to my article index

"Good" ASP.NET Coding Practices

In an effort to provide "best practice" coding techniques, I have created this page. This page can be used as a standalone reference but more importantly you will link to this document within each of my articles. We should all strive to build the best applications possible because someday you will be working on someone elses code. =)

Have a best practice that you think should be listed on this page? Please send them here! Thanks!

1. Structured Error Handling

This article on MSDN does an excellent job of explaining the how, what, why, and when of structured error handling in VB.NET.

2. String Concatenation

The good news is that regardless of what technique you use to concatenate strings in ASP.NET it will be faster than it was in classic ASP. That said, there are two common ways that strings are usually concatenated using the .NET Framework/VB.NET. One is to use the & character to concatenate two strings like so:

Dim myOutputString As String = "My name is"
Dim myInputString As String = " Alex"
myOutputString = myOutputString & myInputString
Response.Write(myoutputString)


The second technique makes use of the StringBuilder class. The StringBuilder class will look foreign to those of you who are new to ASP.NET. You can read the documentation about the StringBuilder class here. To concatenate strings using the StringBuilder class you would use code such as this:

Dim myStringBuilder As New StringBuilder("My name is")
Dim myInputString As String = " Alex"
myStringBuilder.Append(myInputString")
Response.Write(myStringBuilder.ToString()

Now, you will probably not notice a performance difference when concatenating less than five times (as concatenation is often done in a loop of some kind). In fact, you may see the & technique of concatenation peform a little better than the StringBuilder class when performing fewer than five concatenations. The "best practice" tip to take away from this section though is that the StringBuilder class will majorly outperform the & character when doing five plus concatenations. Some people have reported up to 30 and 40 times better performance using the StringBuilder class with large numbers of concatenations!

Dan Green pointed out this resource leak problem over on the [review-websites] list at AspFriends.com (the greatest ASP/ASP.NET lists in the world!). In VB 6 and VBScript, it was a best practice to always close objects (especially precious resources like connections, recordsets, etc.) and to always set them equal to nothing. Well, that is still partially true. We still need to close connection objects when we are done with the database connection. We also need to remember to close our DataReader. Here are a couple examples that demonstrate how the database connection and/or DataReader object should be closed:

Here we are using the CommandBehavior.CloseConnection enumeration which will close the connection as soon as all of the data as been streamed into the SqlDataReader. So, we don't have close the connection. Instead, we need to close the SqlDataReader in our Finally segment.

Dim myConnection As SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings("DSN_pubs"))

Dim myCommand As SqlCommand = new SqlCommand("Select pub_id, pub_name From publishers", myConnection)

Dim myDataReader As SqlDataReader

Try
  myConnection.Open()

  myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

  DropDownList1.DataSource = myDataReader
  DropDownList1.DataBind()
Catch myException As Exception
  Response.Write("An error has occurred: " & myException.ToString())
Finally
  If Not myDataReader Is Nothing Then
    'Notice that we close the DataReader here!
    myDataReader.Close()
  End If
End Try
Here we are directly passing the results of the ExecuteReader method to the DataSource property of the DropDownList. So, we need to close the connection which we do in the Finally segment. Before we call the Close method we check to make sure the connection is open because attempting to close a connection that is not open will cause an exception to be thrown.
Dim myConnection As SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings("DSN_pubs"))

Dim myCommand As SqlCommand = new SqlCommand("Select pub_id, pub_name From publishers", myConnection)
	
Dim myDataReader As SqlDataReader

Try
  myConnection.Open()

  'Notice that we are not using the CommandBehavior.CloseConnection enum in this example

  DropDownList1.DataSource = myCommand.ExecuteReader()
  DropDownList1.DataBind()
Catch myException As Exception
  Response.Write("An error has occurred: " & myException.ToString())
Finally
  If Not myConnection Is Nothing AndAlso ((myConnection.State And ConnectionState.Open) = ConnectionState.Open) Then
    myConnection.Close()
  End If
End Try

4. Using the Web.Config/Maching.Config file to store application wide data

While you can use the web.config file to store your database connection string it is more secure to store the database connection string in the machine.config file. The machine.config file contains machine-wide settings for various parts of the .NET Framework. Most of the setting stored in the machine.config file pertain to ASP.NET. There is also a section of the machine.config file where you (the developer) can add your own elements called . Check out Steve Smith's article here for more information.

5. Use ASP.NET's Trace feature to debug instead of using Response.Write!

I train a lot of classic ASP developers who got really good at using Response.Write to debug their applications. Using Response.Write to debug class ASP applications was a necessary evil. ASP.NET provides a new debugging facility in the Trace class. Tracing is much cleaner than Response.Write and can be turned on and off by simply changing a single setting in either the page or the web.config file (never again will you have to remember to comment out those Response.Write statements!). In addition to custom debugging information, tracing also provides us with a snapshot of the Form, Querystring, Headers, Cookies, and Session collections. Also viewable in the trace information is the page's control tree and the web server variables.

We can turn tracing on at the page level (using the Trace attribute of the @Page directive) or at the application level in our web.config file. Page level tracing displays trace information for a single page and the trace information is simple tacked onto the output of the page. Application level tracing works a little bit different than page level tracing. Instead of displaying trace information on each and every page, application level tracing provides trace information for a user definable number of requests. The localOnly attribute determines whether trace information is viewable (via a browser) remotely or only from the console of the web server. The number of requests available is set using the requestLimit attribute (shown above) of the trace element. Each pages trace information is stored in memory and is viewable by pointing a browser at http://domainname.com/applicationname/trace.axd. Because trace information is stored in memory, it is good practice to keep the number of requests low (less than 20).

Here is how you can turn tracing on or off in a single ASP.NET page:

<%@ Page Language="VB" Trace="True" %>
We can also turn tracing on or off for the entire ASP.NET application using syntax similar to the following (in our web.config file):
<configuration>
 <system.web>
  <trace enabled="true" requestLimit="10" localOnly="false"/>
 </system.web>
</configuration>
Then, in our ASP.NET page, we can use code such as the following to write custom trace (debug) information out to the page:
Trace.Write("This is some custom debugging information")
or
Trace.Write("This is is my variable and it's value is:" & myVariable.ToString())
Remember, the Trace class is your friend! =)

6. Follow the recommended design guidelines and use FxCop when developing reusable libraries

If you want to build well designed reusable libraries with the .NET Framework then you should check out these design guidelines. To aid in the development of the .NET Framework, the Framework team built a tool (FxCop) they used to ensure that their own libraries were well designed and passed over 100 security, versioning, language interoperability, and naming guideline tests. You can download FxCop here.

7. Read and follow Microsoft's internal "ASP.NET Performance Tips and Best Practices"

Fabio Yeon has written an excellent white paper that details some Microsoft's recommended ASP.NET tips and best practices. You can read the white paper here.

Have a best practice that you think should be listed on this page? Please send them here! Thanks!

 Copyright © 2000-2003 ASPAlliance.com  Page Rendered at 8/28/2008 3:07:12 AM