How Is ASP.NET Different from ASP?


This question can be answered in one word “ very! ASP.NET is not just a new version, but a whole new idea and way of programming web applications. New features weren't retrofitted into ASP to give us a new version “ ASP.NET has been written from the ground up to provide the best possible application framework. This has meant that, in many areas, compatibility with ASP has been broken, but in the long run this is a good thing. It means that ASP.NET provides a much stronger platform for developing applications, and gives many more benefits.

If you're worried about the compatibility issue, then remember we mentioned earlier that ASP.NET runs alongside ASP. Even though there are many differences between the two, installing ASP.NET won't break existing applications. That's because your existing ASP pages are still processed by the same mechanism as before, and the new framework processes ASP.NET pages. This is achieved by ASP.NET pages having a new file extension ( .aspx ), meaning they are not processed in the same way as ASP pages.

Note

ASP -ASP.NET compatibility and migration issues are covered in Chapter 23.

Why Do We Need a New Technology?

ASP has achieved enormous success as a way of developing web sites, so why do we see the need for something new? Simply put, ASP hasn't evolved to take into account the way it's now being used. Although designed with great scope and flexibility, I don't think even its authors could have seen how it would become the cornerstone of many applications. Like a tempestuous Hollywood starlet, its rapid rise to fame has led to problems:

  • ASP is a scripted language, relying mainly on VBScript and JScript. Other languages are available if we install an interpreter, but it's still interpreted. The two disadvantages of interpreted languages are the lack of strong types (as supported by typed languages such as Visual Basic and C/C++), and the lack of a compiled environment. ASP does cache code, but it's still interpreted, and this inevitably leads to performance and scalability problems.

  • ASP doesn't provide an inherent structure for applications. In the days of static web pages, we used to see small, focused source files. With the dynamic concept of ASP, it was possible to build code into the web page, again leading to problems. There's the eternal worry of mixing code and content, which can be a problem if you have a mixed team, with certain people designing the HTML and the interface, with different people doing the coding. Having two sets of people working on the same files is asking for trouble. Another problem was the ability to make the code complex, leading to larger source files. Include files allow a certain amount of structure and code reuse, but it was never really a great solution.

  • You have to write code in ASP to do most things, no matter how simple. For example, consider the task of validating form fields. Just to ensure that values are entered into a field requires code. Other areas such as caching content, maintaining form state, and so on, all require code. Even adding new HTML controls requires writing the raw HTML to the page.

  • The world of browser-compatibility has morphed into device-compatibility. While the majority of Web access still takes place from a PC and browser, how long will that remain the case? Mobile devices are becoming more prevalent , and more powerful, leading to more problems designing sites. If you want your web site to obtain maximum reach, you need to contend with these devices, and this means writing code to detect the device and render the appropriate content.

  • Standards compatibility also plays a big part in Web development. XHTML is becoming more widely accepted, XML and XSLT are both now widely used, and talking to mobile devices might mean support for WML. Support for these standards mean that your ASP applications not only have to work with existing standards, but also be easily upgradeable to support future standards.

These are just few of the problems that are encountered when building ASP applications. The rapidly changing nature of the Internet often requires rapid changes to applications. For languages that have strong development environments, practices such as componentization, code reuse, rapid development, and so on, are a great boon to a developer, but this sort of support is lacking in ASP. The rise of Business- to-Business applications and peer-to-peer data-sharing also brings great challenges to the developer.

ASP.NET was written from the ground up to meet these needs. Not only does it answer many of the questions posed by the existing development environment, but also provides great extensibility, and brings great tool support. At its minimum, all you require is the ASP.NET redistributable, which is freely available, and you can continue to use your favorite editor of choice (come on, admit it “ it's Notepad). This gives you access to everything possible with ASP.NET, including multi-language support. For a richer environment you can use Visual Studio .NET, where you get the drag and drop support, colored code (more useful than you'd think), context-sensitive help and tooltips, and all of the usual great editing features that Visual Studio has brought in the past.

Benefits of ASP.NET

