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

Summary C# and the .NET Platform, Second Edition

by Andrew Troelsen ISBN:1590590554

ADO.NET is a new data access technology developed with the disconnected n-tier application firmly in

Apress © 2003 (1200 pages)

mind. The System.Data namespace contains most of the core types you need to programmatically interact

This comprehensive text starts with a brief overview of the

with rows, columns,C# tables,l nguageandandviewsthen. Asquicklyyou movhavesseen,to keythetechnicalSystemand.Data.SqlClient and System.Data.OleDbarchitecturalnamespacesissuesdefinefor .NETthedevtypeslopersyou.need to establish an active connection.

The centerpiece of ADO.NET is the DataSet. This type represents an in-memory representation of any

Tablenumberof Cofntablesents and any number of optional interrelationships, constraints, and expressions. The beauty C#of andestablishingthe .NET relationsPlatform,onSecondyour Editionlocal tables is that you are able to programmatically navigate between

them while disconnected from the remote data store.

Introduction

Part One - Introducing C# and the .NET Platform

Here you examined the role of the data adapter (OleDbDataAdapter and SqlDataAdapter). Using this type (and the related SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand properties), the adapter can resolve changes in the DataSet with the original data store. Also, you learned about the

connected layer of ADO.NET, and came to understand the role of data reader types.

Chapter 3 - C# Language Fundamentals

ChapterWe wrapped4 - Objectthings-Orientedup by checkingProgrammingout a withsubsetC#of the tools available from VS .NET. As you have seen,

Chapterthe numerous5 - ExceptionsintegratedandwizardsObject doLifetimeindeed help you with mundane and repetitive coding details. Like any

Chaptercode generation6 - Interfacestool, youand mayCollectionsfind that a given wizard does not bring you all the way home. However, Chaptergiven your7 -workCallbackthroughoutInterfaces,thisDelegates,chapter, youandshouldEventsbe able to tweak the wizard-generated code to suit

your needs.

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

Part Five:C#Weband the .NETApplicationsPlatform, Sec d Editionand XML Web Services

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

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

Chapter 18: ASP.NET Web Pages and Web Controls

Table of Contents

Chapter 19: ASP.NET Web Applications

C# and the .NET Platform, Second Edition

Introduction

Chapter 20: XML Web Services

Part One - Introducing C# and the .NET Platform

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

Chapter C#18:andASPthe .NET.NETPlatform,WebSecondPagesEdition and Web Controls

by Andrew Troelsen ISBN:1590590554

Apress © 2003 (1200 pages)

Until now, all of the example applications in this text have focused on Windows Forms and console-based

This comprehensive text starts with a brief overviewplatformf the

front ends. In the next two chapters, you explore how the .NET facilitates the construction of

C# language and then quickly moves to key technical and

browser-based presentation layers. To begin, you'll quickly review a number of key Web-centric atoms architectural issues for .NET developers.

(HTTP, HTML, client-side, and server-side code bases) as well as the role of commercial Web servers (such as Microsoft IIS). During this process, you will create a simple Web application using HTML and

classic ASP. Of course, if you are already "Web aware," feel free to skim or skip these initial sections

Table of Contents

entirely. On the other hand, if you come to ASP.NET with limited Web development experience, this primer

C# and the .NET Platform, Second Edition

will provide a valuable frame of reference for the chapters that follow.

Introduction

Part One - Introducing C# and the .NET Platform

With this Web primer complete, the remainder of this chapter will concentrate upon the composition of

Chapter 1

- The Philosophy of .NET

ASP.NET pages and the related topic of ASP.NET Web controls. As you will see, ASP.NET provides a far

Cha

ter 2

- Building C# Applications

superior programming model than classic (COM-based) ASP. For example, you can now partition your

Pa

Two - The C# Programming Lan uage

presentation logic and business logic into discrete files using a technique called code behind. Also be very

Chapter 3

- C# Language Fu amentals

aware that ASP.NET demands that you to use "real" programming languages for your server-side logic

