To read the article online, visit http://www.4GuysFromRolla.com/webtech/chapters/BuildASPNETWebSite/ch02.2.shtml

Return to the Build Your Own ASP.NET Web Site Sample Chapter Page
Return to the Complete Listing of Sample Chapters

Understanding Namespaces

Because ASP.NET is part of the .NET Framework, we have access to all the goodies that are built into it in the form of the .NET Framework Class Library. This library represents a huge resource of tools and features in the form of classes, all organized in a hierarchy of namespaces. When we want to use certain features that .NET provides, we have only to find the namespace that contains that functionality, and import that namespace into our ASP.NET page. Once we’ve done that, we can make use of the .NET classes in that namespace to achieve our own ends.

For instance, if we wanted to access a database from a page, we would import the namespace that contains classes for this purpose, which happens to be the System.Data.OleDb namespace. The dots (.) here indicate different levels of the hierarchy I mentioned—in other words, the System.Data.OleDb namespace is grouped within the System.Data namespace, which in turn is contained in the System namespace.

To import a particular namespace into an ASP.NET page, we use the Import directive. Consider the following excerpt from an ASP.NET page; it imports the System.Data.OleDb namespace, which contains classes called OleDbConnection, OleDbCommand, and OleDbDataReader. Importing the namespace lets us use these classes in a subroutine to display records from an Access database:

<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
<script runat="server" language="VB">
Sub ReadDatabase(s As Object, e As EventArgs)
  Dim objConn As New OleDbConnection( _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Database\books.mdb")
  Dim objCmd As New OleDbCommand("SELECT * FROM BookList", _
    objConn)
  Dim drBooks As OleDbDataReader

  objConn.Open()
  drBooks = objCmd.ExecuteReader()
  While drBooks.Read()
    Response.Write("<li>")
    Response.Write(drBooks("Title"))
  End While
  objConn.Close()
End Sub
</script>
</head>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
<script runat="server" language="C#">
void ReadDatabase(Object s, EventArgs e) {
  OleDbConnection objConn = new OleDbConnection(
    "Provider=Microsoft.Jet.OLEDB.4.0;" +
    "Data Source=C:\\Database\\books.mdb");
  OleDbCommand objCmd = new OleDbCommand("SELECT * FROM BookList",
    objConn);
  OleDbDataReader drBooks;
  objConn.Open();
  drBooks = objCmd.ExecuteReader();
  while (drBooks.Read()) {
    Response.Write("<li>");
    Response.Write(drBooks["Title"]);
  }
  objConn.Close();
}
</script>
</head>

Don’t worry too much about the code right now (we cover this in detail in Chapter 6, Database Design and Development). Suffice it to say that, as we’ve imported that namespace, we have access to all the classes that it contains, and we can use them to get information from an Access database for display on our page.

Specifically, the classes from System.Data.OleDb that are used in the above code are:

OleDbConnection

Used for connecting to the database

OleDbCommand

Used for creating a statement of contents to read from the database.

OleDbConnection

Used for connecting to the database

OleDbCommand

Used for creating a statement of contents to read from the database

OleDbDataReader

Used for actually reading contents from database

Object Oriented Programming Concepts

VB.NET and C# are great programming languages because they offer a structured way of programming. By structured, I mean that code is separated into modules, where each module defines classes that can be imported and used in other modules. Both languages are relatively simple to get started with, yet offer features sophisticated enough for complex, large-scale enterprise applications.

The languages’ ability to support more complex applications—their scalability—stems from the fact that both are object oriented programming (OOP) languages. But ask a seasoned developer what OOP really is, and they’ll start throwing out buzzwords and catch phrases that are sure to confuse you—terms like polymorphism, inheritance, and encapsulation. In this section, I aim to explain the fundamentals of OOP and how good OOP style can help you develop better, more versatile Web applications down the road. This section will provide a basic OOP foundation angled towards the Web developer. In particular, we’ll cover the following concepts:

  • Objects

  • Properties

  • Methods

  • Classes

  • Scope

  • Events

  • Inheritance

Objects

In OOP, one thinks of programming problems in terms of objects, properties, and methods. The best way to get a handle on these terms is to consider a real world object and show how it might be represented in an OOP program. Many books use the example of a car to introduce OOP. I’ll try to avoid that analogy and use something friendlier: my dog, an Australian Shepherd named Rayne.

Rayne is your average great, big, friendly, loving, playful mutt. You might describe him in terms of his physical properties: he’s gray, white, brown, and black, stands roughly one and a half feet high, and is about three feet long. You might also describe some methods to make him do things: he sits when he hears the command "Sit", lies down when he hears the command "Lie down", and comes when his name is called.

So, if we were to represent Rayne in an OOP program, we’d probably start by creating a class called Dog. A class describes how certain types of objects look from a programming point of view. When we define a class, we must define the following two things:

Properties

Properties hold specific information relevant to that class of object. You can think of properties as characteristics of the objects that they represent. Our Dog class might have properties such as Color, Height, and Length.

Methods

Methods are actions that objects of the class can be told to perform. Methods are subroutines (if they don’t return a value) or functions (if they do) that are specific to a given class. So the Dog class could have methods such as sit(), and lie_down().

Once we’ve defined a class, we can write code that creates objects of that class, using the class a little like a template. This means that objects of a particular class expose (or make available) the methods and properties defined by that class. So, we might create an instance of our Dog class called Rayne, set its properties accordingly, and use the methods defined by the class to interact with Rayne, as shown in Figure 3.3.

Figure 3.3. The methods defined by the class interact with the object.

The methods defined by the class interact with the object.

This is just a simple example to help you visualize what OOP is all about. In the next few sections, we’ll cover properties and methods in greater detail, talk about classes and class instances, scope, events, and even inheritance.

Properties

As we’ve seen, properties are characteristics shared by all objects of a particular class. In the case of our example, the following properties might be used to describe any given dog:

  • Color

  • Height

  • Length

In the same way, the more useful ASP.NET Button class exposes properties including:

  • Width

  • Height

  • ID

  • Text

  • ForeColor

  • BackColor

Unfortunately for me, if I get sick of Rayne’s color, I can’t change it. ASP.NET objects, on the other hand, let us change their properties very easily in the same way that we set variables. For instance, we’ve already used properties when setting text for the Label control, which is actually an object of class Label in the namespace System.Web.UI.WebControls:

lblMyText.Text = "Hello World"
lblMyText.Text = "Hello World";

In this example, we’re using a Label control called lblMyText. Remember, ASP.NET is all about controls, and, as it’s built on OOP, all control types are represented as classes. In fact, as you’ll learn in Chapter 4, Web Forms and Web Controls, all interaction with ASP.NET pages is handled via controls. When we place a control on a page, we give it a name through its id attribute, and this ID then serves as the name of the control. Rayne is an object. His name, or ID, is Rayne. Rayne has a height of eighteen inches. The same holds true for the Label control. The Label control’s name or ID in the previous example is lblMyText. Next, we use the dot operator (.) to access the property Text that the object exposes and set it to the string "Hello World."

Methods

With our dog example, we can make a particular dog do things by calling commands. If I want Rayne to sit, I tell him to sit. If I want Rayne to lie down, I tell him to lie down. In object oriented terms, I tell him what I want him to do by calling a predefined command or method, and a resulting action is performed. In VB.NET or C#, we would write this as rayne.Sit(), or rayne.LieDown().

As Web developers, we frequently call methods when a given event occurs. For instance, the example earlier in this chapter that took information from an Access database created an object called objConn to represent the connection to the database. We then opened the connection by calling the Open() method on that object as follows:

Dim objConn As As New OleDbConnection(
  "Provider=Microsoft.Jet.OLEDB.4.0;" & _
  "Data Source=C:\Database\books.mdb")
…
objConn.Open()

We say that the Open() method is exposed by the connection object, and that we’re calling the Open() method on the OleDbConnection object stored in objConn. We don’t need to know what dark secrets the method uses to do its magic; all we need to know is its name and what we use it for.

Classes

You can think of a class as a template for building as many objects as you like of a particular type. When you create an instance of a class, you are creating an object of that class, and the new object has all the characteristics and behaviors (properties and methods) defined by the class.

In our dog example, Rayne was an instance of the Dog class as shown in Figure 3.4.

Figure 3.4. A class serves as the blueprint for an object.

A class serves as the blueprint for an object.

We see that Rayne is an object of class Dog. In our code, we could create a new instance of the Dog class, call it rayne, and use all the properties and methods exposed by the object.

In OOP, when we create new instances of a class, we say we’re instantiating that class. For instance (no pun intended!), if we need to programmatically create a new instance of the Button control class, we could write the following code:

Dim myButton As New Button()
Button myButton = new Button();

As you can see, we’ve essentially created a new object called myButton from the Button class. We can then access the properties and methods that the Button exposes through our new instance:

myButton.Text = "Click Me!"
myButton.Text = "Click Me!";

Scope

You should now have a concept of programming objects as entities that exist in a program and are manipulated through the methods and properties they expose. However, in some cases, we want to create methods to use inside our class, which are not available when that class is used in code. Let’s return to the Dog class to illustrate.

Imagine we’re writing the Sit() method inside this class, and we realize that before the dog can sit, it has to shuffle its back paws forward a little (Just bear with me on this one…)! We could create a method called ShufflePaws(), then call that method from inside the Sit() method. However, we don’t want code in an ASP.NET page or in some other class to call this method—it’d just be silly. We can prevent this by controlling the scope of that method.

The two types of scope available in VB.NET and C# that you should know about are:

Public

Defining a property or method of a class as public allows that property or method to be called from outside the class itself. In other words, if an instance of this class is created inside another object (remember, too, that ASP.NET pages themselves are objects), public methods and properties are freely available to the code that created it. This is the default scope in VB.NET and C# classes.

Private

If a property or method of a class is private, it cannot be used from outside the class itself. If an instance of this class is created inside an object of a different class, the creating object has no access to private methods or properties of the created object.

Events

We’ve covered events fairly well already. To sum up, events occur when a control object sends a message in response to some change that has happened to it. Generally, these changes occur as the result of user interaction with the control in the browser. For instance, when a button is clicked, a Click event is raised, and we can handle that event to perform some action. The object that triggers the event is referred to as the event sender, while the object that receives the event is referred to as the event receiver. You’ll learn more about these terms in Chapter 4, Web Forms and Web Controls.

Understanding Inheritance

The term inheritance refers to the ability for one class to use properties and methods exposed by another class.

In our dog example, we first created a class called Dog, then created instances of that class to represent individual dogs such as Rayne. However, dogs are types of animals, and many characteristics of dogs are shared by all (or most) animals. For instance, Rayne has four legs, two ears, one nose, two eyes, etc. It might be better, then, for us to create a base class called Animal. When we then define the Dog class, it would inherit from the Animal class, and all public properties and methods of Animal would be available to instances of the Dog class.

Similarly, we could create a new class based on the Dog class. In programming circles, this is called deriving a subclass from Dog. For instance, we might create a class for Australian Shepherd and one for my other dog Amigo, called Chihuahua, both of which would inherit the properties and methods of the Dog base class, and define new ones specific to each breed.

Don’t worry too much if this is still a little unclear. The best way to appreciate inheritance is to see it used in a real program. The most obvious use of inheritance in ASP.NET comes with the technique of code-behind.

Separating Code From Content With Code-Behind

Most companies that employ development teams usually split projects into two groups, visual design and functional development, because software engineers are usually poor designers, and designers are often poor engineers. Until now, our ASP.NET pages have contained code render blocks that place VB.NET or C# code directly within the ASP.NET page. The problem with this approach is that there is no separation between the presentational elements of the page and the application logic. Traditional ASP was infamous for creating “spaghetti” code, which was scattered and intertwined throughout the presentation elements. This made it very tricky to manage the code between development teams, as you’ll know if you’ve ever tried to pick apart someone else’s ASP code. In response to these problems, ASP.NET introduces a new way of developing pages that allows code developers to work separately from the presentational designers who lay out individual pages.

This new method, called code-behind, keeps all of your presentational elements (controls) inside the .aspx file, but moves all your code to a separate class in a .vb or .cs code-behind file. Consider the following ASP.NET page, which displays a simple button and label:

<html>
<head>
  <title>Sample Page using VB.NET</title>
  <script runat="server" language="VB">
    Sub Click(s As Object, e As EventArgs)
      lblMessage.Text = "Hello World"
    End Sub
  </script>
</head>

<body>
  <form runat="server">
    <asp:Button id="btnSubmit" Text="Click Me" runat="server"
      OnClick="Click" />
    <br /><br /><asp:Label id="lblMessage" runat="server" />
  </form>
</body>
</html>
<html>
<head>
  <title>Sample Page using C#</title>
  <script runat="server" language="C#">
    void Click(Object s, EventArgs e) {
      lblMessage.Text = "Hello World";
    }
  </script>
</head>

<body>
  <form runat="server">
    <asp:Button id="btnSubmit" Text="Click Me" runat="server"
      OnClick="Click" />
    <br /><br /><asp:Label id="lblMessage" runat="server" />
  </form>
</body>
</html>

Let’s see how this example could be separated into the following two distinct files:

sample.aspx

layout, presentation, and static content

sample.vb, sample.cs

code-behind files containing a custom page class

First, we take all the code and place it in the code-behind file (sample.vb or sample.cs). This file is a pure code file, and contains no HTML or other markup tags. What it does contain is a class definition. Nevertheless, we can still access presentation elements from this file, using their IDs, such as lblMessage:

Example 3.16. sample.vb

' First off we import some useful namespaces
Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls

' All code-behind classes generally inherit from Page
Public Class Sample
  Inherits Page

  ' Declare the presentation elements on the ASPX page
  Protected WithEvents lblMessage As Label
  Protected WithEvents btnSubmit As Button

  ' Here's the Click handler just as it appeared before
  Sub Click(s As Object, e As EventArgs)
    lblMessage.Text = "Hello World"
  End Sub
End Class

Example 3.17. sample.cs

// First off we import some useful namespaces
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

// All code-behind classes generally inherit from Page
public class Sample : Page 
{
  // Declare the presentation elements on the ASPX page
  protected Label lblMessage;
  protected Button btnSubmit;

  // Here's the Click handler just as it appeared before
  public void Click(Object s, EventArgs e) {
    lblMessage.Text = "Hello World";
  }
}

Without code, the main ASP.NET page becomes much simpler:

Example 3.18. sample.aspx

<%@ Page Inherits="Sample" Src="Sample.vb" %>
<html>
<head>
  <title>Sample Page using VB.NET</title>
</head>

<body>
  <form runat="server">
    <asp:Button id="btnSubmit" Text="Click Me" runat="server"
      OnClick="Click" />
    <br /><br /><asp:Label id="lblMessage" runat="server" />
  </form>
</body>
</html>

Example 3.19. sample.aspx

<%@ Page Inherits="Sample" Src="Sample.cs" %>
<html>
<head>
  <title>Sample Page using C#</title>
</head>

<body>
  <form runat="server">
  <asp:Button id="btnSubmit" Text="Click Me" runat="server"
    OnClick="Click" />
  <br /><br /><asp:Label id="lblMessage" runat="server" />
  </form>
</body>
</html>

As you can see, the only line that’s different between the .aspx pages is the Page directive:

Example 3.20. sample.aspx (excerpt)

<%@ Page Inherits="Sample" Src="Sample.vb" %>

Example 3.21. sample.aspx (excerpt)

<%@ Page Inherits="Sample" Src="Sample.cs" %>

The only real change between the VB.NET and C# versions of the page is the source filename extension. In both cases, the page inherits from the class Sample.

The code-behind file is written differently from what you’re used to seeing so far. While we no longer need <script> tags, we find a class definition in its place. Looking at the VB.NET example, we start with three lines that import namespaces to be used in the code:

Example 3.22. sample.aspx (excerpt)

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls

The next lines create a new class, named Sample. Because our code-behind page contains code for an ASP.NET page, our class inherits from the Page class:

Example 3.23. sample.aspx (excerpt)

Public Class Sample
  Inherits Page

This is the practical application of inheritance that I mentioned above. Instead of using the built-in Page class, the code-behind method has you derive a subclass of Page for each page in your site. Next, we have to declare the controls that we want to use from the .aspx page—if we forget this step, we won’t be able to access them from our code:

Example 3.24. sample.aspx (excerpt)

  Protected WithEvents lblMessage As Label
  Protected WithEvents btnSubmit As Button

Finally, we create the Click subroutine just as before, and terminate the class:

Example 3.25. sample.aspx (excerpt)

  Sub Click(s As Object, e As EventArgs)
    lblMessage.Text = "Hello World"
  End Sub
End Class

As I hope you can see, code-behind files are reasonably easy to work with, and they can make managing and using our pages much more straightforward. On a typical project, I tend to use code-behind files quite frequently, but for simplicity’s sake, we’ll stick with code declaration blocks for at least the next few chapters.

Summary

Phew! That’s quite a few concepts to understand over the course of a single chapter. Don’t worry—with a little practice, these concepts will become second nature. I hope you leave this chapter with a basic understanding of programming concepts as they relate to the Web developer. The next chapter will begin to put all the concepts that we’ve covered so far into practice, beginning by covering HTML Controls, Web Forms, and Web Controls, before launching into our first hands-on project.



[3] Strictly speaking, a page is simply another type of control, and so page events are actually control events. When you’re first coming to grips with ASP.NET, however, it can help to think of them differently, especially since you don’t usually use OnEventName attributes to assign subroutines to handle them.

Buy this Book!
Want to read the entire book? Pick up a copy of Build Your Own ASP.NET Web Site from Amazon.com today!


Article Information
Article Title: Build Your Own ASP.NET Web Site Sample Chapter
Article Author: Author Unknown
Published Date: Thursday, May 13, 2004
Article URL: http://www.4GuysFromRolla.com/webtech/chapters/BuildASPNETWebSite/ch02.2.shtml


Copyright 2017 QuinStreet Inc. All Rights Reserved.
Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers