Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать

Some Benefits of ASP.NET

 

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

ASP.NET addressesApresseach© 2003of the(1200limitationspages)

of classic ASP (and brings a number of new bells and whistles

to the game). First and foremost, ASP.NET files (*.aspx) do not use server-side scripting languages. As

This comprehensive text starts with a brief overview of the

mentioned earlier,C#ASPlanguage.NET allowsand thenyouquicklyto usemovesreal programmingto key techniclanguagesl and such as C#, MC++, and Visual Basic .NETarchitectural(or any otherissues.NETfor-aware.NET developerslanguage).. Because of this, you can apply all of the technique you have learned throughout this book directly to your Web development efforts. As you would expect, *.aspx pages can make use of the .NET class libraries as well as the functionality provided by any of your

Table of Contents

custom assemblies. Like always, simply access the Add References dialog box and find the assembly in

C# and the .NET Platform, Second Edition

question.

Introduction

Note While it is true that you can literally use any .NET assembly, it should make sense that the types

Part One - Introducing C# and the .NET Platform

within System.Windows.Forms.dll are of no use within a Web application. Surprisingly,

Chapter 1 - The Philosophy of .NET

System.Drawing.dll is extremely useful when programming with ASP.NET, given that you can

Chapter 2 - Building C# Applications

use GDI+ to dynamically generate an image file on the Web server (as seen at the end of this

Part Two - The C# Programming Language

chapter).

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Next, ASP.NET applications provide numerous ways to decrease the amount of code you need to write to

Chapter 5 - Exceptions and Object Lifetime

begin with. For example, through the use of server-side Web controls, you can build a browser-based front

Chapter 6 - Interfaces and Collections

end using various GUI widgets that emit raw HTML tags automatically. Other Web controls are used to

Chapter 7 - Callback Interfaces, Delegates, and Events

perform automatic validation of your GUI items, which decreases (if not eliminates) the amount of client- Chapterside JavaScript8 - Advancedyou areC#responsibleTy Constructionfor authoringTechniques. To add to the current laundry list of benefits, ponder the

Padditionalrt Three -aspectsProgrammingof ASPwith.NET:.NET Assemblies

Chapter 9 - Understanding .NET Assemblies

ASP.NET supports a technique termed code behind, which allows you to separate your presentation

Chapter 10 - Processes, AppDomains, Contexts, and Threads

logic from your business logic.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

ASP.NET makes use of true compiled .NET assemblies, not interpreted scripting languages, which

Chapter 12 - Object Serialization and the .NET Remoting Layer results in much faster execution.

Chapter 13 - Building a Better Window (Introducing Windows Forms)

ChapterASP14.NET- A BetterWeb controlsPainting allowFramewprogrammersrk (GDI+) to build the GUI of a Web app in a manner similar to

Chapterbuilding15 - Programmingtraditional desktopwith WindowsapplicationForms. Controls

Chapter 16 - The System.IO Namespace

ASP.NET Web controls automatically maintain their state during postbacks using a hidden form field

Chapter 17 - Data Access with ADO.NET named __VIEWSTATE.

Part Five - Web Applications and XML Web Services

Chapter 18

- ASP.NET Web Pages and Web Controls

ASP.NET Web applications are completely object oriented. You no longer need to examine the Form

Chapter 19

- A P.NET Web Applicati ns

or QueryString collections to obtain the values submitted by the client (although these techniques are

Chapter 20

- XML Web Services

still supported).

Index

ASP.NET Web applications can be easily configured using standard IIS settings or using a Web

List of Figures

application configuration file (web.config).

List of Tables

ASP.NET Web applications are extremely simple to deploy given that .NET assemblies are not registered into the system registry.

To begin seeing these and other benefits in action, let's get to know the ASP.NET namespaces, all of which are contained within the System.Web.dll assembly.

Chapter 20 - XML Web Services
Chapter 19 - ASP.NET Web Applications

The ASP.NETC# andNamespacesthe .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

The .NET base class libraries contain numerous namespaces focused on Web-based technologies.

Apress © 2003 (1200 pages)

Generally speaking, these namespaces can be grouped into three major categories: core Web atoms

This comprehensive text starts with a brief overview of the

