Search   Articles   Dev Forums   Personalize   Favorites   Member Login   ASP.Net Hosting
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Thursday, August 28, 2008

Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

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# we 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 Common Language Runtime (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.

  What's also provided is extensibility, meaning that additional languages can be 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
  I think that 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 on average I think programmers don't make great designers, and I count myself firmly in this group. While I'm extremely interested in interface design and usability, I'm not particularly good at it. 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, as well as risking potential 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 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 example we saw above, 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 exactly 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 to existing ASP applications. The second is the configuration file, an XML file containing the metadata 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.

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 that'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.

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.

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

Writing ASP.NET Pages
  The first part of this chapter has been a brief overview of some of the differences between ASP and ASP.NET, and Chapter4 goes into this in more detail. Now it's time to show you how to get those ASP.NET pages up and running as quickly as possible. Let's consider a simple form that extracts the author details from the pubs database. We'll have a drop-down list to show the various states where the authors live, a button to fetch the information, and a grid. This will quickly show you several simple techniques you can use in your pages.
Creating the Web Site
  The first thing to do is decide on where you want to create your own samples. Like ASP we can create a directory under \InetPub\wwwroot, or create a directory elsewhere and use a Virtual Site or Virtual Directory to point to it. There's no difference between the methods, it's purely a matter of preferences.

Next you can create your web pages, using whatever editor you prefer. You should give them an extension of .aspx.

The Sample Page
  Now let's add the code for the sample page – call this SamplePage.aspx (we'll examine it in more detail after we've seen it running). This page assumes that the Pubs database is installed on your system.

<%@ Import Namespace="System.Data.SqlClient" %>

<script language="VB" runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)

  If Not Page.IsPostBack Then
    state.Items.Add("CA")
    state.Items.Add("IN")
    state.Items.Add("KS")
    state.Items.Add("MD")
    state.Items.Add("MI")
    state.Items.Add("OR")
    state.Items.Add("TN")
    state.Items.Add("UT")
  End If
  
End Sub

Sub ShowAuthors(Sender As Object, E As EventArgs)

  Dim con As New SqlConnection("Data Source=.; " & _
                 "Initial Catalog=pubs; UID=sa; PWD=")
  Dim cmd As SqlCommand
  Dim qry As String
  
  con.Open()
  
  qry = "select * from authors where state='" & _
     state.SelectedItem.Text & "'"
  cmd = New SqlCommand(qry, con)
  

  DataGrid1.DataSource = cmd.ExecuteReader()
  DataGrid1.DataBind()
  
  con.Close()

End Sub

</script>

<form runat="server">

State: <asp:DropDownList id="state" runat="server" />

<asp:Button Text="Show Authors" OnClick="ShowAuthors" runat="server"/>

<p/>
<asp:DataGrid id="DataGrid1" runat="server"/>

</form>

When initially run we see the following:

  Nothing particularly challenging here, and when the button is pressed, the grid fills with authors from the selected state:


Click on image to see the full view

  Again, nothing that couldn't be achieved with ASP, but let's look at the page code, starting with the controls:

<form runat="server">

State: <asp:DropDownList id="state" runat="server" />

<asp:Button Text="Show Authors" OnClick="ShowAuthors" runat="server"/>

<p/>
<asp:DataGrid id="DataGrid1" runat="server"/>

</form>

  Here we have a form marked with the runat="server" attribute. This tells ASP.NET that the form will be posting back data for use in server code. Within the form there is a DropDownList (the equivalent of an HTML SELECT list) to contain the states, a Button (equivalent of an HTML INPUT type="button") to postback the data, and a DataGrid to display the authors. The button uses the OnClick event to identify the name of the server-side code to run when the button is pressed. Don't get confused by thinking this is the client-side, DHTML onClick event, because it's not. The control is a server-side control (runat="server") and therefore the event will be acted upon within server-side code.

  Now let's look at the remaining code, starting with the Import statement. This tells ASP.NET that we are going to use some data access code, in this case code specific to SQL Server.

