Migrating to ASP.NET


ASP.NET has its roots in ASP; however, the technologies are completely separate and do not share a single line of code. In all possible ways, we designed ASP.NET to be backward-compatible with ASP. However, some key areas just aren’t, and some language nuances will affect your application.

If you’re looking to move an existing project to ASP.NET, you have two options—you can rewrite your existing application, or you can integrate ASP and ASP.NET. If you rewrite your existing application to take full advantage of ASP.NET, you benefit from many of its new capabilities and features, which simplify common tasks such as table rendering and authentication. In ASP, these tasks required lots of custom code. Alternately, if you choose to integrate ASP and ASP.NET—or for that matter, any other application model such as Java Server Pages (JSP) or Hypertext Preprocessor (PHP)—you won’t have to worry about ASP.NET colliding with other application extensions. However, in an integration model, you have to define your own methodologies for sharing information between the various application models. ASP.NET does not provide any facilities for sharing any information with ASP.

The good news is that no matter which option you choose, ASP and ASP.NET can coexist within the same directories and IIS applications. Unfortunately, ASP and ASP.NET cannot share any information such as Session state data, but you can design around these limitations.

Rewriting for ASP.NET

Rewriting is the recommended option for moving your ASP application to ASP.NET. ASP.NET is a completely different programming model, so even if you do have existing ASP code, for a complex real-world application, you can’t simply rename the .ASP file extension to .ASPX.

Why should you rewrite your application? There are many reasons, but five top my list. First, the tool support for ASP.NET through Visual Studio .NET or other tool vendors such as Macromedia is phenomenal. You get features such as statement completion for your source code as well as design-time support for the layout and presentation of your UI.

Second, unlike other Web application programming models that use parsed bytecode or script code (such as ASP), ASP.NET code is compiled when the application is first started.

Third, since ASP.NET code is compiled, you can expect an immediate performance benefit when you rewrite your application. In many cases, you can boost performance by 200 percent simply by typing the variables within your application, that is, specifying that a variable used as an integer is created as an integer type:

Dim i As Integer

Fourth, ASP.NET introduces a new UI component model called server controls that allows for many UI tasks to be encapsulated in reusable components. For example, any table rendering code can be replaced with the ASP.NET DataGrid server control. Additionally, many specialized server controls are available, such as menuing or charting controls.

Finally, the caching features are my fifth top reason for rewriting your application to take advantage of ASP.NET. These caching features are designed to help you get more performance out of your application by reusing work you’ve already performed. For example, a dynamic page whose content changes infrequently can be output cached, giving you an additional performance gain of 2–3 times.

You can take advantage of many other great benefits when you rewrite your application for ASP.NET. Let’s look at some of the differences between ASP and ASP.NET.

Request Name and Value Pairs

The Request API is familiar to all ASP developers—it interacts with request information that is sent to the server. Commonly, we ask this API for any query string or form name value pairs sent along with the request.

For example, if the ProductID value is passed in the query string, we would expect to see the following URL: default.asp?ProductID=10. In ASP Visual Basic code, we would ask for the value of the ProductID, as shown here:

 ‘ Value on the query string
Dim productID = Request.QueryString("ProductID")

‘ Value passed as a form name/value pair
Dim productID = Request.Form("ProductID")

In ASP, these values were stored in memory as an array. When accessed, the array would be walked to find the corresponding name/value match. The preceding code wouldn’t be different in ASP.NET, however, the values would be stored as a NameValueCollection rather than as an array. When multiple items such as a list of products are passed in using the same name, the items are programmatically accessed differently. For example, assume that a list of ProductID values can be passed in as query string values:

Default.asp?ProductID=10&ProductID=5&ProductID=15

In ASP, the following code could be used to retrieve and list those values:

 ‘ Display posted items
For i = 1 to Request.QueryString("ProductID").Count
Response.Write( Request.QueryString("ProductID")(i) & "<br>" )
Next

However, in ASP.NET, the NameValueCollection value is 0-based, not 1-based. The preceding code would need to be rewritten as follows:

 ' Display posted items
Dim i As Integer
For i = 0 to (Request.QueryString.GetValues("ProductID").Length – 1)
Response.Write( Request.QueryString.GetValues("ProductID")(i) & "<br>" )
Next

Another option is to use the String.Split method if you still desire to work with the items as an array. Request.QueryString(“ProductID”) still returns 10,5,15 in ASP.NET, just as it does in ASP.

 ‘ Display posted items
Dim arraySize As Integer
arraySize = (Request.QueryString.GetValues("ProductID").Length – 1)

Dim products As String[arraySize]
products = Request.QueryString("ProductID").Split(‘,’)

In-Line Methods

Probably one of the most painful changes for ASP developers is the need to move method declarations from <% %> code blocks to <script runat="server"> code blocks. Functions in ASP could be written as follows:

<%
Public Sub DisplayUsername
Response.Write("<b>Some username</b>")
End Sub
%>

When migrating to ASP.NET, the method shown in the next code snippet must be defined in a <script runat="server"> block.

Note