(e.g., types that allowC# languageyou to interactand thenwithquicklythe HTTPmovesrequestto k y technicaland response,and configuration types, e-mail, and security types), UIarchitecturalwidgets (WebFormissues forand.NETHTMLdeveloperscontrols),. and XML Web services (examined in Chapter 20).Table 18-2 documents the ASP.NET-centric namespaces.

Table of Contents

 

 

 

 

 

Table 18-2: ASP.NET Namespaces

C# and the .NET Platform, Second

 

Edition

 

 

 

 

IntroductionWeb-Centric Namespace

 

Meaning in Life

 

 

 

 

 

 

 

 

Part One - Introducing C# and the

 

.NET Platform

 

 

 

 

System.Web

 

System.Web defines core types that enable browser/Web server

 

 

Chapter 1

- The Philosophy of .NET

 

communication (such as request and response capabilities,

 

 

Chapter 2 - Building C# Applications

 

cookie manipulation, and file transfer).

 

 

 

 

 

 

 

 

Part Two - The C# Programming Language

 

 

 

ChapterSystem.Web.Caching3 - C# Language FundamentalsThis namespace contains types that facilitate caching support

 

 

 

 

 

 

 

for a Web application.

 

 

 

Chapter 4 - Object-Oriented Programming with C#

 

 

 

 

 

 

 

 

 

 

Chapter 5 - Exceptions and Object

 

Lifetime

 

 

 

 

System.Web.Configuration

 

This namespace contains types that allow you to

 

 

 

Chapter 6

- Interfaces and Collections

programmatically interact with the project's Web.config file.

 

 

 

 

 

 

 

 

 

Chapter 7

- Callback Interfaces,

 

Delegates, and Events

 

 

 

 

System.Web.Mail

 

Defines the types that allow you to integrate e-mail functionality.

 

 

 

 

Chapter 8

- Advanced C# Type

 

Construction Techniques

 

 

PartSystemThree.Web- Programmi.SessionStateg with .NET AssembliesDefines the types that allow you to maintain stateful information Chapter 9 - Understanding .NET Assemblieson a per-user basis (e.g., session state variables).

Chapter 10 - Processes, AppDomains, Contexts, and Threads

System.Web.Security

Defines types that allow you to programmatically secure your

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

site.

Part Four - Leveraging the .NET Libraries

ChapterSystem12.Web- Object.UI Serialization and Theset .NETnamespacesRemoting Laydefiner a number of types that allow you to

Chapter 13 - Building a Better Windowbuild(Introducinga GUI frontWindowsend forForms)your Web application. System.Web.UI.WebControls

Chapter 14 - A Better Painting Framework (GDI+)

System.Web.UI.HtmlControls

Chapter 15 - Programming with Windows Forms Controls Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

The Core Types of System.Web

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

The System.Web namespace defines the minimal and complete set of types that allow you to build an ASP.NET Web application. Table 18-3 is a quick rundown of some items of interest, many of which are

examined in greater detail throughout this chapter.

Index

List of Figures

Table 18-3: Core Types of the System.Web Namespace

List of Tables

 

 

 

 

 

 

 

 

System.Web TypeC# and the

.MeaningNET Platform,in LifeSecond Edition

 

 

 

 

 

 

 

 

 

 

by Andrew

Troelsen

ISBN:1590590554

 

 

HttpApplication

 

The HttpApplication class defines the members common to all

 

 

 

Apress © 2003 (1200 pages)

 

 

 

 

 

ASP.NET applications. As you will see, the global.asax file defines a

 

 

 

This comprehensive text starts with a brief overview of the

 

 

 

 

 

class derived from HttpApplication.

 

 

 

C# language

 

and then quickly moves to key technical and

 

 

 

architectural

 

issues for .NET developers.

 

 

 

HttpApplicationState

 

The HttpApplicationState class enables developers to share global

 

 

 

 

 

information across multiple sessions in an ASP.NET application.

 

 

 

 

 

 

 

 

 

HttpBrowserCapabilities

 

Enables the server to compile information on the capabilities of the

 

 

Table of Cont nts

 

 

 

 

 

C# and the .NET Platform, SecondbrowserEditionthat sent the HTTP request.

 

 

 

 

 

 

 

 

 

 

Introduction

 

Provides a type-safe way to access multiple HTTP cookies.

 

 

 

HttpCookie

 

 

 

Part One - Introducing C# and

 

the .NET Platform

 

 

 

 

 

ChapHttpRequester 1 - The Philosophy of Provides.NET

an object-oriented way to enable browser-to-server

 

 

Chapter 2 - Building C# Applicationscommunication.

 

 

 

 

 

 

 

 

Part Two - The C# Programming

 

Language

 

 

 

HttpResponse

 

Provides an object-oriented way to enable server-to-browser

 

 

Chapter 3 - C# Language

 

Fundamentals

 

 

 

 

 

communication.

 

 

 

Chapter 4 - Object-Oriented

 

Programming with C#

 

 

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

 

 

 

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

SqlConnection sqlConn =

Creating an ASP.NET Web Application by Hand

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

ASP.NET Web applicationsA ress typically make use of a technique termed code behind, which allows you to

© 2003 (1200 pages)

separate your programming code from your HTML presentation logic. While this is certainly the recommended

This comprehensive text starts with a brief overview of the

approach, it is stillC#technicallylangu ge possibleand then toquicklyavoidmovesusing toa codekey technicalbehind fileandand directly embed .NET code within the *.aspx file. However,architecturalbe veryissuesawarefor .thatNETifdevelopersyou choose. to build your ASP.NET pages in this manner, you are essentially re-creating a major issue found with classic ASP (the hodgepodge of script blocks and HTML presentation tags in a single server-side file).

Table of Contents

C#Nevertheless,and the .NETlet'sPlatform,walk throughSecond Editionan example of building a single-paged Web application that does not make

use of code behind, and learn some basic features of ASP.NET in the process. Create a new virtual directory

Introduction

named CarsInventoryPage that maps to a specific directory on your hard drive. Next, create a new file named

Part One - Introducing C# and the .NET Platform

CarsInventoryPage.aspx and save it in the physical directory you just created.

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

PartCodingTwo - ThetheC# Programming*.aspx FileLanguage

Chapter 3 - C# Language Fundamentals

For this example (and this example only), you will avoid the use of a code behind file, and therefore your

Chapter 4 - Object-Oriented Programming with C#

server-side programming logic will be embedded directly within the *.aspx file. The goal of this page is simple:

Chapter 5 - Exceptions and Object Lifetime

Open a connection to the Cars database (created in Chapter 17) and display the current inventory. To do so,

Chapter 6 - Interfaces and Collections

you will make use of three ASP.NET WebForm controls (a Label, DataGrid, and Button type) and a block of

Chapter 7 - Callback Interfaces, Delegates, and Events

server-side C# code. Here is the complete page, with analysis to follow:

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

<%@ Page language="c#"%>

Chapter 9 - Understanding .NET Assemblies

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

Chapter 10 - Processes, AppDomains, Contexts, and Threads

<HTML>

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

<HEAD>

Part Four - Leveraging the .NET Libraries

<title>This is the cars inventory page</title>

Chapter 12 - Object Serialization and the .NET Remoting Layer

<script language="C#" runat="server">

Chapter 13 - Building a Better Window (Introducing Windows Forms) void GetTheData(object sender, EventArgs e)

Chapter 14 - A Better Painting Framework (GDI+)

{

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

new SqlConnection("Data Source=.;Initial Catalog=Cars;UID=sa;PWD=");

Chapter 17 - Data Access with ADO.NET sqlConn.Open();

Part Five - Web Applications and XML Web Services

SqlCommand cmd =

Chapter 18 - ASP.NET Web Pages and Web Controls

new SqlCommand("Select * From Inventory", sqlConn);

Chapter 19 - ASP.NET Web Applications

inventoryGrid.DataSource = cmd.ExecuteReader();

Chapter 20 - XML Web Services

inventoryGrid.DataBind();

Index sqlConn.Close();

List of Figures}

List of Tables</script>

</HEAD>

<body>

<form id="Form1" method="post" runat="server"> <asp:Label id="Label1" runat="server">

Click on the button below to fill the DataGrid </asp:Label></p>

<asp:Button id="btnGetData" OnClick="GetTheData" runat="server" Text="Get the Data!">

</asp:Button></p>

<asp:DataGrid id=" inventoryGrid" runat="server" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4">

</asp:DataGrid> </form>

</body>

</HTML>

Chapter 20 - XML Web Services
Chapter 19 - ASP.NET Web Applications

C# and the .NET Platform, Second Edition

by Andrew Troelsen ISBN:1590590554

The <%@Page%> Directive

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

The first thing to be aware of is that a given *.aspx file will typically open with a set of page-level directives.

C# language and then quickly moves to key technical and

ASP.NET directives are always denoted with <%@ XXX %> markers, and may be qualified with various architectural issues for .NET developers.

attributes to inform the ASP.NET runtime how to process the information.

Every *.aspx file must have at minimum a <%@Page%> directive that is used to define the managed language

Table of Contents

used within the page (via the language directive). Also, the <%@Page%> directive may also define the name

C# and the .NET Platform, Second Edition

of the related code behind file (if any), enable tracing, and so forth. Table 18-4 documents some of the more

Introduction

 

 

 

 

 

 

interesting <%@Page%>-centric attributes.

Part One - Introducing C# and the .NET Platform

Chapter 1

- The Philosophy of .NET

 

 

Table 18-4: Some (But Not All) of the @Page Attributes

 

 

 

Chapter 2

- Building C# Applications

 

 

PartAttributeTwo - The C#ofProgrammingthe

 

LanguageMeaning in Life

 

 

Chapter@Page3

Directive- C# Language Fundamentals

 

 

 

 

 

 

 

 

 

 

 

Chapter 4

- Object-Oriented

 

Programming with C#

 

 

 

 

 

ClassName

 

This attribute allows you to define a specific name for the auto-

 

 

 

Chapter 5

- Exceptions and Object Lifetime

 

 

 

 

 

 

 

 

generated class type.

 

 

 

 

 

Chapter 6

- Interfaces and Collections

 

 

 

 

 

 

 

ChapterCodeBehind7 - Callback Interfaces, Delegates,This attributeandisEventsused to specify the name of the related code behind

 

 

 

 

 

Chapter 8

- Advanced C# Type

 

file.

 

 

 

 

Construction Techniques

 

 

 

 

 

 

 

Part Three - Programming with

 

.NET Assemblies

 

 

 

 

 

EnableViewState

 

Indicates whether view state is maintained across page requests (more

 

 

Chapter 9

- Understanding .NET

 

Assemblies

 

 

 

 

 

 

 

 

details later). True if view state is maintained; otherwise, false. The

 

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

 

 

 

 

 

 

 

 

default value is true.

 

 

 

 

 

 

 

 

 

 

 

Chapter 11

- Type Reflection, Late

Binding, and Attribute-Based Programming

 

 

 

 

 

Inherits

 

 

Defines a code behind class for the page to inherit. Can be any class

 

 

Part Four - Leveraging the .NET

Libraries

 

 

Chapter 12

- Object Serialization

derived from the Page class. Used to specify the name of the class in

 

 

and the .NET Remoting Layer

 

 

 

 

 

 

 

 

the code behind file from which this type derives.

 

 

 

Chapter 13

- Building a Better Window (Introducing Windows Forms)

 

 

 

 

 

Trace

- A Better Painting

 

Indicates whether tracing is enabled (true or false).

 

 

 

Chapter 14

 

Framework (GDI+)

 

 

 

 

 

 

 

 

 

 

 

 

Chapter 15

- Programming with Windows Forms Controls

Chapter 16

- The System.IO Namespace

The <%Import%> Directive

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

In addition to the <%@Page%> directive, a given *.aspx file may specify further directives. In this example, you

Chapter 18 - ASP.NET Web Pages and Web Controls

make use of the <%@Import%> directive (in conjunction with the Namespace attribute) to explicitly state that this page is using types within the System.Data.SqlClient namespace. As you would guess, if you need to

make use of additional .NET namespaces, you simply specify multiple <%@Import%> directives.

Index

List ofNoteFiguresThe <%@Import%> directive is only necessary if you are not making use of code behind. When you

List of Tablesdo make use of code behind, you will reference external namespaces using the C# "using" keyword.

Given your current knowledge of .NET, you may wonder how this *.aspx file avoided specifying the System.Data or System namespaces. The reason is due to the fact that all *.aspx pages automatically have access to a small set of key .NET namespaces:

System

System.Collections

System.Configuration

System.IO

System.Text

System.Text.RegularExpressions

Chapter 18 - ASP.NET Web Pages and Web Controls
Part Five - Web Applications and XML Web Services
Chapter 17 - Data Access with ADO.NET

All of the System.Web-centric namespaces

C# and the .NET Platform, Second Edition

ASP.NET does defineby Andrewa numberTroelsenof other directives that may appearISBN:1590590554in an *.aspx file above and beyond <%@Page%> andApress<%@Import%>;© 2003 (1200 pages)however, I'll reserve comment for the time being.

This comprehensive text starts with a brief overview of the

The "Script" C#Blocklanguage and then quickly moves to key technical and

architectural issues for .NET developers.

Even though server-side scripting is dead under ASP.NET, code that is embedded within an *.aspx file is scoped within <script> tags. Note that it is critical that all of your server-side code blocks are defined to execute

Table of Contents

at the server, using the runat="server" attribute:

C# and the .NET Platform, Second Edition

Introduction

<script language="C#" runat="server">

Part One - Introducing C# and the .NET Platform

void GetTheData(object sender, EventArgs e)

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

...

Part Two - The C# Programming Language

}

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