Chapter(such as4 C#,- ObjectVB .NET,-OrientedMC++,Programmingetc.), ratherwiththanC#interpreted scripting languages (such as VBScript). Given

Chapterthis last5point,- Exceptionsit is criticalndtoObjectunderstandLifetimethat you simply cannot build ASP.NET applications without solid Chapterknowledge6 - ofInterfacesOOP, interfaces,and Collectionsand attributes.

Chapter 7 - Callback Interfaces, Delegates, and Events

ChaptTher Role8 - Advancedof HTTPC# Type Construction Techniques

Part Three - Programming with .NET Assemblies

ChapterWeb applications9 - Understandingare very .differentNET Assembliesanimals than traditional desktop applications (to say the least). The first

obvious difference is that a production-level Web application will always involve at least two networked

Chapter 10 - Processes, AppDomains, Contexts, and Threads

machines (of course, during development it is entirely possible to have a single machine play the role of

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

both client and server). Given this fact, the machines in question must agree upon a particular wire

Part Four - Leveraging the .NET Libraries

protocol to determine how to send and receive data. The wire protocol that connects the computers in

Chapter 12 - Object Serialization and the .NET Remoting Layer

question is the Hypertext Transfer Protocol (HTTP).

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

Chapter 14 - A Better Painting Framework (GDI+)

When a client machine launches a Web browser (such as Netscape Navigator or Microsoft Internet

Chapter 15 - Programming with Windows Forms Controls

Explorer), an HTTP request is made to access a particular resource (such as an *.aspx file or *.htm file)

Chapter 16 - The System.IO Namespace

located on a server machine. HTTP is a text-based protocol that is built upon a standard request/response Chparadigmpter 17.-ForDataexample,Access withif youADOnavigate.NET to http://www.intertech-inc.com, the browser software PartleveragesFive - Weba WebApplitechnologyations andtermedXML WebDomainServicesName System (DNS), which converts the registered URL into Chapterafour-part18 -numericalASP.NET WebvaluePages(akaandIPWebaddress)Controls. At this point, the browser opens a socket connection

Cha(typicallyter 19via- ASPport.NET80),WebandApplicationssends the HTTP request to the default page at the Intertech-inc.com Web site.

Chapter 20 - XML Web Services

Once the hosting Web server receives the incoming HTTP request, the specified resource may contain

Index

logic that scrapes out any client-supplied input values (such as values within a text box) in order to format a

List of Figures

proper HTTP response. Web programmers may leverage any number of technologies (CGI, ASP,

List of Tables

ASP.NET, Java Servlets, etc.) to dynamically generate the content to be emitted into the HTTP response. At this point, the client-side browser renders the HTML emitted from the Web server. Figure 18-1 illustrates the basic HTTP request/response cycle.

Figure 18-1: The HTTP request and response cycle

Another aspect of Web development that is markedly different from traditional desktop programming is the fact that HTTP is a stateless wire protocol. As soon as the Web server emits a response to the client browser, everything about the previous interaction is forgotten. Therefore, as a Web developer, it is up to

you take specific steps to "remember" information (such as items in a shopping cart) about the clients who

C# and the .NET Platform, Second Edition

are currently logged onto your site. As you will see in the next chapter, ASP.NET provides numerous ways

by Andrew Troelsen ISBN:1590590554

to handle state, many of which are commonplace to any Web platform (session variables, cookies, and

Apress © 2003 (1200 pages)

application variables) as well as some new techniques (such as view state and the application cache).

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 of Contents

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# 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

UnderstandingC# andWebthe .NETApplicationsPlatform, SecondandEditionWeb Servers

by Andrew Troelsen

ISBN:1590590554

Now that you better understand the role of HTTP and the underlying request/response cycle of the Web,

Apress © 2003 (1200 pages)

we need to qualify some further terminology. To begin, a Web application can be understood as a

This comprehensive text starts with a brief overview of the

collection of filesC#(*.htm,language*.asp,and*.aspx,thenimagequicklyfiles,movesandtosokeyon)technicaland relatedand components (.NET or classic COM binaries) storeda chitecturalwithin aissuesparticularfor .NETdirectorydevelopers(and .optional subdirectories) on a given Web server. As you will see in the next chapter, Web applications have a specific life cycle and provide numerous events (such as initial startup or final shutdown) that you can hook into.

Table of Contents

C#AWeband theserver.NETisPlatform,a softwareSecondproductEditionin charge of hosting your Web applications and typically provides a

number of related services such as integrated security, File Transfer Protocol (FTP) support, mail

Introduction

exchange services, and so forth. Internet Information Server (IIS) is Microsoft's enterprise-level Web server

Part One - Introducing C# and the .NET Platform

product, and as you would guess, has intrinsic support for classic ASP as well as ASP.NET Web

Chapter 1 - The Philosophy of .NET

applications.

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Note It is perfectly fine to have a single installation of IIS host classic ASP and ASP.NET Web

Chapter 3 - C# Language Fundamentals

applications. Because both Web platforms make use of distinct file extensions (for example,

Chapter 4 - Object-Oriented Programming with C#

*.asp versus *.aspx), IIS will load the correct host process based on the incoming HTTP request.

Chapter 5 - Exceptions and Object Lifetime

ChapterWhen you6 -buildInterfacesASP.NETand CollectionsWeb applications, you will be required to interact with IIS. Be aware, however, Chapterthat IIS7is not- Cautomaticallyllback Interfaces,selectedDelegates,whenandyouEventsinstall the Windows OS 2000 or XP Professional Edition

(you can't run ASP.NET on the "Home" editions of Windows). Therefore, depending on the configuration

Chapter 8 - Advanced C# Type Construction Techniques

of your development machine, you may be required to manually install IIS before proceeding through this

Part Three - Programming with .NET Assemblies

chapter. To do so, simply access the Add/Remove Program applet from the Control Panel folder and

Chapter 9 - Understanding .NET Assemblies

select "Add/Remove Windows Components."

Chapter 10 - Processes, AppDomains, Contexts, and Threads

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

Note Ideally, your development machine will have IIS installed before you install the .NET Framework.

Part Four - Leveraging the .NET Libraries

If you install IIS after you install the .NET Framework, none of your ASP.NET Web applications

Chapter 12 - Object Serialization and the .NET Remoting Layer

will execute correctly (you will simply get back a blank page). Luckily, you can reconfigure IIS to

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

host .NET applications by running the aspnet_regiis.exe command line tool (using the /i flag).

Chapter 14 - A Better Painting Framework (GDI+)

ChapterAssuming15 -youProgramminghave IIS properlywith WindowsinstalledFormson yourContrworkstation,ls you can interact with IIS from the

Administrative Tools folder (located in the Control Panel folder). For the purposes of this chapter, we are

Chapter 16 - The System.IO Namespace

only concerned with the Default Web Site node (Figure 18-2).

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter

Chapter

Chapter

Index

List of

List of

Figure 18-2: The IIS applet

Working with IIS Virtual Directories

A single IIS installation is able to host numerous Web applications, each of which resides in a virtual directory. Each virtual directory is mapped to a physical directory on the local hard drive. Therefore, if you create a new virtual directory named CarsAreUs, the outside world can navigate to this site using a URL such as http://www.CarsAreUs.com (assuming your site's IP address has been registered with the world at large). Under the hood, the virtual directory maps to a physical root directory such as C:\TheCarsSite, which contains the set of files (and optional subdirectories) that constitutes the Web

Chapter 4 - Object-Oriented Programming with C#

application.

C# and the .NET Platform, Second Edition

When you createbyASPAndrew.NETTroelsenWeb applications using VS .NET, youISBN:1590590554will automatically receive a new virtual directory for the currentAp ss ©project2003 (1200. However,pages) as you would guess, you are able to manually create a virtual directory by handThis. Forcomprehthe sakensiveof illustration,text startsassumewith a briefyou overviewwish to createof thea simple Web application named Cars. The first stepC#islanguageto createanda newthenfolderquicklyonmovesyour machineto key t chnicalto holdandthe collection of files that constitute

architectural issues for .NET developers. this new site (for example, C:\CarsWebSite).

Next, you need to create a new virtual directory to host the Cars site. Simply rightclick the Default Web Site

Table of Contents

node of IIS and select New | Virtual Directory from the context menu. This menu selection launches an C#integratedand the .wizardNET Platform,. Skip pastSecondthe welcomeEdition screen and give your Web site a name (Cars). Next, you are

Introductionasked to specify the physical folder on your hard drive that contains the various files and images that

PartrepresentOne - Introducingthis site (in C#thisandcase,theC:\CarsWebSite).NET Platform .

Chapter 1 - The Philosophy of .NET

The final step of the wizard prompts you for some basic traits about your new virtual directory (such as

Chapter 2 - Building C# Applications

read/write access to the files it contains, the ability to view these files from a Web browser, the ability to

Part Two - The C# Programming Language

launch executables [e.g., CGI applications], and so on). For this example, the default selections are just

Chapter 3 - C# Language Fundamentals

fine (be aware that you can always modify your selections after running this tool using various "right-click"

Property dialog boxes integrated within IIS). When you are finished, you will see that your new virtual

Chapter 5 - Exceptions and Object Lifetime directory has been registered with IIS (Figure 18-3).

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter

Part

Chapter

 

Chapter

Threads

Chapter

-Based Programming

Part

 

Chapter

Layer

Chapter

Forms)

Chapter

 

Chapter

 

Chapter

 

Figure 18-3: The Cars virtual directory

 

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

The Role ofC#HTMLand the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Once you have configured a virtual directory to host your Web application, you need to create the content

Apress © 2003 (1200 pages)

itself. Recall that Web application is simply the term given to the set of files that constitute the functionality

This comprehensive text starts with a brief overview of the

of the site. To beC#sure,langua vastge numberand th nofquicklythesemovesfiles willto containkey technicalsyntacticand tokens defined by the Hypertext Markup Languagearchitectural(HTML). HTMLissuesisfora standard.NET developersmarkup. language used to describe how literal text, images, external links, and various HTML-based GUI widgets are rendered by the client-side browser.

TableThisofparticularContentsaspect of Web development is one of the major reasons that many programmers dislike C#buildingand theWeb.NET-basedPlatform,programsSecond. WhileEditionit is true that modern IDEs (including Visual Studio .NET) and Web

development platforms (such as ASP.NET) hide much of the raw HTML tokens from view, you will do well

Introduction

to have a working knowledge of HTML as you work with ASP.NET. While this chapter will most certainly

Part One - Introducing C# and the .NET Platform

not cover all aspects of HTML (by any means), let's check out some basics.

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

PartTheTwoBasic- The C#StructureProgramming Languof angeHTML Document

Chapter 3 - C# Language Fundamentals

An HTML file consists of a set of tags that describe the look and feel of a given Web page. As you would

Chapter 4 - Object-Oriented Programming with C#

expect, the basic structure of an HTML document tends to remain the same. For example, *.htm files (or

Chapter 5 - Exceptions and Object Lifetime

alternatively, *.html files) open and close with <html> and </html> tags, typically define a <body> section,

Chapter 6 - Interfaces and Collections

and so forth. Keep in mind that HTML is not case sensitive. Therefore, in the eyes of the hosting browser,

Chapter 7 - Callback Interfaces, Delegates, and Events

<HTML>, <html>, and <Html> are identical.

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

To illustrate some HTML basics, open Visual Studio .NET, insert an empty HTML file using the File | New |

Chapter 9 - Understanding .NET Assemblies

File menu selection, and save this file under your physical directory as default.htm. If you examine the new

Chapter 10 - Processes, AppDomains, Contexts, and Threads

*.htm file created by the IDE, you will find something like the following:

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

Part Four - Leveraging the .NET Libraries

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

Chapter 12 - Object Serialization and the .NET Remoting Layer

<html>

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

<head>

Chapter 14 - A Better Painting Framework (GDI+)

<title></title>

Chapter 15 - Programming with Windows Forms Controls

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

Chapter 16 - The System.IO Namespace

<meta name="vs_targetSchema"

Chapter 17 -content="http://shemasData Access wi ADO.NET .microsoft.com/intellisense/ie5">

Part Five</head>- Web Applications and XML Web Services

Chapter<body>18 - ASP.NET Web Pages and Web Controls

Chapter</body>19 - ASP.NET Web Applications

</html>

Chapter 20 - XML Web Services

Index

List of Figures

The <html> and </html> tags are used to mark the beginning and end of your document. As you may

List of Tables

guess, Web browsers use these tags to understand where to begin applying the rendering formats specified in the body of the document.

The <head> and </head> tags are used to hold any metadata about the document itself. Here the HTML header uses some <meta> tags that describe the origin of this file (VS .NET) and general bits of information. These tags will have no effect for the examples in this text, so feel free to delete them. Finally, note that a <title> tag is set (currently empty) that may be modified as follows:

<html>

<head>

<title>This Is the Cars Web Site</title>

</head>

<body>

</body>

</html>

As you would guess,C# andthe <title>the .NETtagsPlaretform,usedSecondto specifyEditionthe text string that should be placed in the title bar

of the Web browserby AndrewapplicationTroelsen.

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.

Table of Contents

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# 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

HTML FormC#Developmentand the .NET Pla form, Second Edition

by Andrew Troelsen

ISBN:1590590554

The real action of an *.html file occurs within the scope of the <form> elements. Nestled within these tags

Apress © 2003 (1200 pages)

are any number of additional tags used to render various user input widgets. Simply put, an HTML form is

This comprehensive text starts with a brief overview of the

simply a named groupC# languageof relatedandUIthenelementsquickly usedmovestotogatherkey technicaluser input,andwhich is then transmitted to the Web application viaarchitecturalHTTP. Doissuesnot confusefor .NETandevelopersHTML form. with the entire display area shown by a given browser. In reality, an HTML form is more of a logical grouping of widgets placed in the <form> and </form> tag set:

Table of Contents

C# and the .NET Platform, Second Edition

<body>

Introduction

<form name = MainForm id = MainForm>

Part One - Introducing C# and the .NET Platform

<!--Add UI elements here -->

Chapter 1 - The Philosophy of .NET

</form>

Chapter 2 - Building C# Applications

</body>

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

ChapterThis form4 has- Objectbeen-OrientedassignedProgrammingthe ID and friendlywith C#name of "MainForm". Typically, the opening <form> tag

supplies an action attribute that specifies the URL to which to submit the form data, as well as the method

Cha ter 5 - Exceptions and Object Lifetime

of transmitting that data itself (POST or GET). You will examine this aspect of the <form> tag in just a bit.

Chapter 6 - Interfaces and Collections

For the time being, let's look at the sort of items that can be placed in an HTML form. The Visual Studio

Chapter 7 - Callback Interfaces, Delegates, and Events

.NET IDE provides an HTML tab on the Toolbox dialog box that allows you to select each HTML-based UI

Chapter 8 - Advanced C# Type Construction Techniques

widget (Figure 18-4).

 

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

 

Chapter

and Threads

Chapter

Attribute-Based Programming

Part

 

Chapter

Remoting Layer

Chapter

Windows Forms)

Chapter

 

Chapter

Controls

Chapter

 

Chapter

Part

Chapter

Chapter

Chapter

Index

List of

List of

Figure 18-4: The HTML Controls Toolbox

Table 18-1 gives a rundown of some of the more common HTML GUI widgets.

Table 18-1: Common HTML GUI Types

HTML GUI

Widget

Button

C#Meaningand the .NETin LifePlatform, Second Edition

ISBN:1590590554

by Andrew Troelsen

Apress © 2003 (1200 pages)

A button that does not support the type attribute used to trigger a SUBMIT or

This comprehensive text starts with a brief overview of the

RESET. This sort of button can be used to trigger a block of client-side script

C# language and then quickly moves to key technical and

code or any other logic that does not require a trip to the Web server. architectural issues for .NET developers.

Checkbox

Standard UI selection elements.

Radio Button

Table of Contents

C#Listboxand the .NET Platform, Second Edition

Introduction

Dropdown

Part One - Introducing C# and the .NET Platform

 

ChapterImage1

- The

 

PhilosophyAllows youof .NETto specify an image to render onto the form.

 

 

 

 

 

 

 

 

Chapter 2

- Building

 

C# Applications

 

 

 

Reset Button

 

This button element has its type attribute set to RESET. This instructs the

 

Part Two - The C#

 

Programming Language

 

 

 

 

 

 

browser to clear out the values in each UI element on the page to their default

 

Chapter 3

- C#

Language Fundamentals

 

 

 

 

 

 

values.

 

 

 

 

 

 

 

 

 

Chapter 4

- Object

 

-Oriented Programming with C#

 

 

 

Submit

 

 

This button element has its type attribute set to SUBMIT, which sends the form

 

 

Chapter 5

- Exceptions and Object Lifetime

 

 

 

Button

 

 

data to the recipient of a request.

 

 

 

Chapter 6

- Interfaces and Collections

 

 

 

 

 

 

 

 

 

Chapter 7

- Callback

Interfaces, Delegates, and Events

 

 

 

Text Field

 

These UI elements are used to hold a single line (or multiple lines) of text. The

 

 

 

Text Area

 

Password Field renders input data using an asterisk (*) character mask.

 

 

Chapter 8

- Advanced C# Type Construction Techniques

 

Part Three - Programming with .NET Assemblies

 

 

 

Password

 

 

 

Chapter 9

- Understanding .NET Assemblies

 

 

 

Field

 

 

 

 

 

 

Chapter 10

- Processes, AppDomains, Contexts, and Threads

 

Chapter 11

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

Note As shown later in this chapter, the System.Web.UI.HtmlControls namespace defines managed

Part Four - Leveraging the .NET Libraries

.NET types that correspond to these raw HTML widgets.

Chapter 12 - Object Serialization and the .NET Remoting Layer

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

Building an HTML-Based User Interface

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Before you add the HTML widgets to the HTML <form>, it is worth pointing out that VS .NET allows you to

Chapter 16 - The System.IO Namespace

edit the overall look and feel of the *.html file itself using the integrated Properties window. For example, if

Chapter 17 - Data Access with ADO.NET

you were to select DOCUMENT (Figure 18-5), you would be able to set the background color of the page

Part Five - Web Applications and XML Web Services

(in addition to other details).

Chapter 18 - ASP.NET Web Pages and Web Controls Chapter 19 - ASP.NET Web Applications

Chapter

Index

List of

List of

Figure 18-5: Editing an HTML document via VS .NET

Now, update the <body> of the default.html file to display some literal text that prompts the user to enter a

user name and password and choose a background color of your liking (be aware that you can enter and

C# and the .NET Platform, Second Edition format textual content directly onto the HTML designer):

 

by Andrew Troelsen

ISBN:1590590554

<html>

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

<head>

C# language and then quickly moves to key technical and

<title>ThisarchitecturalIsissuestheforCars.NET Webdevelopers.Site</title>

</head>

 

 

<body BGCOLOR="#66ccff">

 

Table of<!Contents-- Prompt for user input-->

 

C# and<h1the .NETalign="center">ThePlatform, Second EditionCars Login Page</h1>

Introduction<p align="center">

name</i> and <i>password</i>.</p>

Part One<br>- IntroducingPlease C#enterand theyour.NET <i>userPlatform

<!-- Build a form to get user info -->

Chapter 1 - The Philosophy of .NET

<form name="MainForm" ID="Form1">

Chapter 2 - Building C# Applications

</form>

Part Two - The C# Programming Language

</body>

Chapter 3 - C# Language Fundamentals

</html>

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Here, the <h1> tag defines the heading (or size) of the text to display. <br> denotes a line break, <p>

Chapter 7 - Callback Interfaces, Delegatitalicizes, and Events marks a paragraph, and <i> will the text in question.

Chapter 8 - Advanced C# Type Construction Techniques

Now let's build the HTML form itself. In general, each HTML widget is described using a name attribute

Part Three - Programming with .NET Assemblies

(used to identify the item programmatically) and a type attribute (used to specify which UI element you are

Chapter 9 - Understanding .NET Assemblies

interested in placing in the <form> declaration). Depending on which UI widget you manipulate, you will

Chapter 10 - Processes, AppDomains, Contexts, and Threads

find additional attributes specific to that particular item. As you would expect, each UI element and its

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

attributes can be modified using the Properties window.

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

The UI you will build here will contain two text fields (one of which is a Password widget), as well as two

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

button types (one for submitting the form data and the other to reset the form data to the default values):

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

<!-- Build a form to get user info -->

Chapter 16 - The System.IO Namespace

<form name="MainForm" ID=" MainForm">

Chapter 17 - Data Access with ADO.NET

<P align="center">User Name:

Part Five - Web Applications and XML Web Services

<input id="txtUserName" type="text" NAME="txtUserName"></P>

Chapter 18 - ASP.NET Web Pages and Web Controls

<P align="center">Password:

Chapter 19 - ASP.NET Web Applications

<input name="txtPassword" type="password" ID="txtPassword"></P>

Chapter align="center">20 - XML Web Se vices

<P

Index<input name="btnSubmit" type="submit" value="Submit" ID="btnSubmit">

List of<Finputgures name="btnReset" type="reset" value="Reset" ID="btnReset">

List of</P>Tables

</form>

Notice that you have assigned relevant names and IDs to each widget (txtUserName, txtPassword, btnSubmit, and btnReset). Of greater importance, note that each input button has an extra attribute named type, which marks these buttons as UI items that automatically clear all fields to their initial values (type = Reset) or send the form data to the recipient (type = Submit). Figure 18-6 illustrates your creation thus far.

Second Edition

ISBN:1590590554

starts with a brief overview of the moves to key technical and

developers.

Table

C# and

Introduction

Figure 18-6: The initial crack at the default.htm page

Part One - Introducing C# and the .NET Platform

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

Part Three - Programming with .NET Assemblies

The Role ofC#Clientand the-Side.NET PlatfoScriptingm, Second Edition

by Andrew Troelsen

ISBN:1590590554

Now that you have a better understanding of how to construct an HTML form, the next issue is to examine

Apress © 2003 (1200 pages)

the role of client-side scripting. A given *.html file may contain blocks of script code that will be emitted in

This comprehensive text starts with a brief overview of the

the response streamC# languageand processedand thenbyquicklythe requestingmoves tobrowserkey technical. Thereandare two major reasons that client- side scripting is used:architectural issues for .NET developers.

To validate user input before posting back to the Web server

Table of Contents

To interact with the Document Object Model (DOM) of the target browser

C# and the .NET Platform, Second Edition

Introduction

Regarding the first point, understand that the inherent evil of a Web application is the need to make

Part One - Introducing C# and the .NET Platform

frequent round-trips (aka postbacks) to the server machine to update the HTML rendered into the

Chapter 1 - The Philosophy of .NET

browser. While postbacks are unavoidable, you should always be mindful of ways to minimize travel

Chapter 2 - Building C# Applications

across the wire. One technique that saves round-trips is to use client-side scripting to validate user input

Part Two - The C# Programming Language

before submitting the form data to the Web server. If an error is found (such as not specifying data within a

Chapter 3 - C# Language Fundamentals

required field), you can prompt the user of the error without incurring the cost of posting back to the Web Chaptserver.4(After- Objectall, nothing-Orientedis morePr grammingannoyingwithto theC# user than posting back on a slow connection, only to

Chapterreceive5instructions- Exceptionsto addressnd ObjectinputLifetimeerrors!)

Chapter 6 - Interfaces and Collections

In addition to validating user input, client-side scripts can also be used to interact with the underlying object

Chapter 7 - Callback Interfaces, Delegates, and Events

model (termed the Document Object Model, or DOM) of the browser itself. Most commercial browsers

Chapter 8 - Advanced C# Type Construction Techniques

expose a set of objects that can be leveraged to control how the browser should behave. One major

annoyance is the fact that different browsers tend to expose similar, but not identical, object models. Thus,

Chapter 9 - Understanding .NET Assemblies

if you emit a block of client-side script code that interacts with the DOM, it may not work identically on all

Chapter 10 - Processes, AppDomains, Contexts, and Threads browsers.

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

Part FourNote- LeveragingASP.NET providesthe .NETtheLibrariesHttpRequest.Browser property, which allows you to determine at runtime

Chapter 12 the- ObjectcapacitiesSerializaof theion browserand the .thatNET sentR motingthe currentLayer request.

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

There are many scripting languages that can be used to author client-side script code. Two of the more

Chapter 14 - A Better Painting Framework (GDI+)

popular are VBScript and JavaScript. VBScript is a subset of the Visual Basic 6.0 programming language.

Chapter 15 - Programming with Windows Forms Controls

Be aware that Microsoft Internet Explorer (IE) is the only Web browser that has built-in support for client-

Chapter 16 - The System.IO Namespace

side VBScript support. Thus, if you wish your HTML pages to work correctly in any commercial Web

Chapter 17 - Data Access with ADO.NET

browser, do not use VBScript for your client-side scripting logic.

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

The other popular scripting language is JavaScript. Be very aware that JavaScript is in no way, shape, or

Chapter 19 - ASP.NET Web Applications

form a subset of the Java language. While JavaScript and Java have a somewhat similar syntax, ChJavaScriptpter 20 -isXMLnotWeba fullServices-fledged programming language, and thus is far less powerful than Java itself. The

Indexgood news is that all modern day Web browsers support JavaScript, which makes it a natural candidate

ListforofclientFigures-side scripting logic.

List of Tables

Note To further confuse the issue, recall that JScript .NET is a full-blown managed language that can be used to build valid .NET assemblies and is not used to author client-side script code!

A Client-Side Scripting Example

To illustrate the role of client-side scripting, we will first examine how to intercept events sent from clientside HTML GUI widgets. Assume you have added an additional HTML Button (btnHelp) type to your default.html page that allows the user to view help information. To capture the Click event for this button, activate the HTML view and select your button from the left drop-down list. Using the right drop-down list box, select the onclick event (Figure 18-7).

Second Edition

ISBN:1590590554

starts with a brief overview of the

moves to key technical and

developers.

Table

C# and

Introduction

Figure 18-7: Capturing HTML widget events a la VS .NET

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Once you do so, VS .NET will create an empty JavaScript function that will be called when the user clicks

Chapter 2 - Building C# Applications

the button. Within this stub, simply make use of the alert() method to display a client-side message box:

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

<html>

Chapter 4 - Object-Oriented Programming with C#

<head>

Chapter 5 - Exceptions and Object Lifetime

<title>This Is the Cars Web Site</title>

Chapter 6 - Interfaces and Collections

<script id="clientEventHandlersJS" language="javascript">

Chapter 7 - Callback Interfaces, Delegates, and Events

<!--

Chapter 8 - Advanced C# Type Construction Techniques

function btnHelp_onclick() {

Part Three - Programming with .NET Assemblies

// Help the user along.

Chapter 9 - Understanding .NET Assemblies

alert("Please click Submit...");

Chapter}10 - Processes, AppDomains, Contexts, and Threads

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

Part Four</script>- Leveraging the .NET Libraries

Chapter</head>12 - Object Serialization and the .NET Remoting Layer

Chapter<body13 - BuildingBGCOLOR="#66ccff">a Better Window (Introducing Windows Forms)

...

Chapter 14 - A Better Painting Framework (GDI+)

<!-- Prompt for user input -->

Chapter 15 - Programming with Windows Forms Controls

...

Chapter 16 - The System.IO Namespace

<form name="MainForm" ID="Form1">

Chapter 17 - Data Access with ADO.NET

<P align="center"><INPUT id="btnHelp" type="button" value="Help"

Part Five - Web Applications and XML Web Services

name="btnHelp" onclick="return btnHelp_onclick()"> </P>

Chapter 18 - ASP.NET Web Pages and Web Controls

</form>

Chapter 19 - ASP.NET Web Applications

</body>

Chapter 20 - XML Web Services

</html>

Index

List of Figures

ListAsofyouTablescan see, a <script> block has been added to your HTML header, with JavaScript specified as the language of choice. Note that the scripting block has been wrapped within HTML style comments (<!-- --

>). The reason is simple. If your page ends up on a browser that does not support JavaScript, the code will be treated as a comment block and ignored. Of course your page may be less functional, but the upside is that your page will not blow up when rendered by the browser. Also, notice that the attribute set for the HTML button has a new attribute named onclick, which is assigned to the name of the correct JavaScript function.

Validating the default.htm Form Data

Now, let's update the default.htm page to support some client-side validation logic. The goal is to ensure that when the user clicks the Submit button, you call a JavaScript function that checks each text box for empty values. If this is the case, you pop up an alert that instructs the user to enter the required data. First, handle an onclick event for the Submit button to a JavaScript method named ValidateFormData(). Within the logic of this method, check each text box for empty strings, as shown here:

<script id="clientEventHandlersJS" language = javascript>

C# and the .NET Platform, Second Edition

...

by Andrew Troelsen

ISBN:1590590554

function ValidateFormData()

 

{Apress © 2003 (1200 pages)

This comprehensive textitem,s arts with a brief overview of the

// If they forget either pop up a message box.

C# language and then quickly moves to key technical and if((MainForm.txtUserName.value == "") ||

architectural issues for .NET developers.

(MainForm.txtPassword.value == ""))

{

alert("You must supply a user name and password!");

Table of Contents

return false;

C# and the .NET Platform, Second Edition

}

Introduction

return true;

Part One - Introducing C# and the .NET Platform

}

Chapter 1 - The Philosophy of .NET

//-->

Chapter 2 - Building C# Applications

</script>

Part Two - The C# Programming Language

...

Chapter 3 - C# Language Fundamentals

<input id = btnSubmit onclick = "return ValidateFormData()" type = submit

Chapter 4 - Object-Oriented Programming with C# value = Submit name = btnSubmit>

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

At this point, you can open your browser of choice and navigate to the default.html page hosted by your

Chapter 7 - Callback Interfaces, Delegates, and Events

Cars virtual directory and test out your client-side script logic:

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

http://localhost/Cars/default.htm

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

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