Why Migrate to ASP.NET

Snoops

   

 
Migrating to .NET: A Pragmatic Path to Visual Basic .NET, Visual C++ .NET, and ASP.NET
By Dhananjay  Katre, Prashant  Halari, Narayana  Rao  Surapaneni, Manu  Gupta, Meghana  Deshpande

Table of Contents
Chapter 5.   Migration Approach for ASP to ASP.NET


The following features can actually benefit the developer and the application immediately without the need to rewrite the entire application.

Compiled Environment

All ASP.NET code is compiled, not interpreted, unlike traditional ASP pages. This leads to certain performance improvements, which account for strong typing and early binding enforced by the .NET Framework. Once the code is compiled, the CLR further compiles it into native code (i.e., processor-specific machine code).

In ASP, pages are interpreted each time that they are accessed. ASP.NET pages, known as Web Forms, have a visual part (.aspx file), which contains HTML and server controls and a logic component (.aspx.vb file) housing the code for the page. This logic component, also known as the code-behind for the Web Form, is compiled into a project .dll file and cached on the server when the Web application is compiled before deployment. Every time a request is made for an ASP.NET page, the project .dll file is instantiated and executed. Every subsequent request is served this cached copy, unless the code-behind in the page has changed and it has to be recompiled. This also means that the .aspx file containing the visual part can be changed without having to recompile and deploy the Web application. Web Forms can still be created in the way ASP pages are written, housing logic within the .aspx page itself.

Multiple Language Support

The .NET Framework inherently supports multiple languages and as a result, ASP.NET pages can be written in any of the languages supported by the .NET Framework. Thus, ASP.NET pages can be written in Visual Basic .NET, C#, Managed VC++, and so on.

Cross-language interoperability is allowed in the .NET Framework and this holds true for ASP.NET also. This means that application developers can develop components in C#, develop their ASP.NET pages in Visual Basic .NET, and then use these components from the ASP.NET pages.

The entire executable code in ASP.NET, whether it is written in Visual Basic .NET, C#, or managed C++, is ultimately compiled into the language-neutral IL. The CLR then executes and using the JIT compiler, compiles this IL into native code. Thus, classes can be created in any .NET-compliant language and inherited into the other.

Code Separation

ASP.NET allows for clean separation of business logic from presentation logic with the help of a method known as CodeBehind . CodeBehind allows you to separate the business logic from the .aspx pages into class files. For Visual Basic .NET, these class files have a file extension of .aspx.vb. The presentation logic can be contained in the .aspx page, and the application logic can be put in the code-behind .aspx.vb file for the page.

The CodeBehind attribute in the Page directive of the .aspx file gives the location of the CodeBehind for that file, and the inherits attribute specifies the class name from which the .aspx page inherits. This way the CLR compiles the page and its CodeBehind class into one assembly.

The following example shows how HTML code can be separated from its Page class. Shown next is the HTML code contained in the .aspx file:

 graphics/icon01.gif <%@ Page Language="vb" AutoEventWireup="false" CodeBe_  hind="samplePage.aspx.vb" Inherits="Samples.samplePage"%>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transi  _  tional//EN">  <HTML>     <HEAD>        <title>samplePage</title>           <meta name="GENERATOR" content="Microsoft Visual _  Studio.NET 7.0">           <meta name="CODE_LANGUAGE" content="Visual Basic _ 7.0">           <meta name="vs_defaultClientScript" _  content="JavaScript">           <meta name="vs_targetSchema" _  content="http://schemas.microsoft.com/intellisense/ie5">         </HEAD>         <body MS_POSITIONING="GridLayout">            <form id="Form1" method="post" runat="server">               <asp:TextBox id="TextBox1" style="Z-INDEX:101;_  LEFT: 158px; POSITION: absolute; TOP: 61px" _ runat="server"><  /asp:TextBox>              <asp:TextBox id="TextBox2" style="Z-INDEX:102;_  LEFT: 160px; POSITION: absolute; TOP: 103px" _ runat="server"><  /asp:TextBox>              <asp:Label id="Label1" style="Z-INDEX:103;_  LEFT: 62px; POSITION: absolute; TOP: 66px" _  runat="server">User Name</asp:Label>             <asp:Label id="Label2" style="Z-INDEX:104; _  LEFT: 65px; POSITION: absolute; TOP: 104px" _  runat="server">Password</asp:Label>              <asp:Button id="Button1" style="Z-INDEX:105; _  LEFT: 130px; POSITION: absolute; TOP: 144px" runat="server"_  Text="Submit"></asp:Button>            </form>         </body>     </HTML> 

