Overview of the ASP.NET Framework
- ASP.NET and the .NET Framework
- Understanding ASP.NET Controls
- Understanding ASP.NET Pages
- Installing ASP.NET
- Summary
Let's start by building a simple ASP.NET page.
If you use Visual Web Developer or Visual Studio, you first need to create a new website. Start Visual Web Developer and select File, New Web Site. The New Web Site dialog box appears (see Figure 1.1). Enter the folder in which you want your new website to be created (such as "Chapter1") in the Location field and click the OK button.
Figure 1.1 Creating a new website.
After you create a new website, you can add an ASP.NET page to it. Select Web Site, Add New Item. Select Web Form and enter the value FirstPage.aspx in the Name field. Make sure that both the Place Code in Separate File and Select Master Page check boxes are unchecked, and click the Add button to create the new ASP.NET page (see Figure 1.2).
Figure 1.2 Adding a new ASP.NET page.
Make sure that your code for FirstPage.aspx looks like the code contained in Listing 1.1.
Listing 1.1. FirstPage.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void Page_Load() { lblServerTime.Text = DateTime.Now.ToString(); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>First Page</title> </head> <body> <form id="form1" runat="server"> <div> Welcome to ASP.NET 4.0! The current date and time is: <asp:Label id="lblServerTime" Runat="server" /> </div> </form> </body> </html>
The ASP.NET page in Listing 1.1 displays a brief message and the server's current date and time. You can view the page in Listing 1.1 in a browser by right-clicking the page and selecting View in Browser (see Figure 1.3).
Figure 1.3 Viewing FirstPage.aspx in a browser.
The page in Listing 1.1 is an extremely simple page. However, it does illustrate the most common elements of an ASP.NET page. The page contains a directive, a code declaration block, and a page render block.
The first line, in Listing 1.1, contains a directive that looks like this:
<%@ Page Language="C#" %>
A directive always begins with the special characters <%@ and ends with the characters %>. Directives are used primarily to provide the compiler with the information it needs to compile the page.
For example, the directive in Listing 1.1 indicates that the code contained in the page is C# code. The page is compiled by the C# compiler and not another compiler, such as the Visual Basic .NET (VB.NET) compiler.
The next part of the page begins with the opening <script runat="server"> tag and ends with the closing </script> tag. The <script> tag contains the code declaration block.
The code declaration block contains all the methods used in the page. It contains all the page's functions and subroutines. The code declaration block in Listing 1.1 includes a single method named Page_Load(), which looks like this:
void Page_Load() { lblServerTime.Text = DateTime.Now.ToString(); }
This method assigns the current date and time to the Text property of a Label control contained in the body of the page named lblServerTime.
The Page_Load() method is an example of an event handler. This method handles the Page Load event. Every time the page loads, the method automatically executes and assigns the current date and time to the Label control.
The final part of the page is called the page render block, which contains everything rendered to the browser. In Listing 1.1, the render block includes everything between the opening and closing <html> tags.
The majority of the page render block consists of everyday HTML. For example, the page contains the standard HTML <head> and <body> tags. In Listing 1.1, two special things are contained in the page render block.
First, notice that the page contains a <form> tag that looks like this:
<form id="form1" runat="server">
This is an example of an ASP.NET control. Because the tag includes a runat="server" attribute, the tag represents an ASP.NET control that executes on the server.
ASP.NET pages are often called web form pages because they almost always contain a server-side form element.
The page render block also contains a Label control. The Label control is declared with the <asp:Label> tag. In Listing 1.1, the Label control is used to display the current date and time.
Controls are the heart of ASP.NET Framework. Most of the ink contained in this book is devoted to describing the properties and features of ASP.NET controls. Controls are discussed in more detail shortly; however, first you need to understand .NET Framework.
ASP.NET and the .NET Framework
ASP.NET is part of the Microsoft .NET Framework. To build ASP.NET pages, you need to take advantage of the features of .NET Framework, which consists of two parts: the Framework Class Library and the Common Language Runtime.
Understanding the Framework Class Library
The .NET Framework contains thousands of classes that you can use when building an application. Framework Class Library was designed to make it easier to perform the most common programming tasks. Following are just a few examples of the classes in the framework:
- File class—Enables you to represent a file on your hard drive. You can use the File class to check whether a file exists, create a new file, delete a file, and perform many other file-related tasks.
- Graphics class—Enables you to work with different types of images such as GIF, PNG, BMP, and JPEG. You can use the Graphics class to draw rectangles, arcs, ellipses, and other elements on an image
- Random class—Enables you to generate a random number.
- SmtpClient class—Enables you to send email. You can use the SmtpClient class to send emails that contain attachments and HTML content.
Framework has only four examples of classes. The .NET Framework contains more than 13,000 classes you can use when building applications.
You can view all the classes contained in the framework by opening the Microsoft .NET Framework SDK documentation on Microsoft's .NET Framework Developer Center website and expanding the Class Library node (see Figure 1.4). The SDK documentation website is located at http://msdn.microsoft.com/en-us/netframework/default.aspx.
Figure 1.4 The online Microsoft .NET Framework SDK documentation.
Each class in the Framework can include properties, methods, and events. The properties, methods, and events exposed by a class are the members of a class. For example, following is a partial list of the members of the SmtpClient class:
- Properties
- Host—The name or IP address of your email server
- Port—The number of the port to use when sending an email message
- Methods
- Send—Enables you to send an email message synchronously
- SendAsync—Enables you to send an email message asynchronously
- Events
- SendCompleted—Raised when an asynchronous send operation completes
If you know the members of a class, you know everything that you can do with a class. For example, the SmtpClient class includes two properties named Host and Port, which enable you to specify the email server and port to use when sending an email message.
The SmtpClient class also includes two methods you can use to send an email: Send() and SendAsync(). The Send method blocks further program execution until the send operation is completed. The SendAsync() method, on the other hand, sends the email asynchronously. Unlike the Send() method, the SendAsync() method does not wait to check whether the send operation was successful.
Finally, the SmtpClient class includes an event named SendCompleted, which is raised when an asynchronous send operation completes. You can create an event handler for the SendCompleted event that displays a message when the email has been successfully sent.
The page in Listing 1.2 sends an email by using the SmtpClient class and calling its Send() method.
Listing 1.2. SendMail.aspx
<%@ Page Language="C#" %> <%@ Import Namespace="System.Net.Mail" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void Page_Load() { SmtpClient client = new SmtpClient(); client.Host = "localhost"; client.Port = 25; client.Send("nate@somewhere", "nate@exclaimcomputing.com", "Beware!", "Watch out for zombies!"); } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Send Mail</title> </head> <body> <form id="form1" runat="server"> <div> Email sent! </div> </form> </body> </html>
The page in Listing 1.2 calls the SmtpClient Send() method to send the email. The first parameter is the from: address; the second parameter is the to: address; the third parameter is the subject; and the final parameter is the body of the email.
Understanding Namespaces
There are more than 13,000 classes in .NET Framework. This is an overwhelming number. If Microsoft simply jumbled all the classes together, you would never find anything. Fortunately, Microsoft divided the classes in the framework into separate namespaces.
A namespace is simply a category. For example, all the classes related to working with the file system are located in the System.IO namespace. All the classes for working a Microsoft SQL Server database are located in the System.Data.SqlClient namespace.
Before you can use a class in a page, you must indicate the namespace associated with the class. There are multiple ways of doing this.
First, you can fully qualify a class name with its namespace. For example, because the File class is contained in the System.IO namespace, you can use the following statement to check whether a file exists:
System.IO.File.Exists("SomeFile.txt")
Specifying a namespace every time you use a class can quickly become tedious. (It involves a lot of typing.) A second option is to import a namespace.
You can add an <$I<%@ Import % directive><%@ Import %> directive to a page to import a particular namespace. In Listing 1.2, we imported the System.Net.Mail namespace because the SmtpClient is part of this namespace. The page in Listing 1.2 includes the following directive near the top of the page:
<%@ Import Namespace="System.Net.Mail" %>
After you import a particular namespace, you can use all the classes in that namespace without qualifying the class names.
Finally, if you discover that you use a namespace in multiple pages in your application, you can configure all the pages in your application to recognize the namespace.
If you add the web configuration file in Listing 1.3 to your application, you do not need to import the System.Net.Mail namespace in a page to use the classes from this namespace. For example, if you include the Web.config file in your project, you can remove the <%@ Import %> directive from the page in Listing 1.2.
Listing 1.3. Web.Config
<?xml version="1.0"?> <configuration> <system.web> <pages> <namespaces> <add namespace="System.Net.Mail"/> </namespaces> </pages> </system.web> </configuration>
You don't have to import every namespace. ASP.NET gives you the most commonly used namespaces for free:
- System
- System.Collections
- System.Collections.Generic
- System.Collections.Specialized
- System.ComponentModel.DataAnnotations
- System.Configuration
- System.Data.Entity.Linq
- System.Data.Linq
- System.Text
- System.Text.RegularExpressions
- System.Web
- System.Web.Caching
- System.Web.DynamicData
- System.Web.SessionState
- System.Web.Security
- System.Web.Profile
- System.Web.UI
- System.Web.UI.WebControls
- System.Web.UI.WebControls.WebParts
- System.Web.UI.HtmlControls
- System.Xml.Linq
The default namespaces are listed inside the pages element in the root web configuration file located at the following path:
\Windows\Microsoft.NET\Framework\v4.0.30128\Config\Web.Config
Understanding Assemblies
An assembly is the actual .dll file on your hard drive in which the classes in .NET Framework are stored. For example, all the classes contained in the ASP.NET Framework are located in an assembly named System.Web.dll.
More accurately, an assembly is the primary unit of deployment, security, and version control in .NET Framework. Because an assembly can span multiple files, an assembly is often referred to as a "logical" dll.
The two types of assemblies are private and shared. A private assembly can be used by only a single application. A shared assembly, on the other hand, can be used by all applications located on the same server.
Shared assemblies are located in the Global Assembly Cache (GAC). For example, the System.Web.dll assembly and all the other assemblies included with .NET Framework are located in the Global Assembly Cache.
Before you can use a class contained in an assembly in your application, you must add a reference to the assembly. By default, an ASP.NET 4 application references the most common assemblies contained in the Global Assembly Cache:
- mscorlib.dll
- Microsoft.CSharp
- System.dll
- System.Configuration.dll
- System.Web.dll
- System.Data.dll
- System.Web.Services.dll
- System.Xml.dll
- System.Drawing.dll
- System.EnterpriseServices.dll
- System.IdentityModel.dll
- System.Runtime.Serialization.dll
- System.ServiceModel.dll
- System.ServiceModel.Activation.dll
- System.ServiceModel.Web.dll
- System.Activities.dll
- System.ServiceModel.Activities.dll
- System.WorkflowServices.dll
- System.Core.dll
- System.Web.Extensions.dll
- System.Data.DataSetExtensions.dll
- System.Xml.Linq.dll
- System.ComponentModel.DataAnnotations.dll
- System.Web.DynamicData.dll
- System.Data.Entity.dll
- System.Web.Entity.dll
- System.Data.Linq.dll
- System.Data.Entity.Design.dll
- System.Web.ApplicationServices.dll
All these assemblies are part of .NET 4 Framework. Websites created on previous versions of .NET referenced a different set of assemblies.
To use any particular class in .NET Framework, you must do two things. First, your application must reference the assembly that contains the class. Second, your application must import the namespace associated with the class.
In most cases, you won't worry about referencing the necessary assembly because the most common assemblies are referenced automatically. However, if you need to use a specialized assembly, you need to add a reference explicitly to the assembly. For example, if you need to interact with Active Directory by using the classes in the System.DirectoryServices namespace, you need to add a reference to the System.DirectoryServices.dll assembly to your application.
Each class entry in .NET Framework SDK documentation lists the assembly and namespace associated with the class. For example, if you look up the MessageQueue class in the documentation, you discover that this class is located in the System.Messaging namespace located in the System.Messaging.dll assembly.
If you use Visual Web Developer, you can add a reference to an assembly explicitly by selecting Web Site, Add Reference, and the name of the assembly that you need to reference. For example, adding a reference to the System.Messaging.dll assembly results in the web configuration file in Listing 1.4 being added to your application.
Listing 1.4. Web.Config
<?xml version="1.0"?> <configuration> <system.web> <compilation> <assemblies> <add assembly="System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> </assemblies> </compilation> </system.web> </configuration>
If you prefer not to use Visual Web Developer, you can add the reference to the System.Messaging.dll assembly by creating the file in Listing 1.4 manually.
Understanding the Common Language Runtime
The second part of .NET Framework is the Common Language Runtime (CLR). The CLR is responsible for executing your application code.
When you write an application for .NET Framework with a language such as C# or Visual Basic .NET, your source code is never compiled directly into machine code. Instead, the C# or Visual Basic compiler converts your code into a special language named Microsoft Intermediate Language (MSIL).
MSIL looks like an object-oriented assembly language; however, unlike a typical assembly language, it is not CPU-specific. MSIL is a low-level and platform-independent language.
When your application actually executes, the MSIL code is just-in-time compiled into machine code by the JITTER (the Just-In-Time compiler). Normally, your entire application is not compiled from MSIL into machine code. Instead, only the methods actually called during execution are compiled.
In reality, .NET Framework understands only one language: MSIL. However, you can write applications using languages such as Visual Basic .NET and C# for .NET Framework because .NET Framework includes compilers for these languages that enable you to compile your code into MSIL.
You can write code for .NET Framework using any one of dozens of different languages, including
- Ada
- Apl
- Caml
- COBOL
- Eiffel
- Forth
- Fortran
- JavaScript
- Oberon
- PERL
- Pascal
- PHP
- Python
- RPG
- Ruby
- Scheme
- Small Talk
The vast majority of developers building ASP.NET applications write the applications in either C# or Visual Basic .NET. Many of the other .NET languages in the preceding list are academic experiments. Once upon a time, if you wanted to become a developer, you concentrated on becoming proficient at a particular language. For example, you became a C++ programmer, a COBOL programmer, or a Visual Basic Programmer.
For .NET Framework, however, knowing a particular language is not particularly important. The choice of which language to use when building a .NET application is largely a preference choice. If you like case-sensitivity and curly braces, you should use the C# programming language. If you want to be lazy about casing and you don't like semicolons, write your code with Visual Basic .NET.
All the real action in .NET Framework happens in the Framework Class Library. If you want to become a good programmer using Microsoft technologies, you need to learn how to use the methods, properties, and events of the 13,000 classes included in the Framework. From the point of view of .NET Framework, it doesn't matter whether you use these classes from a Visual Basic .NET or C# application.