The signature of this helper method should look strangely familiar. Recall from our examination of Windows

Chapter 5 - Exceptions and Object Lifetime

Forms that a given event handler must match the pattern defined by a related .NET delegate. And, just like

Chapter 6 - Interfaces and Collections

Windows Forms, when you wish to handle a server-side button click, the delegate in question is

Chapter 7 - Callback Interfaces, Delegates, and Events

System.EventHandler (which, as you recall, can only call methods that take a System.Object as the first

Chapter 8 - Advanced C# Type Construction Techniques

parameter and a System.EventArgs as the second).

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Within the scope of the GetTheData() method, you make use of standard ADO.NET logic to bind the records

Chapter 10 - Processes, AppDomains, Contexts, and Threads

returned by the DataReader to a variable of DataGrid. Now, if you have a background in classic ASP, I am

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

pleased to inform you that your days of nested for-loops and table-centric HTML tags are over. Rather than PartmanuallyFour - LeverabuildingingthetheHTML.NETtableLibrariesby hand, ASP.NET DataGrids automatically emit the correct tag set

Chapterautomatically12 - Object. Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

ChapterThe ASP14 -.ANETBetterWidgetPainting FrameworkDeclarations(GDI+)

Chapter 15 - Programming with Windows Forms Controls

The final point of interest is the declaration of the Button, Label, and DataGrid WebForm controls. Like classic