If you’ve been working with ASP since version 1, you know that the original version of ASP recommended that methods be defined in <script runat="server"> blocks. However, most developers—myself included—rarely followed this guideline. Had we followed it, our code would migrate much more easily! If you’re still authoring ASP files but anticipate moving them to ASP.NET in the future, define all methods and functions in <script runat="server"> blocks.

<script runat="server" >
Public Sub DisplayUsername
Response.Write("<b>Some username</b>")
End Sub
</script>

Render Functions

A popular ASP trick that many developers took advantage of was partially defining a function in <% %> blocks and containing raw HTML output. Such a function was known as a render function, which you can see in the following snippet:

<%
Public Sub MyRenderFunction
%>
<font size="5" color="red"><b>Render functions are great!</b></font>
<%
End Sub
%>

Q: What do you think about Render functions?
A: <% MyRenderFunction()%>

This code would render the following:

Q: What do you think about Render functions?
A: <font size="5" color="red"><b>Render functions are great!</b></font>

Render functions were handy because functions that rendered HTML could leave the HTML in normal form and avoid performing Response.Write for each HTML element added to the output.

You can’t use render functions in ASP.NET. Render functions aren’t legal in ASP.NET and need to be rewritten using normal Response.Write statements. Also, as stated earlier, methods would have to be declared in <script runat="server"> blocks. The following code still renders the same output as the preceding render function in ASP, and though it is called within <% and %>, the method is defined within a <script runat="server"> block and no raw, inline HTML is allowed.

<script runat="server">
Public Sub MyRenderFunction
Response.Write("<font size=\"5\" color=\"red\">")
Response.Write("<b>Render functions are great!</b>")
Response.Write("</font>")
End Sub
</script>
Q: What do you think about Render functions?
A: <% MyRenderFunction()%>

If you desire the benefit of encapsulated rendering, another option is to employ a user control to capture all the HTML output and then use the declarative XML syntax to control where the user control output is rendered on your page.

Parentheses Requirement for Functions and Methods

As you can already see, many of the migration headaches are related to nuances of ASP that developers took advantage of. Another such nuance was that there was no requirement for parentheses when calling functions for ASP code written with VBScript. The most egregious—and unfortunately common— situation in which parentheses were not used was when using the Response.Write functionality of ASP to output content.

<%
Response.Write "Hello World!"
%>

The preceding code is actually more of a VBScript language nuance than an ASP nuance, but we’re covering it here rather than in the VBScript section of this chapter. It wouldn’t work in ASP.NET. Instead, we would have to rewrite this code to use parentheses:

<%
Response.Write( "Hello World!" )
%>

If you’re still authoring ASP files and plan to eventually convert them to ASP.NET, ensure that you use parentheses for all functions and methods.

Common Tasks Simplified

One of the great benefits of moving to ASP.NET is that many common tasks are simplified. We can’t cover all the simplifications offered by ASP.NET, but we can show you one of the most common. The following is standard ASP code for connecting to a database and rendering the contents in an HTML table:

<%
‘ Database connection and table creation
Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.RecordSet")
objConn.ConnectionString = "DRIVER={SQL Server};server=localhost;
database=pubs; uid=sa; pwd=00password"
objConn.Open()
objRS.Open "SELECT * FROM Authors", objConn

Response.Write "<Table width=""100%"" cellpadding=""3"" border=""1""
cellspacing=""1"">"
Response.Write "<tr><td>Author Name</td><td>Address</td></tr>"
Do While Not objRS.EOF
Response.Write "<tr>"
Response.Write " <td>"
Response.Write objRS("au_fname") + ", " + objRS("au_lname")
Response.Write " </td>"
Response.Write " <td>"
Response.Write objRS("city") + ", " + objRS("state") + " " + objRS("zip")
Response.Write " </td>"
Response.Write "</tr>"
objRS.MoveNext
Loop
Response.Write "</Table>"

objConn.Close()
%>

This is common code that any experienced ASP developer could author. This type of dynamic table rendering code can be simplified within ASP.NET:

<script runat="server">
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim sqlString As String
sqlString = "server=.; database=pubs; uid=sa; pwd=00password"
Dim sqlConn As New SqlConnection(sqlString)
Dim sqlCommand As New SqlCommand("SELECT * FROM Authors", sqlConn)

sqlConn.Open()
DataGrid1.DataSource = sqlCommand.ExecuteReader()
DataGrid1.DataBind()
sqlConn.Close()
End Sub
</script>
<asp:DataGrid runat="server" />

The code uses the ASP.NET DataGrid server control and simply binds the results from the executed SQL statement to the data grid. The datagrid then renders its contents as HTML.

Note

An additional benefit of server controls is that they can intelligently render the appropriate markup based on the device or browser making the request. For example, DataGrid’s rendering will be slightly different for Microsoft Internet Explorer than for Netscape. The display is identical, but DataGrid can make choices about which display is better for each browser to guarantee correct rendering.

Error Handling

One of the frustrating issues with ASP was the manner in which errors were managed. ASP had no concept of try/catch blocks, unlike ASP.NET. Rather, developers had to aggressively check for errors in ASP pages. The following code demonstrates this:

<%
‘ Database connection and table creation
Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.RecordSet")
objConn.ConnectionString = "DRIVER=(SQL Server);server=localhost;
database=pubs; uid=sa; pwd=00password"
On Error Resume Next
objConn.Open()
objRS.Open "SELECT * FROM Authors", objConn

Response.Write "<Table width=""100%"" cellpadding=""3"" border=""1""
cellspacing=""1"">"
Response.Write "<tr><td>Author Name</td><td>Address</td></tr>"
Do While Not objRS.EOF
Response.Write "<tr>"
Response.Write " <td>"
Response.Write objRS("au_fname") + ", " + objRS("au_lname")
Response.Write " </td>"
Response.Write " <td>"
Response.Write objRS("city") + ", " + objRS("state") + " " +
objRS("zip")
Response.Write " </td>"
Response.Write "</tr>"
objRS.MoveNext
Loop
Response.Write "</Table>"

objConn.Close()
%>

The preceding code is identical to the ASP dynamic table-generation code shown earlier, with the exception of the addition of On Error Resume Next, which instructs the code to continue executing when an error occurs. This instruction assumes that code exists for checking for and handling the error. The result of this code is that when the connection fails, an error will occur, but the code will continue to execute and the end result will be an error message.

Note

Error pages in ASP.NET are much more detailed than they were in ASP—another great benefit! Rather than simply stating ASP Error: 0x8005xxxx, the system provides a detailed exception message with line number information and other useful details about the error.

The preceding code can be more gracefully rewritten in ASP.NET using the try/catch syntax to catch exceptions, such as the failure to connect to the database server, as shown here:

<script runat="server">
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim sqlString As String
sqlString = "server=.; database=pubs; uid=sa; pwd=00password"
Dim sqlConn As New SqlConnection(sqlString)
Dim sqlCommand As New SqlCommand("SELECT * FROM Authors", sqlConn)

Try
sqlConn.Open()
DataGrid1.DataSource = sqlCommand.ExecuteReader()
DataGrid1.DataBind()
sqlConn.Close()
Catch exp As SqlException
‘ Clean up
sqlConn.Close()

Response.Write("Unable to open connection.")
End Try
End Sub
</script>
<asp:DataGrid runat="server" />

Note that all .NET languages support try/catch, which greatly simplifies managing errors within the application.

Visual Basic Language Nuances

You should be aware of some specific Visual Basic language nuances. For example, by default, ASP.NET is configured to require Option Explicit for Visual Basic .NET. This simply means that variables must be declared before being used. Whereas with VBScript you could simply declare a variable with first use, in ASP.NET you must explicitly dimension the variable. For example, to dimension a variable iLoop, you would simply write Dim iLoop.

In VBScript, parameters to methods and functions were passed as by reference (ByRef). This essentially meant that a pointer to the memory location of the data was passed to the method. Thus, if a method changed, the value of the parameter was affected. However, with Visual Basic .NET, all values are passed by value (ByValue), meaning that a copy of the data is passed as the parameter and changes to the value of the parameter do not affect the memory copied.

The Let and Set operators are no longer supported in ASP.NET and objects can be assigned directly without needing to explicitly set the value.

Objects in Visual Basic 6 and VBScript supported the concept of default properties. The most common use in ASP is on the ADO RecordSet to access a contained item, for example, adoRS(“Title”). Default properties are no longer supported in Visual Basic .NET, and this code would need to be rewritten as adoRS(“Title”).Value. Do not use default properties if you are still authoring ASP or Visual Basic 6 code that you intend to eventually migrate.

Tip

In addition to dimensioning all your variables, it is also recommended that you type all your variables Dim iLoop As Integer. By simply typing your variables, you can increase the performance of your application. You can enforce this by requiring the Option Strict Visual Basic .NET compiler option rather than the Option Explicit option.

Compiled Code vs. Include Files

One of the tricks that many ASP developers use is to store frequently accessed code libraries in include files that are then included in all the ASP pages that need to use those libraries. Although they appear useful, include files, if misused, adversely affect ASP.

In design reviews and conferences that I’ve attended, many developers would show ASP pages with very little code but with several includes at the top of the page. These seemingly lightweight ASPs were definitely simplified from an administrative point of view, that is, common code was stored in a single file that was shared. However, these ASPs were anything but lightweight—in fact, they tended to be memory hogs!

When the ASP ISAPI extension loads an .ASP file, it also loads and expands all the include files into one large virtual file in memory. So although developers thought they were getting benefits by moving common logic into include files, they were in fact hurting their programs since many include files would contain routines that were never used by more than 2 percent of the pages. A better strategy would have been to move this common logic into Visual Basic 6 COM servers.

It is recommended that you move code from include files to compiled code in ASP.NET. Take the code from the include file or files and create a single Visual Basic .NET or C# class. Because ASP.NET is compiled, rather than each page having its own copy of all the routines, each compiled ASP.NET page can link to the Visual Basic .NET or C# class instance where this business/rendering logic resides. In addition to compiled classes, you could also use server controls or user controls rather than include files.




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net