<%@ Import Namespace="System.Data.SqlClient" %>

Next comes the actual code, written in Visual Basic.

<script language="VB" runat="server">

  Here is the first real introduction to the event architecture. When a page is loaded, the Page_Load event is raised, and any code within the event procedure is run. In our case, we want to fill the DropDownList with a list of states, so we just manually add them to the list. In reality, this data would probably come from a database.

Sub Page_Load(Sender As Object, E As EventArgs)

  If Not Page.IsPostBack Then
    state.Items.Add("CA")
    state.Items.Add("IN")
    state.Items.Add("KS")
    state.Items.Add("MD")
    state.Items.Add("MI")
    state.Items.Add("OR")
    state.Items.Add("TN")
    state.Items.Add("UT")
  End If
  
End Sub

  One thing to note about this code is that it is wrapped in an If statement, checking for a boolean property called IsPostBack. One of the great things about the Web Controls is that they retain their contents across page posts, so we don't have to refill them. Since the Page_Load event runs every time the page is run, we'd be adding the states to the list that already exists, and the list would keep getting bigger. The IsPostBack property allows us to identify whether or not this is the first time the page has been loaded, or if we have done a postback to the server.

  Now, when the button is clicked, the associated event procedure is run. This code just builds a SQL statement, fetches the appropriate data, and binds it to the grid.

Sub ShowAuthors(Sender As Object, E As EventArgs)

  Dim con As New SqlConnection("Data Source=.; " & _
                 "Initial Catalog=pubs; UID=sa; PWD=")
  Dim cmd As SqlCommand
  Dim qry As String
  
  con.Open()
  
  qry = "select * from authors where state='" & _
     state.SelectedItem.Text & "'"
  cmd = New SqlCommand(qry, con)
  
  DataGrid1.DataSource = cmd.ExecuteReader()
  DataGrid1.DataBind()
  
  con.Close()

End Sub

</script>

  This code isn't complex, although it may seem confusing at first glance. The rest of the book explains many of these concepts in more detail, but we can easily see some of the benefits. The code is neatly structured, making it easy to write and maintain. Code is broken down into events, and these are only run when invoked. Chapter 4 contains a good discussion of the page events, how they can be used, and the order in which they are raised.

  What's also noticeable is that there's less code to write compared to an equivalent ASP page. This means that we can create applications faster – much of the legwork is done by the controls themselves. What's also cool about the control architecture is that we can write our own to perform similar tasks. Because the whole of the .NET platform is object-based, we can take an existing control and inherit from it, creating our own, slightly modified control. A simple example of this would be a grid within a scrollable region. The supplied grid allows for paging, but not scrolling.

Summary
  This chapter has been a real whistle-stop tour of why ASP.NET has come about, some of the great features it has, and how easily we can create pages. We've looked at:

  • The problems of ASP
  • Why ASP.NET came about
  • The differences between ASP and ASP.NET
  • A simple example of an ASP.NET page

  ASP is still a great product, and it's really important to focus on why we had to change, and the benefits it will bring in the long term. Initially there will be some pain as you learn and move towards the .NET architecture, but ultimately your applications will be smaller, faster, and easier to write and maintain. That's pretty much what most developers want from life.

  Now it's time to learn about the .NET Framework itself, and how all of these great features are provided.

Copyright and Authorship Notice

  This chapter is written by Richard Anderson, Brian Francis, Alex Homer, Robert Howard, David Sussman, Karli Watson and are taken from "Professional ASP.NET" published by Wrox Press Limited in June 2001; ISBN 1861004885; copyright © Wrox Press Limited 2001; all rights reserved.

  No part of this chapter may be reproduced, stored in a retrieval system or transmitted in any form or by any means -- electronic, electrostatic, mechanical, photocopying, recording or
otherwise -- without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.

<<<<.....back  
DevASP.Net - Disclaimer - Privacy
Copyright © 2008 DevASP.net