From this discussion of the problems with ASP it would be easy to say that ASP.NET solves those problems, and while that is so, there's a lot more to it than that. To understand what's been done, have a look at four of the main goals of ASP.NET:

  • Make code cleaner.

  • Improve deployment, scalability, security, and reliability.

  • Provide better support for different browsers and devices.

  • Enable a new breed of web applications.

You may not see some of this support directly, as the Common Language Runtime ( CLR ) handles much of it. This is discussed in detail in the next chapter, but for now we shall concentrate on how ASP.NET improves our lives.

Multiple Languages

ASP has been limited to scripting engines, notably VBScript and JScript. The .NET Framework inherently supports multiple languages, so you can use whichever you feel most comfortable with. By default the CLR comes with Visual Basic .NET, C#, and JScript .NET (all compiled), and there are a number of third party languages that we can use, such as Perl, COBOL, and many others. Additionally, Visual Studio .NET adds support for Visual C++, and an implementation of Java (called J#.NET). Because this language support is part of the framework, it really doesn't matter what language you, or others in your team, use. Obviously, from your point of a view, it's probably best to maintain some degree of compatibility (for maintenance purposes if nothing else), but as far as the framework is concerned , anything goes.

This multiple language support isn't just limited to what's available, but also to how it's used. It's quite possible to write components in one language, and use (or reuse) them from another language. The server-based controls are written in C#, but they can quite conveniently be sub-classed from Visual Basic .NET, and then sub-classed again in JScript .NET (or any .NET supported language).

Note

The framework is covered in more detail in the next chapter, while Chapter 3 delves into the languages themselves in more detail.

Server Processing

If you've done some Visual Basic programming, then you'll find the switch to the new ASP.NET Server Controls fairly painless, but they might cause some initial confusion if your programming has been limited to ASP. There's no need to worry though, as they are extremely easy to understand and use “ it's just that they are very different from ASP.

One of the big problems with ASP is that pages simply define one big function, starting at the top of the page and finishing at the bottom. The page content is rendered in the page order, whether it is straight HTML or ASP-generated HTML. Therefore, our logic was dependent upon its position in the page, and there's no way to target HTML controls except by rendering them as part of the stream. Anything we do requires us to write code, and that includes the output of HTML elements.

ASP.NET solves this problem by introducing a declarative, server-based model for controls. This is where the concept may seem alien to ASP programmers, because the controls are declared on the server, can be programmed against on the server, but can be event driven from the client. This sounds pretty weird, but it's simple to use. All you have to do to turn a normal HTML control into a server control is add runat ="server" as an attribute. For example:

  <input id="FirstName" type="text" runat="server">  

This is a standard HTML control, but the addition of the runat attribute allows the control to be programmed against with server-side code. For example, if this control is placed within a form and we submit the form back to the same page, we can do this in our server-side code:

  Dim PersonFirstName As String   PersonFirstName = FirstName.Text  

Making a control run on the server allows us to use the ID attribute to identify it directly. This allows the code to become more readable, since we don't have to refer to the form contents or copy the contents into variables . It's also more natural to refer to the control directly, which makes developing pages simpler. If you've done any Visual Basic or VBA programming, this won't seem too alien for you.

If you've only done scripting in ASP, then this may seem strange , but that's only because it's a different way of working with content to and from the browser. You've probably done database access, so you've used objects, called methods , and set properties, and the ASP.NET Server Controls aren't any different from this.

Note

The new server processing architecture is covered in Chapter 4.

Web Form Controls

Converting existing HTML controls to server-side ones is simple, but there are still several problems with this approach:

  • Consistency : We are still stuck with the rather non-intuitive nature of some HTML controls. Why for example, is there an INPUT tag for single line text entry, but a TEXTAREA tag for multi- line text entry? Surely a single control where we specify the rows and columns makes more sense?

  • User Experience : How do we easily write sites that render rich content for browsers such as IE, while also preserving compatibility with down level browsers? HTML doesn't have the ability to change its content depending on the browser “ we have to write the code for that.

  • Devices : How do we write sites that cope with devices other than browsers? WAP-Phones, PDAs, and even fridges have browsers nowadays. Like the browser issue, we'd have to manually write code for this.

To alleviate these problems, Microsoft has created a set of server controls, identified by the asp: prefix. The ASP.NET server controls tackle these problems by:

  • Providing a consistent naming standard. For example, all text entry fields are handled by the TextBox control. For the different modes (such as multi-line and password), we just specify attributes.

  • Providing consistent properties. All server controls use a consistent set of properties, making it easier to remember. For example, the Text field of a TextBox is more intuitive than a Value field.

  • Providing a consistent event model. Traditional ASP pages often have large amounts of code handling the posting of data, especially when one page provides multiple commands. With ASP.NET we wire-up controls to event procedures, giving our server-side code more structure.

  • Emitting pure HTML, or HTML plus client-side JavaScript. With one minor exception (which is intentional), the server controls emit HTML 3.2 by default, giving great cross-browser compatibility. This can be changed so that by default we target up-level browsers such as IE, where the controls will emit HTML 4.0 and DHTML, providing a richer interface. All the user ever sees is the HTML content, not the server controls.

  • Emitting device specific code. Certain controls will emit HTML when requested by a browser, but WML when requested by a WAP phone. The control handles the detection of the device and the generation of the correct markup.

The controls will be covered in detail in later chapters, but let's take a quick look at a simple example to see how these controls work:

  <html>   <script language="VB" runat="server">   Public Sub btn_Click(Sender As Object, E As EventArgs)   ' some code goes here   End Sub   </script>   <body>   <form runat="server">   Press the button: <asp:Button runat="server"   Text="Press Me" OnClick="btn_Click />   </form>   </body>   </html>  

The server control in this example is a button, added to the page using the asp:Button element. There are several things to note about this control:

  • It has the runat="server" attribute set, to tell ASP.NET that it should process this control.

  • It uses the Text attribute to set the text to be shown on the button. This is consistent with other controls.

  • It uses the OnClick attribute to identify the event procedure to be run when the button is clicked. Since this is a server control, this event procedure runs on the server.

The event procedure is automatically supplied with two parameters “ the control that generated the event, and any additional arguments the procedure requires. Within the event procedure, we can access any other server controls, including the contents of input fields submitted during a postback.

HTML Output

In traditional ASP pages, the ASP processor runs server-side code, stripping it out so that only HTML and client-side script is sent to the client. This process is exactly the same for ASP.NET pages (the <% %> tags still work), with the server controls being converted to their HTML equivalents. For example, the preceding page code renders the following HTML to the browser:

  <html>   <body>     <form name="ctrl2" method="post" action="test.aspx" id="ctrl2">   <input type="hidden" name="__VIEWSTATE"   value="YTB6MTU5NDYxNjE5Ml9fX3g=2dbab7f5" />     Press the button: <input type="submit" name="ctrl5" value="Press Me" />   </form>     </body>   </html>  

There are several things to note here:

  • The first is that the form has method , action , and id attributes added automatically. We can add these in ourselves (with the exception of the action attribute) if we want to, but it's not necessary.

  • A hidden input field is added, which contains (in a compressed form) the state of the server controls. This is called the ViewState, and is how ASP.NET manages the content of the controls. View State is covered in Chapter 4.

  • The Button is converted into a standard submit button.

So, we can see that even though we have better code on the server, it doesn't affect how the code is presented on the client. It's still standard HTML, with standard forms and elements.

Server Control Hierarchy

The server controls are logically broken down into a set of families:

  • HTML Server controls :The server equivalents of the HTML elements.

  • Web Form controls :Map closely to individual HTML elements.

  • List Controls :Map to groups of HTML elements that produce grids or grid-like layout.

  • Rich controls :Produce rich content and encapsulate complex functionality, and will output pure HTML or HTML and script. A good example of this is the Calendar control, which provides the user with a calendar from only one line of code.

  • Validation controls :Non-visible controls, but allow the easy use of both server-side and client- side form validation.

  • Mobile controls :Output HTML or WML depending upon the device accessing the page.

    Note

    Chapters 5 and 6 deal extensively with most of these controls, and Chapter 21 covers the Mobile Controls.

