Home > Articles > Programming > Windows Programming

Overview of the ASP.NET Framework

Get to know the ASP.NET 4 Framework, including how to build a simple ASP.NET page, how to work with ASP.NET controls and pages, and how to install ASP.NET.
This chapter is from the book

This chapter is from the book

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

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

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

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

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
    • HostThe name or IP address of your email server
    • PortThe number of the port to use when sending an email message
  • Methods
    • SendEnables you to send an email message synchronously
    • SendAsyncEnables you to send an email message asynchronously
  • Events
    • SendCompletedRaised 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020