Lesson 2: Using ASP.NET

Lesson 2: Using ASP.NET

In this lesson, you will learn how ASP.NET organizes a Web application into parts, and you will learn the roles and names of those parts. You will be introduced to Web forms, which are the central user-interface element of Web applications.

ASP.NET is part of the larger .NET Framework, so this lesson will also discuss how the .NET Framework is organized and how .NET applications run differently from the traditional Windows applications you might be used to.

Finally, this lesson ends with a discussion of the programming languages you can use to create Web applications. ASP.NET is not bound to any one programming language, and the end of this lesson lists some of the other available languages and explains some of the major differences between the two languages (Visual Basic .NET and Visual C#) featured in this book.

After this lesson, you will be able to

  • List the parts of a Web application and describe how they run on the server

  • Explain how a Web form differs from and is similar to both an HTML page and a Windows form

  • Describe some of the different components you can place on a Web form

  • Explain the parts of the .NET Framework and how the common language runtime (CLR) executes .NET applications

  • Understand how the .NET Framework is organized and know where to look for classes that handle common application programming tasks

  • Compare the Visual Basic .NET and Visual C# programming languages

Estimated lesson time: 10 minutes

Parts of a Web Application

A Web application consists of three parts: content, program logic, and Web configuration information. Table 1-2 summarizes these parts and gives examples of where they reside in an ASP.NET Web application.

Table 1-2. Parts of an ASP.NET Web Application

Part

Types of files

Description

Content

Web forms, HTML, images, audio, video, other data

Content files determine the appearance of a Web application. They can contain static text and images as well as elements that are composed on the fly by the program logic (as in the case of a database query).

Program logic

Executable files, scripts

The program logic determines how the application responds to user actions. ASP.NET Web applications have a dynamic-link library (DLL) file that runs on the server, and they can also include scripts that run on the client machine.

Configuration

Web configuration file, style sheets, IIS settings

The configuration files and settings determine how the application runs on the server, who has access, how errors are handled, and other details.

The Web form is the key element of a Web application. A Web form is a cross between a regular HTML page and a Windows form. It has the same appearance as and similar behavior to an HTML page, but it also has controls that respond to events and run code, like a Windows form.

In a completed Web application, the executable portion of the Web form is stored in an assembly (.dll) that runs on the server under the control of the ASP.NET worker process (asp_wp.exe), which runs in conjunction with IIS. The content portion of the Web form resides in a content directory of the Web server, as shown in Figure 1-4.

figure 1-4 asp.net web application parts on a web server

Figure 1-4. ASP.NET Web application parts on a Web server

When a user navigates to one of the Web forms from his or her browser, the following sequence occurs:

  1. IIS starts the ASP.NET worker process if it is not already running. The ASP.NET worker process loads the assembly associated with the Web form.

  2. The assembly composes a response to the user based on the content of the Web form that the user requested and any program logic that provides dynamic content.

  3. IIS returns the response to the user in the form of HTML.

Once the user gets the requested Web form, he or she can enter data, select options, click buttons, and use any other controls that appear on the page. Some controls, such as buttons, cause the page to be posted back to the server for event processing, and the sequence repeats itself, as shown in Figure 1-5.

figure 1-5 how the parts interact

Figure 1-5. How the parts interact

This cycle of events is described in greater detail in Lesson 2 of Chapter 2, Creating Web Forms Applications.

Web Form Components

Web forms can contain several different types of components, as summarized in Table 1-3.

Table 1-3. Components on a Web Form

Component

Examples

Description

Server controls

TextBox, Label, Button, ListBox, DropDownList, DataGrid

These controls respond to user events by running event procedures on the server. Server controls have built-in features for saving data that the user enters between page displays. You use server controls to define the user interface of a Web form.

HTML controls

Text Area, Table, Image, Submit Button, Reset Button

These represent the standard visual elements provided in HTML. HTML controls are useful when the more complete feature set provided by server controls is not needed.

Data controls

SqlConnection, SqlCommand, OleDbConnection, OleDbCommand, DataSet

Data controls provide a way to connect to, perform commands on, and retrieve data from SQL and OLE databases and XML data files.

System components

FileSystemWatcher, EventLog, MessageQueue

These components provide access to various system-level events that occur on the server.

You use the server and HTML controls to create the user interface on a Web form. The data controls and system components appear on the Web form only at design time to provide a visual way for you to set their properties and handle their events. At run-time, data controls and system components do not have a visual representation. Figure 1-6 shows a Web form containing components.

figure 1-6 a web form with components

Figure 1-6. A Web form with components

Chapter 4, Creating a User Interface, provides more detail about using server and HTML controls on a Web form.

The .NET Framework

ASP.NET is an important part of the .NET Framework, but it is just one part. Understanding what else the .NET Framework provides will help you program your ASP.NET application effectively and avoid writing new code to perform tasks that are already implemented within the .NET Framework.

First, a little background. The .NET Framework is the new Microsoft programming platform for developing Windows and Web software. It is made up of two parts:

  • An execution engine called the common language runtime (CLR)

  • A class library that provides core programming functions, such as those formerly available only through the Windows API, and application-level functions used for Web development (ASP.NET), data access (ADO.NET), security, and remote management

.NET applications aren t executed the same way as the traditional Windows applications you might be used to creating. Instead of being compiled into an executable containing native code, .NET application code is compiled into Microsoft intermediate language (MSIL) and stored in a file called an assembly. At run time, the assembly is compiled to its final state by the CLR. While running, the CLR provides memory management, type-safety checks, and other run-time tasks for the application. Figure 1-7 shows how this works.

figure 1-7 how a .net application runs

Figure 1-7. How a .NET application runs

Applications that run under the CLR are called managed code because the CLR takes care of many of the tasks that would have formerly been handled in the application s executable itself. Managed code solves the Windows programming problems of component registration and versioning (sometimes called DLL hell) because the assembly contains all the versioning and type information that the CLR needs to run the application. The CLR handles registration dynamically at run time, rather than statically through the system registry as is done with applications based on the Component Object Model (COM).

The .NET class library provides access to all the features of the CLR. The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes. Table 1-4 summarizes the .NET namespaces that are of the most interest to Web application programmers.

Table 1-4. Summary of the .NET Framework Class Library

Category

Namespaces

Provides classes for

Common types

System

All the common data types, including strings, arrays, and numeric types. These classes include methods for converting types, for manipulating strings and arrays, and for math and random number tasks.

Data access

System.Data, System.Data.Common, System.Data.OleDb, System.Data.SqlClient, System.Data.SqlTypes

Accessing databases. These classes include methods for connecting to databases, performing commands, retrieving data, and modifying data.

Debugging

System.Diagnostics

Debugging and tracing application execution.

File access

System.IO, System.IO.IsolatedStorage, System.DirectoryServices

Accessing the file system. These include methods for reading and writing files and getting paths and filenames.

Network communication

System.Net, System.Net.Sockets

Communicating over the Internet using low-level protocols such as TCP/IP. These classes are used when you re creating peer-to-peer applications.

Security

System.Security, System.Security.Cryptography, System.Security.Permissions, System.Security.Policy, System.Web.Security

Providing user authentication, user authorization, and data encrypting.

Web applications

System.Web, System.Web.Caching, System.Web.Configuration, System.Web.Hosting, System.Web.Mail, System.Web.SessionState, System.Web.UI, System.Web.UI.Design, System.Web.UI.WebControls, System.Web.UI.HtmlControls

Creating client/server applications that run over the Internet. These are the core classes used to create ASP.NET Web applications.

Web services

System.Web.Services, System.Web.Services.Configuration, System.Web.Services.Description, System.Web.Services.Discovery, System.Web.Services.Protocols

Creating and publishing components that can be used over the Internet. These are the core classes used to create ASP.NET Web services.

Windows applications

System.Windows.Forms, System.Windows.Forms.Design

Creating applications using Windows user interface components. These classes provide Windows forms and controls as well as the ability to create custom controls.

XML data

System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.Xpath, System.Xml.Xsl

Creating and accessing XML files.

Because the .NET namespaces organize classes by function, you can use them to help locate the classes and class members that provide the CLR features you want to use. For example, the System namespace is one of the most commonly used namespaces because it contains the classes for all the fundamental data types. Any time you declare a variable with a numeric, a string, or an array type, you are using the System namespace.

This approach allows the .NET Framework to provide built-in methods for converting data types and manipulating strings and arrays. For instance, the following lines of code use the built-in methods of the String and Array classes to sort a list.

Visual Basic .NET

' Declare and initialize a string. Dim strFruit As String = "oranges apples peaches kumquats nectarines mangos" ' Declare an array. Dim arrFruit As String() ' Place each word in an array element. arrFruit = strFruit.Split(" ") ' Sort the array. System.Array.Sort(arrFruit) ' Put the sorted data back in the string. strFruit = String.Join(" ", arrFruit)

Visual C#

// Declare and initialize a string. string strFruit = "oranges apples peaches kumquats nectarines mangos"; // Declare an array. string[] arrFruit; // Place each word in an array element. arrFruit = strFruit.Split(" ".ToCharArray()); // Sort the array. System.Array.Sort(arrFruit); // Put the sorted array back in the string. strFruit = System.String.Join(" ", arrFruit);

Many of the class methods in the System namespace can be used directly without first creating an object from the class. These are called shared members in Visual Basic .NET and static members in Visual C#. Shared and static members can be called from the class name itself, as in the System.Array.Sort line in the preceding code. Another example of a class with shared/static members is the Math class, as shown by the following Pi and Pow methods:

Visual Basic .NET

' Get the area of a circle. dblCircArea = System.Math.Pi * System.Math.Pow(intRadius, 2)

Visual C#

// Get the area of a circle. dblCircArea = System.Math.PI * System.Math.Pow(intRadius, 2) ;

The .NET Framework provides 124 different namespaces. Only about 40 of the most common ones are summarized in Table 1-4. For a list of the .NET Framework namespaces, see the topic titled Class Library in the Visual Studio .NET online Help.

Programming Languages

ASP.NET and, indeed, the whole .NET Framework are programming language independent. This means that you can choose any language that has implemented a CLR-compliant compiler. In addition to developing its own programming languages, Microsoft has formed partnerships with many language vendors to provide .NET support for Perl, Pascal, Eiffel, Cobol, Python, Smalltalk, and other programming languages.

This book covers creating Web applications with the Visual Basic .NET and the Visual C# programming languages. These two languages are functionally equivalent, which means that they each provide equal capabilities to create Web applications. The differences between the two languages are syntactical and stylistic.

Most current programmers will choose the language they are most familiar with. Current Visual Basic programmers will be more comfortable developing Web applications in Visual Basic .NET; C or C++ programmers will be more comfortable developing with Visual C#.

If you are new to programming or if you are choosing to extend your programming skills to new languages, learning both Visual Basic .NET and Visual C# is a practical goal. This is especially true when you create Web applications, because most of the tasks are performed through the .NET Framework classes, which means Visual Basic .NET code and Visual C# code often look nearly identical.

Table 1-5 summarizes some significant differences between Visual Basic .NET and Visual C#. This information is useful to keep in mind if you are choosing a programming language for the first time or if you are planning to switch between languages.

Table 1-5. Visual Basic .NET and Visual C# Differences

Feature

Visual Basic .NET

Visual C# .NET

Case sensitive

Not case sensitive: response.write( Yo ) OK

Case sensitive: response.write( Yo ); // Error! Response.Write( Yo ); // OK

Functional blocks

Use beginning and ending statements to declare functional blocks of code: Sub Show(strX as String) Response.Write(strX) End Sub

Use braces to declare functional blocks of code: void Show(string strX) { Response.Write(strX); }

Type conversion

Implicit type conversions are permitted by default:

Dim X As Integer X = 3.14 ' OK

You can limit conversions by including an Option Strict On statement at the beginning of modules.

Implicit type conversions are limited to operations that are guaranteed not to lose information, such as converting from int to float:

int X = 0; float Y = X; // OK

Other type conversions are performed explicitly by casts:

Y = 3.14F; X = (int)Y; //Cast, OK.

Or, by using type conversion methods:

string Z; Z = Y.ToString();

Comments

Comments always start with an apostrophe ( ):

' This is a comment.

There are three different types of comments: block (/* */), inline (//), and documentation (///):

/* Block comments can span lines or be used to comment out code. */ // Inline comments appear // to the right of code. /// <summary>Description /// of class.</summary>

For more information about documentation comments, see the XML Documentation topic in the Visual Studio online Help.

Arrays

Array elements are specified using parentheses:

arrFruit(1) = "Apple"

Array elements are specified using square brackets:

arrFruit[1] = "Apple";

Methods

You can omit parentheses after method names if arguments are omitted:

strX = objX.ToString

You must include parentheses after all methods:

strX = objX.ToString();

Statement termination

Statements are terminated by carriage return:

Response.Write("Hello")

Statements are terminated by the semicolon (;):

Response.Write("Hello");

Statement continuation

Statements are continued using the underscore (_):

intX = System.Math.PI * _ intRadius

Statements continue until the semicolon (;) and can span multiple lines if needed:

intX = System.Math.PI * intRadius;

String operator

Use the ampersand (&) or plus sign (+) to join strings:

strFruit = "Apples" & _  " Oranges"

Use the plus sign (+) to join strings:

strFruit = "Apples" +  " Oranges";

Comparison operators

Use =, >, <, >=, <=, <> to compare values:

If intX >= 5 Then

Use ==, >, <, >=, <=, != to compare values:

if (intX >= 5)

Negation

Use the Not keyword to express logical negation:

If Not IsPostBack Then

Use the ! operator to express logical negation:

if (!IsPostBack)

Object comparison

Use the Is keyword to compare object variables:

If objX Is objY Then

Use == to compare object variables:

if (objX == objY)

Object existence

Use the Nothing keyword or the IsNothing function to check whether an object exists:

If IsNothing(objX) Then

Use the null keyword to check whether an object exists:

if (objX == null)

In addition to the differences shown in Table 1-5, there are significant keyword differences between the two languages. The code examples throughout this book illustrate those differences. The Visual Studio .NET Help topic Language Equivalents provides a complete comparison of Visual Basic .NET, Visual C#, and other Microsoft languages.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

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