Chapter 16 - The System.IO Namespace

ASP and raw HTML, ASP.NET Web widgets are scoped within <form> elements. This time, however, the opening <form> element is marked with the runat="server" attribute. This again is critical, as this tag informs the ASP.NET runtime that before the HTML is emitted into the response stream, the contained ASP.NET

widgets have a chance to render their HTML appearance.

Chapter 19 - ASP.NET Web Applications

ChapterASP.NET20 -WebXMLcontrolsWeb Servicesare declared with <asp> and </asp> tags, and are also marked with the

Indexrunat="server" attribute. Within the opening tag, you will specify the name of the WebForm control (such as

ListLabel,of FigButton,res DataGrid) and any number of name/value pairs that will be used at runtime to render the correct ListHTMLof Tables. Now, as you will see in the next example, these name/value pairs correspond directly to properties of the corresponding class type. For example, when you declare a DataGrid and specify BackColor="White", you have basically set the BackColor property of the System.Web.UI.WebControls.DataGrid type. In any case, ponder the following declarations:

<form id="Form1" method="post" runat="server"> <P> <asp:Label id="Label1" runat="server">

Click on the button below to fill the DataGrid </asp:Label><p/>

<asp:Button id="btnGetData" OnClick="GetTheData" runat="server" Text="Get the Data!">