At such an early stage in the book, you may not be able to see the implications that these controls have for you, but let's take a couple of common examples. First off, the case of displaying data from a database, perhaps in some form of grid. In ASP, we'd open the Recordset containing the data, and loop through the rows and columns building up an HTML table. We might well have this abstracted into a separate function in an include file, but we still had to write the code. With the ASP.NET DataGrid control, it's the control itself that handles this for us. The list controls (which include the DataGrid) have built in support for extracting data from a data source and creating the HTML for us. For example, consider the following ASP code:

  <%   Dim rs   Dim fld     Set rs = Server.CreateObject("ADODB.Recordset")     rs.Open "SELECT * FROM authors", _   "Provider=SQLOLEDB; Data Source=.; Initial Catalog=pubs; UID=sa; PWD="     If Not rs.EOF Then   Response.Write "<table border='1'><tr>"   For Each fld In rs.Fields   Response.Write "<td>" & fld.Name & "</td>"   Next   Response.Write "</tr>"     While Not rs.EOF   Response.Write "<tr>"   For Each fld In rs.Fields   Response.Write "<td>" & fld.Value & "</td>"   Next   Response.Write "</tr>"   rs.MoveNext   Wend     Response.Write "</table>"   End If   %>  

There's nothing special about this “ it just creates an HTML table. Now compare this to the equivalent ASP.NET code using a DataGrid:

  <%@ Import Namespace="System.Data.SqlClient" %>   <script language="VB" runat="server">   Sub Page_Load(Sender As Object, E As EventArgs)   Dim con As New SqlConnection("Data Source=.; " & _   "Initial Catalog=pubs; UID=sa; PWD=")   Dim cmd As SqlCommand   con.Open()   cmd = New SqlCommand("SELECT * FROM authors", con)   DataGrid1.DataSource = cmd.ExecuteReader()   DataGrid1.DataBind()   con.Close()   End Sub   </script>   <asp:DataGrid id="DataGrid1" runat="server"/>  
Note

Note that you should always close a database connection when you have finished with it. Either call the Close method of the Connection object, or pass the value CommandBehavior.CloseConnection as the parameter to the ExecuteReader method. See Chapter 8 for more details.

We can immediately see how much less code needs to be written. In fact, all of the code here relates to getting the data from the database and binding it to the grid. There isn't any code to create a table as the DataGrid does this.

Note

Data binding is covered in Chapter 7.

Another great example of the power of controls is the Calendar control, which with one line of code creates a fully functional calendar on our web page:

  <asp:Calendar runat="server"/>  

That's it “ nothing extra is needed to get it working.

This sort of simplified approach doesn't mean that the controls are simple, just simple to use. The onus on coding has moved from the web page developer to the control developer. There are also plenty of other non-Microsoft controls, either planned or released, covering everything from more advanced grids to TreeViews. Alternatively you can write your own controls. This is covered in Chapter 18.

Language Improvements

One of the greatest new features is that scripting is dead “ hooray. This is a slight exaggeration, as what's really dead is the typeless, interpreted nature of these languages. VBScript is no longer supported, and is replaced with full Visual Basic support, while JScript is still supported but has the addition of types. In addition, a new language called C# (pronounced C Sharp) is introduced, with a format similar to C/C++. As ASP.NET is entirely written in C#, you can understand that this isn't a minor addition

We look at the detailed improvements in languages in Chapter 3, but for now, all we need to understand is that all languages:

  • Support data types.

  • Use a common set of data types.

  • Are fully compiled.

  • Are object oriented, and support inheritance.

What's also important is that the language support is built into the CLR, which provides this common support. This means that things such as inheritance are cross-language, so we can write components in C# and inherit and extend them in Visual Basic. The CLR manages all of this for us, as well as providing cross-language debugging, giving such features as being able to use a debugger to step through Visual Basic code in an ASP.NET page into a C# component.

Extensibility is also provided, meaning that additional languages are supported. Microsoft supply VB.NET, JScript, and C# as standard with the .NET SDK, but many other languages are being worked on by third parties.

Code and Content Separation