Notice the @ Page directive at the beginning of the code containing the CodeBehind and Inherits attributes. The CodeBehind attribute points to the name of the CodeBehind file SamplePage.aspx.vb and Inherits contains the name of the CodeBehind class in a hierarchical manner Samples.SamplePage , where Samples is the name of the Web application containing the specified class. The controls in the HTML have an attribute called RUNAT , which is by default set to server . This allows the controls to be accessed from the server-side code in the code-behind. The code-behind for the class follows :

 graphics/icon01.gif Public Class samplePage        Inherits System.Web.UI.Page        Protected WithEvents TextBox1 As _           System.Web.UI.WebControls.TextBox        Protected WithEvents TextBox2 As _           System.Web.UI.WebControls.TextBox        Protected WithEvents Label2 As _           System.Web.UI.WebControls.Label        Protected WithEvents Button1 As _           System.Web.UI.WebControls.Button        Protected WithEvents Label1 As _           System.Web.UI.WebControls.Label     #Region " Web Form Designer Generated Code "      'This call is required by the Web Form Designer.     <System.Diagnostics.DebuggerStepThrough ()> Private Sub_        InitializeComponent ()     End Sub     Private Sub Page_Init (ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles MyBase.Init        'CODEGEN: This method call is required by the Web Form  Designer        'Do not modify it using the code editor.        InitializeComponent ()     End Sub   #End Region     Private Sub Page_Load (ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles MyBase.Load      'Put user code to initialize the page here        Dim strName As String        Dim strPwd As String        strName = TextBox1.Text        strPwd = TextBox2.Text     End Sub  End Class 

ASP.NET Server Controls

ASP.NET introduces the concept of server-side controls whereby the controls appear on the client side, but their events can be captured and their value manipulated on the server side. A control, say a text box, can be made a server-side control by adding the runat="server" attribute to it, as follows:

 <input type="text" id="myTextControl" runat="server" /> 

The server generates the corresponding HTML tags for this user interface at the server end with the attributes specified within the tag. When the page containing the preceding control is rendered on the browser, the following HTML is generated:

 <input name="myTextControl" type="text" _    id="myTextControl"/> 

An advantage of using these server controls is that the controls appear on the client side, but due to the runat="server" attribute, they can fire server-side events. This is particularly useful during form validation. The server controls can be divided into following categories.

INTRINSIC CONTROLS

Also known as HTML server controls, these controls map directly on to the HTML elements on the client browser with the added capability of maintaining the state. The control is identified on the server side with the help of its ID, which allows access to its properties, events, and methods . The HTML server controls are defined within the namespace System.Web. UI.HtmlControls . An example of HTML server controls is shown in the preceding code.

WEB SERVER CONTROLS

Web server controls are similar to the normal HTML controls. However, their advantage is that they offer standardized set of property names for the controls. Web Form controls are prefixed with asp, as shown in the following example:

 graphics/icon01.gif <asp:Button id="Button1" style="Z-INDEX: 105; LEFT:130px;_    POSITION: absolute; TOP: 144px" runat="server" _     Text="Submit"></asp:Button> 

In this code, the control asp:button is a Web Form control. All Web Form controls derive from the namespace System.Web.UI.WebControls .

LIST CONTROLS

The list controls are generally used in conjunction with ADO.NET. They provide data binding facilities, allowing display of data from a data store via a control. These controls allow application developers to produce grids or grid-like layouts easily. The list controls have properties that allow formatting of output. Some examples of list controls are Table , DataGrid , DataList , and Repeater .

RICH CONTROLS

Rich controls are similar to the built-in components that come with ASP and provide a rich user interface. So far there are only two such controls provided in ASP.NET, the Calendar and Ad Rotator control:

 <asp:adRotator AdvertisementFile="Ad.xml" runat="server" Bor- derColor="#000000" BorderWidth="1"></asp:adRotator> 
VALIDATION CONTROLS

Validation controls make the task of validating Web Form data very easy. ASP.NET provides a set of six controls for this purpose. These are nonvisible controls that can provide client- and server-side validation routines. They allow testing for a common set of conditions and can also customize routines and summarize the display. There is an attribute to enter the error message of your choice when a bad response is encountered .

These controls reference an input control on the Web Form. When the form is submitted, the ASP.NET page framework passes the value of the input control to its associated validation control. The validation control tests the value and sets a property indicating whether the input is valid. After all the validation controls have been called, a property on the page is set. If any of the validation controls fails the check, the page property is set to invalid.

Validation controls also detect the browser type and generate client-side validation code specific to the browser. This way the developer does not have to write client-side code that first detects the browser and then performs the necessary validation accordingly .

An example of a RequiredFieldValidator control follows:

 graphics/icon01.gif <asp:RequiredFieldValidator id="RequiredFieldValidator1"_  ControlToValidate="control Name" Display="Static" Initial_  Value="" Width="100%" runat="server" ErrorMessage="Error _  Message goes here"></asp:RequiredFieldValidator> 