</asp:Button><p/>

<asp:DataGrid id="DataGrid1" runat="server" BorderColor="#CC9966" BorderStyle="None"

BorderWidth="1px" BackColor="White" CellPadding="4"> </asp:DataGrid>

</form>

C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Finally, notice thatAprthessButton© 2003 type(1200 hasp ges)made use of the OnClick attribute to specify the name of the serverside function thatThiswill becomprehensivecalled whentextthestartsuser clickswith athebriefButtonoverviewwidgetof .theAt this point, you can open a browser and navigate to theC#CarsInventoryPagelanguage and then quickly.aspx page:moves to key technical and

architectural issues for .NET developers.

http://localhost/FirstAspNetWebApp/CarsInventoryPage.aspx

TableTheofresultsContentsare seen in Figure 18-9.

C# and the .NET Platform, Second Edition

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Part

 

Chapter

 

Chapter

Forms)

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Part

 

Chapter

 

Chapter 19 - ASP.NET Web Applications

 

Figure 18-9: Your first ASP.NET Web application

 

Chapter 20 - XML Web Services

 

Index

 

List of Figures

 

List of Tables

 

The ASP.NETC# andCompilationthe .NET Platform,CycleSecond Edition

by Andrew Troelsen

ISBN:1590590554

One question that may be on your mind at this point is how exactly your block of C# code was executed by

Apress © 2003 (1200 pages)

the ASP.NET runtime. As you are already well aware, the CLR can only interact with CIL code that is

This comprehensive text starts with a brief overview of the

contained within aC#.NETlanguageassemblyand then(obviously,quickly yourmoves*.aspxto keyfiletechis noticalaand.NET binary, but a simple text file). Behind the scenes,architecturalwhen the issuesinitial HTTPfor .NETrequestdeveloperscomes. in for a given *.aspx file, the runtime will parse all of the code within the <script> blocks and generate a brand new dynamic assembly. This image is then persisted to file, and stored under a very specific location (sometimes called the shadow directory) on the

Table of Contents

Web server machine:

C# and the .NET Platform, Second Edition

Introduction

<drive>:\<%windir%>\Microsoft .NET\Framework\<version>\Temporary ASP.NET Files

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

ChaptUnder this2 -directory,Building C#youApplicationswill find subdirectory that reflects the name of the hosting virtual directory. From

Parthere,Twoyou- Thewill C#needProgrammingto drill downLanguagethrough some further auto-generated folders (which are named based on

Chvariouspter 3hash- C#algorithms)Language untilFundamentalsyou find the name of the compiled *.dll assembly. Again, the name of your

Chapter.NET assembly4 - Objectwill-Orientedbe uniqueProgramming(Figure 18-wit10h). C#

Chapter 5 - Exceptions and Object Lifetime

Chapter

 

Chapter

Events

Chapter

Techniques

Part

 

Chapter

 

Chapter

and Threads

Chapter

Attribute-Based Programming

Part

 

Chapter

Remoting Layer

Chapter

Windows Forms)

Chapter

Figure 18-10: The location of the dynamically created assembly

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Like any .NET assembly, you are able to open up the binary using ildasm.exe and check out the underlying PartCIL,Fivemanifest,- Web Applicationsand metadataand. LookingXML Webat ServicesFigure 18-11, you can see that your immediate base class is

ChapSystemr 18.Web- ASP.UI.PageNET Web. Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of

List of

Figure 18-11: *.aspx files become classes that extend System.Web.UI.Page.

After the assembly has been created upon the initial HTTP request, it will be reused for all subsequent requests, and thus will not have to be recompiled. Understanding this factoid should help explain why the first request of an *.aspx page takes the longest, and subsequent hits to the same page are extremely efficient.

Now, open up your CarsInventoryPage.aspx file in Notepad and make some sort of code update, such as changing the Text value for the Button type:

Part Five - Web Applications and XML Web Services
Chapter 17 - Data Access with ADO.NET

<asp:Button id="btnGetData"C# and the .NET Platform,OnClick="GetTheData"Second Edition

runat="server"Text="Get the Data NOW!"> ISBN:1590590554 by Andrew Troelsen

</asp:Button>

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