This is generally an unused feature of web site design, as many sites are created entirely by programmers. In itself, this isn't a bad thing, but I think programmers don't usually make great designers, and I count myself firmly in this group . ASP tended to build on this problem, as the code (ASP script) is, more often than not, intermingled with the content (HTML).

This makes it difficult for design and coding to be done at the same time, and also increases the risk of problems if updates to the page are required.

Code Inline

ASP.NET gets around this problem in one of two ways. The first is the code inline model, where code is still held within the ASP.NET page, but is not mixed with the HTML. It's easy to separate the code and content into two sections. For example:

  <html>   <% This is the code section %>   <script runat="server">   Public Sub btn_Click(Sender As Object, E As EventArgs)   YourName.Text = Name.Text   End Sub   </script>   <body>   <% This is the content section %>   <form runat="server">   Enter your name: <asp:TextBox id="Name" runat="server"/>   <br/>   Press the button: <asp:Button OnClick="btn_Click"   runat="server" Text="Press Me"/>   <br/>   Your name is: <asp:Label id="YourName" runat="server"/>   </form>   </body>   </html>  

This isn't that radical a design, but it is a marked difference from ASP where the <% %> server blocks are often intermingled with the HTML. Don't worry about what the code does for the moment, as we'll be covering that later. What's important is that all of the script is kept separate from the content. This split is possible in ASP.NET because of the new server control architecture, which allows access to the HTML controls from server-based code. We'll be looking at this in a moment.

Code-Behind

The second way of separating code from content is the code-behind model, where the code is completely removed into a separate file. Using the previous example, our HTML file would now look like this:

  <%@Page Language="VB" Inherits="Ch1CodeBehind"   src="Components\Ch1CodeBehind.vb" %>   <html>   <body>   <% This is the content section %>   <form runat="server">   Enter your name: <asp:TextBox id="Name" runat="server"/>   <br/>   Press the button: <asp:Button OnClick="btn_Click"   runat="server" Text="Press Me"/>   <br/>   Your name is: <asp:Label id="YourName" runat="server"/>   </form>   </body>   </html>  

Once again don't worry too much about the code itself “ it's the structure that's important. Notice how the script block has been removed, and a special Page directive has been added (these are covered in Chapter 4). This tells the CLR that the current page inherits its code from the named file, which looks like:

  Imports System   Imports System.Web.UI   Imports System.Web.UI.WebControls     Public Class Ch1CodeBehind   Inherits System.Web.UI.Page   Public Sub btn_Click(Sender As Object, E As EventArgs)   YourName.Text = Name.Text   End Sub   End Class  

Notice that the procedure btn_Click is the same as it was when it was inline. That's one of the great features of the code-behind model; apart from a few directives, the code remains exactly the same. And since we're now working in a compiled environment, there's no performance loss either.

Configuration

Two things govern the configuration of ASP.NET. The first is the standard IIS settings, no different from existing ASP applications. The second is the configuration file, an XML file containing the meta data for our application. There is a machine-wide file ( machine.config ) containing the defaults for all ASP.NET applications, and each application can have its own file ( web.config ) to override the defaults. The advantage of a file containing configuration information is that we don't need to touch the registry to modify settings “ each application is self-contained. This has an added advantage when we look to deploy an ASP.NET application, because the configuration is just one of the files that we deploy.

Note

The configuration files are covered in detail in Chapter 13.

Deployment

Deployment is another area made significantly simpler in ASP.NET, and is generally called XCopy Deployment , for the simple reason that it's all we generally have to do. Each application is self-contained, including the configuration file and components. In the .NET Framework, components no longer require registration, and copying them to their target location is all that's required.

Note

Deployment is covered in detail in Chapter 13.

There are exceptions to this model of deployment. One is if we are interacting with COM/COM+ components, which still need to be registered. Another is if we are using shared assemblies , where .NET components are being used by more than one ASP.NET application. In this case the component isn't kept within the same directory as the rest of the ASP.NET files.

Note

Interoperability with COM/COM+ is covered in Chapter 23.




Professional ASP. NET 1.1
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)
ISBN: 0470384611
EAN: 2147483647
Year: 2006
Pages: 243

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