MOBILE CONTROLS

Mobile controls are used for building Web pages that can be rendered on handheld devices such as PDAs and mobile phones. The mobile controls generate either HTML or WML depending on the device accessing the Web pages. The specifics of the devices on which the Web page is to be rendered are automatically taken care of to a large extent, thus leaving application developers little to do.

Browser and Device Independence

The ASP.NET execution environment detects the type of browser requesting the Web page and generates the HTML content for that page accordingly. Also, device independence is obtained with the help of the mobile controls, as mentioned in the previous section.

Interoperability with Existing COM Components

The major advantage of ASP.NET applications (and other applications developed in the Microsoft .NET environment) is that they can interoperate with existing COM components. This is achieved with the help of the COM interoperability layer provided by the Microsoft .NET Framework. The interoperability mechanism allows application developers to preserve their investments in existing COM components and reuse them from the new ASP.NET applications.

Configuration

ASP.NET applications are provided with a configuration file. A configuration file is an XML file that developers can use to change settings without recompiling the application and administrators can use to change policies regarding how applications should run on their machines. Such machine-level settings can be changed through a file named machine.config located in the %runtime install path%\Config directory.

In addition to the settings specified in the machine.config file, each ASP.NET application has its own configuration file called web.config . The settings in this file override the settings at the machine level as specified in the machine.config file. These files contain all the settings pertaining to ASP.NET applications. A typical web.config follows:

 graphics/icon01.gif <?xml version="1.0" encoding="utf-8" ?>  <configuration>      <system.web>            <compilation defaultLanguage="vb" debug="true" />            <customErrors mode="Off" defaultRedirect=  "http://localhost/samples/webform1.aspx">                  <error statusCode="404" redirect=  "/samples/404Page.aspx" />            </customErrors>            <authentication mode="Windows" />            <authorization>                  <allow users="*" />            </authorization>            <trace enabled="false" requestLimit="10"  pageOutput="false" traceMode="SortByTime" localOnly="true" />            <sessionState mode="InProc" stateConnectionString=  "tcpip=127.0.0.1:42424" sqlConnectionString="data source=  127.0.0.1;user id=sa; password=" cookieless="false"  timeout="20" />            <httpHandlers>                  <add verb="*" path="*.vb" type=  "System.Web.HttpNotFoundHandler,System.Web" />                  <add verb="*" path="*.cs" type=  "System.Web.HttpNotFoundHandler,System.Web" />                  <add verb="*" path="*.vbproj"  type="System.Web.HttpNotFoundHandler,System.Web" />                  <add verb="*" path="*.csproj"  type="System.Web.HttpNotFoundHandler,System.Web" />                  <add verb="*" path="*.webinfo"  type="System.Web.HttpNotFoundHandler,System.Web" />            </httpHandlers>            <globalization requestEncoding="utf-8"  responseEncoding="utf-8" />      </system.web>  </configuration> 

Deployment

Deployment of ASP.NET applications is very simple. It only involves copying the source files into a virtual directory on the Web server. Also, .NET components can be deployed by placing the .NET assembly in the /bin directory of the Web application. The /bin directory is present in the root of the Web application. There is no need to update the registry because .NET components need not be registered. The .NET components are self-describing because assemblies created after compiling the component contain the manifest and metadata information.

The CLR can manage multiple versions of the same component under the same environment, with the runtime using the exact version that's available at compile time. All that we need to do to deploy a component is to copy the component to the desired location and start using it.

Security

An important part of many Web applications is the ability to identify users and control access to resources. ASP.NET works in conjunction with the .NET Framework and IIS to provide security to the Web application. ASP.NET application security is based on the following three fundamental functions:

  1. Authentication. The process of asking a user for credentials, usually by way of username and password, to prove that the claims made by the user for identification are true.

  2. Authorization. Once the user is authenticated, the requested resource can be made available only after certain permissions are granted. The Access Control List (ACL) belonging to the resource determines the type of access to be granted to the user: read access, write access, or both and whether the user can modify or delete the resource.

  3. Impersonation. The process of requesting a resource under a different identity, usually in the context of remote users.

Because ASP.NET is built on the Microsoft .NET Framework, the ASP.NET application developer also has access to all of the built-in security features of the .NET Framework, such as code access security and role-based user-access security.

State Management

In ASP.NET, the session state is automatically maintained by using a hidden field called view-state. It allows control of session state at both page and control level.

It is also possible to store the session state directly into SQL Server database and retrieve it at a later time. Session state can now be maintained in a separate process, on a separate machine, or even in a database allowing for cross-server sessions. This makes adding more Web servers to accommodate the increasing traffic relatively easy, for example, for applications running on Web farms. Session management in Web farms using ASP is difficult because each server in the Web farm provides its own session state, and maintaining a common session across servers can be done best by passing session information in a query string. The out-of-process model of session state in ASP.NET allows users to maintain session in a state server, which can be shared across servers in a Web farm.