If you save this filearchitecturaland requestissuthespagefor .NEToncedevelopersagain, you. will indeed find a time lag. Also, if you were to look at the shadow directory, you will find another auto-generated *.dll. Because the runtime is smart enough to detect changes to *.aspx files, it becomes painfully simple to update a running Web application. All you

TableneedoftoContentsdo is place the updated *.aspx files into the directory of the Web applications and the ASP.NET

C#runtimeand thewill.NETtakePlatform,care of theSecondrest.EditionClients who are currently using the older version of the .NET assembly are Introductioncompletely unaware of the change as they still make use of the previous version. However, new clients will Pautomaticallyrt One - IntroducingreceiveC#theandlatesttheand.NETgreatestPl tformassembly. Figure 18-12 illustrates the ASP.NET compilation

cycle.

Chapter 1 - The Philosophy of .NET Chapter 2 - Building C# Applications

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

ChapterFigure10 - 18Processes,-12: TheAppDomains,ASP.NET compilationContexts, andcycleThreads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Note This is a huge improvement to classic ASP, where updating ASP files typically involved re-

Chapter 12 - Object Serialization and the .NET Remoting Layer registering COM servers and rebooting the Web server.

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Controlling the Generated Class Name

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

As you have seen, the ASP.NET compilation cycle will automatically generate a class derived from System.Web.UI.Page when the initial HTTP request comes through. By default, the name of this class will

be based on the filename of the *.aspx file; however, this can be changed by using the ClassName attribute

Chapter 18 - ASP.NET Web Pages and Web Controls of the @Page directive:

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

<%@ Page language="c#" ClassName="CarsInventory"%>

Index

List of Figures

List of Tables

If you were now to open this auto-generated *.dll using ildasm.exe, you would find that the name of your derived class is indeed CarsInventory, rather than CarsInventoryPage_aspx.

Cool! At this point you have seen that you can indeed embed your C# code directly within a *.aspx file. However, this is evil and I will not take this approach for the remainder of this text. Speaking of "evil things," you may agree that it is a bit of a drag to manually build a virtual directory by hand. Given both of these issues, let's check out how VS .NET will not only build a virtual directory automatically, but also automatically configure ASP.NET pages to make use of an associated code behind file.

SOURCE

The CarsInventoryPage.aspx file is included under the CarsInventoryPage

CODE

subdirectory.

Creating anC#ASPand the.NET.NETWebPlatform,ApplicationSecond Editionvia VS .NET

by Andrew Troelsen

ISBN:1590590554

Visual Studio .NET simplifies the process of building ASP.NET Web applications in a number of ways. To

Apress © 2003 (1200 pages)

illustrate, let's now re-create the previous Web page using the functionality of VS .NET. First, create a new

This comprehensive text starts with a brief overview of the

C# Web ApplicationC# languageproject workspaceand then quicklynamedmovesBetterAspNetCarAppto key technical and(Figure 18-13). architectural issues for .NET developers.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter 8 - Advanced C# Type Construction Techniques

Figure 18-13: Creating an ASP.NET application project with VS .NET

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Before you click the OK button, take a minute to notice that the Location text box maps not to a specific

Chapter 10 - Processes, AppDomains, Contexts, and Threads

folder on your hard drive, but rather to the URL of the machine hosting this Web application. The Visual

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Studio .NET solution files (*.sln) are stored under the "My Documents\Visual Studio Projects" subfolder.

Part Four - Leveraging the .NET Libraries

Once the new project workspace has been created, you will notice that a design time template has been

Chapter 12 - Object Serialization and the .NET Remoting Layer

opened automatically (Figure 18-14).

 

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter

Forms Controls

Chapter

 

Chapter

 

Part

Services

Chapter

Controls

Chapter

 

Chapter 20 - XML Web Services

 

Figure 18-14: Your design time template

Index

List of Figures

Much like a Windows Forms application, this template represents the visual appearance of the *.aspx file

List of Tables

you are constructing. The difference, of course, is that you are using HTML-based WebForm controls rather than Win32-based Windows Forms controls. Note that the default name for this page is WebForm1; however, using the VS .NET Properties window, you are free to change this to a more fitting name (such as BetterAspNetCarApp.aspx).

Note The GUI of an *.aspx page may be authored in two manners. If the pageLayout property of the DOCUMENT object is set to GridLayout (the default), you will be able to use absolute position of your GUI widgets. While this is very Windows Forms-like, be aware that older browsers may not support absolute positioning of HTML elements. If you wish to build a GUI that will be displayed correctly in all browsers, you should switch the pageLayout property to FlowLayout.

Next, click the Show All Files button and check out the Solution Explorer window (Figure 18-15). You have been given a number of new files and external assembly references.

Edition

ISBN:1590590554

brief overview of the

to key technical and

.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Figure 18-15: Initial files of an ASP.NET application

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

You will get to know the role of these files over the course of this chapter; for now, Table 18-5 hits the

Chighlightsapter 11.- Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

ChTablepter 182-5:- ObjectInitialSerializationProject Filesand the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Generated Files of

