Professional Documents
Culture Documents
ASP.NET
Your visual blueprint for
creating Web applications on the .NET framework
by Danny Ryan and Tommy Ryan
TM
From
®
&
Best-Selling Books • Digital Downloads • e-Books • Answer Networks • e-Newsletters • Branded Web Sites • e-Learning
New York, NY • Cleveland, OH • Indianapolis, IN
013617-6 FM.F 9/26/01 2:27 PM Page ii
ASP.NET
Your visual blueprint for
creating Web applications on the .NET framework
013617-6 FM.F 9/26/01 2:27 PM Page iv
At maranGraphics, we believe in producing great and organizing the content for each topic. Our artists
computer books — one book at a time. rebuild every screen shot to provide the best clarity
maranGraphics has been producing high-technology possible, making our screen shots the most precise and
products for over 25 years, which enables us to offer the easiest to read in the industry. We strive for perfection,
computer book community a unique communication and believe that the time spent handcrafting each
process. element results in the best computer books money
can buy.
Our computer books use an integrated communication
process, which is very different from the approach used Thank you for purchasing this book. We hope you
in other computer books. Each spread is, in essence, a enjoy it!
flow chart — the text and screen shots are totally Sincerely,
incorporated into the layout of the spread. Introductory Robert Maran
text and helpful tips complete the learning experience.
President
maranGraphics’ approach encourages the left and right
sides of the brain to work together — resulting in faster maranGraphics
orientation and greater memory retention. Rob@maran.com
Above all, we are very proud of the handcrafted nature www.maran.com
of our books. Our carefully-chosen writers are experts www.hungryminds.com/visual
in their fields, and spend countless hours researching
013617-6 FM.F 9/26/01 2:27 PM Page v
CREDITS
ACKNOWLEDGMENTS
Hungry Minds, Inc.: John Kilcullen, CEO; Bill Barry, President and COO; John Ball, Executive VP, Operations &
Administration; John Harris, Executive VP and CFO
Hungry Minds Technology Publishing Group: Richard Swadley, Senior Vice President and Publisher; Mary Bednarek,
Vice President and Publisher, Networking; Walter R. Bruce III, Vice President and Publisher; Joseph Wikert, Vice
President and Publisher, Web Development Group; Mary C. Corder, Editorial Director, Dummies Technology; Andy
Cummings, Publishing Director, Dummies Technology; Barry Pruett, Publishing Director, Visual/Graphic Design
Hungry Minds Manufacturing: Ivor Parker, Vice President, Manufacturing
Hungry Minds Marketing: John Helmus, Assistant Vice President, Director of Marketing
Hungry Minds Production for Branded Press: Debbie Stailey, Production Director
Hungry Minds Sales: Michael Violano, Vice President, International Sales and Sub Rights
013617-6 FM.F 9/26/01 2:27 PM Page vi
AUTHORS’ ACKNOWLEDGMENTS
Both Danny and Tommy would like to thank Extreme Logic and all of the exceptional people that we worked with there.
Special thanks to Wain Kellum, Keith Landers, Saima Adney, Alicia Ford, Bruce Harple, and Nancy Wehunt — along with
all of the team members that we worked with on projects including: Anthony Yott, Brian Erwin, Dave Cohen, Alan Fraser,
Jerry Rasmussen, Tim Coalson, Jim Davis, Stacy Parrish, Chris Cumpton, John Underwood, Desiree Tuvell, Rich Sabo, Teo
Lachev, John Camp, Scott Matthews, Jennifer Aase, Amy Bauland, Russell Groover, Todd Ransom, David Steyer, Tony
Heffner, Sean Gerety, Jason Etheridge, Julie Kellum, Ashley Aiken, and Tammy Conaway.
We would like to thank the clients that we have worked with during the past couple of years for challenging us to be
better consultants, including Nick Callivas, Brian Blinco, Jay Dalke, Bob Hughes, and Harwell Thrasher.
We would also like to thank Megan Mathews and Joe Chancey of Drew Eckl & Farnham LLP, and Eddie Scott and
Brad Pearce of Jackson, Reece, and Scott for the great service they provide.
We would like to thank all of the hardworking people at Hungry Minds for helping us produce this book —
especially Jennifer Dorsey, Jade Williams, and our Editors. Jennifer made sure that we were taken care of well. Jade
did an awesome job of editing our work — we appreciate how hard she worked on this book, and we are very
thankful that she was our Production Editor.
Tommy would like to thank his colleagues at W.L. Gore and Associates who helped him start his professional career,
including John Reaney, Mark Fundakowsi, Diccon Bancroft, John Pysczynski, Pamela Perdue, Erik Nightwine, Debra
Raup, Ray Edmanson, Bob McCleary, Lawrence Anderson, Wolfgang Holma, and Line 10 Production Team; the
WinCC Team at Siemens that helped him in his transition to being a Microsoft geek, including Emilio Matt, Rob
Bohm, Bob Meads, Rich Miceli, Charlie Moore, Jörg Allmendinger, and Rene Wolf; and his extended family and
friends for the support in the things outside of work including Joe and Rosemarie Markiewicz, Robert and Donna
Philips, Joe and Jan Markiewicz, Chuck and Mary Hanson, Rob and Gretchen Pfeiffer, and Reverend Joe Ciccone CSP.
Danny would like to thank: his friends for their support while writing the book, especially Dan Bassett and family,
Nitin Dixit, Ellen Wu, Amy Bauland, Lisa and Stephen Cox and family, Jennifer and Wyatt Gordon, Danielle and Otan
Ayan, Jack and Lisa Swift and family, Chikako and Takashi Asai and family, Robin Moon, Catherine Williams, Asad
Jafari, Dan and Kelly Clark and family, Darnel Barnes and family, the Harding family, the Heap family, Kitty Pinto,
Wendy Marinaccio, and Erica Pearlberg; everyone involved in the Jamaica trip for their good work including Father
Kevin Hargaden, Shannon Smith, Michelle Basket, Ana Nerio, and everyone who sponsored the trip; the members of
the MHS 10 Year Reunion Committee for picking up my slack including Sydney Whitmer, Tina Shamblin, and
Jennifer Gordon; and finally, past colleagues who have made a difference in my life including Ivan Lee, Neil Russo,
Jeff Shaw, Bobby Lee, Matthew Thayer, and Steve Johnston.
013617-6 FM.F 9/26/01 2:27 PM Page vii
TABLE OF CONTENTS
3) C# BASICS
Write Your First C# Application ........................................................................................34
Compile a C# Application ................................................................................................36
Format Your Code ............................................................................................................38
Declare a Variable ..............................................................................................................40
Initialize a Variable ............................................................................................................42
Access Properties ..............................................................................................................44
Make Decisions Using Conditional Statements ..............................................................46
Work with Arrays ..............................................................................................................48
Control Logic Using Iterative Statements ........................................................................50
Concatenate a String ........................................................................................................52
Convert a Variable ............................................................................................................54
Enumerate a Collection ....................................................................................................56
viii
013617-6 FM.F 9/26/01 2:27 PM Page ix
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
ix
013617-6 FM.F 9/26/01 2:27 PM Page x
TABLE OF CONTENTS
x
013617-6 FM.F 9/26/01 2:27 PM Page xi
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
xi
013617-6 FM.F 9/26/01 2:27 PM Page xii
TABLE OF CONTENTS
xii
013617-6 FM.F 9/26/01 2:27 PM Page xiii
ASP.NET:
Your visual blueprint for JAVASCRIPT:
creating
Your visual blueprint
Web applications on the .NET
for framework
building portable
Java programs
INDEX ................................................................................................................................306
xiii
013617-6 FM.F 9/26/01 2:27 PM Page xiv
ASP.NET: Your visual blueprint for creating Web The Conventions In This Book
applications on the .NET framework uses straightforward
A number of typographic and layout styles are used
examples to teach you many of the tasks required to write
throughout ASP.NET: Your visual blueprint for creating Web
Web applications on the .NET framework.
applications on the .NET framework to distinguish
To get the most out of this book, you should read each different types of information.
chapter in order, from beginning to end. Each chapter
introduces new ideas and builds on the knowledge
learned in previous chapters. Once you become familiar Courier Font
with ASP.NET, this book can be used as an informative
desktop reference. Indicates the use of C#, VB, or Jscript variable names,
keywords, and other elements of ASP.NET code.
xiv
013617-6 FM.F 9/26/01 2:27 PM Page xv
JAVASCRIPT:
ASP.NET:
Your visual blueprint for
buildingfor
Your visual blueprint dynamic
creatingWeb pages
Web applications on the .NET framework
Chapter 2, Web Development Basics, presents the Chapter 10, ASP.NET Applications and State Management,
fundamentals of working with ASP.NET including explains how to work with application and session state
exploring and browsing your Web site, opening and with ASP.NET. It also covers working with cookies and page
saving files, and creating your first ASP.NET Web page. state.
This chapter also shows you how to use the sample Chapter 11, Configure Your ASP.NET Applications,
program templates on the CD-ROM. describes the process for setting and retrieving
Chapter 3, C# Basics, introduces you to the C# configuration information for your ASP.NET application.
programming language, including how to work with Chapter 12 introduces you to debugging your ASP.NET
variables, conditional statements, arrays, looping applications.
structures, strings, collections, and exception handling.
This will prepare you for the material in later chapters if Chapter 13, Security and ASP.NET, shows you several
you are not familiar with the C# programming language. different ways to secure your ASP.NET applications.
Chapter 4, Work with HTML Controls, gets you started Chapter 14, Localization and ASP.NET, walks you through
with creating Web pages in ASP.NET that have buttons, how to globalize your ASP.NET application for different
text boxes, check-boxes, drop-down lists, and tables. cultures, locales, and languages.
Chapter 5, Work with Web Controls, will show you how to The final chapter explains some of the details about
add many of the common controls to Web pages like text migrating to ASP.NET, including migrating code from
boxes using ASP.NET Web controls. The chapter then VBScript to VB.NET and other important issues to address
demonstrates how to add special controls like calendars when migrating.
and advertisement banners. Finally, the chapter explains The Appendices include useful tables of reference
how to validate user input in ASP.NET. material and a summary of important elements of
Chapter 6, Access Data with ASP.NET, explains how to use ASP.NET syntax and the C#, VB, and Jscript languages.
some of the controls you will use to display data like the
Repeater and the DataGrid control. You will see how to What Is On The CD-ROM
insert, update, delete, and sort data. The chapter also
covers working with stored procedures and XML. The CD-ROM in the back of this book contains the
sample code from each of the two-page lessons, as well as
Chapter 7, Work with Web Services, explains how you can the code from most of the Apply It sections. This saves
create, test, and consume Web services. The chapter you from having to type the code and helps you quickly
explains how to return a number of data types including get started creating ASP.NET programs. The CD-ROM also
arrays, enumerations, objects, XML, and SQL Data. You contains several shareware and evaluation versions of
see how to create clients for the Web service, including a programs that can help you work with ASP.NET. An
Web page client and a Console client. e-version of this book is also available on the companion
Chapter 8, Create Custom Components, explains how to disc.
create components, build a two-tier and a three-tier Web
Form, and store code in Code-behind components for
your ASP.NET Web pages.
Chapter 9, Using ASP.NET Components, explains how to
work with components not covered in other chapters
including the Browser Capabilities component and
components necessary to send e-mail. Page and Data
caching of your ASP.NET Web pages is covered as well.
xv
023617-6 Ch01.F 9/26/01 9:39 AM Page 2
ASP.NET
INTRODUCTION TO ASP.NET
SP.NET is a programming framework developed
2
023617-6 Ch01.F 9/26/01 9:39 AM Page 3
Power
With ASP.NET, you now have access to the common
language runtime (or CLR). Running on the CLR gives
access to many of the features available in the .NET
Framework, such as debugging, security, data access,
language interoperability, and more.
3
023617-6 Ch01.F 9/26/01 9:39 AM Page 4
ASP.NET
⁄ Insert the Windows 2000 ¤ In the Control Panel, ■ The Windows Components ■ This area displays a
CD-ROM into your CD-ROM double-click Add/Remove Wizard dialog box appears description of the Internet
drive. Programs. listing the installation size of Information Services
the component you can add subcomponents.
Note: If the Microsoft Windows ■ The Add/Remove Programs or remove.
2000 dialog box appears, close the window appears. ˇ Click Details.
dialog box. › Click next to Internet
‹ Click Add/Remove Information Services to select
Windows Components. it ( changes to ).
4
023617-6 Ch01.F 9/26/01 9:39 AM Page 5
You have several other IIS subcomponents that You can administer IIS through the Internet Services
you can install. If you choose Documentation, it Manager, which is available from Start ➪ Programs
will install help files and samples to assist you ➪ Administrative Tools ➪ Internet Services Manager.
with administering IIS. File Transfer Protocol Because this tool is designed as a Microsoft
(FTP) Server installs support for uploading and Management Console Snap-In, you can add it to
downloading files using FTP sites. If you are your own custom console along with any other
using Visual Studio or FrontPage for working Snap-Ins that you use often.
with any of your sites, you may want to install
FrontPage 2000 Server Extensions. The Internet
Services Manager (HTML) is a Web-based
version of the administration functionality that
enables you to administer the server using a
browser. Install the NNTP service if you need
support for network news. Install the SMTP
service if you need support for e-mail
functionality.
■ The Internet Information ‡ Click OK to confirm your ■ When the installation is · Click Finish to close the
Services (IIS) dialog box selections and close the complete, a message appears Wizard.
opens. dialog box. confirming the successful
installation of IIS. Note: You should now restart your
Á Click next to each ° Click Next to install the computer.
subcomponent you want to parts of the Internet
install ( changes to ). Information Services and
subcomponents you selected.
5
023617-6 Ch01.F 9/26/01 9:39 AM Page 6
ASP.NET
⁄ Insert the CD-ROM with ■ The .NET Framework SDK ■ The license agreement for ‹ Click „ next to I accept
the .NET SDK and run the Setup page appears. the software appears in the the agreement to accept the
setup.exe file. middle of the dialog box. You software license („ changes
¤ Click Next to continue. may need to scroll down to to ´).
Note: This task assumes that you see the entire license
have the installation program on agreement. › Click Next to continue.
CD-ROM. You can also install the
.NET SDK from a local drive or a
network drive.
6
023617-6 Ch01.F 9/26/01 9:39 AM Page 7
You can download the latest .NET Platform SDK Be careful when searching the Web for source code
from http://msdn.microsoft. that runs on the .NET Runtime. The namespace
com/downloads/. This task uses Build names have changed often, especially from Beta 1
1.0.2914 of the .NET Platform SDK. You can also to Beta 2. In particular, data access framework
go to the Microsoft newsgroups for the .NET classes changed dramatically.
Platform SDK by going to http://msdn.
microsoft.com/newsgroups/.
Before installing the .NET Platform SDK, be sure
to check the release notes for any special
instructions. These notes will let you know what
issues are present in the build that you are
installing. The availability of namespaces on
each operating system changes quite often. For
example, going from Beta 1 to Beta 2 of the .NET
Platform SDK, ASP.NET and transactions from
managed code support were dropped for
Windows NT 4.0.
■ A dialog box appears Á Click next to SDK ■ The Destination Folder ■ The .NET SDK is installed.
allowing you to specify Samples to select it ( window appears.
whether to install the .NET changes to ).
software, samples, and ° Click Next to select the
documentation. ‡ Click Next to continue. default folder and to
continue.
ˇ Click next to Software
Development Kit to select it
( changes to ).
7
023617-6 Ch01.F 9/26/01 9:39 AM Page 8
ASP.NET
⁄ In the Control Panel, ‹ Click to expand the list ■ The Default Web Site ‡ Click Browse to open the
double-click Administrative of Web sites on the Web Properties dialog box Browse for Folder dialog box.
Tools to open the server ( changes to ). appears.
Administrative Tools window.
› Click the Web site whose Á Click the Home
¤ Double-click Internet home directory you want to Directory tab.
Services Manager to open the change.
Internet Information Services
window. ˇ Click the Properties
button ( ).
8
023617-6 Ch01.F 9/26/01 9:39 AM Page 9
OPTION DESCRIPTION
A directory located on this computer Use this option for specifying a directory located on the Web
server as the home directory. This is the most common choice.
A share located on another computer Use this option if you want to specify a share directory as the home
directory. You can specify the user that you want to connect as
using the Connect As button.
A redirection to a URL Use this option if you want to have users redirected to another
URL when they are trying to access any part of your site.
° Click the directory you · Click OK to set the new ■ The new home directory — Close the Internet
want to set as your new home directory and to close appears in the Local Path. Information Services window.
home directory. the dialog box.
‚ Click OK to close the
properties dialog box.
9
023617-6 Ch01.F 9/26/01 9:39 AM Page 10
ASP.NET
New
Virtual Directory
⁄ In the Control Panel, ‹ Click to expand the list ˇ Click Action ➪ New ➪
double-click Administrative of Web sites on the Web Virtual Directory.
Tools to open the server ( changes to ).
Administrative Tools window.
› Click the Web site in
¤ Double-click Internet which you want to add the
Services Manager to open the virtual directory.
Internet Information Services
window.
10
023617-6 Ch01.F 9/26/01 9:39 AM Page 11
Virtual directories can also be set using Windows You can also remove a virtual directory you no
Explorer. Select the folder you want to set up as longer need from IIS. Perform steps 1 through 3 to
a virtual directory in Windows Explorer. Click open the Internet Information Services window, and
the File Menu, then choose Properties. Then then select the virtual directory you want to
click the Web Sharing tab and select the Web remove. Click the Delete button and then click Yes
site you want to make the virtual directory with. in the dialog box that appears. Removing a virtual
Click the Share This Folder option. In the Edit directory does not remove the actual directory and
Alias dialog box, specify an alias and set the its contents from the computer.
appropriate access and application permissions.
Click OK when you finish. Then click OK again to
close out the Properties dialog box.
■ The Virtual Directory Á Click Next to continue. ‡ Type an alias for the ° Click Next to continue.
Creation Wizard appears. virtual directory.
CONTINUED
11
023617-6 Ch01.F 9/26/01 9:39 AM Page 12
ASP.NET
· Type the path to the ‚ Click Next to continue. — Click next to the ± Click Next to continue.
directory in which you want appropriate access
to create a virtual directory. permissions ( changes
to ).
■ You can also click Browse
to locate the directory on
your computer.
12
023617-6 Ch01.F 9/26/01 9:39 AM Page 13
Like home directories in Web sites, virtual You can also use virtual directories to isolate
directories can be specified as either a directory unstable sections of your Web application. A virtual
on a Web server, a share on another computer, directory enables you to choose the application
or as a redirection to a URL. The option to protection level, unlike normal subdirectories of the
create a virtual directory map to a network share Web site. Choose High (Isolated) for virtual
or URL is not available from the virtual directory directories that contain code that needs isolation
creation Wizard. To work around this, initially from the rest of the site.
set out the virtual directory to be mapped to the
directory. Then, change this by accessing the
properties of the virtual directory and specifying
a network share or URL.
books
■ The wizard confirms that ¡ Click Finish. ■ The new virtual directory ™ Click to close the
you have successfully created appears under the Web site Internet Information
a new virtual directory. you selected. Services window.
13
023617-6 Ch01.F 9/26/01 9:39 AM Page 14
ASP.NET
⁄ In the Control Panel, ‹ Click to expand the list ■ The Default Web Site ‡ Click Enable Default
double-click Administrative of Web sites on the Web Properties dialog box Document to select it
Tools to open the server ( changes to ). appears. ( changes to ).
Administrative Tools window.
› Click the Web site that Á Click the Documents tab.
¤ Double-click Internet you want to set as your
Services Manager to open the default document.
Internet Information Services
window. ˇ Click the Properties
button ( ).
14
023617-6 Ch01.F 9/26/01 9:39 AM Page 15
home.htm
° Click Add to open the ‚ Click OK to add the new ■ The new default document ± Click OK to confirm
Add Default Document default document to your list. is added to the list. your changes and close the
dialog box. dialog box.
— Click an arrow button (
· Type the name of the new or ) to move the document Note: If the Inheritance Override
default document. up or down in the list. dialog box appears, click Cancel to
close the dialog box.
¡ Click to close the IIS
window.
15
023617-6 Ch01.F 9/26/01 9:39 AM Page 16
ASP.NET
⁄ In the Control Panel, ‹ Click to expand the list ■ The Default Web Site ° Click to open the
double-click Administrative of Web sites on the Web Properties dialog box appears. Active log format menu.
Tools to open the server ( changes to ).
Administrative Tools window. Á Click the Web Site tab. · Click to select the log file
› Click the Web site that format that you want to use.
¤ Double-click Internet you want to change. ‡ Click next to Enable
Services Manager to open the Logging to enable the Web ‚ Click Properties to open
Internet Information Services ˇ Click the Properties site to log information ( the Extended Logging
window. button ( ). changes to ). Properties dialog box.
Note: This option maybe enabled by
16 default.
023617-6 Ch01.F 9/26/01 9:39 AM Page 17
— Click „ to select the time ■ You can also click Browse ¡ Click OK to confirm the £ Click to close the
period that you want to use to select a directory on the log file properties that you Internet Information Services
to create new log files („ computer. specify. window.
changes to ´).
™ Click OK to close the
± Type the path of the Properties dialog box.
directory where you want to
store log files.
17
023617-6 Ch01.F 9/26/01 9:39 AM Page 18
ASP.NET
*devserver
STOP A WEB SITE ¤ Double-click Internet › To stop a Web site, click ■ The Web site stops.
Services Manager to open the the Web site.
⁄ In the Control Panel, Internet Information Services
double-click Administrative window. ˇ Click the Stop button ( ).
Tools to open the
Administrative Tools window. ‹ Click to expand the list
of Web sites on the Web
server ( changes to ).
18
023617-6 Ch01.F 9/26/01 9:39 AM Page 19
COMMAND DESCRIPTION
iisreset /restart Stop and then restart the Web server.
iisreset /start Start the Web server.
iisreset /stop Stop the Web server.
iisreset /reboot Restart the computer.
iisreset /rebootonerror Restart the computer if an error occurs while stopping,
starting, or pausing the Web server.
iisreset /status Stop and then restart the Web server.
iisreset /? Display information about the iisreset command.
START A WEB SITE ¤ Click the Start button ( ). PAUSE A WEB SITE ■ The Web site pauses.
⁄ To start a Web site, click ■ The Web site restarts. ⁄ To pause a Web site, click ■ To resume running the
the Web site. the Web site. Web site, click the Pause
button again.
¤ Click the Pause
button ( ).
19
033617-6 Ch02.F 9/26/01 9:40 AM Page 20
ASP.NET
Administrative Tools
20
033617-6 Ch02.F 9/26/01 9:40 AM Page 21
‹ Click to expand the list › Right-click Default Web ■ The Default Web site Note: The IIS 5.0 Documentation
of Web sites on the Web Site to open the pop-up menu. appears. opens.
server ( changes to ).
ˇ Click Browse.
21
033617-6 Ch02.F 9/26/01 9:40 AM Page 22
ASP.NET
Administrative Tools
22
033617-6 Ch02.F 9/26/01 9:40 AM Page 23
An alternative way to get to the Internet Services The Computer Management Console is a very
Manager is to open the Computer Management useful console when it comes to managing your
Console. This console can be reached by right- Web site. You can connect to other machines on
mouse clicking on the “My Computer” icon on your network and manage resources on those
the desktop and choosing Manage from the machines that are used by your Web site. For
pop-up menu. You can also get to the Computer example, you can maintain the shares that are
Management Console through the Control Panel. exposed by a remote machine. For a share, you can
give the share name, path, and security rights.
Shares are sometimes used for virtual directories in
your Web sites. See page 10 for information on
how to create a virtual directory.
wwwroot
‹ Click to expand the list › Right-click Default Web ■ The Windows Explorer
of Web sites on the Web Site to open the pop-up menu. displays the directory where
server ( changes to ). the files for the Default Web
ˇ Click Explore. site are located.
23
033617-6 Ch02.F 9/26/01 9:40 AM Page 24
ASP.NET
⁄ Start your text editor. › Click to select All Files ■ The template file loads into Note: You can open
from the drop-down list. your text editor. the template from the CD at
¤ Click File ➪ Open. D:\VISUALASPNET\Code Templates\.
ˇ Click to select a template. Note: If you installed the software from
‹ Click to select the the CD, the path to the Code Templates
folder that contains your Á Click Open to open the
Code Templates. template. directory is C:\Program Files\Visual
ASP.Net\Code Templates\ plus the
filename for the specific html template,
24 such as GenericTemplate.htm.
033617-6 Ch02.F 9/26/01 9:40 AM Page 25
Y that you and others can request the file from the
Web server.
The Default Web site is a Web site that is on your
find the physical location of where your Web site files
are stored, see page 22.
Common files that will make up your Web sites
Web server when you install Internet Information include Web Forms, Code-behind Pages, Web
Server 5.0. If you have not mapped the Default Web Services/Web Service Clients, components, and
site to another location, the default location for the configuration files. Unlike ASP 3.0 sites that use
Default Web site is C:\InetPub\wwwroot. That is components, ASP.NET applications are self-describing
the path you should use if you have not changed the and do not require registry entries. Therefore, you
default configuration. can simple copy the application with XCOPY or FTP.
Copy deployment works in most cases, but there are
If your Web server is on a different machine than the other configurations that take a few more steps to
physical files of your Web site, you need to save the properly configure.
files on the file share that is designated for your Web
⁄ Click File ➪ Save As. ‹ Type a name for the file. ˇ Browse to the Default Web ■ The Web page appears in
site at http://localhost. the Default Web site.
¤ Click to select the folder › Click Save to save the Web
where you want to store your page. Note: See page 20 for instructions on Note: See page 14 for more
file. browsing the Default Web site. information about the default
Note: To enable the file to load
■ If the folder where you document in IIS.
automatically in the Default Web
want to store the files is not site, save the file to the root directory
onscreen, click the Save in (C:\Inetpub\wwwroot\) as Default.htm.
to select the folder. 25
033617-6 Ch02.F 9/26/01 9:40 AM Page 26
ASP.NET
Open... Ctrl+O
⁄ Start your text editor. › Click to select All Files ‡ Type a description of the · Add additional HTML
from the drop-down list. page between the <H3> tags. controls to the form to collect
¤ Click File ➪ Open. information.
ˇ Click to select a template. ° Position the cursor
‹ Click to select the insertion point between ‚ Add a Submit button to
folder that contains your Á Click Open to open the the <BODY> tags and the form.
Code Templates. template. create a form for collecting
information about user
comments.
26
033617-6 Ch02.F 9/26/01 9:40 AM Page 27
Save As...
— Click File ➪ Save As. ¡ Type SubmitComments.htm £ Browse to the saved Web ■ The Web page appears
as your filename. page at http://localhost with the form on it.
± Click to select the Default /SubmitComments.htm.
Web Site folder where you ™ Click Save to save and Note: If you click the Send
want to store your file. close the dialog box. Note: See page 20 for instructions on Comments button on this form,
browsing the default Web site. a File not Found error will appear
■ If the Default Web Site
folder is not onscreen, click onscreen because you have not
the Save in to select the created the page.
folder. 27
033617-6 Ch02.F 9/26/01 9:40 AM Page 28
ASP.NET
Open... Ctrl+O
⁄ Start your text editor. › Click to select All Files ‡ Declare the scripting · Type the HTML and ASP
from the drop-down list. language used for the page. code to display what the user
¤ Click File ➪ Open. fills in on the form.
ˇ Click to select a template. ° Type a description of the
‹ Click to select the page between the <H3> tags
folder that contains your Á Click Open to open the and press Enter.
Code Templates. template.
28
033617-6 Ch02.F 9/26/01 9:40 AM Page 29
Example:
<P><STRONG>Form Collection</STRONG> </P>
<P>
<%
For Each Item in Request.Form
For intLoop = 1 to Request.Form(Item).Count
Response.Write Item & " = " &
Request.Form(Item)(intLoop)
%>
<br>
<% Next
Next %>
</P>
Save As...
‚ Click File ➪ Save As. ± Type ReceiveComments.asp ™ Browse to the saved Web £ Type your information
as your filename. page at http://localhost into the fields on the form.
— Click to select the Default /SubmitComments.htm.
Web Site folder where you ¡ Click Save to save and ¢ Click the Send Comments
want to store your file. close the dialog box. Note: See page 20 for instructions button.
on browsing the default Web site.
■ If the Default Web Site Note: You will need to copy ■ The Web page echoes
folder is not onscreen, click SubmitComments.htm to ■ The Web page appears with back the information that you
the Save in to select the C:\InetPub\wwwroot\ from the the form on it. filled in on the form.
folder. installation directory or the CD. 29
033617-6 Ch02.F 9/26/01 9:40 AM Page 30
ASP.NET
Open... Ctrl+O
⁄ Start your text editor. › Click to select All Files ‡ Type a description of the · Add additional HTML
from the drop-down list. page between the <H3> tags. controls to the form to collect
¤ Click File ➪ Open. information.
ˇ Click to select a template. ° Click between the <BODY>
‹ Click to select the tags and create a form for ‚ Add a Submit button to
folder that contains your Á Click Open to open the collecting information about the form.
Code Templates. template. user comments.
30
033617-6 Ch02.F 9/26/01 9:40 AM Page 31
Creating a Web Form that submits to itself, With ASP.NET Web Forms, you can either have your
postback, is a common Web development server-side code imbedded in the Web Form,
technique. When you configure your Web Forms extension is .aspx, or place the code in a code-
to postback, you will need a placeholder for behind page, in the case of C# the extension is .cs.
displaying information when the page comes The concept of code-behind pages is a new feature
back to the user. You can put an empty SPAN tag that was not available in ASP 3.0. Code-behind
into your Web Form as a placeholder for pages enable you to separate code from
displaying results back to the user. presentation (HTML). This is a cleaner programming
model that is closer to what is available to event-
driven programming tools that programmers have
had for years.
Save As...
— Click File ➪ Save As. ¡ Type Comments.aspx as £ Browse to the saved Web ■ The Web page appears
your filename. page at http://localhost with the form on it.
± Click to select the Default /Comments.aspx.
Web Site folder where you ™ Click Save to save and Note: If you click the Send
want to store your file. close the dialog box. Note: See page 20 for instructions Comments button on this form,
on browsing the default Web site. nothing significant should happen
■ If the Default Web Site
folder is not onscreen, click because no code has been created
the Save in to select the for when the page submits the form
folder. to itself.
31
033617-6 Ch02.F 9/26/01 9:40 AM Page 32
ASP.NET
Open... Ctrl+O
⁄ Start your text editor. › Click to select All Files ‡ Declare the language used · Create an event handler.
from the drop-down list. for the page.
¤ Click File ➪ Open. ‚ Add the ONCLICK event
ˇ Click to select a template. ° Declare a script block to handler to the form and call
‹ Click to select the run server-side. the event created.
folder that contains your Á Click Open to open the
Code Templates. template.
32
033617-6 Ch02.F 9/26/01 9:40 AM Page 33
The Web Forms architecture gives you the ability Instead of responding to events on the server, you can
to run server-side code when client-side events write client-side script that handles events on your
are fired. This is how you can run C# code when Web page. These scripts are interpreted by the client’s
the button is clicked. The Web Forms framework browser. Because users can have one of many
handles virtually all of the mechanics of browsers, you are not assured that the event-handling
capturing, transmitting, and interpreting the code will run properly. Also you are not assured that
event and handling it appropriately on the server. the user will access your page with a browser that can
interpret script. There are programmatic ways to
address these issues, but you will find that server-side
code is a more reliable way to process events.
Save As...
— Click File ➪ Save As. ¡ Type £ Browse to the saved Web ∞ Click the Send Comments
SubmitReceiveComments.aspx page at http://localhost button.
± Click to select the Default as your filename. /SubmitReceive
Web Site folder where you Comments.aspx. ■ The Web page echoes
want to store your file. ™ Click Save to save and back the information that you
close the dialog box. ■ The Web page appears with filled in on the form.
■ If the Default Web Site the form on it.
folder is not onscreen, click
the Save in to select the ¢ Type your information into
folder. the fields on the form. 33
043617-6 Ch03.F 9/26/01 9:40 AM Page 34
ASP.NET
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Between the curly braces,
you want to create and press type static void Main() and type in the code to print out
¤ Type using System; to Enter. press Enter to create the "Hello World using C#!".
import the System Main function.
namespace and press Enter. › Type { }, placing the
opening and closing curly Á Type { }, placing the
braces on separate lines, to opening and closing curly
set off the body of the class. braces on separate lines, to
34 set off the body of the Main
function.
043617-6 Ch03.F 9/26/01 9:40 AM Page 35
C# BASICS 3
If you are familiar with object-oriented The C# language is case sensitive. This will be one
programming, you may know that a class defines of the first bugs you will find when compiling your
the operations an object can perform, such as C# application. To avoid problems with case
methods, events, or properties, and defines a sensitivity, you can use an editor and compiler that
value that holds the state of the object. Although assists by being compliant with the case sensitivity.
a class generally includes both definition and
implementation, it can have one or more
members that have no implementation.
An instance of a .NET Framework class is an
object. You can access an object’s services by
calling its methods and accessing its properties,
events, and fields. Each language chooses its own
syntax for creating instances of classes.
Save Ctrl+S
C:\CSharp\FirstApp.cs
° Click File ➪ Save to open ‚ Click Save. ■ The source file saves to the Note: You can save all of your console
the Save As dialog box. directory and can now be applications in a specific directory
compiled. (example: C:\CSharp).
· Type a name for the file.
35
043617-6 Ch03.F 9/26/01 9:40 AM Page 36
ASP.NET
COMPILE A C# APPLICATION
nce you have created your C# source file, specify the source file that you want to compile,
COMPILE A C# APPLICATION
Run...
⁄ Click Start ➪ Run. ■ The Run dialog box ‹ Click OK to open the
appears. command line window.
¤ Type cmd in the Open
field.
36
043617-6 Ch03.F 9/26/01 9:40 AM Page 37
C# BASICS 3
› Change directories to the Note: In this example, the command is ■ The program displays the
source file location by using csc FirstApp.cs. Hello World using C#!
the cd command. message.
■ An executable file is
Note: In this example, the command is created from the source file.
cd C:\Csharp.
Á Run the program by typing
ˇ Compile the class at the the name of the executable
command prompt using the file and pressing Enter.
csc command. 37
043617-6 Ch03.F 9/26/01 9:40 AM Page 38
ASP.NET
⁄ Open your text editor. ‹ Type { }, placing the ˇ Type using System; to ‡ Type the name of the class
opening and closing curly import the System you want to create followed
¤ Type the name of the braces on separate lines. namespace and press Enter. by {}, placing the opening
namespace you want to and closing braces on
create and press Enter. › Between the curly braces, Á Add a documentation separate lines.
press Tab and type // to begin comment by typing ///
a single line comment, add followed by the comment.
the comment details, and
then press Enter.
38
043617-6 Ch03.F 9/26/01 9:40 AM Page 39
C# BASICS 3
° To create a flower box, ‚ To end the flower box, ± Within the Main function, ™ Type the remaining code,
type / to specify a multiple type / to specify the end of a add a single line comment by adding comments on the line
line comment. multiple line comment. typing //. before the code.
· Type in the details of the — Type public static void ¡ Type the comment.
class. Main() followed by { },
placing the opening and
closing curly braces on
separate lines, to create the
Main function. 39
043617-6 Ch03.F 9/26/01 9:40 AM Page 40
ASP.NET
DECLARE A VARIABLE
ou can structure the way you store information allocate memory for the information you want to
DECLARE A VARIABLE
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, Á Type { }, placing the
you want to create and press type static void Main() and opening and closing curly
¤ Type using System; to Enter. press Enter to create the braces on separate lines.
import the System Main function.
namespace and press Enter. › Type { }, placing the
opening and closing curly
braces on separate lines, to
40 specify the body of the class.
043617-6 Ch03.F 9/26/01 9:40 AM Page 41
C# BASICS 3
You must declare and initialize variables
before using them to avoid an error.
Failing to initialize a variable produces a
runtime error.
TYPE THIS:
namespace DeclareInitializeVariables
{
using System;
/// <summary>
/// Summary description for ApplyIt.
/// </summary>
public class ApplyVariableDeclaration
{
public void ApplyIt()
{
string sTest;
RESULT:
41
043617-6 Ch03.F 9/26/01 9:40 AM Page 42
ASP.NET
INITIALIZE A VARIABLE
fter you declare a variable, you initialize it by strFirstName is Hungarian notation. Using this
INITIALIZE A VARIABLE
Save Ctrl+S
C:\Csharp\DeclareInitializeVariables.cs
⁄ Type the statement to ¤ Add the ‹ Click File ➪ Save. ■ The source file saves to the
declare and initialize a Console.Writeline directory and can now be
multiple variable of the same function to write the values › Type a name for the file. compiled.
type on the same line and for the variables to the ˇ Click Save.
press Enter. console screen. Note: You can save all of your Console
applications in a specific directory
(example: C:\CSharp).
42
043617-6 Ch03.F 9/26/01 9:40 AM Page 43
C# BASICS 3
You need to know what data types are available to
you in C# to properly store data. The following
table outlines the intrinsic data types used by C#.
Run...
Á Click Start ➪ Run to open ‡ Type cmd in the Open · Change directories to Note: See page 36 for more
the Run dialog box. field. where information on compiling and running
DeclareInitialize a file.
■ The Run dialog box ° Click OK. Variables.cs is located
appears. by using the cd command. — Run the program by typing
the name of the executable
‚ Compile the class at the file and pressing Enter.
command prompt with the
csc command. ■ The program displays the
message about the initialized
variables.
43
043617-6 Ch03.F 9/26/01 9:40 AM Page 44
ASP.NET
ACCESS PROPERTIES
ou can access the attributes of an object by Accessing properties requires the class that defines
ACCESS PROPERTIES
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, Á Declare variable to hold a
you want to create and press create the Main function. Date Time string.
¤ Type using System; to Enter.
import the System
namespace and press Enter. › Type { }, placing the
opening and closing curly
braces on separate lines, to
set off the body of the class.
44
043617-6 Ch03.F 9/26/01 9:40 AM Page 45
C# BASICS 3
Object-oriented languages have three import Properties are a natural extension of fields. They
concepts for working with objects. To work with are both named members with associated types,
an object, you will need to know what properties, and the syntax for accessing fields and properties
methods, and events are. This chapter covers is the same. In general, you should expose
these three concepts. Properties describe properties instead of public fields. With
attributes of your object. For example, you could properties you have better control over the
represent a pencil as an object. Some of the storage and access of the information stored.
properties of this object would be its length, You will want to use Get and Set accessors to
color, and thickness of lead. control reading and writing to properties.
AccessProperties.cs - Notepad
‡ Access the Now property ° Send this value to the ‚ Compile and run the ■ The program displays the
from the DateTime class console. program. message about the date and
that is part of the "System" time.
Framework class. · Save as the class name.
Note: See page 35 for more
information on saving a file.
45
043617-6 Ch03.F 9/26/01 9:40 AM Page 46
ASP.NET
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Declare a character
you want to create and press create the Main function that variable and read the user
¤ Type using System; to Enter. reads in the arguments from input into the variable.
import the System the command line.
namespace and press Enter. › Type { }, placing the Note: Only the first character is read,
opening and closing curly Á Use the Console.Write not the line.
braces on separate lines, to function to write a message
46 set off the body of the class. to the console for collecting a
character.
043617-6 Ch03.F 9/26/01 9:40 AM Page 47
C# BASICS 3
MakeStatements - Notepad
° Create an if-then · Write the appropriate — Compile and run the ■ The program displays the
statement to determine message to the console. program. message about the character
whether the input was a the user input.
number. ‚ Save the file as the class
name.
Note: See page 35 for more
information on saving a file. 47
043617-6 Ch03.F 9/26/01 9:40 AM Page 48
ASP.NET
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Store goals in an array for
you want to create and press create the Main function. displaying a message to the
¤ Type using System; to Enter. console.
import the System Á Declare an array
namespace and press Enter. › Type { }, placing the variable for holding the goals ° Store responses in another
opening and closing curly and a string variable for the array.
braces on separate lines. question to the user.
48
043617-6 Ch03.F 9/26/01 9:40 AM Page 49
C# BASICS 3
You can use the Array class provided in the
.NET Framework to manipulate and sort
the members of the array.
WorkArrays - Notepad
· Write the message to the Note: See page 35 for more — Compile and run the ■ The program displays the
console. information on saving a file. program. message about the goal list
and options.
‚ Save the file as the class
name.
49
043617-6 Ch03.F 9/26/01 9:40 AM Page 50
ASP.NET
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Create a case statement.
you want to create and press create the Main function.
¤ Type using System; to Enter.
import the System Á Declare variables for use
namespace and press Enter. › Type { }, placing the by the case statement and
opening and closing curly the if-then logic.
braces on separate lines, to
50 set off the body of the class.
043617-6 Ch03.F 9/26/01 9:40 AM Page 51
C# BASICS 3
ControlLogic - Notepad
° Create an if-then ‚ Save as the class name. — Compile and run the ■ The program displays the
statement. program. message about the goal set.
Note: See page 35 if you need more
· Use the Writeline information on saving a file.
method to send the
appropriate value to the
console.
51
043617-6 Ch03.F 9/26/01 9:40 AM Page 52
ASP.NET
CONCATENATE A STRING
ou will find many cases that you need to message which welcomes the user using their name.
CONCATENATE A STRING
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, Á Declare two string
you want to create and press create the Main function. variables.
¤ Type using System; to Enter.
import the System ‡ Concatenate the strings
namespace and press Enter. › Type { }, placing the together.
opening and closing curly
braces on separate lines, to
52 set off the body of the class.
043617-6 Ch03.F 9/26/01 9:40 AM Page 53
C# BASICS 3
You can shorten the code required to concatenate a string
to itself by using the += assignment operator. The sample
below passes arguments into a console application from
the command line and builds a single string that puts all
the command line parameters into one string.
// Loop through the arguments and concatenate into one string RESULT:
for(int i = 0; i < args.Length; i++)
{
strDynamicString += args[i] + “; “; Your goal list is: Run a
} marathon; Go to top of
Empire State Building;
// Write the result of the concatenated string to the console
Console.WriteLine(“Your goal list is: “ +
strDynamicString);
}
}
ConcatenateString.cs - Notepad
° Concatenate the strings ‚ Save as the class name. — Compile and run the ■ The program displays the
within a statement. program. message about the
Note: See page 35 for more concatenated strings.
· Write the two statements information on saving a file.
to the console.
53
043617-6 Ch03.F 9/26/01 9:40 AM Page 54
ASP.NET
CONVERT A VARIABLE
ou will want to convert variables when when converting from one data type to another data
CONVERT A VARIABLE
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Declare an integer
you want to create and press create the Main function. variable and initialize the
¤ Type using System; to Enter. value to the byte variable
import the System Á Declare a byte variable created.
namespace and press Enter. › Type { }, placing the and initialize the value to 3.
opening and closing curly ° Output the two values to
braces on separate lines, to the console.
set off the body of the class.
Note: This is an example of an implicit
54 conversion.
043617-6 Ch03.F 9/26/01 9:40 AM Page 55
C# BASICS 3
The following example represents a class definition that does
several different types of conversions. The first conversion
changes the data type from a number to a string. The second
conversion demonstrates a conversion from a string to a
number. Finally, the dates are converted into different formats.
Example:
using System;
public class ApplyConversion
{
static void Main()
{
string strExample = “1.2”;
string strDate;
// This is how to convert a string to number
double dblValue = Double.Parse(strExample);
// This is how numerics are converted to strings
string strDoubleValue = dblValue.ToString();
// This is conversion of full dates to other data types
strDate = DateTime.Now.ToLocalTime().ToString();
strDate = DateTime.Now.ToLongTimeString();
strDate = DateTime.Now.ToShortDateString();
}
}
ConvertVariables.cs - Notepad
· Declare a long variable Note: This is an example of an explicit ¡ Compile and run the ■ The program displays the
and initialize the value to the conversion. program. message about the byte and
maximum value for a long long variable conversions.
variable. — Output the two values to
the console.
‚ Declare an integer
variable and initialize the ± Save as the class name.
value to the byte variable Note: See page 35 for more
created. information on saving a file. 55
043617-6 Ch03.F 9/26/01 9:40 AM Page 56
ASP.NET
ENUMERATE A COLLECTION
ollections give you a sophisticated way to work The foreach statement automatically increments
ENUMERATE A COLLECTION
Untitled - Notepad
⁄ Open your text editor. ‹ Type the name of the ˇ Between the curly braces, ‡ Declare a collection of
class you want to create create the Main function. integers.
¤ Type using System; to and press Enter.
import the System Á Declare an integer ° Add the foreach
namespace and press Enter. › Type { }, placing the variable and initialize the statement to display all the
opening and closing curly value to 0. members over 5.
braces on separate lines, to
56 set off the body of the class.
043617-6 Ch03.F 9/26/01 9:40 AM Page 57
C# BASICS 3
You can use a for statement instead of a foreach
statement. Note how much extra programming
you must do to make this work.
Example:
static void Main()
{
int iCount = 0;
int[] iNumberList = new int [] {0,1,2,5,7,8,11};
{
if (iNumberList[i]>5)
{
iCount++;
}
}
EnumerateCollection.cs - Notepad
· Output the results to the ‚ Save as the class name. — Compile and run the ■ The program displays the
console. program. message about the results.
Note: See page 35 for more
information on saving a file.
57
043617-6 Ch03.F 9/26/01 9:40 AM Page 58
ASP.NET
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Write a message about the
you want to create and press create the Main function. types of formats to the
¤ Type using System; to Enter. console.
import the System Á Declare a string
namespace and press Enter. › Type { }, placing the variable to hold the date, and
opening and closing curly a character variable to
braces on separate lines, to hold the user input.
set off the body of the class.
58
043617-6 Ch03.F 9/26/01 9:40 AM Page 59
C# BASICS 3
° Read the input from the · Call the ‚ Write the message about
console. GetFormattedDate the current date to the
function with the user input console.
and put into the variable for
the current date. CONTINUED
59
043617-6 Ch03.F 9/26/01 9:40 AM Page 60
ASP.NET
60
043617-6 Ch03.F 9/26/01 9:40 AM Page 61
C# BASICS 3
A method has four possible signatures.
Example:
using System;
DeclareUseMethods.cs - Notepad
™ Create the different cases £ Save as the class name. ¢ Compile and run the ■ The program displays the
for the user input, formatting program. options for different dates and
the return variable Note: See the section “Write Your First times and displays results for
appropriately. C# Application,” earlier in this chapter, the current date and time.
if you need more information on
saving a file.
61
043617-6 Ch03.F 9/26/01 9:40 AM Page 62
ASP.NET
IMPLEMENT EXCEPTION
HANDLING
hen programmatically working with errors, If you do not code for handling errors, your code
⁄ Open your text editor. ‹ Type the name of the class ˇ Between the curly braces, ‡ Use the try statement to
you want to create and press create the Main function. create a new string
¤ Type using System; to Enter. variable set to null, and use
import the System Á Create a new variable of this variable to call
namespace and press Enter. › Type { }, placing the type Implement EvaluateString.
opening and closing curly ExceptionHandling.
braces on separate lines, to ° Use the catch statement
62 set off the body of the class. to write out the exception.
043617-6 Ch03.F 9/26/01 9:41 AM Page 63
C# BASICS 3
Exceptions can be thrown in two different ways. A
throw statement can be executed programmatically
or it can happen at runtime where the processing of
the C# statement causes the error (like dividing by zero).
Below is a table of common exception classes:
EXCEPTION DESCRIPTION
System.OutOfMemoryException Thrown when an attempt to allocate memory (via new) fails.
System.StackOverflowException Thrown when the execution stack is exhausted by having too
many pending method calls; typically indicative of very deep
or unbounded recursion.
System.NullReferenceException Thrown when a null reference is used in a way that causes
the referenced object to be required.
System.InvalidCastException Thrown when an explicit conversion from a base type or
interface to a derived type fails at runtime.
System.ArrayTypeMismatchException Thrown when a store into an array fails because the actual
type of the stored element is incompatible with the actual
type of the array.
System.IndexOutOfRangeException Thrown when an attempt to index an array via an index that
is less than zero or outside the bounds of the array fails.
System.ArithmeticException A base class for exceptions that occur during arithmetic
operations, such as DivideByZeroException and
OverflowException.
DeclareUseMethods.cs - Notepad
· Create a function called — Save as the class name. ± Compile and run the ■ The program displays the
EvaluateString. program. error that was raised.
Note: See page 35 for more
‚ Use this function to raise an information on saving a file.
ArgumentNullException
error.
63
043617-6 Ch03.F 9/26/01 9:41 AM Page 64
ASP.NET
64
043617-6 Ch03.F 9/26/01 9:41 AM Page 65
C# BASICS 3
Leverage the use of components when you write You will typically not choose to write console
a console application that eventually becomes an applications if you build a production application.
ASP.NET application. When implementing your There are cases in which you would choose a
application functionality, encapsulate logical console application. Some examples of useful
units of code behind methods in the classes that console-type applications include testing out
make up the component. If you program in this programming syntax, building quick test harnesses,
way, you will be able to reuse the code when building administrative applications, or building
migrating to a new user interface (Windows debugging tools.
application or ASP.NET application). Also, if you
put your code into components, you will be able
to share these components with future or
existing applications.
› Paste the ■ Scroll down the page to ˇ Save the file and request ‡ Click the Submit button.
GetFormattedDate view the from the Web server.
function into the <SCRIPT> SubmitBtn_Click ■ The date appears in the
section of the ASP.NET Web function in the page, which Á Select a date format. format selected.
page. calls the
GetFormattedDate
function.
■ A Submit button calls the
SubmitBtn_Click
function. 65
053617-6 Ch04.F 9/26/01 9:41 AM Page 66
ASP.NET
INTRODUCTION TO
HTML CONTROLS
ou can take standard HTML elements and over attributes of these elements while processing
HTML server controls are essentially HTML elements onServerClick to map to a function that is called
that the server can process. This processing can occur when the user clicks the button.
before sending the Web page to the user and/or when
the page is posted back to the server. All HTML server HTML server controls derived from the HtmlInput
controls (also known as HTML controls) map directly to abstract class need to be within an HtmlForm control.
an HTML element. Also, “the properties of” almost For all HTML server controls, overlapping tags are not
every HTML control are identical to the corresponding allowed — you need to make sure that the HTML tags
HTML element’s attribute. are properly closed and cleanly nested.
HTML controls are defined in the The .NET Framework provides classes to handle the
System.Web.UI.HtmlControls namespace. You can most commonly used HTML elements. For HTML
create an HTML control in most cases simply by adding elements that corresponding HTML controls, lacking
the RUNAT="Server" attribute within the tag of the the HtmlGenericControl class. You can
HTML element. If you incorrectly set the RUNAT programmatically read and write to attributes on the
attribute on the HTML element, you lose all server-side HTML element and map events to server-side code.
processing capabilities. You want to give each HTML Note that any attribute declared on an HTML server
control a unique ID attribute so you have a way to control is added to the HtmlGenericControl’s
reference the control in your server-side code. Attribute collection and can be manipulated
in server-side code. For example, with a <body
You can set attributes for the HTML controls to ID="Body" RUNAT="Server"> element, you can
establish control properties and to handle events. programmatically attribute on a body tag change the
Property attributes configure how the control appears bgcolor.netframeworkoffers with the following
and behaves as an HTML element on a Web page. In code:
most cases, the property attributes map directly to the Body.Attributes["bgcolor"] = "blue";).
standard attributes on the HTML 4.0 element. For
example, the ID attribute on an HTML control renders All HTML controls are derived from the HtmlControl
in the client’s browser as an ID attribute on the HTML abstract class. Within this abstract class, there are two
element, too. As for handling events, you distinguish other abstract classes, HtmlContainerControl and
events as attributes on an HTML control to map an HtmlInputControl, which contain all HTML controls,
HTML control’s event to a procedure that will process except for the HtmlImage class, which is derived
the event. For example, when working with the directly from the HtmlControl abstract class.
HTMLButton control, you can add an attribute
66
053617-6 Ch04.F 9/26/01 9:41 AM Page 67
HtmlInputControl derived classes share the Border (Read/Write) — The width of a frame for
following properties: an image
Name (Read/Write) — A unique identifier name for Height (Read/Write) — The height of the image
the HtmlInputControl Src (Read/Write) — The source of the image file to
Value (Read/Write) — The contents of an input display
control Width (Read/Write) — The width of the image
Type (Read) — The type of HtmlInputControl
67
053617-6 Ch04.F 9/26/01 9:41 AM Page 68
ASP.NET
⁄ Open the ¤ Add a heading for › Add a form to the page and Á Add a <span> tag
GenericTemplate.aspx the page. give the form an ID attribute on the form to display
template from the Code and set the RUNAT attribute a message to the user.
Templates directory. ‹ Add a message to to "Server".
the user.
ˇ Add a button using the
OnServerClick event to call the
buttonContinue_OnClick
function.
68
053617-6 Ch04.F 9/26/01 9:41 AM Page 69
When working with forms, you often use You can also set the DISABLED attribute. The
ACTION and METHOD attributes. The ACTION default value for this attribute is false, but you can
attribute tells the Web browser where to send change it to true if you want a non-editable
the form data. In most cases with ASP.NET, you version of the form. When you do this, the form
do not use this attribute, so by default the controls appear grayed out.
browser posts to the page where the form is
located, enabling you to validate the form data
before sending the user to the next page or to
display a message on the page the user was
viewing. The METHOD attribute tells the Web
browser whether to send the form data to the
Web server via the URL in the query string (this
would be a GET) or through the HTTP Request
(this would be a POST). A <POST> allows you to
send more form data to the server.
‡ Add the ° Set the InnerHTML · Save the file and request it ‚ Click the Continue
buttonContinue_OnClick property of the <span> from the Web server. button.
function between the <HEAD> tag on the form.
tags. Note: See pages 20 to 25 for ■ A continue message
instructions on saving a file to the appears.
Web server and then requesting
the file using the IIS Admin.
69
053617-6 Ch04.F 9/26/01 9:41 AM Page 70
ASP.NET
Then, add an HTMLInputButton with the TYPE attribute set to Button. For
this control, use the OnServerClick event to call the ClearBtn_Click event.
RESULT:
A Web page that allows the user to click the Clear button to clear the form
° Create a SubmitBtn_Click · Use an if statement ‚ Save the file and request it ± Click the Submit button.
function to check the password. to check the password and from the Web server.
display the message using ■ A message appears
the HTMLSpan control on Note: See pages 20 to 25 for notifying you if your
the page. instructions on saving a file to the password is correct.
Web server and then requesting
Note: Try entering an incorrect
the file using the IIS Admin.
password.
— Type in a name and a
correct password. 71
053617-6 Ch04.F 9/26/01 9:41 AM Page 72
ASP.NET
⁄ Open the ‹ Set the STYLE Á Save the file and request it ■ The button background
WelcomeTemplate.aspx attribute for the button. from the Web server. color changes.
template from the Code
Templates directory. › Set the background Note: See pages 20 to 25 for ° Click Continue and move
color of the button for the instructions on saving a file to the the mouse off the button.
¤ Add a Continue button onMouseOver event. Web server and requesting the file
with the HTMLButton ■ The button background
ˇ Set the background using the IIS Admin. color changes back.
control to the form and call the
Button_OnClick function for color for the button for ‡ Position your mouse over ■ A continue message
the onServerClick event. the onMouseOut event. the button. appears.
72
053617-6 Ch04.F 9/26/01 9:41 AM Page 73
⁄ Open the › Set the image for the ‡ Save the file and request it ° Move your mouse over
WelcomeTemplate.aspx onMouseOver event. from the Web server. the button and click.
template from the Code
Templates directory. ˇ Set the image for the Note: See pages 20 to 25 for ■ The light changes to green
onMouseOut event. instructions on saving a file to the and a continue message
¤ Add an HTMLInputImage Web server and then requesting appears.
control to the form and call the Á Change the parameters
on the Button_OnClick the file using the IIS Admin.
Button_OnClick function.
function from EventArgs ■ The light is red.
‹ Set the SRC attribute for to ImageClickEventArgs.
the button.
73
053617-6 Ch04.F 9/26/01 9:41 AM Page 74
ASP.NET
74
053617-6 Ch04.F 9/26/01 9:41 AM Page 75
You can create a read-only text box by setting You can limit the number of characters that a user
the Disabled property of the HTMLInputText can type into a text box. The MAXLENGTH property
control to true. is used for this purpose.
Example: Example:
Enter Name: <INPUT ID="inputName" TYPE="Text" Enter Name: <INPUT ID="inputName" TYPE="Text"
SIZE="40" RUNAT="Server" VALUE="Guest" SIZE="40" RUNAT="Server" MAXLENGTH="40">
DISABLED="true">
Example:
Enter Name: <INPUT ID="inputName"
TYPE="Text"SIZE="40" RUNAT="Server"
VISIBLE="false">
° Create a function called · Add an if statement ‚ Save the file and request it ± Click the Submit button.
SubmitBtn_Click to check to check the password and from the Web server.
the password. display the message using ■ A message appears
the HTMLSpan control on Note: See pages 20 to 25 for notifying you if your
the page. instructions on saving a file to the password is correct.
Web server and then requesting
the file using the IIS Admin.
— Type in a name and the
incorrect password. 75
053617-6 Ch04.F 9/26/01 9:41 AM Page 76
ASP.NET
⁄ Open the ‹ Add the code in the › Save the file and request it ˇ Fill in a suggestion.
SuggestionsTemplate.aspx SubmitBtn_Click from the Web server.
template from the Code function to echo back Á Click the Submit button.
Note: See pages 20 to 25 for
Templates directory. the contents of the ■ A message appears
HTMLTextArea control. instructions on saving a file to the
¤ Add an HTMLTextArea displaying the suggestion.
Web server and then requesting
control to the form and set the the file using the IIS Admin.
COLS and ROWS attributes.
76
053617-6 Ch04.F 9/26/01 9:41 AM Page 77
⁄ Open the ‹ Add the code in the › Save the file and request it ˇ Check the check box.
SuggestionsTemplate.aspx SubmitBtn_Click from the Web server.
template from the Code Templates function to send an Á Click the Submit button.
■ The ASP.NET Web page
directory. appropriate message
appears. ■ A message appears
back to the user. displaying the suggestion.
¤ Add an HTMLInputCheckBox
control to the form and set the Note: See pages 20 to 25 for
VALUE attribute. instructions on saving a file to the
Web server and then requesting
the file using the IIS Admin.
77
053617-6 Ch04.F 9/26/01 9:41 AM Page 78
ASP.NET
⁄ Open the ‹ Add the code in the › Save the file and request it ˇ Check the first radio
SuggestionsTemplate.aspx SubmitBtn_Click from the Web server. button.
template from the Code function to send an
Templates directory. appropriate message ■ The ASP.NET Web page Á Click the Submit button.
appears.
¤ Add multiple
back to the user. ■ A message appears
HTMLInputRadioButton Note: See pages 20 to 25 for displaying the suggestion.
controls to the form and set instructions on saving a file to the
NAME attributes. Web server and then requesting
the file using the IIS Admin.
78
053617-6 Ch04.F 9/26/01 9:41 AM Page 79
⁄ Open the ‹ Add the code in the › Save the file and request it ˇ Click and select the
SuggestionsTemplate.aspx SubmitBtn_Click from the Web server. first option from the drop-
template from the Code function to send an down list.
Templates directory. appropriate message ■ The ASP.NET Web page
back to the user. appears. Á Click the Submit button.
¤ Add an HTMLSelect control
and a number of options to the Note: See pages 20 to 25 for ■ A message appears
form. instructions on saving a file to the displaying the suggestion.
Web server and then requesting
the file using the IIS Admin.
79
053617-6 Ch04.F 9/26/01 9:41 AM Page 80
ASP.NET
CREATE A LINK
ou can work with the anchor tag, <a>, create parts of the anchor tag. To properly configure a
CREATE A LINK
⁄ Open the ¤ Add a heading for › Add a form to the page ˇ Place an anchor with
GenericTemplate.aspx the page. with a RUNAT attribute set to a RUNAT attribute set to
template from the Code "Server". "Server" on the page for
Templates directory. ‹ Add a message to the user to click.
the user.
80
053617-6 Ch04.F 9/26/01 9:41 AM Page 81
You can override the redirect of the You can set the attributes for the anchor tag in the
HTMLAnchor control by implementing the HTML as well.
ServerClick event.
Example:
Example: <A ID="aWebsite" RUNAT="Server"
HREF="http://www.mylifetimegoals.com">
<SCRIPT LANGUAGE="C#" RUNAT="Server">
Go To Home Page for My Lifetime Goals Website
void aWebsite_OnClick(object Source,
EventArgs e) { </A>
aWebsite.InnerText="You clicked?";
}
</SCRIPT>
<A ID="aWebsite" RUNAT="Server"
HREF="http://www.mylifetimegoals.com"
onServerClick="aWebsite_OnClick">
Go To Home Page for My Lifetime Goals Website
</A>
Á Add the Page_Load ‡ Set the HREF property · Save the file and request it Note: See pages 20 to 25 for
function between the of the anchor on the form. from the Web server. instructions on saving a file to the
<HEAD> tags. Web server and then requesting
° Set the InnerText ■ The ASP.NET Web page
property of the anchor on appears. the file using the IIS Admin.
the form. ■ The anchor appears
properly.
81
053617-6 Ch04.F 9/26/01 9:41 AM Page 82
ASP.NET
RENDER AN IMAGE
ou can use the HTMLImage control to have programmatically, or you could set the property by
RENDER AN IMAGE
⁄ Open the ¤ Add a heading for › Add a form to the page Á Add a button on the page
GenericTemplate.aspx the page. with a RUNAT attribute set to for the user to click and use the
template from the Code "Server". OnServerClick event to call
Templates directory. ‹ Add a message to the SubmitButton_Click
the user. ˇ Add an HTMLSelect function.
control on the page so the
user can select a goal type. ‡ Add an Image control on
the page and set the source for
the image control.
82
053617-6 Ch04.F 9/26/01 9:41 AM Page 83
You can use the ALT property to display a You can use the BORDER property to display a
message when the user places the mouse pointer border around the image by setting it to a value
over the image. greater than zero. The default setting of zero
<FORM RUNAT="Server"> displays no border around the image.
<IMG ID="imageGoalImages"
SRC="/visualaspdotnet/Chapter04/Code/images/tr Example:
avel.gif" <FORM RUNAT="Server">
ALT="Picture of a road and a distant planet <IMG ID="imageGoalImages"
earth" RUNAT="Server"/> SRC="/visualaspdotnet/Chapter04/Code/images/
</FORM> travel.gif"
BORDER="2" RUNAT="Server"/>
To change the size of the image, you can set the
</FORM>
WIDTH and HEIGHT properties of the image.
Example:
<FORM RUNAT="Server">
<IMG ID="imageGoalImages"
SRC="/visualaspdotnet/Chapter04/Code/images/tr
avel.gif"
WIDTH="100" HEIGHT="100" RUNAT="Server"/>
</FORM>
° Add the · Set the InnerHTML ‚ Save the file and request it ■ The Travel graphic
SubmitButton_Click property of the span on the from the Web server. appears.
function. form in the Sub.
■ The ASP.NET Web page — Click and select
appears. Educational as the goal type.
Note: See pages 20 to 25 for ± Click the Apply button.
instructions on saving a file to the
■ The Educational graphic
Web server and then requesting appears.
the file using the IIS Admin. 83
053617-6 Ch04.F 9/26/01 9:41 AM Page 84
ASP.NET
BUILD A TABLE
ou can use the HTMLTable control to When working with the HTMLTable control, you
⁄ Open the › Add a form to the page. Á Add the Page_Load ° Create and initialize a
GenericTemplate.aspx function. variable for the number of
template from the Code ˇ Add a table to the page cells and a variable for the
Templates directory. and set the BORDER attribute ‡ Create and initialize a number of rows.
equal to 1. variable to be a counter for
¤ Add a heading for the the rows. · Create and initialize an
page. array for the contents of the
table.
‹ Add a message to the user.
84
053617-6 Ch04.F 9/26/01 9:41 AM Page 85
You can specify the cell padding, cell spacing, You can use table row properties to format a table
border color, and background color for the table. with alternating colors for each row.
Example: Example:
<FORM RUNAT="Server"> HtmlTableRow row = new HtmlTableRow();
<TABLE ID="tableExample" Border="1" if (rowcount%2 == 1)
CellPadding="5" CellSpacing="0"
BorderColor="Black" BgColor="#C0C0C0" row.BgColor="#C0C0C0";
RUNAT="Server" /> rowcount++;
</FORM>
Example:
HtmlTableCell cell = new HtmlTableCell();
cell.Align="Right";
cell.VAlign="Top";
‚ Process each row ¡ Create a new ¢ Save the file and request it Note: See pages 20 to 25 for
with a for loop. HTMLTableCell for each from the Web server. instructions on saving a file to the
cell and add the value in Web server and then requesting
— Create a new the array to the cell. ■ The ASP.NET Web page
HTMLTableRow for appears. the file using the IIS Admin.
each row. ™ Add the cell to the row. ■ A table appears with the
± Process each cell in £ Add the row to the table. contents of your array.
the row with a for loop.
85
053617-6 Ch04.F 9/26/01 9:41 AM Page 86
ASP.NET
86
053617-6 Ch04.F 9/26/01 9:41 AM Page 87
Source
ˇ Save the file and request it Á Type in a suggestion. ■ The source for the
from the Web server. page appears and the
‡ Click the Submit button. hiddenSuggestions
■ The ASP.NET Web page
appears. ° Click View ➪ Source from tag contains the suggestion.
the menu in Internet Explorer.
Note: See pages 20 to 25 for
instructions on saving a file to the
Web server and then requesting
the file using the IIS Admin. 87
053617-6 Ch04.F 9/26/01 9:41 AM Page 88
ASP.NET
UPLOAD FILES
eople who visit your Web sites can upload files browser that one of the controls is a file that needs to
UPLOAD FILES
⁄ Open the ¤ Add the ENCTYPE › In the SubmitBtn_Click Á Catch the exception if
SuggestionsTemplate.aspx attribute and specify that function, check to make sure the post was unsuccessful
template from the Code the form will be posting there is a filename entered. and set the message to
Templates directory. multipart form data. reflect an error.
ˇ Post the file up to the Web
‹ Add a message and an server and set the message for
HTMLInputFile control the <SPAN> tag.
to the form.
88
053617-6 Ch04.F 9/26/01 9:41 AM Page 89
‡ Save the file and request it ■ The Choose file dialog box ■ The path and filename ■ A message appears
from the Web server. appears. appear in the text box. notifying you that the file
successfully uploaded to the
Note: See pages 20 to 25 for · Select a file to upload to — Click the Submit button. Web server.
instructions on saving a file to the the Web server.
Web server and then requesting ‚ Click Open.
the file using the IIS Admin.
° Click the Browse button.
89
063617-6 Ch05.F 9/26/01 9:41 AM Page 90
ASP.NET
Basics of Web Form Controls controls. Web controls all have the ASP namespace
Web server controls are a close cousin to the HTML prefix in front of every control in the
server controls covered in Chapter 4. At first glance, you System.Web.UI.WebControls namespace. Like
may not understand why Web form controls (also an HTML control, each tag needs to contain the
known as Web controls) exist and you may get the two RUNAT="Server" attribute within it. You also want
confused. Just like HTML controls, Web controls are to give each Web control a unique ID attribute, so that
HTML elements that can be processed on the server. you have a way to reference the control in your server-
This processing can occur before sending the Web page side code.
to the user and/or when the page is posted back to the You can set attributes for the Web controls to set
server. Unlike HTML controls, Web controls do not properties of the control and handle events. Property
always map directly to an HTML element. Also, a Web attributes configure how the control will appear and
control’s properties are not identical to the behave as an HTML element on a Web page. As for
representative HTML element’s attribute. handling events, you mark up events as attributes on a
Seeing the high-level differences and similarities between Web control. This gives you the ability to map a Web
Web server controls and HTML server controls control’s event to a procedure that will process the
(especially the overlap of representation for HTML event. For example, when working with the
elements), you should ask, “Why Web controls?” The ASP:ImageButton control, you can add an attribute
answer is “uniformity and ease of use.” Web server onServerClick to map to a function that is called
controls use consistent naming conventions and when the user clicks the button.
programming models across the controls in the When working with Web controls, you may find the
namespace for Web controls. The Web controls wrap syntax foreign if you have not previously worked with
common HTML elements and give a consistent interface XML. The requirement for the notation is similar to
(hiding the programmers from the inconsistencies that building well-formed XML documents (like closing all
cause a longer learning curve for Web development). tags). For all HTML server controls, you should make
Web controls are defined in the sure that the HTML tags are properly closed and cleanly
System.Web.UI.WebControls namespace. Web nested (overlapping tags are not allowed).
forms have a slightly different convention than HTML
90
063617-6 Ch05.F 9/26/01 9:41 AM Page 91
91
063617-6 Ch05.F 9/26/01 9:41 AM Page 92
ASP.NET
⁄ Open the ¤ Add a Button Web ‹ Set the TEXT attribute › Set an initial style for the
WebWelcomeTemplate.aspx control on the page for the equal to Continue. button.
template from the Code user to click.
Templates directory.
92
063617-6 Ch05.F 9/26/01 9:41 AM Page 93
Example:
<SCRIPT LANGUAGE="C#" RUNAT="Server">
void Button_OnClick(object Source, EventArgs e)
{
labelMessage.Text="You are continuing to Step 2..."
+ "</BR>" + "Your Command Name was "
+ buttonContinue.CommandName + ".</BR>" +
"Your Command Argument was "
+ buttonContinue.CommandArgument + ".</BR>";
}
</SCRIPT>
<ASP:BUTTON ID="buttonContinue"
TEXT="Continue"
STYLE="height=30;width:100"
onMouseOver="this.style.backgroundColor='Silver'"
onMouseOut="this.style.backgroundColor='White'"
onClick="Button_OnClick"
CommandName="Move"
CommandArgument="Homepage"
RUNAT="Server"/>
ˇ Add the code for the ‡ Add the onClick event ° Save the file and request it · Click the Continue button.
onMouseOver event to set to call the from the Web server.
the background color of the Button_OnClick function. ■ A message appears.
button to silver. Note: See pages 20 to 25 for
instructions on saving a file to the
Á Add the code for the Web server and then requesting the
onMouseOut event to set the file using the IIS Admin.
background color for the
button back to white. 93
063617-6 Ch05.F 9/26/01 9:41 AM Page 94
ASP.NET
⁄ Open the ¤ Add a LinkButton Web ‹ Save the file and request it › Click the link.
WebWelcomeTemplate.aspx control to the page and have from the Web server.
template from the Code it call the Button_OnClick ■ A message appears.
Templates directory. when the onClick event is Note: See pages 20 to 25 for
fired. instructions on saving a file to the
Web server and then requesting
the file using the IIS Admin.
94
063617-6 Ch05.F 9/26/01 9:41 AM Page 95
⁄ Open the › Call the Á Save the file and request it ■ A red light appears.
WebWelcomeTemplate.aspx Button_OnClick when the from the Web server.
template from the Code onClick event is fired for ‡ Position your mouse over
Templates directory. the ImageButton Web Note: See pages 20 to 25 for the stoplight and click.
instructions on saving a file to the
¤ Add a ImageButton Web
control. ■ A green light appears with
Web server and then requesting a continuing message.
control to the page. ˇ Add the onMouseOver the file using the IIS Admin.
and onMouseOut event
‹ Set the initial value for the handlers to create the
image. rollover effect. 95
063617-6 Ch05.F 9/26/01 9:41 AM Page 96
ASP.NET
⁄ Open the › Type a Server form to the Á Add a Label control for ° Add a password and set
GenericTemplate.aspx page. the message. the WIDTH attribute to 200
template from the Code pixels.
Templates directory. ˇ Add a Button Web ‡ Add a single-line text box
control that calls the and set the WIDTH attribute
¤ Type a heading for the SubmitBtn_Click for the to 200 pixels.
page. onClick event.
‹ Type a message to the user.
96
063617-6 Ch05.F 9/26/01 9:41 AM Page 97
You can create a text box that is read only by You can limit the number of characters that a user
setting the Disabled attribute of the TextBox can type into a textbox. with the MAXLENGTH
Web control to True. attribute.
Example: Example:
Enter Name: <ASP:TEXTBOX ID="inputName" Enter Name: <ASP:TEXTBOX ID="inputName"
TEXTMODE="SingleLine" TEXT="" WIDTH="200px" TEXTMODE="SingleLine" TEXT="" WIDTH="200px"
RUNAT="Server" DISABLED="True"/> RUNAT="Server" MAXLENGTH="40"/>
· Create a function called ‚ Add an if statement to — Save the file and request it ± Type in a name and a
SubmitBtn_Click to check the password and from the Web server. correct password.
check the password. display the message using the ¡ Click the Submit button.
Label Web control on the Note: See pages 20 to 25 for
page. instructions on saving a file to the ■ A message appears
Web server and then requesting notifying you that the
the file using the IIS Admin. password is correct.
97
063617-6 Ch05.F 9/26/01 9:41 AM Page 98
ASP.NET
⁄ Open the ‹ Type a message to the ˇ Add a Button Web Á Add a Label control for
GenericTemplate.aspx user. control that calls the the message.
template from the Code SubmitBtn_Click for the
Templates directory. › Add a server form to the onClick event. ‡ Add a CheckBox Web
page. server control.
¤ Type a heading for the
page.
98
063617-6 Ch05.F 9/26/01 9:41 AM Page 99
Example: Example:
<FORM RUNAT="Server"> <SCRIPT LANGUAGE="C#" RUNAT="Server">
<P/> void SubmitBtn_Click(object Source,
EventArgs e) {
<ASP:CHECKBOXLIST ID="checkboxlistSuggestions"
RUNAT="Server"> String sMessage = "";
<ASP:LISTITEM>Have more goals to choose for (int i=0; i <
from.</ASP:LISTITEM> checkboxlistSuggestions.Items.Count; i++) {
<ASP:LISTITEM>Have more goal if ( checkboxlistSuggestions.
categories.</ASP:LISTITEM> Items[ i ].Selected ) {
<ASP:LISTITEM>Make the goal setting wizard sMessage = sMessage +
easier.</ASP:LISTITEM> checkboxlistSuggestions.Items[i].Text;
</ASP:CHECKBOXLIST> sMessage = sMessage + "<BR />";
<P/> }
<ASP:BUTTON TEXT="Submit" }
OnClick="SubmitBtn_Click" RUNAT="Server"/>
if (sMessage != "") {
<P/>
labelMessage.Text ="Your suggestions"
<ASP:LABEL ID="labelMessage" RUNAT="SERVER"/> + "are...<BR />" + sMessage;
</FORM> }
else {
labelMessage.Text = "You have no
suggestions.";
}
}
</SCRIPT>
° Create a function called · Add an if statement to ‚ Save the file and request it — Click to select the check
SubmitBtn_Click to check whether the control from the Web server. box.
check the password. was checked and set the
appropriate message. Note: See pages 20 to 25 for ± Click the Submit button.
instructions on saving a file to the
■ The suggestion echoes
Web server and then requesting back.
the file using the IIS Admin.
99
063617-6 Ch05.F 9/26/01 9:41 AM Page 100
ASP.NET
⁄ Open the ‹ Type a message to the ˇ Add a Button Web ‡ Add a RadioButton
GenericTemplate.aspx user. control that calls the Web server control for each
template from the Code SubmitBtn_Click for the of the radio button options
Templates directory. › Add a server form to the onClick event. and set the GROUPNAME
page. attribute for the controls to be
¤ Type a heading for the Á Add a Label control for the same so they are in a
page. the message. group.
100
063617-6 Ch05.F 9/26/01 9:41 AM Page 101
Example: Example:
<FORM RUNAT="Server"> <SCRIPT LANGUAGE="C#" RUNAT="Server">
<P/> void SubmitBtn_Click(object Source, EventArgs e)
{
<ASP:RADIOBUTTONLIST
ID="radiobuttonlistSuggestions" if
RUNAT=”Server”> (radiobuttonlistSuggestions.SelectedIndex > -1)
{
<ASP:LISTITEM>Fewer Goals</ASP:LISTITEM>
labelMessage.Text = "You suggested "
<ASP:LISTITEM>More Goals</ASP:LISTITEM> + radiobuttonlistSuggestions.SelectedItem.Text;
<ASP:LISTITEM>Same Number of }
Goals</ASP:LISTITEM>
}
</ASP:RADIOBUTTONLIST>
</SCRIPT>
<P/>
<INPUT TYPE="Submit" VALUE="Submit"
OnServerClick="SubmitBtn_Click"
RUNAT="Server">
<P/>
<ASP:LABEL ID="labelMessage" RUNAT="Server"/>
</FORM>
° Create a function called · Add an if statement to ‚ Save the file and request it — Click to select the first
SubmitBtn_Click to check whether the control from the Web server. radio button.
check the suggestion was checked and send the
selected. appropriate message. Note: See pages 20 to 25 for ± Click the Submit button.
instructions on saving a file to the
■ The suggestion echoes
Web server and then requesting back.
the file using the IIS Admin.
101
063617-6 Ch05.F 9/26/01 9:41 AM Page 102
ASP.NET
⁄ Open the ‹ Type a message to the Á Add a Label control for ° Add ListItem Web
GenericTemplate.aspx user. the message. server controls for each
template from the Code option.
Templates directory. › Add a server form to the ‡ Add a DropDownList
page. Web server control and set its
¤ Type a heading for the attributes.
page. ˇ Add a Button Web
control that calls the
SubmitBtn_Click for the
onClick event.
102
063617-6 Ch05.F 9/26/01 9:41 AM Page 103
· Create a function called ‚ Set the label according to — Save the file and request it ± Click to select an
SubmitBtn_Click to the input received from the from the Web server. option.
check the input. user.
Note: See pages 20 to 25 for ¡ Click the Submit button.
instructions on saving a file to the
■ The suggestion echoes
Web server and then requesting
back on screen.
the file using the IIS Admin.
103
063617-6 Ch05.F 9/26/01 9:42 AM Page 104
ASP.NET
⁄ Open the ‹ Type a message to the ˇ Add a Label control for Á Add a Calendar control to
GenericTemplate.aspx user. the message. the page and have the control
template from the Code call the Date_Selected
Templates directory. › Add a server form to the function for the
page. onSelectionChanged
¤ Type a heading for the event.
page.
104
063617-6 Ch05.F 9/26/01 9:42 AM Page 105
Example:
<ASP:CALENDAR ID="calendarGoal" RUNAT="Server"
onSelectionChanged="Date_Selected"
DAYNAMEFORMAT="FirstLetter"
SELECTIONMODE="DayWeekMonth"
FONT-NAME="Verdana" FONT-SIZE="12px"
HEIGHT="180px" WIDTH="230px"
TODAYDAYSTYLE-FONT-BOLD="True"
DAYHEADERSTYLE-FONT-BOLD="True"
OTHERMONTHDAYSTYLE-FORECOLOR="Gray"
TITLESTYLE-BACKCOLOR="Navy"
TITLESTYLE-FORECOLOR="White"
TITLESTYLE-FONT-BOLD="True"
SELECTEDDAYSTYLE-BACKCOLOR="LightBlue"
SELECTEDDAYSTYLE-FONT-BOLD="True"
‡ Create the ° Set the label according to · Save the file and request it ■ A calendar appears.
Date_Selected function. the input received from the from the Web server.
user. ‚ Click to select a date.
Note: See pages 20 to 25 for
■ The date echoes back.
instructions on saving a file to the
Web server and then requesting
the file using the IIS Admin.
105
063617-6 Ch05.F 9/26/01 9:42 AM Page 106
ASP.NET
CREATE A LINK
o create a hyperlink programmatically with Web The HREF for the anchor tag represents the URL that
CREATE A LINK
⁄ Open the WebVisit ‹ Add the code to set the › Save the file and request it ■ The page appears with a
HompageLinkTemplate.aspx HREF and Text properties from the Web server. HyperLink.
template from the Code for the HyperLink
Templates directory. control. Note: See pages 20 to 25 for
instructions on saving a file to the
¤ Add a HyperLink Web Web server and then requesting
server control to the form. the file using the IIS Admin.
106
063617-6 Ch05.F 9/26/01 9:42 AM Page 107
RENDER AN IMAGE
ou can use the Image Web server control to set the IMAGEURL attribute for mapping the path of
RENDER AN IMAGE
⁄ Open the ¤ Add an Image ‹ Save the file and request it › Click to select the
WebGoalTypesTemplate.aspx control to the server from the Web server. Educational goal type from
template from the Code form. the drop-down list box.
Templates directory. Note: See pages 20 to 25 for
instructions on saving a file to the ˇ Click the Apply button.
Web server and then requesting ■ The image is updated with
the file using the IIS Admin. the Education image.
■ The page appears with the
Travel image.
107
063617-6 Ch05.F 9/26/01 9:42 AM Page 108
ASP.NET
BUILD A TABLE
ou can use the Table Web server control to When working with the Table Web control, you can
BUILD A TABLE
⁄ Open the › Add a form to the page. Á Add the Page_Load ° Create and initialize
GenericTemplate.aspx function. variables for number of rows
template from the Code ˇ Add a table to the page and number of cells.
Templates directory. and set the BORDER attribute ‡ Create and initialize a
equal to 1. variable for counting rows. · Create and initialize an
¤ Add a heading for the array for the contents of the
page. Note: You need to give the form an table.
ID attribute and set the RUNAT
‹ Add a message to the user. attribute to "Server".
108
063617-6 Ch05.F 9/26/01 9:42 AM Page 109
‚ Process each row with a ¡ Create a new ¢ Save the file and request it ■ A table with the contents
for loop. HTMLTableCell for each from the Web server. of your array appears.
cell and add the value in the
— Create a new array to the cell. Note: See pages 20 to 25 for
HTMLTableRow for instructions on saving a file to the
each row. ™ Add the cell to the row. Web server and then requesting
± Process each cell in the £ Add the row to the table. the file using the IIS Admin.
row with a for loop.
109
063617-6 Ch05.F 9/26/01 9:42 AM Page 110
ASP.NET
MANIPULATE TEXT
he Label Web server control is used for with the <ASP: Label> tag. You will need an ID
MANIPULATE TEXT
⁄ Open the ‹ Add a button to the pages ˇ Save the file and request it Á Type a message in the
WebWelcomeTemplate.aspx that calls the from the Web server. text box.
template from the Code Button_OnClick event. ‡ Click the Submit button.
Templates directory. Note: See pages 20 to 25 for
› Modify the code in the instructions on saving a file to the ■ A message appears.
¤ Add a Text box to the page. Button_OnClick event so Web server and then requesting
that the label is updated with the file using the IIS Admin.
■ Note the Label control on the text from the text box.
the page.
110
063617-6 Ch05.F 9/26/01 9:42 AM Page 111
⁄ Open the ‹ Create an HTML server ˇ Save the file and request it ■ The HTMLAnchor control
WebVisitHomepage control and set its properties. from the Web server. appears where the
Template.aspx template placeholder is located.
from the Code Templates › Add the control to the Note: See pages 20 to 25 for
directory. Placeholder control. instructions on saving a file to the
Web server and then requesting
¤ Add a Placeholder
control to the form. the file using the IIS Admin.
111
063617-6 Ch05.F 9/26/01 9:42 AM Page 112
ASP.NET
⁄ Open the › Create a Panel control Á Add a button for the user ° Add a message to the user
GenericTemplate.aspx and give it an ID. to click and call the about being on the second
template from the Code Button_OnClick function step.
Templates directory. ˇ Type a message to the for the onClick event.
user.
¤ Add a heading for the ‡ Create a Panel control
page. and give it an ID and set the
VISIBLE attribute for the
‹ Create a server form. control to False.
112
063617-6 Ch05.F 9/26/01 9:42 AM Page 113
You can use the Panel control’s properties to give an improved visual effect as
the user moves to the next step in a process. For example, you can change the
BACKCOLOR property to give a nice visual effect as the user moves from one panel
to the next. You can also set the HEIGHT and the WIDTH properties for the panel.
Example:
<ASP:PANEL ID="panelStep1" HEIGHT="100px" WIDTH="300px"
BACKCOLOR="Silver" RUNAT="SERVER"/>
Are you ready to set your goals? Click the Continue button to go to Step 2.
<P/>
<ASP:BUTTON ID="buttonContinue" RUNAT="Server"
onClick="Button_OnClick" TEXT="Continue"/>
</ASP:PANEL>
<ASP:PANEL ID="panelStep2" BACKCOLOR="Gold"
HEIGHT="100px" WIDTH="300px" RUNAT="SERVER" VISIBLE="False"/>
You are on Step 2.
<P/>
</ASP:PANEL>
· Create the ‚ Set the Visible property ± Save the file and request it ■ The first panel appears.
Button_OnClick function. of the first panel to False. from the Web server.
¡ Click the Continue button.
— Set the Visible property Note: See pages 20 to 25 for
of the second panel to True. ■ The second panel appears
instructions on saving a file to the
informing you that you are on
Web server and then requesting step 2.
the file using the IIS Admin.
113
063617-6 Ch05.F 9/26/01 9:42 AM Page 114
ASP.NET
⁄ Open the ‹ Add a server form to the ˇ View the contents of the
GenericTemplate.aspx page. advertisement file.
template from the Code
Templates directory. › Add an AdRotator Web
server control to the page and
¤ Add a heading for the specify the location of the
page. advertisement file.
114
063617-6 Ch05.F 9/26/01 9:42 AM Page 115
Á Save the file and request ■ An advertisement appears. ‡ Press F5 to refresh the ■ Another advertisement
from the Web server. Web page. may appear.
Note: See pages 20 to 25 for
instructions on saving a file to the
Web server and then requesting
the file using the IIS Admin.
115
063617-6 Ch05.F 9/26/01 9:42 AM Page 116
ASP.NET
⁄ Open the ‹ Add a message to the user. ˇ Add another message to ° Add a
GenericTemplate.aspx the user. RequiredFieldValidator
template from the Code › Add a server form to the control to the page and
Templates directory. page. Á Add a TextBox control to specify a name for the control
the form. by adding the ID attribute.
¤ Add a heading for the
page. ‡ Add a Button control to
the form.
116
063617-6 Ch05.F 9/26/01 9:42 AM Page 117
· Within the ‚ Save the file and request it Note: Do not fill in the login name
RequiredFieldValidator from the Web server. box.
control, set the validation
message by specifying the Note: See pages 20 to 25 for — Click the Submit button.
TEXT attribute. instructions on saving a file to the
Web server and then requesting
■ A validation message
appears.
the file using the IIS Admin.
117
063617-6 Ch05.F 9/26/01 9:42 AM Page 118
ASP.NET
⁄ Open the ‹ Add a message to the user. ˇ Add a message to the user ‡ Add a Button control to
GenericTemplate.aspx and TextBox control to the the form.
template from the Code › Add a server form to the form.
Templates directory. page. ° Add the
Á Add another message to CompareValidator
¤ Add a heading for the the user and TextBox control to the page.
page. control to the form.
118
063617-6 Ch05.F 9/26/01 9:42 AM Page 119
· Within the ‚ Save the file and request it — Fill in the form with a
CompareValidator from the Web server. smaller number for the first
control, set the validation question.
message by specifying the Note: See pages 20 to 25 for
TEXT attribute. instructions on saving a file to the ± Click the Submit button.
Web server and then requesting ■ A validation message
the file using the IIS Admin. appears.
119
063617-6 Ch05.F 9/26/01 9:42 AM Page 120
ASP.NET
⁄ Open the ‹ Add a message to the user. ˇ Add a message to the user ‡ Add the
GenericTemplate.aspx and TextBox control to the RangeValidator control to
template from the Code › Add a server form to the form. the page.
Templates directory. page.
Á Add a Button control to
¤ Add a heading for the the form.
page.
120
063617-6 Ch05.F 9/26/01 9:42 AM Page 121
° Within the · Save the file and request it ‚ Fill in the form with a date
RangeValidator control, from the Web server. outside the range.
set the validation message by
specifying the TEXT attribute. Note: See pages 20 to 25 for ■ A validation message
instructions on saving a file to the appears.
Web server and then requesting
the file using the IIS Admin.
121
063617-6 Ch05.F 9/26/01 9:42 AM Page 122
ASP.NET
⁄ Open the ‹ Add a message to the user. ˇ Add a message to the user ‡ Add the Regular
GenericTemplate.aspx and TextBox control to the ExpressionValidator
template from the Code › Add a server form to the form. control to the page.
Templates directory. page.
Á Add a Button control to
¤ Add a heading for the the form.
page.
122
063617-6 Ch05.F 9/26/01 9:42 AM Page 123
CODE DESCRIPTION
\d{3}-\d{2}-\d{4} Testing for a valid Social Security Number.
\d{5}(-\d{4})? Testing for valid US postal code.
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} Testing for a valid US phone number.
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4} Testing for a valid e-mail address.
http://([\w-]\.)+[\w-](/[\w- ./?%=]*)? Testing for a valid URL.
\d{4}-?\d{4}-?\d{4}-?\d{4} Testing for Visa Credit Card.
° Within the · Save the file and request it ‚ Type in an invalid zip
RegularExpressionValidator from the Web server. code.
control, set the validation message
by specifying the TEXT attribute. Note: See pages 20 to 25 for — Click the Submit button.
instructions on saving a file to the
■ A message appears.
Web server and then requesting
the file using the IIS Admin.
123
063617-6 Ch05.F 9/26/01 9:42 AM Page 124
ASP.NET
⁄ Open the ■ You can scroll down ■ You can scroll down to
WebValidationTemplate.aspx to view the form view the validation controls
template from the Code controls on the page. on the page.
Templates directory.
124
063617-6 Ch05.F 9/26/01 9:42 AM Page 125
¤ Add the ValidationSummary ‹ Save the file and request it › Fill out invalid input in
control to the page and set the from the Web server. each field.
properties for the control.
Note: See pages 20 to 25 for ˇ Click the Submit button.
instructions on saving a file to the
■ A message appears
Web server and then requesting showing all the validation
the file using the IIS Admin. errors.
125
073617-6 Ch06.F 9/26/01 9:42 AM Page 126
ASP.NET
INTRODUCTION TO DATA
ACCESS WITH ASP.NET
ata access is an intergral part of creating
In this chapter, you will look at how to work with After you have the data from the data source, you will
databases in ASP.NET using ADO.NET technology. The probably want to display this data on the Web page. To
origin of where the data is provided is called the data do this, you can bind the data to a control. There are
source. To get to this data, you can use a couple of several controls to which you can bind data. These
controls that are supplied by ADO.NET. These controls include the Repeater, DataList, and DataGrid
include a Connection object, which is used to make the controls. The simplest control is the Repeater control.
connection to the database. An important property of the It enables you to create simple header, footer, and item
Connection object is the Connection string, which is templates for data. For more complex lists, you can
used to specify how to open the database. Another control work with the DataList control. This control allows
used for data access is the Command object, which is for more complex formatting of your data. The
especially useful when executing a stored procedure. The DataGrid control is the most functional control
Command object enables you to specify the parameters for available in ASP.NET for dealing with data. You have
the stored procedure. When you have a connection, you many formatting options for the DataGrid control,
can then use a control called a Data Adapter to retrieve including paging and support for editable columns.
the data. You can use the DataSet object as the target for
this data.
Connection
PROPERTY DESCRIPTION
Connections are the starting point to data access. You
ConnectionString (read/write) String used to
need to give connection parameters to establish a open a SQL Server database.
connection. After those parameters are set (typically
Database (read) Name of the current (or
through the ConnectionString property), you will soon to be) connected
invoke the Open method to create an active connection. database.
The following table provides Key Properties and DataSource (read) Name of SQL Server
Methods of the SQLConnection class, which is the class instance with which to connect.
for connections with Microsoft SQL Server databases.
126
073617-6 Ch06.F 9/26/01 9:42 AM Page 127
Command
PROPERTY DESCRIPTION
The Command object in
ADO.NET is very similar CommandText (read/write) The T-SQL statement or stored procedure to
execute at the data source.
to its cousin ADO.
Commands are important CommandType (read/write) A value indicating how the CommandText property
is to be interpreted.
for stored procedures and
you still want to use Connection (read/write) The SqlConnection used by this instance of the
SqlCommand.
stored procedures in your
data access routines (for Parameters (read) The SqlParameterCollection.
both security and
performance reasons).
The following table METHOD DESCRIPTION
provides Key Properties Cancel Cancels the execution of a SqlCommand.
and Methods of the
CreateParameter Creates a new instance of a SqlParameter object.
SQLCommand class, which
is the class for commands ExecuteNonQuery Executes a T-SQL statement against the Connection and
returns the number of rows affected.
with Microsoft SQL Server
databases.
DataAdapter
PROPERTY DESCRIPTION
A DataAdapter object
bridges the source data AcceptChangesDuringFill (read/write) A value indicating whether AcceptChanges
is called on a DataRow after it is added to the DataTable.
and the DataSet so that
retrievals and updates TableMappings (read) A collection that provides the master mapping
between a source table and a DataTable.
can occur. The following
table provides Key
Properties and Methods METHOD DESCRIPTION
of the DataAdapter class. Fill Adds or refreshes rows in the DataSet to match those in
the data source using the DataSet name, and creates a
DataTable named Table.
GetFillParameters Retrieves the parameters set by the user when executing a
SQL SELECT statement.
Update Calls the respective INSERT, UPDATE, or DELETE
statements for respective action in the specified DataSet
from a DataTable named Table.
127
073617-6 Ch06.F 9/26/01 9:42 AM Page 128
ASP.NET
⁄ Open ‹ Add a message to the user. Á Add the header ° Add the footer
GenericTemplate.aspx template tags and begin a template tags and end the
from the Code Templates › Add a Server Form to the new table with a heading. table.
directory. page.
‡ Add the item template
¤ Add a heading for the ˇ Declare a Repeater tags and output the data
page. control on the page and give items from the Repeater
it an ID. control.
128
073617-6 Ch06.F 9/26/01 9:42 AM Page 129
· Add the Page_Load — Add some travel goals to ™ Save the file and request it ■ A properly formatted table
function to the page. the array list. from the Web server. appears with the data from
the array list.
‚ Create an array list. ± Set the data source for the
Repeater control to the
array list.
¡ Bind the Repeater
control to the array list data.
129
073617-6 Ch06.F 9/26/01 9:42 AM Page 130
ASP.NET
⁄ Open the › Declare a DataList Á Import the System.Data · Create a data row
GenericTemplate.aspx control on the page and give namespace. variable.
from the Code Templates it an ID.
directory. ‡ Add the Page_Load ‚ Add a column to the data
ˇ Add an item template function. table.
¤ Add a heading and a to the page and output the
message to the user. goal items. ° Create a data table — For each row, add a row
variable. and set the value for the Goal
‹ Add a Server Form to the column.
page.
130
073617-6 Ch06.F 9/26/01 9:42 AM Page 131
± Create a DataView from ™ Bind the data list to the £ Save the file and request it ■ A properly formatted table
the table that was created. data source. from the Web server. appears with the data from
the data table.
¡ Set the data source for the
data list.
131
073617-6 Ch06.F 9/26/01 9:42 AM Page 132
ASP.NET
⁄ Open the ‹ Add a message to the user. ˇ Import the System.Data Á Add the Page_Load
GenericTemplate.aspx and System.Data. function.
from the Code Templates › Add the control to the SqlClient namespaces.
directory. page. ‡ Create a
SQLConnection object
¤ Add a heading for the and use a connection string
page. to connect to the database.
132
073617-6 Ch06.F 9/26/01 9:42 AM Page 133
° Create a ‚ Add the ¡ Save the file and request ■ A message appears.
SQLDataAdapter and set SQLDataAdapter to the file from the Web server.
the SQL statement to retrieve populate the DataSet.
business type books using the
SQLConnection object. — Set the DataGrid Data
Source property to the
· Create a new DataSet DataSet.
object.
± Bind the DataGrid to the
DataSet. 133
073617-6 Ch06.F 9/26/01 9:42 AM Page 134
ASP.NET
‚ Use the insert command ± Populate the DataSet ™ Save the file and request it ■ A new record appears in
string and the connection object. from the Web server. the titles table.
object to create a
SQLCommand object. ¡ Set the DataSource and
DataBind properties of the
— Open, execute, and then DataGrid on the page.
close the connection to the
database with the
SQLCommand object.
135
073617-6 Ch06.F 9/26/01 9:42 AM Page 136
ASP.NET
‚ Use the insert command ± Populate the DataSet ™ Save the file and request it ■ A record is updated from
string and the connection object. from the Web server. the titles table. The price is
object to create a now $35, as opposed to $25.
SQLCommand object. ¡ Set the DataSource and
DataBind properties of the
— Open, execute, and then DataGrid on the page.
close the connection to the
database with the
SQLCommand object.
137
073617-6 Ch06.F 9/26/01 9:42 AM Page 138
ASP.NET
TYPE THIS:
String deleteCmd = "DELETE FROM titles WHERE title_id = @Id";
SqlCommand sqlcommandTitles = new SqlCommand(deleteCmd, sqlconnectionPubs);
sqlcommandTitles.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar, 6));
sqlcommandTitles.Parameters["@Id"].Value = inputTitleId.Text;
RESULT:
This produces a page that asks for a title ID. When a valid ID is provided, you
get an updated DataGrid control that shows a list of books that are in the
pubs database (minus the record for the title that you deleted).
‚ Use the delete command ± Populate the DataSet ™ Save the file and request it ■ The record disappears
string and the connection object. from the Web server. from the titles table.
object to create a
SQLCommand object. ¡ Set the DataSource and
DataBind properties of the
— Open, execute, and then DataGrid on the page.
close the connection to the
database with the
SQLCommand object.
139
073617-6 Ch06.F 9/26/01 9:42 AM Page 140
ASP.NET
TYPE THIS:
<ASP:DATAGRID ID="datagridTitles" RUNAT="Server" ALLOWSORTING="True" OnSortCommand="datagridTitles_Sort"/>
protected void datagridTitles_Sort
(Object sender, DataGridSortCommandEventArgs e) {
BindGrid(e.SortExpression);
}
public void BindGrid(String sortfield) {
SqlDataAdapter sqldataadapterTitles = new SqlDataAdapter("select title, notes, price"+
"from titles where type='business'", sqlconnectionPubs);
DataSet datasetTitles = new DataSet();
sqldataadapterTitles.Fill(datasetTitles, "titles");
DataView Source = datasetTitles.Tables["titles"].DefaultView;
Source.Sort = sortfield;
datagridTitles.DataSource=Source;
datagridTitles.DataBind();
}
RESULT:
This produces a DataGrid control that sorts the table by the column that is clicked.
— Create a DataView based ¡ Set the DataSource and ™ Save the file and request it ■ The table is sorted based
on the DataSet that was DataBind properties of the from the Web server. on the Title column.
filled. DataGrid on the page.
± Sort the DataView on the
title column with the Sort
command.
141
073617-6 Ch06.F 9/26/01 9:42 AM Page 142
ASP.NET
⁄ Open the ‹ Add a message to the user. Á Create the Page_Load ° Create a
GenericTemplate.aspx event. SQLDataAdapter and set
from the Code Templates › Add a DataGrid control stored procedure using the
directory. to the page and set its ‡ Create a SQLConnection object.
properties. SQLConnection object and
¤ Add a heading for the use a connection string to · Set the command type for
page. ˇ Import the System.Data connect to the database. the SQLAdapter.
and System.Data.
SqlClient namespaces. ‚ Add a parameter to the
142 Command object.
073617-6 Ch06.F 9/26/01 9:42 AM Page 143
TYPE THIS:
<FORM RUNAT="Server">
<ASP:DATAGRID ID="datagridTitles" RUNAT="Server" SHOWHEADER="False" VISIBLE="False"/>
<P/>
Enter the royalty percentage
<P/>
<ASP:TEXTBOX ID="inputPercentage" TEXTMODE="SingleLine" TEXT="" WIDTH="200px" RUNAT="Server"/><BR/>
<ASP:BUTTON OnClick="SubmitBtn_Click" TEXT="Submit" RUNAT="Server"/>
</FORM>
sqldataadapterTitles.SelectCommand.Parameters["@Percentage"].Value =
inputPercentage.Text;
RESULT:
This produces a page that asks for a royalty percentage. When the percentage is submitted, a
DataGrid control that contains a list of author IDs that meet the stored procedures criteria results.
— Set the value for the ¡ Populate the DataSet £ Save the file and request it ■ The authors with a royalty
command. object. from the Web server. percentage of 50% appear.
± Create a DataSet object. ™ Set the DataSource and
DataBind properties of the
DataGrid on the page.
143
073617-6 Ch06.F 9/26/01 9:42 AM Page 144
ASP.NET
⁄ Open ¤ Add the SQL statement to ‹ Add the DataGrid to the ˇ Specify the title_id
DataGridTemplate.aspx retrieve a couple of columns page and set properties. column as an
from the Code Templates from the titles table. <ASP:HYPERLINKCOLUMN>
directory. › Configure a special and set the other properties
column with the of the column.
<COLUMNS> tag.
Á Save the file as the
master file.
144
073617-6 Ch06.F 9/26/01 9:42 AM Page 145
Example: <asp:EditCommandColumn
<asp:ButtonColumn ButtonType="LinkButton|PushButton"
ButtonType="LinkButton|PushButton" CancelText="CancelButtonCaption"
Command="BubbleText" EditText="EditButtonCaption"
DataTextField="DataSourceField" FooterText="FooterText"
DataTextFormatString="FormatString" HeaderImageUrl="url"
FooterText="FooterText" HeaderText="HeaderText"
HeaderImageUrl="url" ReadOnly="True|False"
HeaderText="HeaderText" SortField="DataSourceFieldToSortBy"
ReadOnly="True|False" UpdateText="UpdateButtonCaption"
SortField="DataSourceFieldToSortBy" Visible="True|False"
Text="ButtonCaption" />
Visible="True|False"
/>
‡ Open ° Add the SQL statement ‚ Request the master file — Click the Details button.
DataGridTemplate.aspx to retrieve the data based on from the Web server.
from the Code Templates what was passed through ■ The full details about the
directory. the URL. title are displayed.
145
073617-6 Ch06.F 9/26/01 9:42 AM Page 146
ASP.NET
If you change the index on the DataSet, you get XML is a key enabling technology for the .NET
the list of all of the goals as opposed to the goal Platform. To create XML for your applications, you
categories. can select data out of Microsoft SQL Server 2000 as
XML. Microsoft SQL Server 2000 has made
Example: enhancements to the OLE DB provider (SQLOLEDB)
DataView Source = new to allow XML documents to be set as command text
DataView(datasetGoals.Tables[1]);
and to return result sets as a stream.
ADO.NET provides disconnected data access by
leveraging the simplicity and power of XML. The
architecture of ADO.NET is very tightly bound to
the .NET XML framework. ADO.NET and the .NET
XML framework converge in the DataSet
object. The native serialization format of the
DataSet in XML is a perfect choice for moving
data between tiers (including remote locations,
like the client’s browser).
± Create a new DataView ¡ Set the DataSource for £ Save the file and request it ■ The goal category names
and initialize it with the the DataGrid. from the Web server. and IDs appear.
values read into the dataset.
™ Bind the DataGrid.
147
073617-6 Ch06.F 9/26/01 9:42 AM Page 148
ASP.NET
⁄ Open and review the XML ¤ Open and review the style
document that you want to sheet that is going to be used
transform. for the transformation.
148
073617-6 Ch06.F 9/26/01 9:42 AM Page 149
‹ Open ˇ Add an <ASP:XML> tag Á Save the file and request ■ The XML document is
GenericTemplate.aspx and set its document source the file from the Web server. transformed and output as
from the Code Templates equal to the filename of the HTML to the Web browser.
directory. style sheet and the transform
source equal to the XML
› Add a server form to the document.
page.
149
083617-6 Ch07.F 9/26/01 9:43 AM Page 150
ASP.NET
Web Services are units of application logic that provide accesses a business façade implemented as a managed
data and services to other applications. Web Services are class using any compliant .NET language. The .NET
the next generation for programming Internet-based Framework SDK also provides tools to generate proxy
applications. Web Services combine the best aspects of classes that client applications can use to access Web
component-based development and the Web. Services.
Applications can access Web Services through standard
protocols and data formats like HTTP, XML, and SOAP. A Web Service interface is defined strictly in terms of
the messages the Web Service accepts and generates. In
ASP.NET Web Services provide the simplest way to ASP.NET, Web Services are implemented with Web
implement Web Services. ASP.NET Web Services Methods that have input parameters and a return value.
automatically generate Web Services Description Consumers of ASP.NET Web Services can be
Language, WSDL, and Web Services Discovery, Disco, implemented on any platform in any programming
files for your Web Services. You can use ASP.NET Web language, as long as they can create and consume the
Services to implement a Web Service listener that messages defined for the Web Service interface.
Web Services enable you to expose business logic and is a presentation layer that can connect to business
data over the internet. The protocols for accessing Web services that obtain data from a SQL data store. The
Services are open standards which make them available other way is by accessing Web Services through a Web
for consumption or production by any platform. Service Client that has the potential to access one to
many Web Services on one to many Web servers. This
One of the large benefits of Web Services is the ability provides new capabilities in distributed computing.
to pull data or apply business logic from many disparate
systems and roll them into one application. For Another benefit to Web Services is security. Exposing
example, you can have a Web Service Client that Web Services over HTTP, where the communication
accesses data from several servers’ Web Services. This is port can be explicitly set, allows for better control over
advantageous for rolling up several data sources in your security. The security issues are easier to control than
organization or for combining Web Services from Distributed Component Object Model (DCOM) access,
different companies to create an application that which is over the range of ports that are allocated for
leverages the “best in breed” in services that are Remote Procedure Calls (RPC). Also, for HTTP access
provided on the Web. over a single port, there are many well-established
products that can provide control over port access and
As seen in the diagram, a user’s browser can access a HTTP commands in packets.
Web server’s data in one of two ways. One way is the
traditional way via an Active Server Page (ASPX) which
150
083617-6 Ch07.F 9/26/01 9:43 AM Page 151
Web
Browser
Web Server
Web
Internet Service
Client
Web Server
ASPX Listener
Data
ASP.NET Web Services support service requests using Although SOAP is the preferred way to access Web
SOAP over HTTP, as well as HTTP GET or POST. Services, you can also easily access a Service with an
HTTP GET or POST. With the HTTP GET, you call a Web
The use of XML is central to the architecture of the .NET Service with parameters by providing a URL with a
Platform, and Web Services is no exception. The most query string that holds the parameters. For example,
feature-rich access is through Simple Object Access you can call the Web Service with the following URL,
Protocol (SOAP). SOAP is a lightweight XML protocol that http://server/ WebService.asmx/
defines the two way communication that occurs between WebMethod?name=value. Where server is the
Web Service Clients and Servers. For Microsoft-based Web server path to the where the Web Service is
Web Services, the SOAP specification defines a set of located, WebService.asmx is the Web Services
rules for how to use XML to represent data, define file, WebMethod is the desired Web Method on the
message envelops — requests and responses — bindings Web Service, and ?name=value is the parameter for
to the HTTP protocol, and RPC over HTTP. the Web Method.
151
083617-6 Ch07.F 9/26/01 9:43 AM Page 152
ASP.NET
⁄ Open a new document in ‹ Set the Language in the ˇ Create an alias for the Á Create an alias for the
your text editor. directive. System namespace. System.Web.Service
namespace.
¤ Add a WebService › Give the WebService
directive to the page. class a name.
152
083617-6 Ch07.F 9/26/01 9:43 AM Page 153
‡ Create the ° Create a WebMethod by ‚ Set the return value for the
SimpleWebService class placing the attribute before function.
as a WebService. the method declaration.
— Save the file to the Web
· Add a public method server with an .asmx
that returns a string variable. extension.
153
083617-6 Ch07.F 9/26/01 9:43 AM Page 154
ASP.NET
⁄ Open a Web browser and ■ The WebMethod appears ‹ Scroll down the page to
navigate to the Web Service as a hyperlink. view samples of a SOAP,
file. HTTP Get, and HTTP Post
¤ Click the hyperlink. request and response for the
■ The Web Service class Web Service.
appears.
154
083617-6 Ch07.F 9/26/01 9:43 AM Page 155
TYPE THIS:
<HTML>
<HEAD>
</HEAD>
<BODY>
<FONT FACE ="Verdana">
<FORM ACTION='http://localhost/visualaspdotnet/Chapter07/Code/SimpleWebService.asmx/SayWelcomeStatement'>
<INPUT TYPE="Submit" VALUE="Test">
</FORM>
</FONT>
</BODY>
</HTML>
RESULT:
A test page that is very similar to the automatically generated test page for a Web Service.
155
083617-6 Ch07.F 9/26/01 9:43 AM Page 156
ASP.NET
USING A PARAMETER
WITH A WEB SERVICE
or most of your Web Services, you will want to in the function declaration for the Web Method, you
⁄ Open the WebServices ¤ Rename the class to ‹ Create a WebMethod with › Use the parameter the
Template.aspx template ParameterWebService. a parameter in the function caller passes to the
from the Code Templates signature. WebMethod for formatting
directory. the welcome statement.
156
083617-6 Ch07.F 9/26/01 9:43 AM Page 157
ˇ Save the file and request it ‡ Fill in your name for the ■ The parameterized
from the Web server. parameter. welcome message appears.
Á Click the WebMethod ° Click the Invoke button.
to test.
157
083617-6 Ch07.F 9/26/01 9:43 AM Page 158
ASP.NET
RETURN AN ARRAY
FROM A WEB SERVICE
ou can return more complex data types from ArrayOfDataType element, and each member in
⁄ Open the WebServices ¤ Rename the class to ‹ Create a WebMethod that › Create a string array
Template.asmx template ArrayWebService. returns a string array. variable for holding the goals.
from the Code Templates
directory.
158
083617-6 Ch07.F 9/26/01 9:43 AM Page 159
if (intNumberOfGoals == 3)
stringarrayGoals[2] = "Keep in contact with old friends";
return stringarrayGoals;
}
}
ˇ Read the goals into the Á Return the string array. ‡ Save the file and test the Note: The ArrayOfString element is
array. Web Service. used.
Note: The array is zero based. ■ The Web Service returns Note: Nested string elements are used
an array. for the string array.
159
083617-6 Ch07.F 9/26/01 9:43 AM Page 160
ASP.NET
RETURN AN ENUMERATED
TYPE FROM A WEB SERVICE
eturning enumerations from a Web Service is To create an enumeration, you can set constant values
⁄ Open the WebServices ¤ Rename the class to ‹ Create a public › Create three enumerated
Template.aspx template EnumeratedTypeWebService. enumeration for the types.
from the Code Templates GoalType.
directory.
160
083617-6 Ch07.F 9/26/01 9:43 AM Page 161
ˇ Add a WebMethod that Á Return the value for a ‡ Save the file and test the ■ The GoalType element
returns the GoalType specific enumeration. Web Service. and value appear.
enumeration.
161
083617-6 Ch07.F 9/26/01 9:43 AM Page 162
ASP.NET
RETURN AN OBJECT
FROM A WEB SERVICE
eturning objects from a Web Service enables repeated for other required members of the class.
⁄ Open the WebServices ¤ Rename the class to ‹ Create a public class for › Create GoalId, Type,
Template.aspx template ObjectWebService. goals. and Name properties for a
from the Code Templates goal.
directory.
162
083617-6 Ch07.F 9/26/01 9:43 AM Page 163
ˇ Add a WebMethod that ‡ Set the GoalId, Type, · Save the file and test the ■ The Goal object returns
returns the Goal class. and Name properties. Web Service. from the Web Service.
Á Create a new Goal ° Return the object.
variable.
163
083617-6 Ch07.F 9/26/01 9:43 AM Page 164
ASP.NET
164
083617-6 Ch07.F 9/26/01 9:43 AM Page 165
ˇ Create a new ‡ Return the XmlDocument ° Save the file and test the ■ The XmlDocument
XmlDocument variable. variable. Web Service. returns from the Web Service.
Á Load an XML string into
the XmlDocument.
165
083617-6 Ch07.F 9/26/01 9:43 AM Page 166
ASP.NET
⁄ Open the WebServices ‹ Add an alias for the › Add a WebMethod that ˇ Create a new
Template.asmx template System.Data and returns the DataSet class. SqlConnection object to
from the Code Templates System.Data.SqlClient connect to the database and
directory. namespaces. initialize the connection with
the connection string to
¤ Rename the class to connect to the Pubs database.
SQLDataWebService.
166
083617-6 Ch07.F 9/26/01 9:43 AM Page 167
Á Create a new ‡ Create a DataSet object. ‚ Save the file and test the ■ The SQL data returns from
SqlDataAdapter variable Web Service. the Web Service.
that uses the ° Fill the DataSet object
SqlConnection object and using the SqlDataAdapter ■ Note the SQL data in the
a SQL string for retrieving object. response.
business titles. · Return the DataSet
object.
167
083617-6 Ch07.F 9/26/01 9:43 AM Page 168
ASP.NET
⁄ Open the WebServices ¤ Rename the class to ‹ Add a WebMethod that › Add an if statement to
Template.asmx template SessionWebService. returns a string variable with initialize the Session
from the Code Templates the Session state enabled. variable.
directory.
168
083617-6 Ch07.F 9/26/01 9:43 AM Page 169
if (Session["sessionName"] == null) {
stringPreviousName = "Null";
}
else {
stringPreviousName = Session["sessionName"].ToString();
}
Session["sessionName"] = stringName;
stringCurrentName = stringName;
return "The previous value for the session variable was " +
stringPreviousName + ". The new value for the session variable is "
+ stringCurrentName + ".";
}
}
ˇ Add an else statement to Á Return a formatted ‡ Save the file and test the ° Refresh the Web page.
increment the Session message to the user using the Web Service.
variable by one. Session variable. ■ The number of times the
■ The Web Service returns a service has been accessed is
message about the number of incremented.
times the service has been
accessed. 169
083617-6 Ch07.F 9/26/01 9:43 AM Page 170
ASP.NET
⁄ Open the WebServices ¤ Rename the class to ‹ Add a WebMethod that › Add an if statement to
Template.aspx template ApplicationWebService. returns a string variable with initialize the Application
from the Code Templates the Session state disabled. variable.
directory.
170
083617-6 Ch07.F 9/26/01 9:43 AM Page 171
ˇ Add an else statement Á Return a formatted ‡ Save the file and test the ° Refresh the Web page.
to increment the message to the user using Web Service.
Application variable the Application variable. ■ The number of times the
by one. ■ The Web Service returns a service has been accessed is
message about the number of incremented.
times the service has been
accessed. 171
083617-6 Ch07.F 9/26/01 9:43 AM Page 172
ASP.NET
⁄ Open the command ‹ Run the wsdl command ˇ Open Á Add a form to the page.
prompt. to create a proxy class for the GenericTemplate.aspx
Web Service. from the Code Templates ‡ Add a Label control to
¤ Change directories to directory. the form.
where the Web Service is › Compile the proxy class to
located. the /bin directory.
■ The proxy class is created
172 and compiled.
083617-6 Ch07.F 9/26/01 9:43 AM Page 173
RESULT:
A Web page displays the greeting. If you submit the page with your name,
it will call a different Web Service that customizes greeting with your name in it.
° Add the Page_Load ‚ Set the result of calling the ± Save the file and request it ■ A welcome message from
function to the page. SayWelcomingMessage from the Web server. the Web Service appears.
from the
· Create a new instance of SimpleWebService into a
SimpleWebService. string variable.
— Update the Label control
with the result.
173
083617-6 Ch07.F 9/26/01 9:43 AM Page 174
ASP.NET
⁄ Open a new document in ‹ Create a new class. ˇ Create an integer variable ‡ Set the result of calling the
your text editor. in the Main function. UpdateApplication
› Create the Main function. Counter from the
¤ Import the System Á Create a new instance of ApplicationWebService
namespace. ApplicationWebService. into an integer variable.
° Format and write the
result to the command line.
174
083617-6 Ch07.F 9/26/01 9:43 AM Page 175
string strHitCountMessage =
applicationwebserviceCounter.
UpdateApplicationCounter(intInitialize);
Console.WriteLine(strHitCountMessage);
}
}
}
· Open the command ± Compile the console class ¡ Run the created ■ A message from the Web
prompt. and the Web Service. executable a couple Service appears about the
of times. number of times the Web
‚ Change directories to ■ The proxy class is created Service has been accessed.
where the Web Service is and compiled and the
located. console application is
compiled.
— Run the wsdl command
to create a proxy class for the
Web Service. 175
093617-6 Ch08.F 9/26/01 9:43 AM Page 176
ASP.NET
⁄ Open a new document in ‹ Add an alias to the ˇ Create a public function ‡ Save the file.
your text editor. System namespace. that returns a string variable.
Note: In this example, the file is
¤ Create a new namespace. › Create a public class. Á Return a message to the being saved to the default Web site
caller. location at C:\InetPub\wwwroot.
176
093617-6 Ch08.F 9/26/01 9:43 AM Page 177
Batch files are very useful to take care of repetitive tasks like compiling
a component. For example, the C# components for this chapter all
come with batch files on the CD-ROM that have the csc commands
for compiling the component. Look in the Code directory for this
chapter and find a batch file with the same name as the component
you create in the task (for example, SimpleComponent.bat is
used to create SimpleComponent). Open this file with a text
editor and find the following source: csc /t:library
/out:bin\SimpleComponent.dll SimpleComponent.cs.
You can use these batch files by simply typing in the name of the
component (for example, SimpleComponent) while at the command
prompt. Note: You must navigate to the directory where the batch file
and the component source code are located.
cmd
Run. . .
° Click Start ➪ Run to open · Type cmd in the Open — Change directories to ¡ Use the csc command to
the dialog box. field. where you saved the source compile the class at the
file by using the cd command prompt.
‚ Click OK to open the command.
command prompt. Note: See page 34 for instructions
± Create a /bin directory on compiling.
for your compiled libraries.
CONTINUED
177
093617-6 Ch08.F 9/26/01 9:43 AM Page 178
ASP.NET
™ Open the ¢ Add the Page_Load § Create a new string • Add a server form.
GenericTemplate.aspx function. variable and read the result of
template from the Code SayWelcomeStatement ª Add a label to the server
Templates directory. ∞ Create a new variable of into that string. form.
type SimpleComponent.
£ Import the ¶ Set the label on the
SimpleComponent page equal to what was
namespace. returned from
SayWelcomeStatement.
178
093617-6 Ch08.F 9/26/01 9:43 AM Page 179
You can package up multiple components into To support some of the advanced features of .NET
deployable units called assemblies. Assemblies components, like sharing a component across
are how the .NET Framework manages multiple applications, you will need to create a
components for: deployment, version control, global assembly. Each computer where the common
reuse, activation scoping, and security language runtime is installed has a machine-wide
permissions. When creating an assembly, you code cache called the global assembly cache. You
need to decide on whether you want the should share assemblies by installing them into the
assembly to be private or global. There are pros global assembly cache only when you need to.
and cons to either choice. The main benefit for Typically, for ASP.NET applications you will create
choosing private assemblies is the ease of use, private assemblies and put them into the /bin
especially with deployment. Private assemblies directory of your Web site.
support the xcopy deployment, which is not
available for COM components.
179
093617-6 Ch08.F 9/26/01 9:43 AM Page 180
ASP.NET
⁄ Open a new document in ‹ Add an alias to the ˇ Create a private ‡ Add a public string
your text editor. System and System.Text string variable for holding variable that has a method to
namespace. state. read the value of the
¤ Create a new namespace. private string variable
› Create a public class. Á Initialize the private and a method to write to the
string variable when an private string variable.
instance of the class
is created. ° Add a function that
returns a string.
180
093617-6 Ch08.F 9/26/01 9:43 AM Page 181
181
093617-6 Ch08.F 9/26/01 9:43 AM Page 182
ASP.NET
£ Open the ¢ Import the § Create a new variable of • Create a new string
GenericTemplate.aspx StatefulComponent type StatefulComponent. variable and read the result of
template from the Code namespace. SayWelcomeStatement
Templates directory. ¶ Set the Name property for into that string.
∞ Add the Page_Load the StatefulComponent.
function.
182
093617-6 Ch08.F 9/26/01 9:43 AM Page 183
Example:
using System;
public class Goal
{
private String m_strDescription;
public Goal()
{
m_strDescription = null;
}
public String Name
{
get
{
return m_strDescription;
}
set
{
if (value.Length < 30)
m_strDescription = value;
}
}
}
ª Set the label on the page º Add a server form. ≠ Save the file and request it ■ A welcome message
equal to what was from the Web server. appears that displays the
returned from – Add a label to the server value set for the Name
SayWelcomeStatement. form. property.
183
093617-6 Ch08.F 9/26/01 9:43 AM Page 184
ASP.NET
⁄ Open a new document in › Create a public class. Á Initialize the ° Add a function that
your text editor. private string variable returns a string.
ˇ Create a when an instance of the class
¤ Create a new namespace. private string variable is created. · Add the Get and Set
for holding state. functions for the
‹ Add an alias to the ‡ Add a public string public string, which
System, System.Data, and variable that has a method to work with the
System.Data.SqlClient read the value of its variable private variable.
namespaces. and a method to write to the
private string variable.
184
093617-6 Ch08.F 9/26/01 9:43 AM Page 185
Example:
namespace DataLayer_ex {
using System;
using System.Data;
using System.Data.SqlClient;
public class DataObject {
private string _stringConnection;
public DataObject(String connStr){
_stringConnection = connStr;
}
public DataView GetTitlesForType(string stringTitleType) {
SqlConnection sqlconnectionPubs = new SqlConnection(_stringConnection);
SqlDataAdapter sqldataadapterTitles = new SqlDataAdapter
("select title, notes, price from" " titles where type='"
+ stringTitleType + "'", sqlconnectionPubs);
DataSet datasetTitles = new DataSet();
sqldataadapterTitles.Fill(datasetTitles, "Titles");
return datasetTitles.Tables["Titles"].DefaultView;
}
}
}
ASP.NET
∞ Open the § Import the DataLayer • Add a DataList to the ª Add an ItemTemplate
GenericTemplate.aspx namespace. page to display the results. to the page to describe the
template from the Code output for each item in the
Templates directory. ¶ Add a server form to the result set.
page.
186
093617-6 Ch08.F 9/26/01 9:43 AM Page 187
TYPE THIS:
public void Page_Load(Object sender, EventArgs E) {
if (!IsPostBack) {
DataObject dataobjectPubs = new DataObject("server=(local)
\\NetSDK;uid=QSUser;pwd=QSPassword;database=pubs");
datalistTitles.DataSource = dataobjectPubs.GetTitlesForType("business");
datalistTitles.DataBind();
labelTitleType.Text = "business"; } }
public void Submit_Click(Object sender, EventArgs E) {
DataObject dataobjectPubs = new DataObject("server=(local)\\NetSDK;
uid=QSUser;pwd=QSPassword;database=pubs");
datalistTitles.DataSource = dataobjectPubs.GetTitlesForType
(dropdownlistTitleTypes.SelectedItem.Value.ToString());
datalistTitles.DataBind();
labelTitleType.Text = dropdownlistTitleTypes.SelectedItem.Text.
ToString().ToLower();
}
RESULT:
º Add the Page_Load ≠ Set the DataSource of “ Save the file and request it ■ The title, notes, and price
function to the page. the DataList on the Web from the Web server. appear for the business titles
page to the function in the from the pubs database using
– Create a new instance of data access Layer that returns the data layer.
the DataObject class and the business titles.
set the connection string.
‘ Bind the DataList.
187
093617-6 Ch08.F 9/26/01 9:43 AM Page 188
ASP.NET
⁄ Open a new document in ‹ Add an alias to the ˇ Create a private Á Add the code to initialize
your text editor. System, System.Data, DataObject class from the the BusinessObject
System.Data.SqlClient, DataLayer namespace. connection string.
¤ Create a new namespace. and the DataLayer
namespaces.
› Create a public class.
188
093617-6 Ch08.F 9/26/01 9:43 AM Page 189
‡ Add the function that calls ° Go to the command · Compile the component
GetBusinessTitles from prompt. using the csc command.
the Data Layer.
CONTINUED
189
093617-6 Ch08.F 9/26/01 9:43 AM Page 190
ASP.NET
‚ Open the ± Add a server form to the ¡ Add a DataList to the ™ Add an ItemTemplate
GenericTemplate.aspx page. page to display the results. to the page to describe the
template from the Code output for each item in the
Templates directory. result set.
— Import the
BusinessLayer namespace.
190
093617-6 Ch08.F 9/26/01 9:43 AM Page 191
£ Add the Page_Load ∞ Set the DataSource of ¶ Save the file and request it ■ The title, notes, and price
function to the page. the DataList on the Web from the Web server. appear for the business titles
page to the function in the from the pubs database using
¢ Create a new instance of Data Access Layer that the business and data layers.
the DataObject class and returns the business titles.
set the connection string.
§ Bind the DataList.
191
093617-6 Ch08.F 9/26/01 9:43 AM Page 192
ASP.NET
⁄ Open your text editor. ‹ Create a public class of ˇ Open the ‡ Cut the Page_Load event
type Page. ThreeTierWebForm.aspx handler from the file.
¤ Create an alias to the template from the Code
BusinessLayer, System, › Create a public variable Templates directory. ° Save the file as the class
System.Web.UI, and of type DataList. name to the Default Web site.
System.Web.UI.Web Á Add a Page directive at
Controls. the top of the page and an
Inherits attribute with a
value of the class name and a
192 Src attribute with the value
of the filename.
093617-6 Ch08.F 9/26/01 9:43 AM Page 193
· Paste the Page_Load ‚ Save the file and request it ■ The title, notes, and price
event handler into the from the Web server. appear for the business titles
CodeBehind page. from the pubs database using
the business and data layers
in a Code-behind.
193
103617-6 Ch09.F 9/26/01 9:44 AM Page 194
ASP.NET
⁄ Open the ‹ Add a message to ˇ Place a drop-down list box Á Add a button control to
GenericTemplate.aspx the user. on the page with suggestions the page.
template from the Code for choosing the suggested
Templates directory. › Add a form to the page. number of goals. ‡ Add a label control to
the page.
¤ Add a heading for
the page.
194
103617-6 Ch09.F 9/26/01 9:44 AM Page 195
° Add the Page_Load ‚ Add the Request.Form — Save the file and request it ¡ Click the Submit button.
function. method to retrieve the value from the Web server.
that was selected in the ■ The suggestion you chose
· Add an if statement to drop-down list box. ± Click and select a appears.
make sure that the code will suggestion.
only run when posting to the
page.
195
103617-6 Ch09.F 9/26/01 9:44 AM Page 196
ASP.NET
⁄ Open the ■ The contents of the page › Open the Á Add a message to the file.
Suggestions.htm template contain a suggestions form. GenericTemplate.aspx
from the Code Templates template from the Code ‡ Add the script delimiters.
‹ Save the file.
directory. Templates directory. ° Call the
¤ Add the ACTION value to ˇ Add a heading to the file. GetRequestParams
the form. function.
196
103617-6 Ch09.F 9/26/01 9:44 AM Page 197
Example:
<SCRIPT LANGUAGE="C#" RUNAT="Server">
public void GetRequestForm() {
int intCounter1;
NameValueCollection namevaluecollectionForm;
namevaluecollectionForm=Request.Form;
String[] stringarrayForm1 = namevaluecollectionForm.AllKeys;
for (intCounter1 = 0; intCounter1 < stringarrayForm1.Length; intCounter1++) {
Response.Write("Form: " + stringarrayForm1[intCounter1] + "<BR/>");
}
}
</SCRIPT>
· Add the GetRequestParams ‚ Save the file and request it ¡ Click the Submit button.
function and code from the file from the Web server.
GetRequestParams.aspx ■ Request data displays
located in the Code Templates — Request the first Web page from looping through the
directory. that you created in this task. Request.Params
collection.
± Click and select a
suggestion.
197
103617-6 Ch09.F 9/26/01 9:44 AM Page 198
ASP.NET
⁄ Open the ‹ Add a message to ˇ Place a drop-down list box Á Add a button control to
GenericTemplate.aspx the user. on the page with suggestions the page.
template from the Code for choosing the suggested
Templates directory. › Add a form to the page. number of goals.
¤ Add a heading for
the page.
198
103617-6 Ch09.F 9/26/01 9:44 AM Page 199
Example:
<% @ PAGE LANGUAGE="C#" %>
<H3>Welcome to mylifetimegoals.com</H3>
What suggestions do you have for improving our site?
<FORM RUNAT="Server" METHOD="GET">
<P/>
<ASP:DROPDOWNLIST ID="dropdownlistSuggestions" RUNAT="Server">
<ASP:LISTITEM>Fewer Goals</ASP:LISTITEM>
<ASP:LISTITEM>More Goals</ASP:LISTITEM>
<ASP:LISTITEM>Same Number of Goals</ASP:LISTITEM>
</ASP:DROPDOWNLIST>
<ASP:BUTTON ID="buttonExample" RUNAT="Server" TEXT="Submit"/><P/>
<% if (IsPostBack) {
Response.Write(Request.QueryString["dropdownlistSuggestions"]);
}
%>
</FORM>
‡ Add a set of script · Add the Request.Form — Save the file and request it ± Click and select a
delimiters after the button. method to retrieve the value from the Web server. suggestion.
that was selected in the drop-
° Add an if statement to down list box. ■ The Web page for ¡ Click the Submit button.
make sure that the code will submitting suggestions
only run when posting to the ‚ Add the appears. ■ The suggestion you chose
page. Response.Write method appears.
to write the value selected in
the drop-down list box.
199
103617-6 Ch09.F 9/26/01 9:44 AM Page 200
ASP.NET
⁄ Open the ■ The contents of the page › Open a new document in Á Add a pair of script
Suggestions.htm contains a suggestions form. your text editor. delimiters.
template from the Code
Templates directory. ‹ Save the file. ˇ Add the page directive, set ‡ Request the data from
the language to C#, and buffer the drop-down list box and
¤ Add the ACTION value to the page. read it into a string
the form. variable.
200
103617-6 Ch09.F 9/26/01 9:44 AM Page 201
° Create a switch — Copy the files ■ The page with suggestions ¡ Click the Submit button.
statement using the FewerGoals.aspx, appears.
string variable. MoreGoals.aspx, ■ You are redirected to a
SameGoals.aspx, and ± Click and select a page according to the option
· Add a case for each of ErrorGoals.aspx from suggestion. you have selected.
the options that redirects the CD-ROM to your working
to the appropriate page. directory.
‚ Save the file and request
from the Web server.
201
103617-6 Ch09.F 9/26/01 9:44 AM Page 202
ASP.NET
⁄ Open a new document in ‹ Add a pair of script › Create a new variable of type ˇ Create a new variable
your text editor. delimiters. HttpBrowserCapabilities of type string and read
and initialize the variable by the Web browser type
¤ Add the page directive, using the Request.Browser property into the string.
set the language for the page property.
to C#, and buffer the page.
202
103617-6 Ch09.F 9/26/01 9:44 AM Page 203
Á Create a case statement ° Save the file. ‚ Request the file from the ■ You are redirected to a
using the string variable. Web server. page according to your Web
· Copy IE.aspx and browser type.
‡ Add a case for each of Other.aspx from the
the options that redirects to CD-ROM to your working
the appropriate page. directory.
203
103617-6 Ch09.F 9/26/01 9:44 AM Page 204
ASP.NET
⁄ Open the Suggestions ‹ In the SubmitBtn_Click ˇ Create a new variable ‡ Set the To property for
Template template from the function, create a string of MailMessage type. the MailMessage.
Code Templates directory. variable for creating your
message. Á Set the From property ° Set the Subject property
¤ Import the for the MailMessage. for the MailMessage.
System.Web.Mail › Set the message contents
namespace. in HTML, using the selected
value from the drop-down
list box.
204
103617-6 Ch09.F 9/26/01 9:44 AM Page 205
Example:
String stringMailPriority =
dropdownlistMailPriority.SelectedItem.Text;
switch(stringMailPriority) {
case "High":
mailmessageSuggestion.Priority = MailPriority.High;
break;
case "Normal":
mailmessageSuggestion.Priority = MailPriority.Normal;
break;
case "Low":
mailmessageSuggestion.Priority = MailPriority.Low;
break;
default:
mailmessageSuggestion.Priority = MailPriority.Normal;
break;
}
· Set the Body property for — Add the SMTPMail’s Send ■ The page with suggestions £ Click the Submit button.
the MailMessage, using the method to send the message. appears.
string variable in which ■ The message appears,
you have placed the message. ± Update the Text property ™ Click and select a notifying you of the e-mail's
for the label on the page to suggestion. status.
‚ Set the BodyFormat reflect that the mail has
property for the been sent.
MailMessage to
MailFormat.Html. ¡ Save the file and request
from the Web server. 205
103617-6 Ch09.F 9/26/01 9:44 AM Page 206
ASP.NET
206
103617-6 Ch09.F 9/26/01 9:44 AM Page 207
If you want to cache the page per user session, You can bypass a cached page each time the user
you can cache based on the users cookie. submits different Form or QueryString data to a
Authentication cookies are used to map a user to page. See ASPPageCache_ex2.aspx on the CD
a session. Open two instances of Internet Explorer for a page that demonstrates this directive.
and note the generated times for each instance
Example:
and note they are not sharing the same cached
<%@ OutputCache Duration="60" VaryByParam="*" %>
page. See ASPPageCache_ex1.aspx on the CD
for a page that demonstrates this directive.
Example:
<%@ OutputCache Duration="60"
VaryByHeader="Cookie" %>
■ You can observe that the ■ You can observe the Á Wait for more than 60 ■ The generated time
generated time is 9:31:40 AM. generated time is the same seconds and refresh the Web updates, indicating that the
as before (9:31:40 AM), page. cached page was not used.
ˇ Press F5 to refresh indicating you are viewing
the page. a cached page.
207
103617-6 Ch09.F 9/26/01 9:44 AM Page 208
ASP.NET
⁄ Open the ‹ Try to read the DataView ˇ Create the new ° Add an else message to
DatagridTemplate.aspx out of the page cache. DataView. indicate that the data cache
template from the Code was used.
Templates directory. › If there was nothing in the Á Cache the DataView.
cache to retrieve, get a new · Update the
¤ Create a new DataView DataView. ‡ Update the label on the DataSource to be
variable. page to show that the dataviewTitles.
DataSet was created
explicitly.
208
103617-6 Ch09.F 9/26/01 9:44 AM Page 209
You can specify how long the data is in the cache. The
following code will expire the data cache after one minute.
Example:
Cache.Insert("cacheTitles", dataviewTitles,
null,DateTime.Now.AddMinutes(1), TimeSpan.Zero );
You can base expiration on the last time the cache was
accessed by using a sliding expiration.
Example:
Cache.Insert("cacheTitles", dataviewTitles,
null,DateTime.MaxValue, TimeSpan.FromMinutes(1) );
25
‚ Save the file and request it — Scroll down to see the ± Press F5 to refresh the ¡ Scroll down to see the
from the Web server. message about the DataSet page. message about the DataSet
being created explicitly. being retrieved from the
■ The business titles from the cache.
pubs database appear.
209
113617-6 Ch10.F 9/26/01 9:44 AM Page 210
ASP.NET
INTRODUCTION TO ASP.NET
APPLICATIONS AND STATE MANAGEMENT
ASP.NET APPLICATIONS
An ASP.NET Application is how you can separate one Within an ASP.NET Application, you can independently
application domain from another. An ASP.NET control security, process isolation, and shared data. The
Application is set up as a Web site or a virtual directory Web sites you build can include multiple Web
that has been configured as an application in Internet applications as part of the Web site, or one main
Information Server (IIS). All resources under the Web application for your entire site.
site or virtual directory are part of the application,
unless the resource is in a subdirectory that has been Having one or more Web applications on your Web site
configured as another application. depends on several factors. Some of the more
important factors that you should be aware of are:
210
113617-6 Ch10.F 9/26/01 9:44 AM Page 211
211
113617-6 Ch10.F 9/26/01 9:44 AM Page 212
ASP.NET
⁄ Start your text editor ¤ Type <SCRIPT LANUAGE="C#" › To create the event handler Note: This code will create an
to create a Global.asax RUNAT="Server"> and press Enter for when the application starts, Application variable.
file. twice. click between the <SCRIPT>
and </SCRIPT> tags, type Note: Indent the code so that
‹ Type </SCRIPT>. void Application_Start() {, and it is easier to read.
press Enter. Á Type } to finish the
ˇ Press Tab to indent, type event handler and press
the code you want to execute Enter.
when the application starts,
212 and press Enter.
113617-6 Ch10.F 9/26/01 9:44 AM Page 213
You can specify the language you want to use in The Global.asax file is configured so that you
the <SCRIPT> tag by setting the language cannot request it as a URL. You should set up
attribute. This could include C# or VB. You will permissions on the file so that unauthorized users
always want to specify the RUNAT attribute to cannot read or update the file, especially if you have
run at the server because that is where the any sensitive configuration information in the file.
Application and Session objects are located.
You do not need to stop the Web server when
Here is what the <SCRIPT> tag would look like
updating the Global.asax file. When you save
when using C# as the language:
changes to the Global.asax file, ASP.NET
<SCRIPT LANGUAGE="C#" RUNAT="Server"> automatically detects that you have changed the
The Global.asax file is an optional file. When file. ASP.NET then restarts the application.
ASP.NET finds no Global.asax file, the
assumption is that there is no need to code for
the application and session events.
Save Ctrl+S
‡ To create the event handler ° Press Tab to indent, type ‚ Click File ➪ Save to open
for when the application ends, the code you want to execute the dialog box.
click between the <SCRIPT> when the application ends,
and </SCRIPT> tags, type and press Enter.
void Application_End() {, and
press Enter. · Type } to finish the event
handler and press Enter.
CONTINUED
213
113617-6 Ch10.F 9/26/01 9:44 AM Page 214
ASP.NET
— Click to select the ■ You can save the file to ™ To create the event handler Note: This code will write a
folder where you want to the C:\Inetpub\wwwroot\ for when the session starts, message when the session starts
store your file. directory with the filename of click between the <SCRIPT> and create a session variable.
Global.asax. and </SCRIPT> tags, type
± Type a name for the Web void Session_Start() {, and ¢ Type } to finish the event
page. ¡ Click Save to save the press Enter. handler and press Enter.
Web page.
£ Press Tab to indent, type
■ The Default Web site now the code you want to execute
has a Global.asax file. when the application starts,
214 and press Enter.
113617-6 Ch10.F 9/26/01 9:44 AM Page 215
void Application_Start() {
</SCRIPT>
∞ To create the event handler § Press Tab to indent, type • Save the file. ■ The message about the
for when the session ends, the code you want to execute session event handler
click between the <SCRIPT> when the application ends, ■ This example is saving the appears.
and </SCRIPT> tags, type and press Enter. Global.asax to the default
void Session_End() {, and
Web site. Note: You can request any
¶ Type } to finish the event ASP.NET Web page in the default
press Enter.
handler and press Enter. ª Request an ASP.NET Web
page from the default Web Web site. In the example, the
site. Comments.aspx ASP.NET Web
page is requested.
215
113617-6 Ch10.F 9/26/01 9:44 AM Page 216
ASP.NET
Open... Ctrl+O
⁄ Start the text editor to edit › Click Open to open the ˇ Type the ASP.NET script Á Position the insertion
the Global.asax file. template. delimiters (<% %>) and press point after the first ASP.NET
Enter. script delimiter (<%) and
¤ Click File ➪ Open. Note: You can open another type a space followed by
Global.asax file that you want
‹ Click to select the Code @ Import Namespace="".
Templates directory and open to use as an import directive.
the UsingImportDirective
GlobalTemplate.asax file.
216
113617-6 Ch10.F 9/26/01 9:44 AM Page 217
The Assembly directive lets you link Another directive you can use in your
components to namespaces that have been Global.asax file is the Application directive.
imported with the Import directive. The Inherits attribute defines the new
application base class. This will need to be a
Example:
compiled .NET class on your server. You can also
<%@ Assembly Name="MyAssembly.dll" %> specify a friendly name for the application with the
Description attribute.
Example
<%@ Application Inherits=" MySampleApp.Object"
Description=
"Sample Description"%>
Save As...
‡ Position the insertion point ° Click File ➪ Save As to — Click Save to save the
between the quotation marks open the dialog box. Web page.
(" ") and type the namespace
you want to import. · Click to select the Note: Click the Yes button if you
folder where you want to are prompted about replacing the
store your file. file.
‚ Type a name for the Web ■ The namespace is now
page. declared for all pages on
the site.
217
113617-6 Ch10.F 9/26/01 9:44 AM Page 218
ASP.NET
Open... Ctrl+O
⁄ Start the text editor to edit › Click Open to open ˇ Click where you want to Note: The scope of an object can
the Global.asax file. the template. declare a server-side object be Session, Application, or
and type <OBJECT AppInstance.
¤ Click File ➪ Open. Note: You can open another RUNAT="Server".
‹ Click to select the Code Global.asax file that you want to ‡ Type ID= and the name
use as a server-side object. Note: Objects must be declared you want to reference the
Templates directory and open
outside the <SCRIPT> tags. object by within your ASP
the DeclareServer
pages.
SideObjectGlobal Á Type SCOPE= and the
Template.asax file. scope of the object.
218
113617-6 Ch10.F 9/26/01 9:44 AM Page 219
Save As...
° Type CLASS= "">. ‚ Click where you want to — Click File ➪ Save As to ™ Click Save to save the
close the <OBJECT> tag and open the dialog box. Web page.
· Between the quotation type </OBJECT>.
marks (""), type the kind of ± Click to select the Note: Click the Yes button if you are
object you want to declare. folder where you want to prompted about replacing the file.
store your file.
Note: A System.Collections.ArrayList
¡ Type a name for the variable with a name of Items will be
Web page. available for each session created for
the default Web site.
219
113617-6 Ch10.F 9/26/01 9:44 AM Page 220
ASP.NET
Y
Application_EventName (Object sender,
in ASP.NET Applications for writing application- EventArgs e). The sender tells you who raised this
specific code. You also have the capability to event and the EventArgs gives you further context
create you own custom application level events. about why the event was raised. The sender and
Typically, you will use the built-in events. You can use EventArgs are not required parameters of the event
any of these built-in events by implementing the handler, but it is good practice to include these
event handlers for these events in the Global.asax parameters.
file. This is done in the Global.asax file with the
following naming convention Some applications’ events are raised for each request
Application_EventName(appropriateevent to the application, and others just occur under special
argumentsignature). conditions. For example, you can also use the
BeginRequest and EndRequest events for code
Usually, you will add parameters to get more that you want to execute each time a user makes a
contextual information on the event. This is a typical request. Place this in the Global.asax file between
event handler signature that includes parameters — the <SCRIPT> tags.
Open... Ctrl+O
⁄ Start the text editor to edit › Click Open to open ˇ To create the event ‡ To create the event
the Global.asax file. the template. handler for request, click handler to end the request,
between the <SCRIPT> and click between the <SCRIPT>
¤ Click File ➪ Open. Note: You can open another </SCRIPT> tags, type void and </SCRIPT> tags, type
Global.asax file if you want.
‹ Navigate to the Code Application_BeginRequest() { , void Application_EndRequest()
Templates directory and and press Enter. { , and press Enter.
open the DeclareServer Á Type } to finish the event ° Press Tab to indent, type }
SideObjectGlobal handler and press Enter. to finish the event handler,
Template.asax file. and press Enter.
220
113617-6 Ch10.F 9/26/01 9:44 AM Page 221
ASP.NET uses a pool of HttpApplication You can write code in the Global.asax file to
instances to service requests made by your override the creation and destruction methods for
application. These managed instances handle the HttpApplication instance, the Init, and
their requests for the lifetime of the request. the Dispose methods. The Init method executes
With ASP.NET, you can write code that will run for each HttpApplication instance that is
when HttpApplication instances are created created, whereas the Dispose method executes
and destroyed. when the HttpApplication instance is destroyed.
Example:
<%
public void Init(){
"Init override code goes here
}
public void Dispose()
" Dispose override code goes here
}
%>
Save As...
· Click File ➪ Save As to — Type a name for the Web ¡ Request an ASP.NET Web Note: In this example, the
open the dialog box. page. page from your site to initiate Comments.aspx file was requested.
the creation of a new
‚ Click to select the ± Click Save to save the application. Note: The Web browser is in
folder where you want to Web page. full-screen mode in this screenshot
store your file. ■ The BeginRequest and so you can see all of the event
Note: Click the Yes button if you are EndRequest methods are
prompted about replacing the file. messages.
called on the page.
221
113617-6 Ch10.F 9/26/01 9:44 AM Page 222
ASP.NET
⁄ Open CreateApplication ¤ Between the quotation › Save the page as ■ The Application
Template.aspx from the Code marks (""), type the name CreateApplication.aspx variable is set, and a
Templates directory, click where of the Application to the Default Web site and message appears.
you want to create application variable you want to display the ASP.NET page in
information, and type create. a Web browser. Note: After the page is executed,
Application[""]=. you can access the information
‹ After the equal sign stored in the Application variable.
(=), type a value for the
Application variable
in quotes.
222
113617-6 Ch10.F 9/26/01 9:44 AM Page 223
Example:
<%
Application.Lock
Application["applicationSiteName"] = "My Sample Site";
Application.UnLock
%>
ˇ Open ReadApplication ‡ Use the ToString() ° Save the page as ■ The Application
Template.aspx from the Code function to convert the ReadApplication.aspx variable’s value appears.
Templates directory, click where variable to a string and and display the ASP.NET page
you want to access application place a Response.Write (); in a Web browser.
information, and type around code that accesses
Application[""]. the Application
variable.
Á Between the quotation CONTINUED
marks (""), type the name of
the Application variable
you want to read. 223
113617-6 Ch10.F 9/26/01 9:44 AM Page 224
ASP.NET
· Open UpdateApplication — Between the quotation ± Save the page as ■ The Web browser displays
Template.aspx from the Code marks (""), type the UpdateApplication.aspx the result of updating the
Templates directory. updated value. to the default Web site and application information.
display the ASP.NET page
‚ Click where you want to in a Web browser.
update the Application
variable and type Application
["applicationSiteMotto"] = "";.
224
113617-6 Ch10.F 9/26/01 9:44 AM Page 225
¡ Open DeleteApplication £ Between the quotation ¢ Save the page as ■ The Web browser displays
Template.aspx from the Code marks (""), type the name DeleteApplication.aspx the result of deleting the
Templates directory. of the variable you want to the default Web site and application information.
to delete. display the ASP.NET page
™ Click where you want to in a Web browser.
delete the Application
variable and type Application.
Contents.Remove("");.
225
113617-6 Ch10.F 9/26/01 9:44 AM Page 226
ASP.NET
⁄ Open CreateSession ‹ After the equal sign (=), › Save the page as Note: After this page has been
Template.aspx from the type a value for the session CreateSession.aspx executed, you can access the
Code Templates directory variable in quotes. to the Default Web site and information stored in the session
and type Session[""] = . display the ASP.NET page variable.
in a Web browser.
¤ Between the quotation
marks (""), type the session
variable you want to create.
226
113617-6 Ch10.F 9/26/01 9:44 AM Page 227
The Session object has many properties that you can configure. One of the important
properties is the Session.Timeout. This value determines the amount of time that a
user can go idle on your site without having to obtain a new session. You can set this
property and read from this property.
TYPE THIS:
<%
Session.Timeout = 5;
Response.Write("The Session Timeout is currently " + Session.Timeout +
" minutes.");
%>
RESULT:
ˇ Open ReadSession ‡ For the value to appear ° Save the page as ■ The Web browser displays
Template.aspx from the as output on the Web page, ReadSession.aspx to the the result of reading the
Code Templates directory use the ToString() function to Default Web site and display application information.
and click where you want to convert the variable to a string the ASP.NET page in a Web
access application information and place a Response.Write (); browser.
and type Session[""]. around code that accesses the
Application variable. CONTINUED
Á Between the quotation
marks (""), type the session
variable you want to read. 227
113617-6 Ch10.F 9/26/01 9:44 AM Page 228
ASP.NET
· Open UpdateSession — Between the quotation ± Save the page as ■ The Web browser displays
Template.aspx from the marks (""), type the updated UpdateSession.aspx the result of updating the
Code Templates directory. value. to the Default Web site and session information.
display the ASP.NET page
‚ Click where you want to in a Web browser.
update the session variable
and type Session["sessionUser
FavoriteColor"] = "";.
228
113617-6 Ch10.F 9/26/01 9:44 AM Page 229
¡ Open DeleteSession £ Between the quotation ¢ Save the page as ■ The Web browser displays
Template.aspx from the marks (""), type the name DeleteSession.aspx the result of deleting the
Code Templates directory. of the variable you want to to the default Web site and session information.
delete. display the ASP.NET page
™ Click where you want in a Web browser.
to delete the Application
variable and type
Session.Contents.Remove("");.
229
113617-6 Ch10.F 9/26/01 9:44 AM Page 230
ASP.NET
⁄ Open CreateCookie ¤ Set the cookie value by › Save the page as ■ The Web browser displays
Template.aspx from the typing cookieUserInfo.Value = CreateCookie.aspx to a message about creating a
Code Templates directory, "Yes";. the Default Web site and cookie.
click where you want to display the ASP.NET page
create a cookie, and type ‹ To write the cookie in a Web browser. Note: The cookie remains available
HttpCookie cookieUserInfo =
to the Web browser, type until the Web browser is closed.
Response.AppendCookie
newHttpCookie("cookieUser
(cookieUserInfo);.
HasVisited"); and press Enter.
230
113617-6 Ch10.F 9/26/01 9:44 AM Page 231
RESULT: RESULT:
The cookie is set for a week. The cookie is set for a month.
ˇ Open ReadCookie Á Read and display the ‡ Save the page as ■ The Web browser displays a
Template.aspx from the cookie contents by typing ReadCookie.aspx to the message about the contents of
Code Templates directory. Response.Write(Request. default Web site and display the cookie.
Cookies["cookieUserHas the ASP.NET page in a Web
Visited"].Value);. browser. ° Open CreatCookie
CollectionTemplate.aspx
from the Code Templates
directory.
CONTINUED
231
113617-6 Ch10.F 9/26/01 9:44 AM Page 232
ASP.NET
· Click where you want — Set another the ¡ Save the page as ■ The Web browser displays
to create a cookie and type cookie subkey by typing CreateCookie.aspx to a message about creating a
HttpCookie cookieUserInfo = cookieUserInfo.Values. the Default Web site and cookie.
new HttpCookie("cookie Add("FontName","Verdana");. display the ASP.NET page
UserFontPreferences");. in a Web browser. Note: The cookie remains available
± To write the cookie until the Web browser is closed.
‚ Set the cookie subkey to the Web browser, type
by typing cookieUserInfo. Response.AppendCookie
Values.Add("FontSize","8pt");. (cookieUserInfo);.
232
113617-6 Ch10.F 9/26/01 9:44 AM Page 233
%>
™ Open ReadCookie £ Read the contents of the ∞ Save the page as Read ■ The Web browser displays
CollectionTemplate.aspx subkey in the cookie into a CookieCollection.aspx a message about the contents
from the Code Templates variable that will style the to the Default Web site and of the cookie.
directory, click where you page by typing stringFont display the ASP.NET page
want to read a cookie, and Size = cookieUserInfo. in a Web browser.
type HttpCookie cookieUserInfo Values["cookieFontSize"];.
= Request.Cookies["cookieUser
FontPreferences"];. ¢ To read the second
subkey, type stringFont
Name = cookieUserInfo.
Values["FontName"];.
233
113617-6 Ch10.F 9/26/01 9:44 AM Page 234
ASP.NET
⁄ Open the Template.aspx ‹ Type a form control to ˇ Type a message about ‡ Add another panel to
template from the directory. the page. which step the user is on the page with an ID of
and output the value from panelStep2 and set the
¤ Type a heading to the page. › Type a panel to the the view state. visible property to False.
page with an ID of
panelStep1. Á Type a button control ° Add a message about
to the page that calls the which step the user is on
Button_OnClick when and output the value from
clicked. the view state.
234
113617-6 Ch10.F 9/26/01 9:44 AM Page 235
· Set the language for the ± Add the Button_OnClick ¡ Save the file as ™ Click the Continue
page to C# using the Page event handler and set the first PageState.aspx to the button.
directive. panel’s visible property to default Web site and request
false and the second panel’s it from the Web server. ■ The Web browser displays
‚ Add the <Script> tag visible property to true. a message about being on
to set up some server-side Also, increment the view ■ The Web browser displays step 2.
code. a message about being on
state variable by 1.
step 1. ■ Note that you stay on the
— Add the Page_Load same page.
event handler and initialize
the view state variable. 235
123617-6 Ch11.F 9/26/01 9:45 AM Page 236
ASP.NET
⁄ Open a new document ‹ Add a pair of ˇ Save the file as web.config. ‡ Import the
in your text editor. <appSettings> tags. System.Configuration
Á Open the namespace.
¤ Add a pair of › Add an <add> tag and DatagridTemplate.aspx
<configuration> tags. set the key attribute pubs template from the Code
to the SQL connection string Templates directory.
for connecting to the pubs
database.
236
123617-6 Ch11.F 9/26/01 9:45 AM Page 237
Making changes to the web.config file causes You can access configuration information by
it to be reloaded the next time a resource is importing the System.Configuration namespace
requested. This will slow down your next and running the following example code.
request, but subsequent requests are not
Example:
affected because the file is cached.
string stringPubsConnectionString =
web.config files can contain very sensitive ConfigurationSettings.AppSettings["pubs"];
information that you do not want a user of your
site to see. These settings could be connection
strings, authorization information, MSMQ
(Microsoft Messsage Queue) settings, and so on.
By default, ASP.NET does not allow this file to be
requested from the Web server. If users attempt
to request a web.config file, they receive an
HTTP access error, “This type of page is not
served.”
° Create a string variable · Modify the creation ‚ Save the file and request it ■ The page appears using the
and initialize the variable using the of the SQL Connection from the Web server. SQL connection setting from
Configuration.AppSettings to use the connection the web.config file.
["pubs"] property. string read from the
configuration file.
237
123617-6 Ch11.F 9/26/01 9:45 AM Page 238
ASP.NET
⁄ Open the ‹ Add a message to ˇ Save the file and request it ■ The error page appears
GenericTemplate.aspx the user. from the Web server. because the code on the
template from the Code page was written in C#
Templates directory. › Write the and C# is not set as the
HTTP_USER_AGENT default language.
¤ Add a heading for server variable to the
the page. Web browser.
238
123617-6 Ch11.F 9/26/01 9:45 AM Page 239
Á Create a web.config file. ° Add the ‚ Request the file from the ■ The page appears without
<compilation> tag and Web server. problems because the default
‡ Add the <system.web> set the defaultLanguage language is set to C#.
tags. attribute to C#.
Note: If you are creating a new · Save the file.
web.config file, first add the
<configuration> tags.
239
123617-6 Ch11.F 9/26/01 9:45 AM Page 240
ASP.NET
⁄ Create a web.config ‹ Add the <sectionGroup> ˇ Add the <goalsetup> tag Á Add the <add> tag
file. tag and set the name attribute within the <system.web> tags. and set the key attribute
to system.web. to maxnumber and the
¤ Add the value attribute to 10.
<configSections> tags. › Add the <section> tag
and set the type attribute to
Note: If you are creating a new System.Configuration.
web.config file, first add the NameValueSectionHandler,
<configuration> tags. System.
240
123617-6 Ch11.F 9/26/01 9:45 AM Page 241
‡ Open the · Add a message to — Save the file and request it ■ A message appears that
GenericTemplate.aspx the user. from the Web server. displays the maxnumber
template from the Code custom setting from the
Templates directory. ‚ Write the value of the web.config file.
maxnumber configuration.
° Add a heading for
the page.
241
133617-6 Ch12.F 9/26/01 9:45 AM Page 242
ASP.NET
⁄ Open the ¤ Create an error on the ■ The page displays and an ■ A message appears from
DatagridTemplate.aspx page by changing the SQL error message appears. the server with a description
template from the Code statement to an invalid SQL of the error; however, no
Templates directory. statement. details are given as to on
which line the error
‹ Save the page and request occurred.
it from the Web server.
242
133617-6 Ch12.F 9/26/01 9:45 AM Page 243
ELEMENT DESCRIPTION
Description A brief description of the error.
Exception Details Indicates which exception was raised and
describes exception.
Source Error Displays a couple of lines of the source code
before and after the line that generated the error.
Source File Specifies the path and filename of the source file
that generated the error.
Line Indicates the line number of the error.
Stack Trace Displays the call stack for the error.
Version Information Displays the Runtime Build and the ASP.NET Build.
› Return to the page you ˇ Save the page and request ■ The page displays and an ■ A message appears from
were creating and add the it from the Web server. error message appears. the server with a description
@Page Debug trace directive. of the error and the line
number and the source code
where the error occurred.
243
133617-6 Ch12.F 9/26/01 9:45 AM Page 244
ASP.NET
⁄ Open a new document ‹ Add <system.web> tags. Á Open the ° Add an error message
in your text editor. GenericTemplate.aspx for the page.
› Add a <customErrors> tag template from the Code
¤ Start a web.config and set the defaultRedirect Templates directory. · Save the page to the
file by adding attribute and the mode attribute. Web site.
<configuration> tags. ‡ Add a heading to
ˇ Save the file as web.config the page.
to the Web site.
244
133617-6 Ch12.F 9/26/01 9:45 AM Page 245
</FONT>
</BODY>
</HTML>
‚ Create an error on the — Save the page and request ■ The error-handling page
page by changing the SQL it from the Web server. appears because of the error
statement to an invalid SQL on the page.
statement.
245
133617-6 Ch12.F 9/26/01 9:45 AM Page 246
ASP.NET
⁄ Open ¤ Add the Page_Error ‹ Add a string variable to › Write the string to the
DatagridTemplate.aspx event handler to the page. create an HTML message for Web browser using the
from the Code Templates informing the user that an Response object.
directory. error has occurred on the
page. ˇ Clear the error using
the Server.ClearError
method.
246
133617-6 Ch12.F 9/26/01 9:45 AM Page 247
Because you are on the same page in which the error occurred, you
can print out a number of details about the error.
Example:
<SCRIPT LANGUAGE="C#" RUNAT="Server">
void Page_Error(Object sender, EventArgs e) {
String stringMessage = "<HTML><FONT FACE =\"Verdana\">"
+ "<H3>Handle Errors Programmatically</H3>"
+ "There was an error processing this page."
+ "<P/>Here is the error information:<P/><PRE>" +
Server.GetLastError().ToString()
+ "</PRE></FONT></HTML>";
Response.Write(stringMessage);
Server.ClearError();
}
</SCRIPT>
Á Create an error on the ‡ Save the page and request ■ You remain on the same
page by changing the SQL it from the Web server. page and an error message
statement to an invalid SQL appears.
statement.
247
133617-6 Ch12.F 9/26/01 9:45 AM Page 248
ASP.NET
⁄ Open ¤ Turn on tracing for ■ The page contents appear. › Scroll down the page
DatagridTemplate.aspx the page by setting the until you get to the Request
from the Code Templates Trace="true" attribute Details.
directory. for the @Page directive.
‹ Save the page and request
248 it from the Web server.
133617-6 Ch12.F 9/26/01 9:45 AM Page 249
datagridTitles.DataSource=datasetTitles.Tables["titles"].DefaultView;
Trace.Write("DataBind","About to bind the datagrid.");
datagridTitles.DataBind();
Trace.Write("DataBind","Done binding the datagrid.");
}
RESULTS:
Trace information that includes details on the start and completion of the
datagrid binding.
■ The Request Details ■ The Control Tree appears. ■ The Cookies Collection ■ The Server Variables
appear. appears. appear.
ˇ Scroll down the page
■ The Trace Information until you get to the Cookies ■ The Headers Collection
appears. Collection. appears.
249
133617-6 Ch12.F 9/26/01 9:45 AM Page 250
ASP.NET
⁄ Open a new document ‹ Add <system.web> Á Request the Trace.axd ‡ Click the View Details
in your text editor. tags. page in the root directory for link to see the details for
the application. a specific request.
¤ Start a web.config › Add a <trace> tag and
file by adding set the enabled attribute. ■ Recent requests are
<configuration> tags. displayed. You may need to
ˇ Save the file as web.config open another instance of your
to the Web site. Web browser and request some
of the other files in the directory
250 to see requests in the trace.
133617-6 Ch12.F 9/26/01 9:45 AM Page 251
You can fine tune the storage of your trace information with the attributes
on the trace element. The requestLimit is the number of requests to
trace. The default for this is 10 requests. You can specify whether to have
individual pages output trace information by setting the pageOutput =
"true". You can also sort the trace information by category, instead of
time, by specifying traceMode="SortByCategory".
Example:
<configuration>
<system.web>
<customErrors defaultRedirect="error.aspx" mode="on" />
<trace enabled="true" requestLimit="50" pageOutput="true"
traceMode="SortByCategory" />
</system.web>
</configuration>
■ Details appear for the ° Scroll down the page ■ The Cookies Collection ■ The Server Variables
request selected, including until you get to the Cookies appears. appear.
the Trace Information. Collection.
■ The Headers Collection
appears.
251
143617-6 Ch13.F 9/26/01 9:45 AM Page 252
ASP.NET
Properties
⁄ Open a new document in ‹ Add the <system.web> Á Open the Internet Services ‡ Right-click the directory
your text editor. start and end tags. Manager and expand the tree and choose Properties.
until you get to the directory
¤ Add the › Add an where you want to save your
<configuration> start <authentication> tag code for this task.
and end tags. and set an attribute named
mode equal to Windows.
252 ˇ Save the file as web.config.
143617-6 Ch13.F 9/26/01 9:45 AM Page 253
RESULT:
Welcome to www.mylifetimegoals.com
You are authenticated as TAR-DEV-LAPTOP\Administrator.
You are authenticated using NTLM.
■ The Properties dialog box · Click the Edit button to ‚ Click the Anonymous ± Click OK to close the
opens. open the Authentication access check box to turn off Properties dialog box.
Methods dialog box. access for the application.
° Click the Directory
Security tab. — Click OK to accept the
changes and close the CONTINUED
Authentication Methods
dialog box.
253
143617-6 Ch13.F 9/26/01 9:45 AM Page 254
ASP.NET
When securing Web applications, you deal with Sometimes the user is mapped over to an account
authentication, authorization, and that is shared by multiple users. This is called
impersonation. impersonation and is used for setting up
anonymous access to a Web application in IIS 5.0.
Authentication is the process of identifying if you
are a configured user of the system. Be cautious when configuring impersonation,
Authentication occurs after the user provides a because configuration requires you to insert the
name/password pair that they enter when password in the text of the web.config file.
logging on to the site. This name/password pair is (Passwords in a text file are not very secure.)
also called the user credentials.
After you have authenticated a user, you need a
way to determine the appropriate access rights
of the user to read, modify, delete, and so on,
resources on your Web site. This is known as
user authorization.
§ Set the values for the ¶ Save the file and request it ■ A message appears
labels including the from the Web server. showing the username and
username and the authentication type.
authentication type.
255
143617-6 Ch13.F 9/26/01 9:45 AM Page 256
ASP.NET
⁄ Open a new document in ‹ Add the <system.web> ˇ Add a <forms> tag and Á Add a set of
your text editor. start and end tags. set the name equal attribute <authorization> start
to a unique name, a and end tags.
¤ Add the › Add an loginURL attribute equal to
<configuration> start <authentication> tag the name of your login page, ‡ Add a <deny/> tag with
and end tags. and set the mode attribute a protection attribute the users attribute set to ?.
equal to Forms. equal to the value of all, and ° Save the file as
a timeout attribute equal web.config.
256 to 60.
143617-6 Ch13.F 9/26/01 9:45 AM Page 257
TYPE THIS:
<SCRIPT LANGUAGE="C#" RUNAT="Server">
void SubmitBtn_Click(object Source, EventArgs e) {
if (inputPassword.Text == "goals") {
FormsAuthentication.RedirectFromLoginPage(inputName.Text, false);
}
else {
labelMessage.Text="That password is not correct.";
}
}
</SCRIPT>
RESULT:
· Open the ‚ Add a heading for the — Create the Page_Load ± Save the file as
GenericTemplate.aspx page that contains a label event handler to set the user FormsAuthentication
template from the Code control for displaying the user name for the label control. Default.aspx.
Templates directory. name.
CONTINUED
257
143617-6 Ch13.F 9/26/01 9:45 AM Page 258
ASP.NET
¡ Open the £ Add a form control to the ∞ Add an alias to the ¶ Check the password field
GenericTemplate.aspx page. System.Web.Security for the correct input and use
template from the Code namespace using @Import. the
Templates directory. ¢ Add a text box for the user RedirectFromLoginPage
name and password, along § Create the to forward on the user.
™ Add a heading for the with a submit button and a SubmitBtn_Click event
page and a message about label for displaying messages. handler. • If the user did not enter
login. correct input, set an
appropriate message for the
258 user.
143617-6 Ch13.F 9/26/01 9:45 AM Page 259
ASP.NET
AUTHORIZE USERS
SP.NET gives you a convenient means to If you want to be less granular with authorization, you
AUTHORIZE USERS
⁄ Open the web.config ‹ Add an <allow/> tag ˇ Copy the files Á Type an unauthorized
template file from the Code and set the users attribute to UserAuthorization user’s name and goals for the
Templates directory. Tommy, Deanna, Bobby. Default.aspx and password.
UserAuthorization
¤ Add another <deny/> tag › Save the web.config Login.aspx from the CD- ‡ Click the Submit button.
between the file. ROM to the Web site and
<authorization> tags; set request
users attribute to Danny. UserAuthorization
Default.aspx from the
260 Web server.
143617-6 Ch13.F 9/26/01 9:45 AM Page 261
■ You are redirected back to ° Enter an authorized name · Click the Submit button.
the login page because the and goals for the password.
user is denied access. ■ Access is given to view the
default page.
261
153617-6 Ch14.F 9/26/01 9:45 AM Page 262
ASP.NET
SET UP ENCODING
ou can use encoding to create a site that supports UCS Transformation Format (UTF-8) is an encoding
SET UP ENCODING
⁄ Open the ¤ Add the @Page directive Note: You will need to install support › Add a Spanish heading for
GenericTemplate.aspx to the page and set the for languages not currently installed the page.
template from the Code ResponseEncoding on your computer.
Templates directory. attribute to UTF-8, as well as
the Language attribute ‹ Add an English heading
to C#. for the page.
262
153617-6 Ch14.F 9/26/01 9:45 AM Page 263
You can set up encoding for the entire application in the web.config file with the
<globalization> tag.
The options for the attributes for encoding are as follows:
requestEncoding Specifies the assumed encoding of each incoming request. The default is us-ascii.
responseEncoding Sets the content encoding of responses. The default is iso-8859-1.
fileEncoding Designates the default encoding for .aspx, .asmx, and .asax files.
Example:
<configuration>
<system.web>
<globalization " requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="utf-8" />
</system.web>
</configuration>
ˇ Add a Japanese heading Á Save the file and request it ■ The messages in the
for the page. from the Web server. various languages appear.
263
153617-6 Ch14.F 9/26/01 9:45 AM Page 264
ASP.NET
USING CULTUREINFO
ou can use the CultureInfo class to display determine the culture, you can set the current
USING CULTUREINFO
⁄ Open the › Add a form control. Á Add a submit button ° Add the @Page directive
GenericTemplate.aspx control. to the page and set the
template from the Code ˇ Create a drop-down list ResponseEncoding attribute
Templates directory. that has several languages ‡ Add a span control on the
from which to choose. form to display messages. to UTF-8, as well as the
¤ Add a heading to the Language attribute to C#.
page. · Add an alias to the
‹ Add a message to the user. System.Threading and
System.Globalization
264
153617-6 Ch14.F 9/26/01 9:45 AM Page 265
TYPE THIS:
<SCRIPT LANGUAGE="C#" RUNAT="Server">
void SubmitBtn_Click(object Source, EventArgs e) {
CultureInfo cultureinfoLanguage = new
CultureInfo(dropdownlistCultures.SelectedItem.Value);
Thread.CurrentThread.CurrentCulture = cultureinfoLanguage;
spanMessage.InnerHtml = "The localized date is " +
DateTime.Now.ToString("D", CultureInfo.CurrentCulture) +
"." + "<BR/> The calendar to use for this culture is " +
CultureInfo.CurrentCulture.Calendar + "." +
"<BR/> The native name for this culture is " +
CultureInfo.CurrentCulture.NativeName + ".";
}
</SCRIPT>
RESULT:
The localized date is domingo, 05 de agosto de 2001.
The calendar to use for this culture is System.Globalization.GregorianCalendar.
The native name for this culture is español (España).
‚ Add the ± Set the current culture. ™ Save the file and request it ¢ Click the Submit button.
SubmitBtn_Click from the Web server.
function. ¡ Set the InnerHtml ■ The message appears
property of the span control £ Click to select a according to the culture
— Create a new to the date based on the culture. selected.
CultureInfo variable current culture.
based on the item selected in
the drop-down list box.
265
153617-6 Ch14.F 9/26/01 9:45 AM Page 266
ASP.NET
USING REGIONINFO
ou can use the RegionInfo class to show user’s Web browser. After you determine the region,
USING REGIONINFO
⁄ Open the ‹ Add a message to Á Add a submit button · Add an alias to the
GenericTemplate.aspx the user. control. System.Threading and
template from the Code System.Globalization
Templates directory. › Add a form control. ‡ Add a span control on the namespaces.
form to display messages.
¤ Add a heading to the ˇ Create a drop-down list
page. that has several languages ° Add the @Page directive to
from which to choose. the page and set the
ResponseEncoding
attribute to UTF-8, as well as
266 the Language attribute to C#.
153617-6 Ch14.F 9/26/01 9:45 AM Page 267
‚ Add the ± Set the InnerHtml ¡ Save the file and request it £ Click the Submit button.
SubmitBtn_Click function. property of the span control from the Web server.
to the date based on the ■ The message appears
— Create a new current culture. ™ Click to select according to the
RegionInfo variable based a culture. region selected.
on the item selected in the
drop-down list.
267
153617-6 Ch14.F 9/26/01 9:45 AM Page 268
ASP.NET
⁄ Open ‹ Add a message to the Á Add a submit ° Add the @Page directive
GenericTemplate.aspx user. button control. to the page and set the
from the Code Templates ResponseEncoding
directory. › Add a form control. ‡ Add a span control on the attribute to UTF-8, as well as
form to display messages.
¤ Add a heading to the ˇ Create a drop-down list the Language attribute to C#.
page. that has several languages · Add an alias to the
from which to choose. System.Threading and
System.Globalization
namespaces.
268
153617-6 Ch14.F 9/26/01 9:45 AM Page 269
Spanish
‚ Add the ± Add a switch statement ¡ Save the file and request it Note: These files are used for the
SubmitBtn_Click to redirect the user to the from the Web server. different cultures you can select.
function. appropriate page.
™ Copy the £ Click to select
— Create a new string Welcomeen_us.aspx, a culture.
variable and read the value of Welcome_es_es.aspx,
the selected item in the drop- and Welcome_ja_jp.aspx ¢ Click the Submit button.
down list. files from the CD-ROM to the ■ The appropriate page for
current directory. the culture appears with a
message.
269
153617-6 Ch14.F 9/26/01 9:45 AM Page 270
ASP.NET
⁄ Open your text editor. ■ Repeat steps 2 to 4 for each ˇ Open the command Á Type the resgen command
culture. prompt and go to the to create the resource file
¤ Type [strings]. directory where your resource from the text file.
Note: The resource files are saved in
‹ Add the welcome a subdirectory called resources.
files are located.
■ Repeat step 6 for each
statement=Welcome! resource file.
name/value pair. Note: This task works with three
› Save the file with a cultures (English, Spanish, and
.txt extension. Japanese). You can expand to other
cultures.
270
153617-6 Ch14.F 9/26/01 9:45 AM Page 271
‡ Open your text editor to ° Add aliases to · Create the — Save the file as Global.asax
create a Global.asax file. System.Globalization, Application_OnStart to the Web site.
System.Resources, event handler.
System.Threading, and ■ You can now use the
System.IO. ‚ Create a Resource Application variable to
Manager application variable access the information in the
and initialize it. resource files.
271
153617-6 Ch14.F 9/26/01 9:45 AM Page 272
ASP.NET
⁄ Open the ˇ Create a drop-down list ° Add the @Page directive · Add an alias to the
GenericTemplate.aspx that has several languages to the page and set the System.Globalization,
template from the Code from which to choose. ResponseEncoding System.Resources, and
Templates directory. attribute to UTF-8, as well System.Threading
Á Add a submit button as the Language attribute namespaces.
¤ Add a heading to the page. control. to C#.
‚ Add the <script> tags.
‹ Add a message to the user. ‡ Add a span control on the
form to display messages. — Create a new
› Add a form control. ResourceManager variable.
272
153617-6 Ch14.F 9/26/01 9:45 AM Page 273
You can convert your resource files from their You can convert from XML back to text as well. For
binary format into XML-formatted files. For example, you can use resgen at the command line
example, you can use the resgen at the to convert the text.en-us.resx file into an XML
command line to convert the text.en- file named newtext.en-us.txt.
us.resources file into an XML file named
Example:
text.en-us.resx.
resgen text.en-us.resources newtext.en-us.resx
Example:
resgen text.en-us.resources text.en-us.resx
± Add the Page_Init ™ Set the ¢ Save the file and request it § Click the Submit button.
event handler that reads the CurrentCulture and from the Web server.
Resource Manager from the CurrentUICulture based ■ The message is localized
application variable. on the selection in the drop- ∞ Click to select a according to the culture
down list. culture. selected.
¡ Create the
SubmitBtn_Click £ Set the message using the
function. Resource Manager.
273
163617-6 Ch15.F 9/26/01 9:46 AM Page 274
ASP.NET
⁄ Open ■ The page displays two ¤ Save the file and request it ■ The JScript code and the
MultipleLanguages.aspx server-side script blocks from the Web server. VBScript code execute.
from the Code Templates using two different
directory. languages.
274
163617-6 Ch15.F 9/26/01 9:46 AM Page 275
ASP.NET Web pages are compiled on the Web When you know how to program in a language that
server. This is why there is support for only one is CLS compliant, you can leverage this knowledge
language per page. This is different than by creating other applications that run on the CLR
traditional ASP pages, which are normally (like a Windows Forms application, a Web Service, a
interpreted each time they are requested. Mobile application, or a distributed application).
If the language is not specified in the @Page
directive and you only have server-side code in a
<script> tag, then you could set the Language
attribute for the script element.
The .NET Framework provides the Common
Language Specification (CLS) to ensure that .NET
compliant language can interoperate. CLS
describes a fundamental set of language features
and defines rules for how those features are
used. CLS-compliant languages enable you to do
such things as inherit classes from other CLS-
compliant classes and pass data types without
having to do any special preparation (like
buffering a string).
‹ Open ■ The page displays two › Save the file and request it ■ An error message appears
MultipleLanguages.aspx server-side script blocks from the Web server. because more than two
from the Code Templates using two different languages cannot be used on
directory. languages. the same page.
275
163617-6 Ch15.F 9/26/01 9:46 AM Page 276
ASP.NET
⁄ Open ■ The page displays the ¤ Save the file and request ■ The ASP code executes
ScriptBlocks.aspx from SayWelcomeStatement ScriptBlocks.asp from without issues.
the Code Templates directory. that outputs the header for the Web server.
the page.
276
163617-6 Ch15.F 9/26/01 9:46 AM Page 277
You can put scripts into files that are external to With ASP.NET, you must declare global
your ASP.NET page. You can do this with the variables within <script runat=server>
<script> element by specifying an external blocks and not between code delimiters
script file using the src attribute. When you (<% and %>).
define the src attribute, all content between
the opening and closing tags of the <script>
element is ignored. Because this is the case,
it is best to define the <script> element
as an empty tag. For example,
<script runat="server"
src="scrStandard.cs" />.
‹ Open ■ The page displays the › Save the file and request it ■ An error message appears
ScriptBlocks.aspx from SayWelcomeStatement from the Web server. because parentheses were
the Code Templates directory. that outputs the header for not used when calling the
the page. subprocedure.
277
163617-6 Ch15.F 9/26/01 9:46 AM Page 278
ASP.NET
⁄ Open ■ The page displays the ¤ Save the file and request it ■ The ASP code is able to
RenderFunctions.aspx SayWelcomeStatement from the Web server. use the render function.
from the Code Templates that outputs the header for
directory. the page.
278
163617-6 Ch15.F 9/26/01 9:46 AM Page 279
‹ Open ■ The page displays the › Save the file and request it ■ An error message appears
RenderFunctions1.aspx SayWelcomeStatement from the Web server. because a render function
from the Code Templates that outputs the header for was used.
directory. the page.
279
163617-6 Ch15.F 9/26/01 9:46 AM Page 280
ASP.NET
⁄ Open ■ The page does not use the ¤ Save the file and request it ■ The ASP code executes
PageDirective.aspx @Page directive. It uses the from the Web server. displaying the header that is
from the Code Templates @Language directive contained in a subroutine.
directory. without the @Page.
280
163617-6 Ch15.F 9/26/01 9:46 AM Page 281
OPTION LOCATION
Any Client, Downstream, or Server
Client Browser client where the request originated
Downstream A server downstream from the Web server that processed the request
None N/A
Server Web server where the request was processed.
‹ Open ■ The page uses the @Page › Save the file and request it ■ The ASP code executes
PageDirective.aspx directive to set the server-side from the Web server. using the @Page directive to
from the Code Templates language. determine the server-side
directory. language.
281
163617-6 Ch15.F 9/26/01 9:46 AM Page 282
ASP.NET
⁄ Open ¤ Scroll down the file to ‹ Save the file and request ■ The ASP code executes
SimpleQuery_VBScript.aspx view the code. SimpleQuery_VBScript.aspx without issues and
from the Code Templates directory. from the Web server. displays data from the
database of the author.
› Copy the file from the CD-ROM
to the working directory.
282
163617-6 Ch15.F 9/26/01 9:46 AM Page 283
Microsoft has made VB a first class language, In VB.NET, the On Error Resume Next and On
keeping the following in mind: Error Goto error handling is still available. Even
though this is still available, you should take
• Making the language more consistent:
advantage of structured error handling that is
bringing together features of the language
available for all CLS (Common Language
with similar purpose.
Specification) compatible languages. This uses the
• Simplifying the language: redesigning those Try, Catch, and Finally keywords.
features which made Visual Basic anything
less than “basic.”
• Improving readability and maintainability:
redesigning features that hide too many
important details from the programmer.
• Improving robustness: enforcing better
practices, such as type-safe programming.
ˇ Save the file with an .aspx ■ An error message Á Change the language ‡ Request
extension and then request it appears because the in the source file from SimpleQuery_VBScript.aspx
from the Web server. Option Explicit is VBScript to VB, add from the Web server.
not allowed. the keyword Page to
the directive at the top ■ An error message appears
of the file, and remove because the Let and Set
the Option Explicit statements are no longer
code. supported.
CONTINUED
283
163617-6 Ch15.F 9/26/01 9:46 AM Page 284
ASP.NET
° Remove the two Set statements ■ An error message ‚ Place parentheses around the ■ An error message
from the source file. appears because VB statement appears because you
requires the argument "Provider=Microsoft.Jet. cannot create
· Save the file and request list to be enclosed in OLEDB.4.0;Data Source=" & apartment threaded
SimpleQuery_VBScript.aspx parentheses. filePath. COM components
from the Web server. without the
— Save the file and request aspcompat=true
SimpleQuery_VBScript.aspx statement in the @Page
284 from the Web server. directive.
163617-6 Ch15.F 9/26/01 9:46 AM Page 285
If you are not explicit in how parameters are All of your server-side code method calls will
passed, you could have issues with your code. In require parentheses.
VB6, parameters were, by default, passed by
Example:
reference (ByRef). This has changed to by value
Response.Write "An error has occurred."
(ByVal) in VB.NET. If your code relied on ByRef
parameters, then you could introduced bugs with
'Changes to:
this change.
Response.Write("An error has occurred.")
VB.NET no longer provides support for default
properties. To account for this, you need to
explicitly call the property from the object.
Example:
Response.Write oRS("FirstName")
'Changes to:
Response.Write (oRS("FirstName").Value)
± Add aspcompat=true to the ■ The page renders ™ Add .Value to the end of the ■ The page displays
@Page directive at the top of the without issues but does oRs(Index) statement. properly as an ASP.NET
page. not display the data page.
because the default £ Save the file and request
¡ Save the file and request properties are not SimpleQuery_VBScript.aspx
SimpleQuery_VBScript.aspx supported in VB. from the Web server.
from the Web server.
285
163617-6 Ch15.F 9/26/01 9:46 AM Page 286
ASP.NET
MIGRATE JSCRIPT TO
JSCRIPT.NET SYNTAX
J Script.NET code implementation is much closer to
the JScript implementation than VB.NET is to
VBScript. Because JScript was more of an Object-
Oriented language than VBScript. Jscript will resemble
then you need to set ASPCOMPAT=true for the
@Page directive.
As with VB.NET, you can not access default properties
to the C# syntax that is used in this book than the VB on COM objects. If default properties are used, you
syntax. The big difference that you will notice is in the have to find the explicit property that retrieves the
variable declaration. default property and program using that explicit
property. For example, if you have a label on a form,
When converting an ASP page (*.asp) to an ASP.NET you can not access the Text property by the default
page (*.aspx) that has JScript in the server-side property of the label. To access the Text property,
code, the first thing you will do is change the file you have to give an explicit reference to that
extension to aspx. If you are going to access STA property’s data type — JScript.NET - var s :
(Single Threaded Apartment) COM components, String = lblFirstName.Text; versus JScript -
var s = lblFirstName;. Note that the String is
explicitly declared when intitializing the variable.
MIGRATE JSCRIPT TO JSCRIPT.NET SYNTAX
⁄ Open ■ The ASPCOMPAT=true ■ The filePath statement ‹ Scroll down the file.
SimpleQuery_JScript.aspx attribute is set in the appears in parentheses, so
from the Code Templates @Page directive. you do not have to change it.
directory.
¤ Scroll down the file. ■ The set statement is not
required in JScript, so there
are no changes with
initializing the object
286 variable.
163617-6 Ch15.F 9/26/01 9:46 AM Page 287
JScript.NET is Microsoft’s implementation of ECMAScript has strong roots with Netscape. Having
the ECMA 262 language. Improvements in JScript is beneficial for those who are inline with
JScript.NET — which is being developed in the standards body that defines ECMAScript. If you
conjunction with ECMAScript Edition 4 — include are looking for features and support, you will find
true compiled code, typed and typeless variables, more of this with the C# and VB languages. There
classes (with inheritance, function overloading, are more books and sample code for these
property accessors, and more), packages, cross- languages.
language support, and access to the .NET
Framework. JScript.NET is a true object-oriented
scripting language. Even though JScript.NET can
now use classes, types, and other “industrial
strength” language features for writing robust
applications, it still keeps its “scripting” feel.
287
173617-6 AppA.F 9/26/01 9:46 AM Page 288
APPENDIX
NAMESPACE: SYSTEM.WEB.UI.HTMLCONTROLS:
HtmlAnchor working with the HTML <a> tag on the server.
HtmlButton working with the HTML <button> tag on the server.
HtmlForm working with the HTML <form> tag on the server.
HtmlGenericControl working with tags not represented by .NET classes (eg. <span> and <div> tags).
HtmlImage working with the HTML <img> tag on the server.
HtmlInputButton working with the HTML <input type= button>, <input type= submit>, and <input type=
reset> tags on the server.
HtmlInputCheckBox working with the HTML <input type= checkbox> tag on the server.
HtmlInputFile working with the HTML <input type= file> tag on the server.
HtmlInputHidden working with the HTML <input type= hidden> tag on the server.
HtmlInputImage working with the HTML <input type= image> tag on the server.
HtmlInputRadioButton working with the HTML <input type= radio> tag on the server.
HtmlInputText working with the HTML <input type= text> and <input type= password> tags on the server.
HtmlSelect working with the HTML <select > tag on the server.
HtmlTable working with the HTML <table> tag on the server.
HtmlTableCell working with the HTML <td> and <th> tags on the server.
HtmlTableCellCollection working with a collection of HTML <td> and <th> tags on the server.
HtmlTableRow working with the HTML <tr> tag on the server.
HtmlTableRowCollection working with a collection of HTML <tr> tags on the server.
HtmlTextArea working with the HTML <textarea> tag on the server.
288
173617-6 AppA.F 9/26/01 9:46 AM Page 289
NAMESPACE: SYSTEM.WEB.UI.WEBCONTROLS:
AdRotator displaying an advertisement banner.
Button posting data back to the server.
Calendar displaying a one-month calendar.
CheckBox creating a check box.
CheckBoxList creating a multi-selection check box group.
DataGrid creating a multi-column data bound grid.
DataList creating a data bound list.
DropDownList creating a drop-down list that contains a single selection.
HyperLink creating a link for navigating to pages.
Image creating a Web-compatible image.
ImageButton creating an image to handle user click events.
Label creating and manipulating static text.
LinkButton creating hyperlink-style buttons that post back to the same page on which they originated.
ListBox displaying a single-selection or multi-selection list box.
Panel providing a container for other controls.
RadioButton creating a radio button.
RadioButtonList creating a radio button group.
Repeater creating a data-bound list that renders a row for every row in the specified data source.
Table Web creating a table and manipulating it programmatically.
TableCell creating a table cell and manipulating it programmatically.
TableRow creating a table row and manipulating it programmatically.
TextBox creating single and multi-line text boxes.
289
173617-6 AppA.F 9/26/01 9:46 AM Page 290
APPENDIX
NAMESPACE: SYSTEM.WEB.UI.WEBCONTROLS:
CompareValidator comparing a user’s entry against a constant value, against a property value of
another control, or against a database value using a comparison operator (less than,
equal, greater than, and so on).
CustomValidator creating custom server and client validation code.
RangeValidator checking that a user’s entry is between specified lower and upper boundaries.
RegularExpressionValidator checking that the entry matches a pattern defined by a regular expression.
RequiredFieldValidator checking that the user does not skip an entry.
ValidationSummary displaying a summary of all validation errors for all of the validation controls on
a page.
GLOBAL.ASAX SYNTAX
WEB.CONFIG SYNTAX
<system.web>
290
173617-6 AppA.F 9/26/01 9:46 AM Page 291
/>
<!— CUSTOM ERROR MESSAGES
Set mode enable="on" or "remoteonly" to enable custom error messages, "off" to disable. Add
<error> tags for each of the errors you want to handle.
—>
<customErrors
mode="Off"
/>
<!— AUTHENTICATION
This section sets the authentication policies of the application. Possible modes are "Windows", "Cookie",
"Passport" and "None"
—>
<authentication mode="Forms">
<forms name=".ASPXUSERDEMO" loginUrl="login.aspx" protection="all" timeout="60" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<!— GLOBALIZATION
This section sets the globalization settings of the application.
—>
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>
</system.web>
</configuration>
291
183617-6 AppB.F 9/26/01 9:46 AM Page 292
APPENDIX
BASICS EXAMPLES
DECLARING VARIABLES
COMMENTS
ASSIGNMENT STATEMENTS
IF...ELSE STATEMENTS
292
183617-6 AppB.F 9/26/01 9:46 AM Page 293
CASE STATEMENTS
C#, VB, AND JSCRIPT LANGUAGE EQUIVALENTS B
Visual Basic JScript
Select Case n switch(n) {
Case 0 case 0 :
MsgBox ("Zero") Response.Write("Zero");
' Visual Basic exits the Select at the end of a Case. break;
Case 1 case 1 :
MsgBox ("One") Response.Write("One");
Case 2 break;
MsgBox ("Two") case 2 :
Case Else Response.Write("Two");
MsgBox ("Default") default :
End Select Response.Write("Default");
}
C#
switch(n) {
case 0:
Console.WriteLine("Zero");
break;
case 1:
Console.WriteLine("One");
break;
case 2:
Console.WriteLine("Two");
break;
default:
Console.WriteLine("?");
}
FOR LOOPS
C#
for (int i = 1; i <= 10; i++)
Console.WriteLine("The number is {0}", i);
WHILE LOOPS
Visual Basic C#
While n < 100 ' Test at start of loop while (n < 100)
n += 1 ' Same as n = n + 1 n++;
End While '
JScript
while (n < 100) {
n++; }
293
183617-6 AppB.F 9/26/01 9:46 AM Page 294
APPENDIX
BASICS EXAMPLES
PARAMETER PASSING BY VALUE
Visual Basic C#
Public Sub ABC(ByVal y As Long) ' The argument Y is // The method:
passed by value. void ABC(int x)
' If ABC changes y, the changes do not affect x. {
End Sub ...
ABC(x) ' Call the procedure }
You can force parameters to be passed by value, // Calling the method:
regardless of how they are declared, by enclosing ABC(i);
the parameters
in extra parentheses. JScript
ABC((x)) ABC(i,j);
294
183617-6 AppB.F 9/26/01 9:46 AM Page 295
Visual Basic C#
Try // try-catch-finally
If x = 0 Then try
Throw New Exception("x equals zero") {
Else if (x == 0)
Throw New Exception("x does not equal zero") throw new System.Exception ("x equals zero");
End If else
Catch throw new System.Exception ("x does not equal zero");
MessageBox.Show("Error: " & Err.Description) }
Finally catch (System.Exception err)
MessageBox.Show("Executing finally block.") {
End Try System.Console.WriteLine(err.Message);
}
finally
{
System.Console.WriteLine("executing finally block");
}
JScript
try {
if (x == 0) {
throw new Error(513, "x equals zero");
}
else {
throw new Error(514, "x does not equal zero");
}
}
catch(e) {
Response.Write("Error number: " + e.number + "<BR>");
Response.Write("Error description: " + e.message + "<BR>");
}
finally {
Response.Write("Executing finally block.");
}
295
183617-6 AppB.F 9/26/01 9:46 AM Page 296
APPENDIX
296
183617-6 AppB.F 9/26/01 9:46 AM Page 297
Addition + + +
Subtraction - - -
MULTIPLICATIVE
Multiplication * * *
Division / / /
Integer division \ /
Modulus (division returning Mod % %
only the remainder)
Exponentiation ^ n/a n/a
ASSIGNMENT
Assignment = = =
Addition += += +=
Subtraction -= -= -=
Multiplication *= *= *=
Division /= /= /=
Integer division \= /= n/a
Concatenate &= += +=
Modulus n/a %= %=
Left shift n/a <<= <<=
Right shift n/a >= >=
Bitwise-AND n/a &= &=
Bitwise-exclusive-OR n/a ^= ^=
Bitwise-inclusive-OR n/a |= |=
297
183617-6 AppB.F 9/26/01 9:46 AM Page 298
APPENDIX
298
183617-6 AppB.F 9/26/01 9:46 AM Page 299
Array element () [] []
Function call () () ()
Type cast Cint, CDbl, ..., CType (type) n/a
Member selection . . .
Postfix increment n/a ++ ++
Postfix decrement n/a — —
UNARY
Conditional IIf() ?: ?:
POINTER TO MEMBER
299
193617-6 AppC.F 9/26/01 9:46 AM Page 300
APPENDIX
300
193617-6 AppC.F 9/26/01 9:46 AM Page 301
GNU software is governed by its own license, which is XML Spy IDE
included inside the folder of the GNU software. There Evaluation version. XML Spy IDE v3.5 is a
are no restrictions on distribution of this software. development environment that supports working with
See the GNU license for more details. XML. This includes editing and validating XML
documents, editing and validating using Schemas or
Trial, demo, or evaluation versions are usually limited DTDs, and editing and transforming stylesheets. From
either by time or functionality. For example, you may ALTOVA, www.xmlspy.com.
not be able to save projects using these versions.
For your convenience, the software titles on the CD TROUBLESHOOTING
are listed in alphabetical order. We tried our best to compile programs that work on
most computers with the minimum system
requirements. Your computer, however, may differ
Acrobat Reader and some programs may not work properly for some
Freeware. Acrobat Reader lets you view the online
reason.
version of this book. For more information on using
Adobe Acrobat Reader, see pg. 302. The two most likely problems are that you don’t have
enough memory (RAM) for the programs you want to
Antechinus C# Programming Editor use, or you have other programs running that are
affecting installation or running of a program. If you
Shareware. The Antechinus C# Programming Editor
get error messages like Not enough memory or
from C Point Pty. Ltd. is an alternate graphic
Setup cannot continue, try one or more of these
programming environment for creating and testing C#
methods and then try using the software again:
programs. You can find more information at www.
c-point.com. * Turn off any anti-virus software.
* Close all running programs.
TextPad * In Windows, close the CD-ROM interface and run
Shareware. TextPad is a general-purpose text editor demos or installations directly from Windows
for many different text files including C# code and Explorer.
HTML code. From Helios Software Solutions,
* Have your local computer store add more RAM to
www.textpad.com.
your computer.
If you still have trouble installing the items from the
VMWare Workstation CD-ROM, please call the Hungry Minds Customer
Trial version. VMWare Workstation lets you create Service phone number: 800-762-2974 (outside the
virtual desktop environments on one computer so U.S.: 317-572-3994).
you can test how your C# programs run in different
operating systems. From VMWare, www.vmware.com.
301
203617-6 Install.F 9/26/01 9:46 AM Page 302
APPENDIX
FLIP THROUGH PAGES First page ZOOM IN ¤ Click the area of the
⁄ Click one of these Previous page ⁄ Click to magnify page you want to magnify.
options to flip through an area of the page. ■ Click one of these
the pages of a section. Next page
options to display the page
Last page at 100% magnification ( )
or to fit the entire page
inside the window ( ).
302
203617-6 Install.F 9/26/01 9:46 AM Page 303
To install Acrobat Reader, insert the CD- Acrobat Reader is a popular and useful program.
ROM disc into a drive. In the screen that There are many files available on the Web that
appears, click Software. Click Acrobat are designed to be viewed using Acrobat Reader.
Reader and then click Install at the bottom Look for files with the .pdf extension. For more
of the screen. Then follow the instructions information about Acrobat Reader, visit the
on your screen to install the program. Web site at www.adobe.com/products/
acrobat/readermain.html.
You can make searching the book more
convenient by copying the .pdf files to your
own computer. Display the contents of the
CD-ROM disc and then copy the PDFs
folder from the CD to your hard drive. This
allows you to easily access the contents of
the book at any time.
FIND TEXT ¤ Type the text you ■ The first instance of ■ Repeat Steps 1
⁄ Click to search want to find. the text is highlighted. and 3 to find the next
for text in the section. instance of the text.
‹ Click Find to start
■ The Find dialog box the search.
appears.
303
213617-6 EULA.F 9/26/01 2:27 PM Page 304
HUNGRY MINDS, INC. the original for backup or archival purposes. You may
END-USER LICENSE AGREEMENT not (i) rent or lease the Software, (ii) copy or
reproduce the Software through a LAN or other
READ THIS. You should carefully read these terms and
network system or through any computer subscriber
conditions before opening the software packet(s)
system or bulletin-board system, or (iii) modify, adapt,
included with this book ("Book"). This is a license
or create derivative works based on the Software.
agreement ("Agreement") between you and Hungry
Minds, Inc. ("HMI"). By opening the accompanying (b) You may not reverse engineer, decompile, or
software packet(s), you acknowledge that you have disassemble the Software. You may transfer the
read and accept the following terms and conditions. If Software and user documentation on a permanent
you do not agree and do not want to be bound by basis, provided that the transferee agrees to accept the
such terms and conditions, promptly return the Book terms and conditions of this Agreement and you retain
and the unopened software packet(s) to the place you no copies. If the Software is an update or has been
obtained them for a full refund. updated, any transfer must include the most recent
update and all prior versions.
1. License Grant. HMI grants to you (either an
individual or entity) a nonexclusive license to use one 4. Restrictions on Use of Individual Programs. You
copy of the enclosed software program(s) (collectively, must follow the individual requirements and
the "Software") solely for your own personal or restrictions detailed for each individual program in the
business purposes on a single computer (whether a What’s on the CD-ROM appendix of this Book. These
standard computer or a workstation component of a limitations are also contained in the individual license
multi-user network). The Software is in use on a agreements recorded on the Software Media. These
computer when it is loaded into temporary memory limitations may include a requirement that after using
(RAM) or installed into permanent memory (hard disk, the program for a specified period of time, the user
CD-ROM, or other storage device). HMI reserves all must pay a registration fee or discontinue use. By
rights not expressly granted herein. opening the Software packet(s), you will be agreeing
to abide by the licenses and restrictions for these
2. Ownership. HMI is the owner of all right, title, and
individual programs that are detailed in the What’s on
interest, including copyright, in and to the compilation
the CD-ROM appendix and on the Software Media.
of the Software recorded on the disk(s) or CD-ROM
None of the material on this Software Media or listed
("Software Media"). Copyright to the individual
in this Book may ever be redistributed, in original or
programs recorded on the Software Media is owned
modified form, for commercial purposes.
by the author or other authorized copyright owner of
each program. Ownership of the Software and all 5. Limited Warranty.
proprietary rights relating thereto remain with HMI
and its licensers. (a) HMI warrants that the Software and Software
Media are free from defects in materials and
3. Restrictions On Use and Transfer. workmanship under normal use for a period of sixty
(60) days from the date of purchase of this Book. If
(a) You may only (i) make one copy of the Software
HMI receives notification within the warranty period
for backup or archival purposes, or (ii) transfer the
of defects in materials or workmanship, HMI will
Software to a single hard disk, provided that you keep
replace the defective Software Media.
304
213617-6 EULA.F 9/26/01 2:27 PM Page 305
(b) HMI AND THE AUTHOR OF THE BOOK pecuniary loss) arising from the use of or inability to
DISCLAIM ALL OTHER WARRANTIES, EXPRESS OR use the Book or the Software, even if HMI has been
IMPLIED, INCLUDING WITHOUT LIMITATION advised of the possibility of such damages.
IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE, WITH (c) Because some jurisdictions do not allow the
RESPECT TO THE SOFTWARE, THE PROGRAMS, THE exclusion or limitation of liability for consequential or
SOURCE CODE CONTAINED THEREIN, AND/OR incidental damages, the above limitation or exclusion
THE TECHNIQUES DESCRIBED IN THIS BOOK. HMI may not apply to you.
DOES NOT WARRANT THAT THE FUNCTIONS 7. U.S. Government Restricted Rights. Use,
CONTAINED IN THE SOFTWARE WILL MEET YOUR duplication, or disclosure of the Software for or on
REQUIREMENTS OR THAT THE OPERATION OF THE behalf of the United States of America, its agencies
SOFTWARE WILL BE ERROR FREE. and/or instrumentalities (the "U.S. Government") is
(c) This limited warranty gives you specific legal subject to restrictions as stated in paragraph (c)(1)(ii)
rights, and you may have other rights that vary from of the Rights in Technical Data and Computer
jurisdiction to jurisdiction. Software clause of DFARS 252.227-7013, or
subparagraphs (c) (1) and (2) of the Commercial
6. Remedies. Computer Software - Restricted Rights clause at FAR
52.227-19, and in similar clauses in the NASA FAR
(a) HMI’s entire liability and your exclusive remedy supplement, as applicable.
for defects in materials and workmanship shall be
limited to replacement of the Software Media, which 8. General. This Agreement constitutes the entire
may be returned to HMI with a copy of your receipt at understanding of the parties and revokes and
the following address: Software Media Fulfillment supersedes all prior agreements, oral or written,
Department, Attn.: ASP.NET: Your visual blueprint for between them and may not be modified or amended
creating Web applications on the .NET framework, except in a writing signed by both parties hereto that
Hungry Minds, Inc., 10475 Crosspoint Blvd., specifically refers to this Agreement. This Agreement
Indianapolis, IN 46256, or call 1-800-762-2974. Please shall take precedence over any other documents that
allow four to six weeks for delivery. This Limited may be in conflict herewith. If any one or more
Warranty is void if failure of the Software Media has provisions contained in this Agreement are held by
resulted from accident, abuse, or misapplication. Any any court or tribunal to be invalid, illegal, or otherwise
replacement Software Media will be warranted for the unenforceable, each and every other provision shall
remainder of the original warranty period or thirty remain in full force and effect.
(30) days, whichever is longer.
(b) In no event shall HMI or the author be liable for
any damages whatsoever (including without limitation
damages for loss of business profits, business
interruption, loss of business information, or any other
305
223617-6 Index.F 9/26/01 9:46 AM Page 306
INDEX
Symbols and Numbers login, 257
password, 258
*.asax. See Global .asax
SQL, 258
*.asmx, 152, 154, 172
Windows 2000, 258
*.aspx, 205
user credentials, 255
*.cs, 152
Windows, 252–257, 260
/bin directory, 152, 176, 184
author’s source code, 300–301
business component, 188
authorization, 260–261
DLL, 178
Web site, 179 B
A banners, 114–115
batch files, 177
Active Directory, 258
Beta 1, 7
Active Server Page (ASPX), 150
Beta 2, 7
ADO.NET, 147, 184
binding
Adobe Acrobat, 300
data, 140, 279
Reader, 301
datagrid, 249
advertisement banners
blocks, 276–277
displaying, 114–115
C#, 276
elements of, 115
Visual Basic, 276
generating income, 114
Boolean
aliases, 177
expressions, 46, 50
anchor tags, 80–81, 106
input, 77
anonymous access, 254
request, 98–99
Antechinus C# Programming Editor, 301
boundaries, 120–121
array
box
creating, 108
check, 27, 91, 98–99
goals, 159
drop-down list, 82, 116–117
index, 63
list, 79
initializing, 108
password, 96
list, 129, 219
text, 27, 91, 110, 116, 119, 122
single-dimension, 56
creating, 97
values, 79
hiding, 97
Web Method, 158
type of, 96
Web services, 158–159
business
XML, 158
layer, 189–191
ASMX file, 152, 154
logic, 176, 188
ASPX (Active Server Page), 150
button
Authentication
controls, 92–93
Basic, 252–253
definition of, 91
cookies, 256
form, 70–71
definition of, 255
graphical, 73, 95
Forms, 256–257, 259
HTML 4.0, 93
Active Directory, 258
hyperlink, 91, 94
CD-ROM, 257
image, 73, 91, 95
HTTP, 258
radio, 27, 78, 91, 100–101
Internet Services Manager (ISM), 256
representing columns, 145
submit, 27, 103, 135, 137, 139, 143
306
223617-6 Index.F 9/26/01 9:46 AM Page 307
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
307
223617-6 Index.F 9/26/01 9:46 AM Page 308
INDEX
collections, 225 creating, 111
cookies, 248 data, 127, 132, 190
definition of, 56 DataGrid, 127, 140–141, 144
enumerating, 56 DataList, 127
headers, 248 declaring, 118
loop, 108 editing, 132
Common Language Runtime (CLR), 3, 274 hiding specific group, 111
Common Language Specification (CLS), 274–275, 283 HTML, 66–67
Common Type System (CTS), 42 naming, 110–111
compiler, 36–37 page, 132, 268–269
components providing a container, 111
.COM, 179 Repeater, 127–129
.NET, 179 Server, 2
business, 188, 190 server-side, 30, 77, 279
control, 183 sorting data, 132
creating simple, 179 specifying, 118
data access, 186 stateful components, 183
definition of, 176, 178 TableCell, 108
multiple, 179 TableRow, 108
simple, 176–178 tree, 248
stateful, 180–183 two equal values, 119
stateless, 180 using placeholder, 111
Web page, 182 validation, 118, 120, 122, 124
Web service, 182 Web page, 134
Computer Management Console, 23 Control Panel, 4, 14, 18, 20–23
conditional statements, 46 conversions, 55
configuration, 3, 17–18, 25 console application, 64
application, 236 explicit, 54, 63
custom, 240–241 implicit, 54
events, 32 cookies, 207
HTML, 194 authentication, 261
session state, 227 collection, 248
setting, 238–239 creating, 230–233
tracing, 250 definition of, 211
URL, 213 expiration date, 231
connection Forms Authentication, 256
object, 134 Internet Information Server (IIS) MMC, 230
string, 185 subkeys, 232–233
console Web browser, 231
application conversions, 64–65 credentials, 258–259
client, 174–175 CTS (Common Type System), 42
container control, 111–113 culture, 264, 265, 266, 267, 268, 269, 272
control CultureInfo, 264, 265
ActiveX, 202 custom
bound, 134 configuration, 240–241
calendar, 121 error handling, 244–246
container, 111–113 modules, 211
settings, 240–241
308 customer order system, 144
223617-6 Index.F 9/26/01 9:46 AM Page 309
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
D database
accessing, 3
data. See also data access
establishing connection, 134
alternating rows, 128
inserting data, 134
binding, 129, 132, 140, 279
DCOM (Distributed Component Object Model), 150
cache, 208
debugging, 239, 248
checking, 120
page-level, 242–243
control, 133
default document, 14
defining layout, 128
delete
deleting, 138–139
data, 138
display, 127–129, 144, 186, 190, 196
SQL database, 139
double-type, 120
Web page, 200
editing control, 132
delimiters, 277
enhance viewing, 133
desktop shortcuts, 21
filtering, 142
DHTML, 72
footers, 128
directives
formatting, 130
application, 216–217
headers, 128
assembly, 216–217
inserting, 134
Global.asax, 216–217
integer-type, 120
import, 216
layer, 188–189
page, 216, 281, 284
list, 187
processing, 218
posting, 92
directory. See also Active Directory
reading, 194
default
repeating, 128
Internet Information Server (IIS), 14
separate rows, 128
home, 8, 9, 10, 13
shared, 166
Internet Information Server (IIS), 12
sorting, 132, 140–141
removing, 11
SQL, 132–137
root, 250
stores, 146, 190, 208
virtual, 10–13, 22, 23
string, 120
web, 20
transporting, 146
Disco (Web Services Discovery), 150, 174
types, 42–43
Distributed Component Object Model (DCOM), 150
data access, 2, 166
DIV, 198
code, 136, 184, 190
DLL
command, 126–127
/bin directory, 178
components, 186
source code, 176
connection, 126
drop-down list, 27, 79, 82, 116
controls, 126
input, 102–103
DataAdapter, 127
validating, 117
DataGrid, 127
DataList, 127 E
definition of, 126
disconnected, 147 e-mail, 5
introduction to, 126 sending, 204–205
layer, 188–189 SMTP server, 204
Repeater, 127 text format, 205
ECMAScript, 287
309
223617-6 Index.F 9/26/01 9:46 AM Page 310
INDEX
encoding flag, 138
attributes, 263 footer, 130
file, 262 form
languages, 262 adding controls, 111
response, 262 attributes, 69
UCS Transformation Format (UTF-8), 262 button, 70–71
enumeration comparing two fields, 118
constant value, 161 event handler, 193
creating, 160 hidden information, 86
error, 62 hidden variable, 87
custom handling, 244–246 HTML, 29, 32
details, 242–243, 247 image, 95
handling programmatically, 246, 247 processing, 122
message, 116, 239 registration, 77
query, 245 resubmitting, 122, 124
stored procedure, 142 server, 76, 100, 120, 131, 133, 141
summarizing validation, 124 validation, 122, 124
troubleshooting, 244 Web, 2, 30–31, 134
validation, 124 Framework SDK, 150
Web page, 200 FTP (File Transfer Protocol) Server, 5
Web server, 238, 239
event, 45 G
application, 220 GAC (Global Assembly Caches), 178
handler, 32–33, 64, 93–94, 99, 104, 192–193, 212, 214, garbage, 182
224, 226 GET, 152
Global.asax, 220–221 global
procedure, 140 assemblies, 178
server-side, 106 variables, 277
exceptions, 63 Global Assembly Caches (GAC), 178
expressions Global.asax, 211
regular, 122–123 application, 218
validating, 122–123 code, 221
creating file, 212–215
F event handlers, 220–221
File Transfer Protocol (FTP) Server, 5 parameters, 221
files processing directives, 216–217
batch, 177 server-side objects, 218–219
converting, 273 session, 218
copying into Web server, 178 statistics, 215
describing data, 146 Globally Unique Identifier (GUID), 89
name, 14, 24, 25 goals, 225
C#, 37 array, 159
nonbinary text, 146 classifying, 160
saving, 25 identifier, 162
sending, 88 list, 165
uploading, 88–89 returning, 165
XML, 114
310
223617-6 Index.F 9/26/01 9:46 AM Page 311
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
graphics I
creating button, 95
IIS (Internet Information Server), 10–11, 13, 17, 210, 228
drop-down list box, 82
default directory, 14
Web browser, 107
installing, 4–5
greeting
log file, 16
displaying, 173
Microsoft Management Console (MMC), 210, 230
personal, 181
virtual directory, 12
GUID (Globally Unique Identifier), 89
Windows Authentication, 252, 260
H IL (Intermediate Language), 274
image, 91
help, 107 aligning, 82
hidden information, 86 border, 83
home directory, 8–10, 13 button, 91, 95
HTML, 150 rendering, 82–83, 107
4.0, 72–73 impersonation, 254–255
4.0 button, 93 input
anchor tags, 81 Boolean, 77
code, 28 checking boundaries, 120–121
configuration, 194 drop-down list, 79, 102–103
container controls, 67 login name, 116
controls, 66–67, 102 multiple line, 76
embedded, 278 parameters, 150
footer, 15 request text, 96
form, 25–27, 29, 32 single line, 74–75
formatting files, 205 soliciting, 102
formatting XML, 148 text, 97
input controls, 67 validating, 122
Image Control, 67 insert
markup, 26, 274 code, 137
page, 28 parameters, 139
server controls, 66–67, 90, 98, 108, 288–291 installing, 4–7
simple page, 196 IIS (Internet Information Server), 4–5
specifying horizontal line, 128 .NET Framework, 6–7
table, 132–133 Intermediate Language (IL), 274
tags, 2, 26, 198 Internet Explorer, 154, 252
transforming XML, 149 Internet Information Server (IIS), 10–11, 13, 17, 210, 228
two-tier web form, 184 default directory, 14
user interface, 64 installing, 4–5
HTTP, 150, 151, 152. See also GET; POST; SOAP log file, 16
application, 211 Microsoft Management Console (MMC), 210, 230
Forms Authentication, 258 virtual directory, 12
request, 69 Windows Authentication, 252, 260
response packets, 200 Internet Information Service (IIS), 20
values, 194 Internet Services Manager (ISM), 5, 10, 16, 18, 20
Windows Authentication, 252 browsing, 21
hyperlink, 91, 145 exploring, 22
creating, 94, 106 Forms Authentication, 256
trace, 250 Windows Authentication, 252, 254
Web browser, 106 311
223617-6 Index.F 9/26/01 9:46 AM Page 312
INDEX
ISM (Internet Services Manager), 5, 10, 16, 18, 20 link
iterative statements, 50 button, 91
links. See also hyperlink
J creating, 80–81, 106
JScript, 287 navigating, 80
assignment statements, 292 lists
case statements, 293 array, 219
comments, 292 box, 79
examples of, 292 comma-separated, 129
exception handling, 295 custom, 128
FOR Loops, 293 data-bound, 187
if...else statements, 292 displaying complex, 130–131
migrating, 286–287 drop-down, 79
object reference, 295 master, 144–145
operators, 297–299 specifying direction, 130
parameters, 294 literals, 109
types, 296 localize, 268, 269
WHILE Loops, 293 log, 16, 17
JScript.NET, 286–287 enable, 16
file, 17
L Internet Information Server (IIS), 16
language, 30 login
C#, 2 Forms Authentication, 257
client-side, 274 input name, 116
CLR (Common Language Runtime), 274 page, 96
CLS (Common Language Specification), 274–275 Loops
compliant, 176 collections, 108
cross-language compatibility, 42 FOR, 293
encoding, 262 WHILE, 293
first class, 283
IL (Intermediate Language), 274
M
industrial strength, 287 machine-wide code, 179
multiple, 272, 274–275 master list, 144–145
object-oriented, 45, 60 master-detail relationships, 144–145
pattern-matching, 122 MDAC (Microsoft Data Access Components), 6
runtime, 179 memory, 63, 301
server-side, 274 message
specifying, 213 displaying, 122, 124
support, 2 header, 124
Visual Basic, 2, 54 string, 176
Web page, 275 summary, 124
Web services, 152 validation, 118, 120, 123
layers methods, 45
business, 188–191 code, 58, 60
data, 188–189 creation, 221
presentation, 188 declaring, 58, 60
user interface, 189 definition of, 58, 60
destruction, 221
312 input parameters, 150
223617-6 Index.F 9/26/01 9:46 AM Page 313
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
INDEX
placeholder render functions, 278–279
tag, 198 images, 107
using for controls, 111 troubleshooting, 279
pop-up Request.Form, 194–195
help text, 107 Request.Params, 196–197
menu, 21 Resource Manager, 270–273
port access, 150 Response.Redirect, 200–201
POST, 151–152 Response.Write, 198–199
testing, 155 return value, 150
postback, 30 rollover effect, 95
power, 3 root directory, 250
procedures runtime, 7, 179
error, 142 error, 41–42
stored, 142–143
program S
object-oriented, 35 scalability, 224
versions, 300 script
properties, 60 blocks, 187, 276–277
access, 44 delimiters, 216
definition of, 44–45 external file, 277
image, 82 server-side, 187, 191
namespace, 44 Secured Sockets Layer (SSL), 252, 258
proxy class, 172, 174–175 security, 3, 23, 210
applications, 255
Q authorization, 260
queries impersonation, 254–255
ad hoc, 142 server,2
control, 142 controls, 2
error, 245 web, 2
string, 195, 199, 201, 206, 245 session
XML engine, 164 code, 213
color, 229
R disable, 170
radio buttons, 27, 100–107 end, 214
ranges Global.asax, 218
currency, 120 in-process, 228
dates, 120 object, 168–169, 182, 211, 227
double-type data, 120 out-of-process, 228
integer-type data, 120 SQL server, 228
string data, 120 start, 214
RDBMS (Relational Database Management System), 126 state, 226–229
redirecting, 200–201 types of, 168
RegionInfo, 266–267 variables, 226, 229
regular expressions, 122–123 settings
Relational Database Management System (RDBMS), 126 application, 236–237
Remote Procedure Calls (RPC), 150 custom, 240–241
signature, 60–61
314
223617-6 Index.F 9/26/01 9:46 AM Page 315
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
INDEX
title page, 185 global, 277
tools hidden, 87
administrative, 8, 10, 14, 20, 22 hidden information, 86
debugging, 65 initialization, 40–43, 48, 180
trace initializing, 108, 286
application-level, 250–251 iteration, 56
configuration, 250 long, 55
hyperlink, 250 private, 180
information, 248–249 public, 180
page-level, 248–250 server, 248
storage, 251 session, 226, 229
virtual directory, 250 setting, 214
Web site, 250 updating, 223
troubleshooting, 17 VB.NET Syntax, 282–283, 285
CD-ROM, 301 migrating, 284
custom errors, 244 VBScript. See Visual Basic
render functions, 279 virtual directory
two-tier web form, 184–187 application, 210
trace, 250
U Visual Basic, 54, 213, 287
UCS Transformation Format (UTF-8), 262, 272 assignment statements, 292
Unicode, 262 case statements, 293
URL comments, 292
configuration, 213 examples of, 292
impersonation, 254 exception handling, 295
passing data, 195 FOR Loops, 293
Web service, 172 if...else statements, 292
user migrating, 282–285
authorization, 260–261 object reference, 295
credentials, 255 operators, 297–299
ID, 134 parameters, 285
passing by reference, 294
V passing by value, 294
validation Request.Form, 194
based on range of values, 120 script blocks, 276
compare fields for, 118 types, 296
enable basic process of, 116 WHILE Loops, 293
summarize errors from, 124 Visual Studio.NET (VS.NET), 6, 21
use regular expressions for, 122 VMware Workstation, 301
variables VS.NET (Visual Studio.NET), 6, 21
application, 170–171, 224–225
converting, 54
W
declaring, 40–41, 48, 292 W3C, 146
defining, 40–41 Web browser, 72, 88
displaying, 197 cookie, 231
fixed values, 160 graphics, 107
form, 197
316
223617-6 Index.F 9/26/01 9:46 AM Page 317
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
317
223617-6 Index.F 9/26/01 9:46 AM Page 318
INDEX
Windows
2000, 204, 254, 258, 260
Authentication, 252–256
CD-ROM, 253
Internet Explorer, 252
Internet Information System (IIS), 252, 260
Internet Services Manager (ISM), 252, 254
Explorer, 11, 22–23
Form
application, 275
Wireless Markup Language (WML), 148
Wizard, 5, 21
Virtual Directory Creation, 11, 13
Windows Component, 4
WML (Wireless Markup Language), 148
WSDL (Web Services Description Language), 150
X
XML
array strings, 158
code, 149
data sources, 146–147
definition of, 236
display, 148–149
file, 114
format, 273
loading documents, 165
request display, 154
Spy IDE, 301
transform, 148–149
Web service, 151, 164
XSL, 148
XSLT, 164
318
223617-6 Index.F 9/26/01 9:46 AM Page 319
ASP.NET:
Your visual blueprint for creating
Web applications on the .NET framework
319
233617-6 BoBAd.F 9/26/01 9:46 AM Page 320
For experienced
computer users,
developers,
network professionals
who learn best visually.
“Apply It” and “Extra” provide ready-to-run code and useful tips.
OD R D M
U M E IRE S F O
P RR EMS S
TM
TRADE & INDIVIDUAL ORDERS EDUCATIONAL ORDERS & DISCOUNTS CORPORATE ORDERS FOR VISUAL SERIES
Phone: (800) 762-2974 Phone: (800) 434-2086 Phone: (800) 469-6616
or (317) 572-3993 (8:30 a.m.–5:00 p.m., CST, weekdays) (8 a.m.–5 p.m., EST, weekdays)
(8 a.m.–6 p.m., CST, weekdays) FAX : (317) 572-4005 FAX : (905) 890-9434
FAX : (800) 550-2747
or (317) 572-4002
Qty ISBN Title Price Total
Subtotal ______________________
• • • • • • • • • • • • • • • • • • • • • • •
Shipping & Handling Charges
Each CA residents add
Description First book add’l. book Total applicable sales tax ___________________
IN, MA and MD
Domestic Normal $4.50 $1.50 $ residents add
Two Day Air $8.50 $2.50 $ 5% sales tax ______________________
Overnight $18.00 $3.00 $
IL residents add
6.25% sales tax __________________________
International Surface $8.00 $8.00 $
Airmail $16.00 $16.00 $ RI residents add
7% sales tax __________________________
DHL Air $17.00 $17.00 $
TX residents add
8.25% sales tax __________________________
Name____________________________________________________________________________________________
Total ______________________
Address __________________________________________________________________________________________
Company ________________________________________________________________________________________
City/State/Zip _____________________________________________________________________________________
Daytime Phone____________________________________________________________________________________