Also, cookies are no longer required for maintaining session state. ASP.NET provides an option to use a munged URL instead of cookie, which is placed in the midst of the URL and can be used to track sessions.

Data Access

By way of ADO.NET, the .NET Framework provides a disconnected and efficient manner of handling data, allowing greater scope for data manipulation. It supports XML and SQL, and it is more standardized than traditional ADO. The properties and methods of ADO.NET are extremely portable, via XML, which increases the possibility of data sharing and in turn reduces the load on the database.

In ADO, we have the OLEDB data providers, which provide a uniform programming interface across databases such as SQL Server, MS Access, and Oracle. ADO.NET supports the common features of OLEDB providers, but extends them by providing managed data providers, such as System.Data. SqlClient , that are specific to SQL Server and System.Data.OleDb for other databases.

Error Handling and Debugging Techniques

Error handling has vastly improved in ASP.NET over the previous versions of ASP. It offers rich support for handling, debugging, and tracing runtime errors. Custom error pages were introduced with ASP3.0, but ASP.NET provides the facility to configure the error pages through its web.config file. It is also possible to specify individual error pages for each ASP.NET page by employing the new ErrorPage directive:

 <%@Page Errorpage = "/myErrorPage.aspx"%> 

In this example, if any error occurs on the page, the user is directed to myErrorPage.aspx .

Error handling features are further enhanced by providing support for the try catch finally block under the .NET Framework.

ASP.NET adds a debugger tool, which has the ability to step through your code and set arbitrary breakpoints.

ASP.NET pages have tracing capability provided by a Trace object, which has methods such as Write to supply extra information to your trace output. Tracing can be enabled and disabled programmatically using the Trace attribute of the Page directive.

The Web application TraceApplication contains an ASP.NET file named Trace.aspx :

 graphics/icon01.gif <%@ Page Language="vb" Trace="true"%>  <%@ Import Namespace="System.Diagnostics"%>     <HTML>     <HEAD>     <title>Trace</title>     <script runat=server>        function divideNum(a as Integer, b as Integer) as _         Double           Trace.Write("Inside function a:" , a.ToString())           Trace.Write("Inside function b:" , b.ToString())           return (a/b)        end function     </script>     </HEAD>     <body MS_POSITIONING="GridLayout">     <form id="Form1" method="post" runat="server">        Result of 12/6 = <%=divideNum(12,6)%>     </form>     </body>     </HTML> 

The output above when viewed in the browser will appear as shown in Figure 5-1. The custom diagnostic messages entered using the Write method of Trace object appear in the Trace Information table of the performance data. Debugging techniques are covered in more detail in Chapter 7.

Figure 5-1. Trace Output

graphics/05fig01.gif

Caching

ASP.NET has three forms of caching built in. The first is page output caching, which provides an in-memory cache of the output from an ASPX page. Page output caching creates cached copies for each combination of URLs as well as various headers that you specify. One limitation is that page output caching doesn't support HTTP Posts, only HTTP Gets. Output caching is particularly suitable when you expect to return the same data in the same format for many different requests .

The second type of caching is fragment caching, which allows you to cache subsections of a page while other parts of the page remain dynamic.

Finally, ASP.NET makes an extensible cache API available to developers for caching any arbitrary objects. The following example makes use of the cache API clear. The LoadDataSet is a function that populates a dataset:

 graphics/icon01.gif Private Function LoadDataSet() As DataSet    Dim sqlConnection As SQLConnection    Dim sqlAdapater As SQLDataSetCommand    Dim datasetProducts As New DataSet()    Dim sqlDSN As String    Dim sqlSelect As String    ' Connection String and Select statement    sqlDSN = "server=localhost;uid=sa;pwd=;database=shoppingmall"    sqlSelect = "Select * From Products"    ' Connect    sqlConnection = new SQLConnection(sqlDSN)    sqlAdapater = new SQLDataSetCommand(sqlSelect, sqlConnection)    ' Fill dataset create product table    sqlAdapter1.FillDataSet(datasetProducts, "products")    Return products  End Function 

Using cache, we can load the dataset in cache only if it is not already present and use the dataset from cache instead of loading it each time we want it:

 graphics/icon01.gif Public Function GetProductData() As DataSet    If (IsNothing(Cache("ProductData")) Then      Cache("ProductData") = LoadDataSet()    Return Cache("ProductData")  End Function 

Snoops

   
Top


Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
Migrating to. NET. A Pragmatic Path to Visual Basic. NET, Visual C++. NET, and ASP. NET
ISBN: 131009621
EAN: N/A
Year: 2001
Pages: 149

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