Meaning in Life

Chapter 14 - A Better Painting Framework (GDI+) an ASP.NET Web

Chapter 15 - Programming with Windows Forms Controls

Application

Chapter 16 - The System.IO Namespace

Project

Chapter 17 - Data Access with ADO.NET

PartassemblyinfoFive - Web Applications.cs and XMLLikeWebany VSServices.NET project, this file is used to hold common

Chapter 18 - ASP.NET Web Pages assemblynd Web Controls-level attributes.

 

 

 

 

 

Chapter 19 - ASP.NET Web Applications

 

*.aspx

 

Every ASP.NET page in your application is represented by three

 

Chapter 20 - XML Web Services

 

related files. The *.aspx file is used to define the WebForm controls

 

*.aspx.cs

 

Index

 

used by the page. The *.aspx.cs file is the code behind file that will

List*.ofaspxFigures.resx

 

 

hold your related C# code. Finally, if your page makes use of any

List of Tables

 

 

.NET resource, they will be defined in the *.aspx.resx file.

 

 

 

 

 

Global.aspx

 

As explained later in this chapter, your ASP.NET Web applications

 

Global.aspx.cs

 

may optionally define a class type that derives from the

 

 

HttpApplication type. These files set up this scenario.

 

Global.aspx.resx

 

 

 

 

 

 

 

 

 

Web.config

 

ASP.NET Web applications also make use of *.config files. Unlike a

 

 

 

desktop application, however, this file will always be named

 

 

 

web.config regardless of the name of the Web application.

Next, if you open IIS, you see that a new virtual directory (BetterAspNetCarApp) has been automatically created on your behalf. As you can see, each file in the workspace has been included in this virtual directory. The physical folder to which this virtual directory is mapped can be located under a subdirectory of <drive>:\Inetpub\wwwroot\<NameOfYourApp>.

Examining the Initial *.aspx File

If you examine theC#structureand theof.NETyourPlatform,*.aspx fileSecond(by switchingEditionto the HTML view on the IDE's designer), you will find a skeletonbydeclarationAndrew Troelsenof an ASP.NET Web page. NoteISBN:1590590554that the <%@Page%> directive now makes use of theApressCodebehind© 2003 (1200andpages)Inherits attributes:

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

<%@ Page language="c#" Codebehind="BetterAspNetCarApp.aspx.cs"

architectural issues for .NET developers.

AutoEventWireup="false"

Inherits="BetterAspNetCarApp.WebForm1" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

Table of Contents

<HTML>

C# and the .NET Platform, Second Edition

<HEAD>

Introduction

<title>WebForm1</title>

Part One - Introducing C# and the .NET Platform

<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">

Chapter 1 - The Philosophy of .NET

<meta name="CODE_LANGUAGE" Content="C#">

Chapter 2 - Building C# Applications

<meta name="vs_defaultClientScript" content="JavaScript">

Part Two - The C# Programming Language

<meta name="vs_targetSchema"

Chapter 3 - C# Language Fundamentals

content="http://schemas.microsoft.com/intellisense/ie5">

Chapter 4 - Object-Oriented Programming with C#

</HEAD>

Chapter 5 - Exceptions and Object Lifetime

<body MS_POSITIONING="GridLayout">

Chapter 6 -<formInte facesid="Form1"and Collectionsmethod="post" runat="server">

Chapter 7 -</form>Callback Interfaces, Delegates, and Events

Chapter</body>8 - Advanced C# Type Construction Techniques

Part</HTML>Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Recall that the Codebehind attribute is used to define the name of the source code file that contains the

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

"real" code used by this page, while the Inherits attribute specifies the name of the class in the file that

Part Four - Leveraging the .NET Libraries

functions as your immediate base class.

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Examining the Code Behind File

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Now, ensure that the Show all Files option has been selected and open up this page's code behind file

Chapter 16 - The System.IO Namespace

(BetterAspNetCarApp.aspx.cs):

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

using System;

Chapter 18 - ASP.NET Web Pages and Web Controls

using System.Collections;

Chapter 19 - ASP.NET Web Applications using System.ComponentModel;

Chapter 20 - XML Web Services using System.Data;

Index

using System.Drawing;

List of Figures

using System.Web;

List of Tables

using System.Web.SessionState; using System.Web.UI;

using System.Web.UI.WebControls; using System.Web.UI.HtmlControls;

namespace BetterAspNetCarApp

{

public class WebForm1 : System.Web.UI.Page

{

private void Page_Load(object sender, System.EventArgs e) { } override protected void OnInit(EventArgs e)

{

InitializeComponent();

base.OnInit(e);

}

private void InitializeComponent()

{

C# and the .NET Platform, Second Edition

this.Load += new System.EventHandler(this.Page_Load);

} by Andrew Troelsen

ISBN:1590590554

}Apress © 2003 (1200 pages)

}This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.

First, because you are making use of a code behind file, you have no need to use the <%@Imports%>

Table of Contents

directive, but can opt for the C# "using" keyword. Next, notice how the class specified by the Inherits

C# and the .NET Platform, Second Edition

attribute of the <%@Page%> directive has a base class of System.Web.UI.Page. Also, your page has

Introduction

been wired up to handle two lifetime events: Init and Load (more information on a page's life cycle later in

Part One - Introducing C# and the .NET Platform

this chapter).

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Coding theC#BetterAspNetCarAppand the .NET Pla form, SecondWebEditionApplication

by Andrew Troelsen

ISBN:1590590554

Rather than manually defining all of the Web widgets used by this *.aspx file (as you did in the previous exampl

Apress © 2003 (1200 pages)

you can make use of the VS .NET designer and the Web Forms tab of the IDE's Toolbox (Figure 18-16).

This comprehensive text starts with a brief overview of the C# language and then quickly moves to key technical and architectural issues for .NET developers.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Chapter

Events

Chapter

Techniques

Part

 

Chapter 9 - Understanding .NET Assemblies

Figure 18-16: The ASP.NET Web Controls Toolbox

Chapter 10 - Processes, AppDomains, Contexts, and Threads

ChapterCreate11a GUI- TypethatReflection,mimics theLatepreviousBinding,*.aspxnd Attributefile. Notice-BasedthatPryougraremmingable to leverage the IDE's Properties

PartwindowF ur to- Leveragingautomaticallytheadd.NETtheLibrname/valueries pairs used for the control's ASP declaration. Handling the Button's ChapterClick event12 - isObjectalso simplifiedSeria zationwhenand usingthe .NETVSRemoting.NET. LikeLayerWindows Forms application, simply activate the event

view from the Properties window, and type in the name of the event handler function. As you would expect, you

Chapter 13 - Building a Better Window (Introducing Windows Forms)

code behind file has been updated to handle this event using standard C# event syntax. In addition, notice that

Chapter 14 - A Better Painting Framework (GDI+)

the class defined in the code behind file has member variables that correspond to the ASP.NET Web widgets

Chapter 15 - Programming with Windows Forms Controls

declared in the *.aspx file.

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

At this point, all you need to do is implement the event handler to bind the data from the Inventory table to the

Part Five - Web Applications and XML Web Services

DataGrid widget:

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

using System.Data.SqlClient;

Chapter 20 - XML Web Services

...

Index

public class WebForm1 : System.Web.UI.Page

List of Figures

{

List of Tables

// Widget member variables.

protected System.Web.UI.WebControls.Button btnGetTheData;

protected System.Web.UI.WebControls.DataGrid inventoryGrid;

private void Page_Load(object sender, System.EventArgs e) {} override protected void OnInit(EventArgs e)

{

InitializeComponent();

base.OnInit(e);

}

private void InitializeComponent()

{

this.btnGetTheData.Click +=

new System.EventHandler(this.btnGetTheData_Click);

this.Load += new System.EventHandler(this.Page_Load);

}

private void btnGetTheData_Click(object sender, System.EventArgs e)

C# and the .NET Platform, Second Edition

{

by Andrew Troelsen

ISBN:1590590554

SqlConnection sqlConn =

 

Apress © 2003 (1200 pages)

new SqlConnection("Data Source=.;Initial Catalog=Cars;UID=sa;PWD="

This comprehensive text starts with a brief overview of the sqlConn.Open();

C# language and then quickly moves to key technical and

SqlCommand cmd =

architectural issues for .NET developers.

new SqlCommand("Select * From Inventory", sqlConn); inventoryGrid.DataSource = cmd.ExecuteReader();

inventoryGrid.DataBind();

Table of Contents

sqlConn.Close();

C# and the .NET Platform, Second Edition

}

Introduction

}

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C#

pplications

You can now take your

ASP.NET application out for a test drive. Of course, the output is identical to the

PartCarsInventoryPageTwo - The C# ProgrammingWeb applicationLanguage.

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

The Role of the \bin Directory

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

When you use VS .NET as the starting point for your ASP.NET Web applications, you will find that the virtual Chapterdirectory7 has- CallbacksubdirectoryInterfaces,namedD legates,\bin. Eachand Eventstime you compile your current project, VS .NET will store the late

Chapterand greatest8 - Advancedcopy of theC#*Type.dll assemblyConstructionwithinTecthisniquesfolder. However, as you may be guessing, this is not the *.dll

PartloadedThreeby-theProgrammingCLR. As always,ith .NETwhenAssemblthe initiales HTTP request comes in, the runtime will copy this precompiled

Chapter*.dll into9 the- Understandingshadow directory.NETforAssubsequentemblies use.

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Note One nice by-product of the "precompilation" cycle is that the name of the *.dll assembly in the shado

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

directory is the same as the item in the \bin folder (rather than the auto-generated filename seen in th

Part Four - Leveraging the .NET Libraries

previous example).

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

SOURCE The BetterAspNetCarApp files are included under the Chapter 18 subdirectory.

Chapter 14 - A Better Painting Framework (GDI+)

CODE

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Соседние файлы в предмете Программирование