asp.net stage1

168
 Toolkit 2543B: Core Web Application Technolog ies with Microsoft ® Visual Studio® 2005 

Upload: fahmi-tajudin

Post on 29-May-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 1/168

 

Toolkit

2543B:Core Web ApplicationTechnologies with Microsoft® 

Visual Studio®

2005 

Page 2: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 2/168

Information in this document, including URL and other Internet Web site references, is subject to

change without notice. Unless otherwise noted, the example companies, organizations, products,

domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,

and no association with any real company, organization, product, domain name, e-mail address,

logo, person, place, or event is intended or should be inferred. Complying with all applicable

copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part

of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted

in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or 

for any purpose, without the express written permission of Microsoft Corporation.

The names of manufacturers, products, or URLs are provided for informational purposes only and

Microsoft makes no representations and warranties, either expressed, implied, or statutory,

regarding these manufacturers or the use of the products with any Microsoft technologies. The

inclusion of a manufacturer or product does not imply endorsement of Microsoft of the

manufacturer or product. Links are provided to third party sites. Such sites are not under the

control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link 

contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for 

webcasting or any other form of transmission received from any linked site. Microsoft is providing

these links to you only as a convenience, and the inclusion of any link does not imply endorsement

of Microsoft of the site or the products contained therein.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual

 property rights covering subject matter in this document. Except as expressly provided in any

written license agreement from Microsoft, the furnishing of this document does not give you anylicense to these patents, trademarks, copyrights, or other intellectual property.

© 2006 Microsoft Corporation. All rights reserved.

Microsoft, Active Directory, ActiveSync, ActiveX, FrontPage, Hotmail, IntelliSense,

JScript, MSDN, Outlook, PowerPoint, Visual Basic, Visual C#, Visual Studio,

Visual Web Developer, Win32, Windows, and Windows Server  are either registered trademarks or 

trademarks of Microsoft Corporation in the United States and/or other countries.

All other trademarks are property of their respective owners.

1 2 3 4 5 6 7 8 9 QWE 9 8 7 6 5

Course Number: 2543B

Part Number: X12-12609

Released: 2/2006

Page 3: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 3/168

END-USER LICENSE AGREEMENT FOR OFFICIAL MICROSOFT LEARNING PRODUCTS – STUDENT EDITION

PLEASE READ THIS END-USER LICENSE AGREEMENT (“EULA”) CAREFULLY. BY USING THE

MATERIALS AND/OR USING OR INSTALLING THE SOFTWARE THAT ACCOMPANIES THIS EULA

(COLLECTIVELY, THE “LICENSED CONTENT”), YOU AGREE TO THE TERMS OF THIS EULA. IF YOU DO

NOT AGREE, DO NOT USE THE LICENSED CONTENT.

1. GENERAL. This EULA is a legal agreement between you (either an individual or a single entity) and Microsoft

Corporation (“Microsoft”). This EULA governs the Licensed Content, which includes computer software (including onlineand electronic documentation), training materials, and any other associated media and printed materials. This EULA appliesto updates, supplements, add-on components, and Internet-based services components of the Licensed Content that Microsoftmay provide or make available to you unless Microsoft provides other terms with the update, supplement, add-on component,or Internet-based services component. Microsoft reserves the right to discontinue any Internet-based services provided to youor made available to you through the use of the Licensed Content. This EULA also governs any product support servicesrelating to the Licensed Content except as may be included in another agreement between you and Microsoft. An amendmentor addendum to this EULA may accompany the Licensed Content.

2. GENERAL GRANT OF LICENSE. Microsoft grants you the following rights, conditioned on your compliancewith all the terms and conditions of this EULA. Microsoft grants you a limited, non-exclusive, royalty-free license to installand use the Licensed Content solely in conjunction with your participation as a student in an Authorized Training Session (asdefined below). You may install and use one copy of the software on a single computer, device, workstation, terminal, or other digital electronic or analog device ("Device"). You may make a second copy of the software and install it on a portable Devicefor the exclusive use of the person who is the primary user of the first copy of the software. A license for the software may not be shared for use by multiple end users. An “Authorized Training Session” means a training session conducted at a MicrosoftCertified Technical Education Center, an IT Academy, via a Microsoft Certified Partner, or such other entity as Microsoft maydesignate from time to time in writing, by a Microsoft Certified Trainer (for more information on these entities, please visitwww.microsoft.com). WITHOUT LIMITING THE FOREGOING, COPYING OR REPRODUCTION OF THE LICENSEDCONTENT TO ANY SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION ISEXPRESSLY PROHIBITED.

3. DESCRIPTION OF OTHER RIGHTS AND LICENSE LIMITATIONS

3.1 Use of Documentation and Printed Training Materials.

3.1.1 The documents and related graphics included in the Licensed Content may include technicalinaccuracies or typographical errors. Changes are periodically made to the content. Microsoft may make improvementsand/or changes in any of the components of the Licensed Content at any time without notice. The names of companies, products, people, characters and/or data mentioned in the Licensed Content may be fictitious and are in no way intended torepresent any real individual, company, product or event, unless otherwise noted.

3.1.2 Microsoft grants you the right to reproduce portions of documents (such as student workbooks,white papers, press releases, datasheets and FAQs) (the “Documents”) provided with the Licensed Content. You may not print any book (either electronic or print version) in its entirety. If you choose to reproduce Documents, you agree that:(a) use of such printed Documents will be solely in conjunction with your personal training use; (b) the Documents will notrepublished or posted on any network computer or broadcast in any media; (c) any reproduction will include either theDocument’s original copyright notice or a copyright notice to Microsoft’s benefit substantially in the format provided below;and (d) to comply with all terms and conditions of this EULA. In addition, no modifications may made to any Document.

“Form of Notice:© 2006. Reprinted with permission by Microsoft Corporation. All rights reserved.

Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the US

and/or other countries. Other product and company names mentioned herein may be the trademarks of their respective owners.”

3.2 Use of Media Elements. The Licensed Content may include certain photographs, clip art, animations,sounds, music, and video clips (together "Media Elements"). You may not modify these Media Elements.

3.3 Use of Sample Code. In the event that the Licensed Content include sample source code (“Sample Code”),Microsoft grants you a limited, non-exclusive, royalty-free license to use, copy and modify the Sample Code; if you elect toexercise the foregoing rights, you agree to comply with all other terms and conditions of this EULA, including withoutlimitation Sections 3.4, 3.5, and 6.

Page 4: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 4/168

3.4 Permitted Modifications. In the event that you exercise any rights provided under this EULA to createmodifications of the Licensed Content, you agree that any such modifications: (a) will not be used for providing trainingwhere a fee is charged in public or private classes; (b) indemnify, hold harmless, and defend Microsoft from and against anyclaims or lawsuits, including attorneys’ fees, which arise from or result from your use of any modified version of the LicensedContent; and (c) not to transfer or assign any rights to any modified version of the Licensed Content to any third party withoutthe express written permission of Microsoft.

3.5 Reproduction/Redistribution Licensed Content. Except as expressly provided in this EULA, you may notreproduce or distribute the Licensed Content or any portion thereof (including any permitted modifications) to any third

 parties without the express written permission of Microsoft.4. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to you inthis EULA. The Licensed Content is protected by copyright and other intellectual property laws and treaties. Microsoft or itssuppliers own the title, copyright, and other intellectual property rights in the Licensed Content. You may not remove or obscure any copyright, trademark or patent notices that appear on the Licensed Content, or any components thereof, asdelivered to you. The Licensed Content is licensed, not sold.

5. LIMITATIONS ON REVERSE ENGINEERING, DECOMPILATION, AND DISASSEMBLY. You may notreverse engineer, decompile, or disassemble the Software or Media Elements, except and only to the extent that such activityis expressly permitted by applicable law notwithstanding this limitation.

6. LIMITATIONS ON SALE, RENTAL, ETC. AND CERTAIN ASSIGNMENTS. You may not provide commercialhosting services with, sell, rent, lease, lend, sublicense, or assign copies of the Licensed Content, or any portion thereof (including any permitted modifications thereof) on a stand-alone basis or as part of any collection, product or service.

7. CONSENT TO USE OF DATA. You agree that Microsoft and its affiliates may collect and use technicalinformation gathered as part of the product support services provided to you, if any, related to the Licensed Content.Microsoft may use this information solely to improve our products or to provide customized services or technologies to youand will not disclose this information in a form that personally identifies you.

8. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed Content. Thethird party sites are not under the control of Microsoft, and Microsoft is not responsible for the contents of any third partysites, any links contained in third party sites, or any changes or updates to third party sites. Microsoft is not responsible for webcasting or any other form of transmission received from any third party sites. Microsoft is providing these links to third party sites to you only as a convenience, and the inclusion of any link does not imply an endorsement by Microsoft of the third party site.

9. ADDITIONAL LICENSED CONTENT/SERVICES. This EULA applies to updates, supplements, add-oncomponents, or Internet-based services components, of the Licensed Content that Microsoft may provide to you or makeavailable to you after the date you obtain your initial copy of the Licensed Content, unless we provide other terms along with

the update, supplement, add-on component, or Internet-based services component. Microsoft reserves the right to discontinueany Internet-based services provided to you or made available to you through the use of the Licensed Content.

10. U.S. GOVERNMENT LICENSE RIGHTS. All software provided to the U.S. Government pursuant to solicitationsissued on or after December 1, 1995 is provided with the commercial license rights and restrictions described elsewhereherein. All software provided to the U.S. Government pursuant to solicitations issued prior to December 1, 1995 is providedwith “Restricted Rights” as provided for in FAR, 48 CFR 52.227-14 (JUNE 1987) or DFAR, 48 CFR 252.227-7013 (OCT1988), as applicable.

11. EXPORT RESTRICTIONS. You acknowledge that the Licensed Content is subject to U.S. export jurisdiction. Youagree to comply with all applicable international and national laws that apply to the Licensed Content, including the U.S.Export Administration Regulations, as well as end-user, end-use, and destination restrictions issued by U.S. and other governments. For additional information see <http://www.microsoft.com/exporting/>.

12. TRANSFER. The initial user of the Licensed Content may make a one-time permanent transfer of this EULA andLicensed Content to another end user, provided the initial user retains no copies of the Licensed Content. The transfer may

not be an indirect transfer, such as a consignment. Prior to the transfer, the end user receiving the Licensed Content mustagree to all the EULA terms.

13. “NOT FOR RESALE” LICENSED CONTENT. Licensed Content identified as “Not For Resale” or “NFR,” maynot be sold or otherwise transferred for value, or used for any purpose other than demonstration, test or evaluation.

14. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this EULA if you fail to complywith the terms and conditions of this EULA. In such event, you must destroy all copies of the Licensed Content and all of itscomponent parts.

15. DISCLAIMER OF WARRANTIES. To the maximum extent permitted by applicable law, Microsoft and itssuppliers provide the LICENSED CONTENT and support services (if any) AS IS AND WITH ALL FAULTS, and Microsoftand its suppliers hereby disclaim all OTHER warranties and conditions, whether express, implied or statutory, including, but

Page 5: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 5/168

not limited to, any (if any) IMPLIED warranties, DUTIES or conditions of MERCHANTABILITY, OF fitness for a particular  purpose, OF RELIABILITY OR AVAILABILITY, OF ACCURACY OR COMPLETENESS OF RESPONSES, OFRESULTS, OF WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE, ALL WITHREGARD TO THE LICENSED CONTENT, AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT OR OTHER SERVICES, INFORMATION, SOFTWARE, AND RELATED CONTENT THROUGH THE LICENSEDCONTENT, OR OTHERWISE ARISING OUT OF THE USE OF THE LICENSED CONTENT. also, there is no warrantyor condition of title, quiet enjoyment, quiet possession, correspondence to description or non-infringement with regard to theLICENSED CONTENT. THE ENTIRE RISK AS TO THE QUALITY, OR ARISING OUT OF THE USE OR PERFORMANCE OF THE LICENSED CONTENT, AND ANY SUPPORT SERVICES, REMAINS WITH YOU.

16. EXCLUSION OF INCIDENTAL, CONSEQUENTIAL AND CERTAIN OTHER DAMAGES. To the maximumextent permitted by applicable law, in no event shall Microsoft or its suppliers be liable for any special, incidental, punitive,indirect, or consequential damages whatsoever (including, but not limited to, damages for loss of profits or confidential or other information, for business interruption, for personal injury, for loss of privacy, for failure to meet any duty including of good faith or of reasonable care, for negligence, and for any other pecuniary or other loss whatsoever) arising out of or in anyway related to the use of or inability to use the LICENSED CONTENT, the provision of or failure to provide Support OR OTHER Services, informatIon, software, and related CONTENT through the LICENSED CONTENT, or otherwise arisingout of the use of the LICENSED CONTENT, or otherwise under or in connection with any provision of this EULA, even inthe event of the fault, tort (including negligence), misrepresentation, strict liability, breach of contract or breach of warranty of Microsoft or any supplier, and even if Microsoft or any supplier has been advised of the possibility of such damages.BECAUSE SOME STATES/JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITYFOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.

17. LIMITATION OF LIABILITY AND REMEDIES. NOTWITHSTANDING ANY DAMAGES THAT YOUMIGHT INCUR FOR ANY REASON WHATSOEVER (INCLUDING, WITHOUT LIMITATION, ALL DAMAGESREFERENCED HEREIN AND ALL DIRECT OR GENERAL DAMAGES IN CONTRACT OR ANYTHING ELSE), THEENTIRE LIABILITY OF MICROSOFT AND ANY OF ITS SUPPLIERS UNDER ANY PROVISION OF THIS EULAAND YOUR EXCLUSIVE REMEDY HEREUNDER SHALL BE LIMITED TO THE GREATER OF THE ACTUALDAMAGES YOU INCUR IN REASONABLE RELIANCE ON THE LICENSED CONTENT UP TO THE AMOUNTACTUALLY PAID BY YOU FOR THE LICENSED CONTENT OR US$5.00. THE FOREGOING LIMITATIONS,EXCLUSIONS AND DISCLAIMERS SHALL APPLY TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLELAW, EVEN IF ANY REMEDY FAILS ITS ESSENTIAL PURPOSE.

18. APPLICABLE LAW. If you acquired this Licensed Content in the United States, this EULA is governed by thelaws of the State of Washington. If you acquired this Licensed Content in Canada, unless expressly prohibited by local law,this EULA is governed by the laws in force in the Province of Ontario, Canada; and, in respect of any dispute which may arisehereunder, you consent to the jurisdiction of the federal and provincial courts sitting in Toronto, Ontario. If you acquired thisLicensed Content in the European Union, Iceland, Norway, or Switzerland, then local law applies. If you acquired this

Licensed Content in any other country, then local law may apply.19. ENTIRE AGREEMENT; SEVERABILITY. This EULA (including any addendum or amendment to this EULAwhich is included with the Licensed Content) are the entire agreement between you and Microsoft relating to the LicensedContent and the support services (if any) and they supersede all prior or contemporaneous oral or written communications, proposals and representations with respect to the Licensed Content or any other subject matter covered by this EULA. To theextent the terms of any Microsoft policies or programs for support services conflict with the terms of this EULA, the terms of this EULA shall control. If any provision of this EULA is held to be void, invalid, unenforceable or illegal, the other  provisions shall continue in full force and effect.

Should you have any questions concerning this EULA, or if you desire to contact Microsoft for any reason, please use theaddress information enclosed in this Licensed Content to contact the Microsoft subsidiary serving your country or visitMicrosoft on the World Wide Web at http://www.microsoft.com.

Si vous avez acquis votre Contenu Sous Licence Microsoft au CANADA :

DÉNI DE GARANTIES. Dans la mesure maximale permise par les lois applicables, le Contenu Sous Licence et les servicesde soutien technique (le cas échéant) sont fournis TELS QUELS ET AVEC TOUS LES DÉFAUTS par Microsoft et sesfournisseurs, lesquels par les présentes dénient toutes autres garanties et conditions expresses, implicites ou en vertu de la loi,notamment, mais sans limitation, (le cas échéant) les garanties, devoirs ou conditions implicites de qualité marchande,d’adaptation à une fin usage particulière, de fiabilité ou de disponibilité, d’exactitude ou d’exhaustivité des réponses, desrésultats, des efforts déployés selon les règles de l’art, d’absence de virus et d’absence de négligence, le tout à l’égard duContenu Sous Licence et de la prestation des services de soutien technique ou de l’omission de la ’une telle prestation desservices de soutien technique ou à l’égard de la fourniture ou de l’omission de la fourniture de tous autres services,renseignements, Contenus Sous Licence, et contenu qui s’y rapporte grâce au Contenu Sous Licence ou provenant autrement

Page 6: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 6/168

de l’utilisation du Contenu Sous Licence. PAR AILLEURS, IL N’Y A AUCUNE GARANTIE OU CONDITION QUANTAU TITRE DE PROPRIÉTÉ, À LA JOUISSANCE OU LA POSSESSION PAISIBLE, À LA CONCORDANCE À UNEDESCRIPTION NI QUANT À UNE ABSENCE DE CONTREFAÇON CONCERNANT LE CONTENU SOUS LICENCE.

EXCLUSION DES DOMMAGES ACCESSOIRES, INDIRECTS ET DE CERTAINS AUTRES DOMMAGES. DANS LAMESURE MAXIMALE PERMISE PAR LES LOIS APPLICABLES, EN AUCUN CAS MICROSOFT OU SESFOURNISSEURS NE SERONT RESPONSABLES DES DOMMAGES SPÉCIAUX, CONSÉCUTIFS, ACCESSOIRES OUINDIRECTS DE QUELQUE NATURE QUE CE SOIT (NOTAMMENT, LES DOMMAGES À L’ÉGARD DU MANQUE À

GAGNER OU DE LA DIVULGATION DE RENSEIGNEMENTS CONFIDENTIELS OU AUTRES, DE LA PERTED’EXPLOITATION, DE BLESSURES CORPORELLES, DE LA VIOLATION DE LA VIE PRIVÉE, DE L’OMISSION DEREMPLIR TOUT DEVOIR, Y COMPRIS D’AGIR DE BONNE FOI OU D’EXERCER UN SOIN RAISONNABLE, DE LA NÉGLIGENCE ET DE TOUTE AUTRE PERTE PÉCUNIAIRE OU AUTRE PERTE DE QUELQUE NATURE QUE CESOIT) SE RAPPORTANT DE QUELQUE MANIÈRE QUE CE SOIT À L’UTILISATION DU CONTENU SOUSLICENCE OU À L’INCAPACITÉ DE S’EN SERVIR, À LA PRESTATION OU À L’OMISSION DE LA ’UNE TELLEPRESTATION DE SERVICES DE SOUTIEN TECHNIQUE OU À LA FOURNITURE OU À L’OMISSION DE LAFOURNITURE DE TOUS AUTRES SERVICES, RENSEIGNEMENTS, CONTENUS SOUS LICENCE, ET CONTENUQUI S’Y RAPPORTE GRÂCE AU CONTENU SOUS LICENCE OU PROVENANT AUTREMENT DE L’UTILISATIONDU CONTENU SOUS LICENCE OU AUTREMENT AUX TERMES DE TOUTE DISPOSITION DE LA U PRÉSENTECONVENTION EULA OU RELATIVEMENT À UNE TELLE DISPOSITION, MÊME EN CAS DE FAUTE, DE DÉLITCIVIL (Y COMPRIS LA NÉGLIGENCE), DE RESPONSABILITÉ STRICTE, DE VIOLATION DE CONTRAT OU DEVIOLATION DE GARANTIE DE MICROSOFT OU DE TOUT FOURNISSEUR ET MÊME SI MICROSOFT OU TOUTFOURNISSEUR A ÉTÉ AVISÉ DE LA POSSIBILITÉ DE TELS DOMMAGES.

LIMITATION DE RESPONSABILITÉ ET RECOURS. MALGRÉ LES DOMMAGES QUE VOUS PUISSIEZ SUBIR POUR QUELQUE MOTIF QUE CE SOIT (NOTAMMENT, MAIS SANS LIMITATION, TOUS LES DOMMAGESSUSMENTIONNÉS ET TOUS LES DOMMAGES DIRECTS OU GÉNÉRAUX OU AUTRES), LA SEULERESPONSABILITÉ ’OBLIGATION INTÉGRALE DE MICROSOFT ET DE L’UN OU L’AUTRE DE SESFOURNISSEURS AUX TERMES DE TOUTE DISPOSITION DEU LA PRÉSENTE CONVENTION EULA ET VOTRERECOURS EXCLUSIF À L’ÉGARD DE TOUT CE QUI PRÉCÈDE SE LIMITE AU PLUS ÉLEVÉ ENTRE LESMONTANTS SUIVANTS : LE MONTANT QUE VOUS AVEZ RÉELLEMENT PAYÉ POUR LE CONTENU SOUSLICENCE OU 5,00 $US. LES LIMITES, EXCLUSIONS ET DÉNIS QUI PRÉCÈDENT (Y COMPRIS LES CLAUSES CI-DESSUS), S’APPLIQUENT DANS LA MESURE MAXIMALE PERMISE PAR LES LOIS APPLICABLES, MÊME SITOUT RECOURS N’ATTEINT PAS SON BUT ESSENTIEL.

À moins que cela ne soit prohibé par le droit local applicable, la présente Convention est régie par les lois de la provinced’Ontario, Canada. Vous consentez Chacune des parties à la présente reconnaît irrévocablement à la compétence des tribunauxfédéraux et provinciaux siégeant à Toronto, dans de la province d’Ontario et consent à instituer tout litige qui pourraitdécouler de la présente auprès des tribunaux situés dans le district judiciaire de York, province d’Ontario.

Au cas où vous auriez des questions concernant cette licence ou que vous désiriez vous mettre en rapport avec Microsoft pour quelque raison que ce soit, veuillez utiliser l’information contenue dans le Contenu Sous Licence pour contacter la filiale desuccursale Microsoft desservant votre pays, dont l’adresse est fournie dans ce produit, ou visitez écrivez à : Microsoft sur leWorld Wide Web à http://www.microsoft.com

Page 7: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 7/168

2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005 iii

Contents

Unit 1: Creating a Web Application 

Types of Web Sites in Visual Web Developer ........................................................1 

How to: Create a File System Web Site .................................................................. 4 Sample Page Design................................................................................................5 

How to: Create a Simple Web Page in Visual Web Developer...............................6 

ASP.NET Web Page Code Model.........................................................................11 

How to: Build a Web Application......................................................................... 17 

<customErrors> Element.......................................................................................18 

<compilation> Element ......................................................................................... 20 

Unit 2: Programming a Web Application 

How to Determine Which Web Server Control Raised an Event..........................21 

The HttpServerUtility Transfer Method ................................................................ 23 

How to: Pass Values Between ASP.NET Web Pages ...........................................24 

How to: Connect Multiple Events to a Single Event Handler in ASP.NETPages......................................................................................................................26 

The Button.Command Event .................................................................................28 

How to: Detect Browser Capabilities .................................................................... 32 

How to: Access Page Header Information.............................................................34 

How to: Handle Page-Level Errors........................................................................35 

How to: Handle Application-Level Errors ............................................................ 36 

Unit 3: Adding and Configuring Server Controls 

Survey.aspx Page Design—HTML Controls.........................................................37 

How to: Add HTML Server Controls to a Web Forms Page by Using theWeb Forms Designer.............................................................................................38 

HTML Controls for ASP.NET Web Pages............................................................39 How to: Add HTML Markup to Web Pages .........................................................40 

Survey.aspx Page Design–Web Server Controls...................................................42 

Introduction to ASP.NET Web Server Controls....................................................43 

Standard Toolbox Controls....................................................................................46 

How to: Create a Simple Web Page by Using Visual Web Developer..................48 

How to: Set ASP.NET Control Properties.............................................................53 

How to: Add Web Server Controls to a Web Forms Page by Using theWeb Forms Designer.............................................................................................54 

  Navigation Controls...............................................................................................55 

The Button.OnClientClick Property ......................................................................57 

How to: Determine How an ASP.NET Web Page Was Invoked .......................... 58 Cross-Page Posting in an ASP.NET Web Page.....................................................59 

How to: Post an ASP.NET Page to a Different Page.............................................61 

Unit 4: Creating a Common Layout by Using Master Pages 

Master Pages Overview.........................................................................................63 

How to: Create a Master Page ............................................................................... 67 

How to: Configure Content Pages .........................................................................68 

How to: Create Nested Master Pages ....................................................................70

Page 8: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 8/168

iv 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Unit 5: Managing State for a Web Application 

ASP.NET State Management Overview................................................................73 

What’s New in ASP.NET State Management ....................................................... 77 

ASP.NET ViewState .............................................................................................78 

Initializing the ASP.NET Application and Session Objects..................................80 

How to: Save Values in Session State ................................................................... 81 

How to: Read Values from Session State ..............................................................82 

How to: Save Values in Application State.............................................................83 

How to: Read Values from Application State .......................................................84 

How to: Implement Out-of-Process Session State.................................................85 

How to: Store and Retrieve State Data in the Cache Object..................................87 

How to: Define Dependencies Between Cached Items ......................................... 89 

How to: Delete Cached Data .................................................................................90 

How to: Implement Deletion Notifications in Cached Data..................................91 

Unit 6: Accessing and Displaying Data 

How to: Create and Retrieve Database Connections .............................................93 

Products.aspx Page Design....................................................................................96 How to: Access Data by Using SqlDataSource Controls ...................................... 97 

How to: Access Data by Using ASP.NET Data-Bound Controls........................100 

How to: Access and Display Data by Using the GridView Control....................104  

How to: Access Objects as Data by Using ObjectDataSource Controls..............106 

How to: Access XML Data by Using XmlDataSource Controls.........................114 

Unit 7: Controlling Access to a Web Application 

How to Configure Authentication for a Web Application...................................117 

How to: Configure Authorization for a Web Application ...................................120 

Introduction to Membership ................................................................................ 122 

How to: Configure an ASP.NET Application to Use Membership .....................125 

How to: Manage Users by Using Membership....................................................127 Login and Membership Page Design...................................................................129 

How to: Implement a Login Page and Add Login Controls ................................132 

How to: Create a Membership Management Administrative User Interface....... 134 

Unit 8: Deploying a Web Application 

Features of the Copy Web Site Utility.................................................................137 

How to: Deploy a Web Site by Using the Copy Web Site Utility.......................139  

Features of the Publish Web Site Utility .............................................................141 

How to: Precompile and Deploy a Web Site by Using the Publish Web Site

Utility...................................................................................................................143  

Features of Windows Installer Setup Projects ..................................................... 144 

How to: Create a Windows Installer Package for Deploying a Web Application145 Unit 9: Making Web Applications Available to Mobile Devices 

How to: Detect and Redirect Mobile Devices ..................................................... 147 

How to: Browse Mobile Web Pages with Specific Device Emulators................ 149 

How to: Design and Implement a Mobile Web Form..........................................151 

Mobile Controls...................................................................................................153 

How to: Design Device Specific Features for a Mobile Web Form....................155 

Page 9: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 9/168

 

Unit 1: Creating a Web Application

Types of Web Sites in Visual Web Developer You can use Microsoft® Visual Studio® 2005 to create and work with Microsoft

ASP.NET Web sites (Web applications) in a variety of hosting scenarios: localInternet Information Services (IIS), file system, FTP, and remote sites.

Local IIS Web Sites

Local IIS Web sites run using a copy of IIS that is installed on your computer.

When you create a local IIS Web site, the pages and folders for your site arestored in a folder under the default IIS folder for Web sites (Inetpub\wwwroot).Visual Studio 2005 also creates the appropriate IIS configuration so that theWeb site is recognized by IIS as an application.

To create a local IIS Web site, you need Administrator privileges on the

computer.

Alternatively, you can create an IIS virtual directory in Visual Studio 2005. In

this case, the pages and folders for your Web site can be placed in anyaccessible folder; a virtual directory in your local copy of IIS points to this

location.

File System Web Sites

In a file-system Web site, you can create files in any folder you like, whether on

your local computer or in a folder on another computer that you access across anetwork share. You do not need to run IIS on your computer. Instead, you cantest pages by using the Visual Studio 2005 Development Web server.

The Visual Studio 2005 Development Web server works locally. It

cannot serve pages to another computer and is therefore suitable only for testing pages locally.

If you create a file-system Web site, you can later create an IIS virtual directorythat points to the Web site.

Note

Note

Page 10: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 10/168

2 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

FTP Sites

Visual Studio 2005 allows you to open and edit Web sites that are accessible byusing an FTP server. This is a typical scenario if your Web site is located on ahosting site.

You can connect from within Visual Studio 2005 to any FTP server on whichyou have read/write privileges. You can then create and edit Web pages on thatserver. If the FTP server is configured with ASP.NET and an IIS virtual rootthat points to the FTP directory, you can also run your pages from the server to

test them.

Remote Web Sites

A remote Web site is a site that uses IIS but is on another computer that you can

access over a local area network. The remote computer must have IIS installedand must be configured with Microsoft Office FrontPage® 2002 Server 

Extensions. When you create a remote Web site, the pages and folders for your 

site are stored in the default IIS folder on the remote computer. When you runthe pages, they are served by using IIS on the remote computer.

Choosing a Web Site Type

The following table summarizes the types of Web sites you can create in VisualStudio 2005 and when you should choose each type.

Web site type Use when

Local IIS Web site You want to create Web pages on your local computer 

and you have IIS installed. A local IIS Web site is also

suitable if you want to make your site accessible to other 

computers.Advantages:

•  The site is accessible from other computers.

•  You can test IIS features such as HTTP-based

authentication, application pooling, and ISAPI filters.

Disadvantages:

•  You must have administrative rights to create or 

debug IIS Web sites.

•  Only one user on the computer can debug IIS at any

one time.

•  Local IIS Web sites have remote access enabled by

default, which you might not want.

Page 11: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 11/168

Unit 1: Creating a Web Application 3

(continued )

Web site type Use when

File-system Web site You want to create Web pages on your local computer or 

on a shared drive and you do not have IIS installed.

You can create a file-system Web site and later create an

IIS virtual directory that points to the folder containingyour pages.

Advantages:

•  The site can be accessed only from the local

computer, reducing security vulnerabilities.

•  You do not need to have IIS installed on your 

computer.

•  You do not need administrative rights to create or 

debug local Web sites.

•  If the computer is configured to allow remote desktop

connections, multiple users can create and debug local

sites at the same time.Disadvantages:

•  You cannot test IIS features, such as HTTP-based

authentication, application pooling, and ISAPI filters.

FTP site Your site already exists on a remote computer that has

 been configured as an FTP server.

You cannot create an FTP Web site—you can only open

one.

Advantages:

•  You can test the Web site on the server where it will

actually be deployed.

Disadvantages:

•  You do not have local copies of the files unless you

copy them yourself.

Remote Web site You want to create a Web site by using IIS running on a

remote computer. The remote computer must be

configured with FrontPage Server Extensions.

Advantages:

•  You can test the Web site on the server where it will

actually be deployed.

•  Multiple developers can work against the same site at

the same time.

Disadvantages:

•  Configuration for debugging can be complex.

•  Only one developer can debug the application at any

one time. All other requests are suspended while the

developer is debugging the Web site.

Page 12: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 12/168

4 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Create a File System Web SiteIn a file-system Web site, you store the files for your application in a folder onyour local computer or on a computer that is accessible on your network. File-system Web sites are useful for developing locally on your computer because

you do not need Internet Information Services (IIS) to create or test them.

 To create a file-system Web site

1.  In Microsoft® Visual Studio® 2005, on the File menu, point to New and then

click Web Site.

2.  Under Visual Studio installed templates, select the template for the type of 

Web site you want to create.

3.  In the Location list, click File System.

4.  In the Language list, click the language you want to use as the default

 programming language for the Web application.

5.  In the Location text box, type the path and folder where you want to create

the Web site. You can specify a local path or a UNC path to a different

computer on your network.

6.  If you prefer to browse to an existing location, do the following:

a.  Click Browse.

 b.  In the Choose Location dialog box, click the File System tab.

c.  In the File System tree, select the folder you want to use or type the path

in the Folder box.

d.  To create a new folder, select the location, click Create New Folder,

and then type a name for the new folder.

e.  Click Open to return to the New Web Site dialog box.

7.  Click OK .Visual Studio 2005 creates the site, opens a default page in the page

designer, and then displays the folder in Solution Explorer.

If the path you specified already contains files, Visual Studio 2005 prompts youto specify a different location, open the existing Web site, or create the Web site

anyway. In the last case, the files that are created with the Web site overwriteany files with the same name that are already in the folder.

Page 13: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 13/168

Unit 1: Creating a Web Application 5

Sample Page DesignThe following diagram shows the page layout required for the Default.aspx prototype that you will develop in the lab.

Page 14: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 14/168

6 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Create a Simple Web Page in Visual WebDeveloper 

Microsoft® Visual Web Developer ™ is the environment in Microsoft VisualStudio® 2005 that is used to create and work with Microsoft ASP.NET Web

applications. Tasks described in this How-to document include:

  Familiarizing yourself with Visual Web Developer 

  Creating a single-file ASP.NET page in Visual Web Developer 

  Adding controls

When you create a new Web application, Visual Web Developer creates a new

 page named Default.aspx. Visual Web Developer displays the page in Sourceview by default. This view displays the HTML description of the page, as

shown in the following illustration:

To switch to different views, you can use the view tabs feature of the VisualStudio 2005 integrated development environment (IDE). For more information

about the view tabs, refer to the next section of this document.

Page 15: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 15/168

Unit 1: Creating a Web Application 7

A Tour of Visual Web Developer 

Before you begin working on a Web page, it is useful to familiarize yourself with the Visual Web Developer development environment. The followingillustration shows you the windows and tools that are available in Visual Web

Developer:

The following list describes the most commonly used windows and tools. (Only

the windows and tools marked in the preceding illustration are listed here.)

  Toolbars. Provide commands for formatting text, finding text, and so on.

Some toolbars are available only when you are working in Design view.

  Solution Explorer . Displays the files and folders on your Web site.   Document windows. Display the documents you are working on in tabbed

windows. You can switch between documents by clicking tabs.

   Properties window. Allows you to change page settings, HTML elements,

controls, and other objects.

  View tabs. Present you with different views of the same document. Design

view is a near-WYSIWYG editing surface. Source view is the HTML editor for the page. You will work with these views later in this walkthrough. If 

you prefer to open Web pages in Design view, on the Tools menu, click 

Options, select the HTML Designer node, and then change the Start

Pages In option.

  Toolbox. Provides controls and HTML elements that you can drag onto your  page. Toolbar elements are grouped by common function.

  Server Explorer . Displays database connections. If Server Explorer is not

visible in Visual Web Developer, on the View menu, click Other Windows 

and then click Server Explorer.

You can rearrange and resize the windows to suit your preferences. TheView menu allows you to display additional windows.Note

Page 16: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 16/168

8 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Adding Existing Items to a Web Application

You can add existing items, such as Web pages, graphics, and XML files, toWeb applications.

To add an existing item to the Web site1.  Select the Web application (or a subfolder of the application) in the Solution

Explorer window.

2.  On the Website menu, click Add Existing Item.

You can also right-click the Web application in the Solution Explorer window and then from the shortcut menu, click Add Existing Item.

3.  Browse to the location of the file (or files) you want to add to the Web

application, and then select the items to add.

4.  Click Open.

Creating a New Web Forms Page

You can use the Default.aspx page as the home page for your Web site.However, for this lab, you will create and work with a new page. You can addmany types of pages and components to your Web site, including plain HTML

 pages, cascading style sheets, Web configuration files, and ASP.NET WebForms.

To add a new page to the Web site1.  Close the Default.aspx page (if it is open).

2.  In Solution Explorer, right-click the Web site (for example, C:\WebSite)

and then click Add New Item.

3.  Under Visual Studio installed templates, click Web Form.

4.  In the Name box, type FirstWebPage.

5.  In the Language list, choose the programming language you prefer to use

(Microsoft Visual Basic® or C#).

When you created the Web site, you specified a default language. However,

each time you create a new page or component for your Web site, you canchange the language from the default. You can use different programming

languages in the same Web site.

6.  Clear the Place code in separate file box.

In this example, you are creating a single-file page with the code and HTMLin the same page. The code for ASP.NET Web Forms can be embedded in

the page or located in a separate class file.

7.  Click Add. Visual Web Developer creates the new page and opens it inSource view.

Note

Page 17: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 17/168

Unit 1: Creating a Web Application 9

Adding HTML to the Page

In this part of the example, you will add some static HTML text to the page.

To add text to the page

1.  At the bottom of the document window, click the Design tab to switch toDesign view. Design view displays the page that you are working on in a

WYSIWYG-like way. At this point, you do not have any text or controls on

the page, so the page is blank.

2.  On the page, type Welcome to Visual Web Developer.

3.  Switch to Source view. You can see the HTML that you created by typing in

Design view.

Adding and Programming Controls

You can add controls to a Web Form. The following procedure describes howto add a Button, TextBox, and Label control to the page and how to write codeto handle the Click event for the Button control.

To add controls to the page1.  Click the Design tab to switch to Design view.

2.  Press ENTER a few times to make some room.

3.  In the Toolbox, from the Standard group, drag three controls onto the page:

a TextBox control, a Button control, and a Label control.

4.  Click on the page directly above the TextBox control, and then type Enter

your name.

This static HTML text is the caption for the TextBox control. You can mixstatic HTML and server controls on the same page.

Page 18: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 18/168

10 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Setting Control Properties

Visual Web Developer offers you various ways to set the properties of controlson the page. In this part of the example, you will set properties in both Designview and Source view.

To set control properties1.  Select the Button control, and then in the Properties window, set the Text 

 property to Display Name.

2.  Switch to Source view.

Source view displays the HTML for the page, including the elements thatVisual Web Developer has created for the server controls. Controls are

declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute runat="server".

Control properties are declared as HTML attributes. For example, when youset the Text property for the Button control in step 1, you were actually

setting the Text HTML attribute of the control.

The controls are inside a <form> element, which also has theattribute runat="server". The runat="server" attribute and the asp: 

 prefix for control tags marks the controls so that they are processed byASP.NET on the Web server when the page runs. Code outside of 

<form runat="server"> and <script runat="server"> elements isinterpreted by the browser as client-side code.

3.  Click to position the insertion point after the text Label in the <asp:Label> 

tag, and then press SPACEBAR.

A drop-down list appears that displays the list of properties you can set for aLabel control. This feature, referred to as IntelliSense®, helps you in Source

view with the syntax of server controls, HTML elements, and other items onthe page.

4.  Select ForeColor and then type an equals sign. IntelliSense displays a list of 

available colors.

You can display an IntelliSense drop-down list at any time by pressing CTRL+J.

5.  Select a color for the Label control’s text.

The ForeColor attribute is set to the color that you have selected.

Note

Note

Page 19: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 19/168

Unit 1: Creating a Web Application 11

ASP.NET Web Page Code ModelA Microsoft® ASP.NET Web page consists of two parts:

  Visual elements, which include HTML markup tags and static text

  Programming logic for the page, which includes event handlers and other 

code

ASP.NET provides two models for managing the visual elements and code— the single-file page model and the code-behind page model. The two models perform the same function, and you can use the same controls and code for both

models.

This topic explains how each model operates and provides guidelines for 

choosing one model or the other.

The Single-File Page Model

In the single-file page model, the page’s HTML markup and its programmingcode are in the same physical .aspx file. The programming code is contained ina <script> block that specifies the attribute runat="server" to mark it as code

that ASP.NET should run.

The following code example shows a single-file page containing a Button control and a Label control. The bold text shows the Click event handler for 

the Button control inside a <script> block.

[Visual Basic]

<%@ Page Language="VB" %>

<script runat="server">

Sub Button1_Click(sender As Object, e As EventArgs)

Label1.Text = "Clicked at " & DateTime.Now.ToString()

End Sub </script>

<html>

<head><title>Single-File Page Model</title></head>

<body>

<form runat="server">

<div>

<asp:Label id="Label1" runat="server">Label</asp:Label>

<br />

<asp:Button id="Button1" runat="server"

onclick="Button1_Click" Text="Button"></asp:Button>

</div>

</form></body>

</html>

Page 20: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 20/168

12 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

[C#]

<%@ Page Language="C#" %>

<script runat="server">

void Button1_Click(Object sender, EventArgs e)

{

Label1.Text = "Clicked at " + DateTime.Now.ToString();

}</script>

<html>

<head><title>Single-File Page Model</title></head> <body>

<form runat="server">

<div>

<asp:Label id="Label1" runat="server">Label</asp:Label>

<br />

<asp:Button id="Button1" runat="server"

onclick="Button1_Click" Text="Button"> </asp:Button>

</div>

</form>

</body>

</html>

The <script> block can contain all the code for the page. The code can consistof event handlers for controls on the page (as in the example), methods, properties, and any other code that you would normally use in a class file. At

run time, the compiler converts a single-file page into a class that derives fromthe System.Web.UI.Page. The compiler-generated class contains the controls as

members. (Not all controls are exposed as page members; some are children of other controls.) The code in the page becomes part of the class; for example,

event handlers that you create become members of the derived Page class.

The Code-Behind Page Model

The code-behind page model allows you to keep the HTML markup in one

file—the .aspx file—and the programming code in another file. The name of thecode file varies according to the programming language you are using.

 Not all .NET programming languages allow you to create code-behind

files for ASP.NET Web pages. Languages must support partial classes. For 

example, J# does not support partial classes and therefore does not supportcreating code-behind files for ASP.NET pages.

For example, if you are working with a page named SamplePage, the HTMLmarkup is placed in the file SamplePage.aspx and the code is created in a file

named SamplePage.aspx.vb (for Microsoft Visual Basic®), or SamplePage.aspx.cs (for C#).

Note

Page 21: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 21/168

Unit 1: Creating a Web Application 13

In the code-behind model, the example used in the preceding section for thesingle-file page is split into two parts. The HTML markup is in one file (in thisexample, SamplePage.aspx) and is similar to the single-file page, as shown in

the following code example:

[Visual Basic]

<%@ Page Language="VB" CodeFile="SamplePage.aspx.vb" Inherits="SamplePage"%>

<html>

<head><title>Code-behind Page Model</title></head>

<body>

<form runat="server">

<div>

<asp:Label id="Label1" runat="server">Label</asp:Label>

<br />

<asp:Button id="Button1" runat="server"

onclick="Button1_Click" Text="Button"></asp:Button>

</div>

</form>

</body>

</html>

[C#]

<%@ Page Language="C#" CodeFile="SamplePage.aspx.cs" Inherits="SamplePage"%>

<html>

<head><title>Code-behind Page Model</title> </head>

<body>

<form runat="server">

<div>

<asp:Label id="Label1" runat="server">Label</asp:Label>

<br />

<asp:Button id="Button1" runat="server"

onclick="Button1_Click" Text="Button"> </asp:Button>

</div></form>

</body>

</html>

There are two differences in the .aspx page between the single-file and thecode-behind models.

  In the code-behind model, there is no <script> block with the

runat="server" attribute. The page can contain <script> blocks without the

runat="server" attribute if you want to write client-side script in the page.

  In the code-behind model, the @ Page directive contains attributes that

reference an external file (SamplePage.aspx.vb or SamplePage.aspx.cs) and

a class. These attributes link the .aspx page to its code.

Page 22: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 22/168

14 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The code is in a separate file. The following example shows a code-behind filethat contains the same Click event handler as the example for the single-file page.

[Visual Basic]

Imports Microsoft.VisualBasic

Partial Class SamplePage

Inherits System.Web.UI.Page

Sub Button1_Click(sender As Object, e As EventArgs)

Label1.Text="Clicked at " & DateTime.Now.ToString()

End Sub

End Class

[C#]

using System;

public partial class SamplePage : System.Web.UI.Page

{

void Button1_Click(Object sender, EventArgs e)

{

Label1.Text="Clicked at "+DateTime.Now.ToString();

}

}

The code file contains a partial class—that is, a class declaration with the

partial keyword (for Microsoft Visual C#®) or Partial (for Visual Basic). This

indicates that the class contains only some of the total code that makes up thefull class for the page. In the partial class, you add the code that your 

application requires for the page. This typically consists of event handlers, butcan include any methods or properties that you need.

The partial class in the code-behind file inherits from a base page class. The

 base page class can be the System.Web.UI.Page, or, alternatively, it can befrom another class that derives from System.Web.UI.Page. In addition, the

.aspx file contains an Inherits attribute that points to the code-behind partialclass. When the page is compiled, ASP.NET creates a new partial class for the.aspx file; this class is a peer of your code-behind partial class file. The

generated partial class file contains declarations for your page’s controls. This partial class allows your code-behind file to be used as part of a complete class

without requiring you to declare the controls explicitly.

Finally, ASP.NET generates a class that inherits from the partial class created

from the .aspx file and the code-behind partial class. This second generatedclass is compiled into an assembly that runs in order to render output to the

 browser.

Page 23: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 23/168

Unit 1: Creating a Web Application 15

The following illustration shows the inheritance model for the page class in acode-behind ASP.NET Web page:

Page 24: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 24/168

16 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Choosing a Page Model

The single-file and code-behind page models perform the same function. At runtime, the models execute the same way, and there is no performance difference between them. Choosing a page model therefore depends on other factors, such

as how you want to organize the code in your application and whether it is

important to separate page design from coding.

Advantages of Single-File Pages 

The single-file model is suitable for pages in which the code consists primarily

of event handlers for the controls on the page.

Advantages of the single-file page model include the following:

  In pages without a lot of code, the convenience of keeping the code andHTML markup in the same file can outweigh other advantages of the code-

 behind model. For example, it can be easier to study a single-file page

 because you can see the code and the HTML markup in one place.

 

Pages written by using the single-file model are slightly easier to deploy or to send to another programmer because there is only one file.

  A single-file page is easier to rename because there is no dependency

 between files.

  Managing files in a source code control system is slightly easier because the

 page is self-contained in a single file.

Advantages of Code-Behind PagesCode-behind pages offer advantages that make them suitable for Web

applications with a significant amount of code or in which multiple developersare creating a Web site.

Advantages of the code-behind model include the following:

  Code-behind pages offer a clean separation of the HTML markup (user 

interface) and code. It is practical for a graphic designer to work on the page

layout while a programmer writes code.

  Code is not exposed to graphic designers or others who are working only

with the page HTML markup.

Compilation and Deployment

Compilation and deployment of both single-file and code-behind pages is

similar. At its simplest, you copy the page to the target server. If you are

working with code-behind pages, you copy both the .aspx page and the codefile. When the page is first requested, ASP.NET compiles the page and runs it. Note that in both scenarios you deploy source code with the markup.

Alternatively, you can precompile your Web site. In this case, ASP.NET produces object code for your pages that you can copy to the target server.

Precompilation works for both single-file and code-behind models and theoutput is the same for both models.

Page 25: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 25/168

Unit 1: Creating a Web Application 17

How to: Build a Web Application

Setting the Start Page

Before running a Web application in Microsoft® Visual Studio® 2005, you

should set the start page for the application. If you do not set the start page, theDefault.aspx page that is created is used as the start page. You can set the start page by using either of the following approaches:

  Right-click the page that you want to be the start page in Solution Explorer,

and then from the shortcut menu, click Set as Start Page.

  Select the page that you want to be the start page in Solution Explorer, and

then from the Website menu, click Set as Start Page.

Building a Web Application

There are a number of ways to build a Web application project in VisualStudio 2005:

  On the Build menu, click Build Solution to compile the project and post it

to the server where it can be run.

The keyboard shortcut for this command is CTRL+SHIFT+B. The same

action can be performed by right-clicking the Web site in Solution Explorer and then clicking Build Web Site from the shortcut menu.

  On the Debug menu, click Start Without Debugging to build and post the

 project to the server where it will run.

The default browser starts and displays the start-up page for the Web

application. The keyboard shortcut for this command is CTRL+F5.

  On the Debug menu, click Start Debugging to run the build process, loadthe debugger, and open the browser to view the content.

The keyboard shortcut for this command is F5. You can also click the Start

Debugging button on the Standard toolbar.

Page 26: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 26/168

18 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

<customErrors> ElementThe customErrors element provides information about how custom error messages are handled for a Microsoft® ASP.NET application. It can be definedin the global web.config file for the host computer and in the web.config file for 

the application. The customErrors element has the following syntax:

<customErrors

defaultRedirect="url"

mode="On|Off|RemoteOnly">

<error

statusCode="statuscode"

redirect="url"/>

</customErrors>

Required Attribute

Attribute Option Description

Mode Specifies whether custom errors are enabled,

disabled, or shown only to remote clients.

On Enables custom errors. If no defaultRedirect 

attribute is specified, users see a generic error.

Off  Disables custom errors. This setting allows

standard detailed error messages to be displayed.

RemoteOnly Specifies that custom errors are shown only to

remote clients and that ASP.NET errors are shown

to the local host. This is the default value.

Optional AttributeAttribute Description

defaultRedirect Specifies the default URL to direct a browser to if an error 

occurs. When the defaultRedirect attribute is not specified,

a generic error is displayed instead. The URL can be absolute

(for example, www.contoso.com/ErrorPage.htm) or it can be

relative. A relative URL such as /ErrorPage.htm is evaluated

relative to the web.config file that specified the

defaultRedirect URL, not to the Web page in which the

error occurred.

A URL starting with a tilde (~), such as ~/ErrorPage.htm,

means that the specified URL is evaluated relative to the root path of the application.

Subtag

Subtag Description

<error> The error tag can appear multiple times. Each appearance

defines one custom error condition and can specify a

different page to use for each error.

Page 27: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 27/168

Unit 1: Creating a Web Application 19

Installation Defaults

When the Microsoft .NET Framework is installed, the machine.config filespecifies the following default values for the customErrors section:

<customErrors mode="RemoteOnly" />

Remarks

The customErrors element does not apply to errors that occur in Web services.

You must ensure that the pages you specify in the redirect and

defaultRedirect attributes cannot contain any run-time errors. If they do causerun-time errors when they are used in response to another error, the standardASP.NET error page will be displayed.

When a page that you specify in the redirect and defaultRedirect 

attributes is loaded in response to a run-time error, the code on that page doesnot have access to the details of the error.

Example

The following configuration example specifies the error-handling pages to usefor an ASP.NET application:

<configuration>

<system.web>

<customErrors

defaultRedirect="GenericError.htm"

mode="RemoteOnly">

<error

statusCode="500"

redirect="InternalError.htm"/>

</customErrors>

</system.web>

</configuration>

Important

Note

Page 28: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 28/168

20 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

<compilation> ElementThe <compilation> element in the system.web section of a configuration fileenables you to specify compilation settings for a Web application. Typically,you will specify compilation settings in the web.config file for your application,

although you can also include default settings in machine.config file or the root

web.config file. The <compilation> element can contain many differentoptional parameters and sub-tags. For a full specification of the<compilation>element, review the Microsoft® Visual Studio® 2005

documentation.

The following example illustrates a simple configuration for the compilation

settings of an application:

<configuration>

<system.web>

<compilation defaultLanguage="VB"

debug="true"

numRecompilesBeforeAppRestart="15">

</compilation>

</system.web>

</configuration>

This example specifies that:

  The default language is Microsoft Visual Basic®.

  The Web application has debugging enabled.

  The application will be restarted after 15 recompile operations are

 performed.

In this example, setting the debug attribute to true enables you to debug theWeb application by using the integrated Visual Studio 2005 debugging tools.

The numRecompilesBeforeAppRestart setting defines how many recompilescan be performed before Microsoft ASP.NET unloads and then reloads the Web

application. An application restart will result in loss of Application state andSession state (if the in-process state option is used), so it is important tounderstand the implication of this setting for your Web application.

Page 29: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 29/168

 

Unit 2: Programming a WebApplication

How to Determine Which Web Server Control Raised anEvent

When an event handler is called, you can determine which control raised theevent. This is useful if you have bound several controls to the same event

handler.

To Determine Which Control Caused the Event

1.  In the event handler, declare a variable with a type that matches the control

that raised the event.

2.  Assign the sender argument of the event handler to the variable, casting it

to the appropriate type.

3.  Examine the ID property of the variable to determine which object raised

the event.

The following example shows the event handler for the Click event of a Button

control. Several different buttons can use this event handler. The handler displays information about which button the user clicked.

[Visual Basic]

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles Button1.Click, Button2.Click, Button3.Click

Dim b As Button

b = CType(sender, Button)

Select Case b.ID

Case "Button1"

Label1.Text = "You clicked the first button"

Case "Button2"

Label1.Text = "You clicked the second button"Case "Button3"

Label1.Text = "You clicked the third button"

End Select

End Sub

Page 30: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 30/168

22 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

[Visual C#]

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

{

Button b;

b = (Button) sender;

switch(b.ID)

{ case "Button1":

Label1.Text = "You clicked the first button";

break;

case "Button2":

Label1.Text = "You clicked the second button";

break;

case "Button3":

Label1.Text = "You clicked the third button";

break;

}

}

Page 31: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 31/168

Unit 2: Programming a Web Application 23

The HttpServerUtility Transfer MethodYou can use the HttpServerUtility.Transfer method to halt the code runningon the current Web page and request that a different Web page carry on the processing. The redirection is performed on the server and, unlike the

Response.Redirect method, does not require a roundtrip to the browser running

on the user’s computer.

Using the Server.Transfer Method

In the following code example, the Server.Transfer method redirects the user 

to a page called Destination.aspx .

The Server object is an instance of the HttpServerUtility class.

[Visual Basic]

Server.Transfer("Destination.aspx")

[Visual C#]

Server.Transfer("Destination.aspx");

Note

Page 32: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 32/168

24 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Pass Values Between ASP.NET Web PagesIf a Web application redirects or moves from one Microsoft® ASP.NET Web page to another, you will frequently want to pass information from the source page to the destination page. For example, in a page on which a user can select

items to purchase, when the user submits the page to the Web server, you can

call another page to process the user’s selections.

You can pass information between pages in various ways. Some techniquesdepend on how you perform the redirection. Options include the following:

  Appending information to the URL of the target page by using a querystring.

You can use a query string in the NavigateUrl property of a Hyperlink  control, and you can add query strings programmatically when you call the

Response.Redirect method. Similarly, you can use query strings when

 performing server-side redirection, such as by using the Server.Transfer method.

You can pass values between pages by using a query string even if the pages

are not part of the same Web application. You can also use this technique if you need to pass information to a Web page that does not use ASP.NET.

Do not  pass sensitive data in a query string, because the information

is visible to the user. It can easily be modified by the user, representing a

 potential threat to the integrity of your Web application.

  Exposing the data as public properties on the source page. On the target

 page, read these property values from the source page. This strategy works

in two situations: when the source page submits data to the target page in an

HTTP post operation, and when you call the Server.Transfer method to

transfer execution from the source to the target page on the server. In the

latter case, the Web pages must be part of the same application.

Note

Page 33: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 33/168

Unit 2: Programming a Web Application 25

Using the Query String

The following code demonstrates how to pass query string parameters calledproductname and color to a page called Productdisplay.aspx by using the

Server.Transfer method:

[Visual Basic]Server.Transfer("Productdisplay.aspx?productname=bike&color=blue")

[Visual C#]

Server.Transfer("Productdisplay.aspx?productname=bike&color=blue");

On the Productdisplay.aspx  page, the following code reads the value of thequery string:

[Visual Basic]

Dim strColor = Request.QueryString("color")

Dim strProduct = Request.QueryString("productname")

Label1.Text = "You have requested a " & strColor & " " & strProduct

[Visual C#]

string strColor = Request.QueryString("color");

string strProduct = Request.QueryString("productname");

Label1.Text = "You have requested a " + strColor + " " + strProduct;

In some scenarios, you might want to transfer execution to another page but not want the query string and form collection from the requested page to be

available to the target page. For example, the data submitted from the source page may no longer be relevant. In this case you can use the Server.Transfer method as earlier, but pass a second, Boolean parameter set to the value False.

Note

Page 34: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 34/168

26 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Connect Multiple Events to a Single EventHandler in ASP.NET Pages

You can bind several control events to the same event handler method. Theseevents can be raised by the same control or by several different controls, as long

as the events all have the same signature. For example, you can bind theCommand events of several Button controls on a Microsoft® ASP.NET page

to a single event handler.

To Connect Multiple Events to a Single Event Handler 

In Microsoft Visual C#® and Microsoft Visual Basic®, you can bind an event to

a handler by editing the HTML source code for the ASP.NET page. In theHTML source code, specify the event name and method name for each control,as shown in the following example:

<asp:Button ID="Button1"

oncommand="Button_Command"

runat="server"

Text="Button1" />

<br />

<asp:Button ID="Button2"

oncommand="Button_Command"

runat="server"

Text="Button2" />

It is up to you to make sure that the method has the correct signature for 

the event it is handling. You can use the Events section in the Propertieswindow to bind event handler methods to events as an alternative to editing the

HTML source code manually.

To Connect Multiple Events to a Single Event Handler in

Visual Basic

In Visual Basic, you can also bind an event to a handler by using the Handles

clause of the event handler method. The Handles clause specifies the names of the events that the method will handle. You can specify multiple events byseparating the event names with commas.

There is no Visual C# equivalent to the Visual Basic Handles keyword.

You do not need to take this approach if you are programming with Visual C#.

The following example shows how you can bind the Button_Command method to events raised by three different Button controls:

[Visual Basic]

Sub Button_Command (ByVal sender as System.Object, _

ByVal e as System.EventArgs) _

Handles Button1.Command, Button2.Command, Button3.Command

Note

Note

Page 35: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 35/168

Unit 2: Programming a Web Application 27

If you use a Handles clause to bind an event and method, do not includethe event attribute in the HTML source code. For example, do not include an

oncommand attribute in the HTML source code for a Button control. If you

do, the method will be called twice when the event occurs.

You can add code to the event procedure to determine which control raised theevent at run time. For details on how to achieve this, refer to the Resource

Toolkit resource How to Determine Which Web Server Control Raised an

 Event .

Note

Page 36: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 36/168

28 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The Button.Command EventThe Button.Command event fires when the user clicks a Button control on aMicrosoft® ASP.NET page.

You can use a Button.Command event handler to implement logic that is

shared by more than one button on the Web page. Each button control can havea unique value specified for its CommandName property. In the event handler,you determine which Button control the user clicked by examining the

CommandName property of the CommandEventArgs parameter.

Furthermore, the CommandEventArgs parameter exposes a

CommandArgument property that enables you to differentiate between

multiple buttons with the same CommandName property. For example, two buttons can raise the same Command event procedure, and both can specify a

CommandName of Sort . However, one of the buttons may provide aCommandArgument of  Ascending , whereas the other button may specify Descending as its CommandArgument property.

ExampleThe following code example demonstrates how to use a Command eventhandler with multiple Button objects on an ASP.NET Web form. The code

shows how to determine the CommandName and CommandArgument  properties of the button that raised the event.

[Visual Basic]

<%@ Page Language="VB" AutoEventWireup="True" %>

<html>

<head>

<script runat="server">

Sub CommandBtn_Command(sender As Object, e As CommandEventArgs)

'Determine the CommandName property of the button that

'initiated the event.

Select e.CommandName

Case "Sort"

' Call the method to sort the list, passing in the

' CommandArgument property of the button that

'initiated this event.

Sort_List(CType(e.CommandArgument, String))

Case "Submit"

' Display a message for the Submit

' button being clicked.

Message.Text = "You clicked the Submit button"

Case Else

' The command name is not recognized.' Display an error message.

Message.Text = "Command name not recognized."

End Select

End Sub

(Code continued on the following page.)

Page 37: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 37/168

Unit 2: Programming a Web Application 29

Sub Sort_List(commandArgument As String)

Select commandArgument

Case "Ascending"

' Insert code to sort the list in ascending order here.

Message.Text = "You clicked the Sort Ascending button."

Case "Descending"

' Insert code to sort the list in' descending order here.

Message.Text = "You clicked the Sort " _

& "Descending button."

Case Else

' The command argument is not recognized.

' Display an error message.

Message.Text = "Command argument not recognized."

End Select

End Sub

</script>

</head>

<body>

<form runat="server"><h3>Button CommandName Example</h3>

Click on one of the command buttons.

<br><br>

<asp:Button id="Button1"

Text="Sort Ascending"

CommandName="Sort"

CommandArgument="Ascending"

OnCommand="CommandBtn_Command"

runat="server"/>

<asp:Button id="Button2"

Text="Sort Descending"

CommandName="Sort"

CommandArgument="Descending"OnCommand="CommandBtn_Command"

runat="server"/>

<br><br>

<asp:Button id="Button3"

Text="Submit"

CommandName="Submit"

OnCommand="CommandBtn_Command"

runat="server"/>

<br><br>

<asp:Label id="Message" runat="server"/>

</form>

</body>

</html>

Page 38: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 38/168

30 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

[Visual C#]

<%@ Page Language="C#" AutoEventWireup="True" %>

<html>

<head>

<script runat="server">

void CommandBtn_Command(Object sender, CommandEventArgs e)

{ switch(e.CommandName)

{

case "Sort":

// Call the method to sort the list.

Sort_List((String)e.CommandArgument);

break;

case "Submit":

// Display a message for the Submit

// button being clicked.

Message.Text = "You clicked the Submit button";

break;

default:

// The command name is not recognized.// Display an error message.

Message.Text = "Command name not recognized.";

break;

}

}

void Sort_List(string commandArgument)

{

switch(commandArgument)

{

case "Ascending":

// Insert code to sort the list in

//ascending order here.Message.Text = "You clicked the Sort Ascending " +

“button.";

break;

case "Descending":

// Insert code to sort the list in

// descending order here.

Message.Text = "You clicked the Sort " +

"Descending button.";

break;

default:

// The command argument is not recognized.

// Display an error message.

Message.Text = "Command argument not recognized.";

break;

}

}

</script>

</head>

(Code continued on the following page.)

Page 39: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 39/168

Unit 2: Programming a Web Application 31

<body>

<form runat="server">

<h3>Button CommandName Example</h3>

Click on one of the command buttons.

<br><br>

<asp:Button id="Button1"

Text="Sort Ascending"CommandName="Sort"

CommandArgument="Ascending"

OnCommand="CommandBtn_Command"

runat="server"/>

<asp:Button id="Button2"

Text="Sort Descending"

CommandName="Sort"

CommandArgument="Descending"

OnCommand="CommandBtn_Command"

runat="server"/>

<br><br>

<asp:Button id="Button3"

Text="Submit"CommandName="Submit"

OnCommand="CommandBtn_Command"

runat="server"/>

<br><br>

<asp:Label id="Message" runat="server"/>

</form>

</body>

</html>

Page 40: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 40/168

32 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Detect Browser CapabilitiesDifferent browsers (and even different versions of the same browser) supportdifferent features. In Microsoft® ASP.NET pages, you frequently need to knowabout the user’s browser, its type, and capabilities. You can use this information

to ensure that a Web page is displayed correctly by a browser. You can also

write code that redirects browsers to Web pages designed with specificcapabilities in mind, such as a text-only version of a Web page for browsersrunning on mobile devices.

To Detect Browser Types and Capabilities in Web Form Pages

Query the HttpRequest.Browser property, which returns an

HttpBrowserCapabilities object. This object retrieves information from the browser or client device during an HTTP request. This information includes thetype and level of support the browser or client device offers.

The following example shows how to display browser information in a text box

on a Web page.[Visual Basic]

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click

Dim s As String = ""

With Request.Browser

s &= "Browser Capabilities" & vbCrLf

s &= "Type = " & .Type & vbCrLf

s &= "Name = " & .Browser & vbCrLf

s &= "Version = " & .Version & vbCrLf

s &= "Major Version = " & .MajorVersion & vbCrLf

s &= "Minor Version = " & .MinorVersion & vbCrLf

s &= "Platform = " & .Platform & vbCrLf

s &= "Is Beta = " & .Beta & vbCrLf

s &= "Is Crawler = " & .Crawler & vbCrLf

s &= "Is AOL = " & .AOL & vbCrLf

s &= "Is Win16 = " & .Win16 & vbCrLf

s &= "Is Win32 = " & .Win32 & vbCrLf

s &= "Supports Frames = " & .Frames & vbCrLf

s &= "Supports Tables = " & .Tables & vbCrLf

s &= "Supports Cookies = " & .Cookies & vbCrLf

s &= "Supports VBScript = " & .VBScript & vbCrLf

s &= "Supports JavaScript = " & _

.EcmaScriptVersion.ToString() & vbCrLf

s &= "Supports Java Applets = " & .JavaApplets & vbCrLf

s &= "Supports ActiveX Controls = " & .ActiveXControls & _vbCrLf

End With

TextBox1.Text = s

End Sub

Page 41: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 41/168

Unit 2: Programming a Web Application 33

[Visual C#]

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

{

System.Web.HttpBrowserCapabilities browser = Request.Browser;

string s = "Browser Capabilities\n"

+ "Type = " + browser.Type + "\n"

+ "Name = " + browser.Browser + "\n"+ "Version = " + browser.Version + "\n"

+ "Major Version = " + browser.MajorVersion + "\n"

+ "Minor Version = " + browser.MinorVersion + "\n"

+ "Platform = " + browser.Platform + "\n"

+ "Is Beta = " + browser.Beta + "\n"

+ "Is Crawler = " + browser.Crawler + "\n"

+ "Is AOL = " + browser.AOL + "\n"

+ "Is Win16 = " + browser.Win16 + "\n"

+ "Is Win32 = " + browser.Win32 + "\n"

+ "Supports Frames = " + browser.Frames + "\n"

+ "Supports Tables = " + browser.Tables + "\n"

+ "Supports Cookies = " + browser.Cookies + "\n"

+ "Supports VBScript = " + browser.VBScript + "\n"+ "Supports JavaScript = "

+ browser.EcmaScriptVersion.ToString() + "\n"

+ "Supports Java Applets = " + browser.JavaApplets + "\n"

+ "Supports ActiveX Controls = "

+ browser.ActiveXControls + "\n";

TextBox1.Text = s;

}

Page 42: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 42/168

34 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Access Page Header InformationThe HTML page header section of a Microsoft® ASP.NET page contains usefulinformation that you can access programmatically. For example, you canexamine the details of a style sheet used by the page, or you can change the

 page title.

Alter the Page Title

The following example shows how to change the Page.Header.Title propertywhen the user clicks an ASP.NET Button control named Button1. The method

displays the value of the Text property of the TextBox1 control in the pageheader:

[Visual Basic]

Protected Sub Button1_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Button1.Click

Page.Header.Title = "Your name is " & TextBox1.Text

End Sub

[Visual C#]

protected void Button1_Click(object sender, EventArgs e)

{

Page.Header.Title = "Your name is " + TextBox1.Text;

}

Page 43: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 43/168

Page 44: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 44/168

36 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Handle Application-Level ErrorsYou can handle errors at the Web-application level in either of the followingways:

  Add an Application_Error event handler to the global.asax file for your 

Web application.  Add a <customErrors> element to the web.config file for your Web

application.

This document describes the latter approach to application-level error handling.

The <customErrors> Element

You can edit the web.config file for your application to configure application-level error handling. Use the <customErrors> child element of the

<system.web> element, as shown in the following example:

<system.web><customErrors defaultRedirect="errorhandler.aspx" mode="On">

<error statusCode="403" redirect="NoAccess.htm" />

<error statusCode="404" redirect="FileNoteFound.htm" />

</customErrors>

</system.web>

In this example, the <error> elements specify pages that the ASP.NET Website displays when HTTP errors 403 and 404 occur. Any other errors display the

errorhandler.aspx Web page.

You can set the mode attribute of the <customErrors> element to Off , in

which case a standard Microsoft® ASP.NET error page will be shown when an

error occurs.

You can also set the mode attribute to RemoteOnly, in which case the customerror page will not apply to visitors logged on locally at the Web server itself.This can be useful for administrators or developers who need to troubleshoot

errors.

Writing Code in the Error Handling Page

You must ensure that the page specified in the web.config file does not cause

any further run-time errors. If further run-time errors do occur, ASP.NET willdisplay its own error page, which will be inappropriate in most cases.

You should be careful not to show sensitive information on error pages.For example, displaying code, Microsoft SQL Server™ error information, or 

operating system version numbers can give malicious users information thatthey can use to attack your Web site.

Note

Page 45: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 45/168

 

Unit 3: Adding and Configuring Server Controls

Survey.aspx Page Design—HTML ControlsThe following illustration shows a model page layout achieved by using HTML

controls for the survey.aspx prototype. You should use this illustration as aguide when you are designing the survey page in the lab.

Page 46: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 46/168

38 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Add HTML Server Controls to a Web Forms Pageby Using the Web Forms Designer 

You can add an HTML control to a Web page by dragging a control from theHTML group in the Toolbox in Microsoft® Visual Studio® 2005. By default, an

HTML control generates static HTML text. To make this control accessible toserver-side code, you must convert it to an HTML server control.

To Add an HTML Server Control to a Web Forms Page

Complete the following procedure in the Design view of an .aspx page inVisual Studio 2005.

1.  From the HTML tab of the Toolbox, drag an HTML element onto the page.

2.  In Design view, right-click the control on the page and then click Run As

Server Control.

The Web Forms Designer adds the attribute runat="server" to the HTMLmarkup for this control. A glyph appears on the control to indicate that it is a

server-based control.

Page 47: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 47/168

Unit 3: Adding and Configuring Server Controls 39

HTML Controls for ASP.NET Web PagesThis document describes controls in the HTML section in the Toolbox. You canadd HTML controls to Microsoft® ASP.NET HTML pages and to Web Forms pages.

By default, HTML elements on a Web Forms page are treated as static text thatis passed through to the browser. However, by converting HTML elements toHTML server controls, you expose them as objects that you can program inserver-side code.

HTML Controls

The following HTML controls can be added to Web pages from the Toolbox inMicrosoft Visual Studio® 2005:

  Div control: This control renders an HTML <div> element.

  Horizontal Rule control: This control renders a horizontal line crossing the

 parent element.  Image control: This control renders an HTML <img> tag. Use the src 

attribute to specify the file from which to take the image.

  Input control: The Input control enables the user to enter information on a

 page. Input controls can take several forms, depending on the type attribute.

An Input control can be a button, check box, file upload, text box, password

 box, or option button. It can also be a hidden control, used to store values

without displaying them to the user, although these values will be present if 

the user views the page source at run time. Each of these types of input

controls is listed in the Toolbox.

  Select control: This control renders a drop-down list from which the user 

can select an option.

  Table control: This control renders a table. When you drag the Table 

control onto the page from the Toolbox, a table with three rows and three

columns is created, which you can edit to the desired dimensions. The tableitself, the rows, or the individual cells can all be converted into server 

controls independently.

  TextArea control: This control renders a large input box into which the user 

can type multiple lines of text.

Page 48: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 48/168

40 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Add HTML Markup to Web PagesYou can use Microsoft® Visual Studio® 2005 to add any HTML markup to astatic Web page or to a dynamic Microsoft ASP.NET page. You can add HTMLcontrols to a Web form by dragging them from the Toolbox and by using the

Block Format list. You can also type HTML markup directly into Source view.

To Add an HTML Control from the Toolbox

You can add the following tags from the Toolbox:

  <Input> tags of various types.

  <TextArea> tags.

  <Table> tags. These will create some <tr> and <td> tags within the table.

  <img> tags.

  <select> tags.

  <hr> tags.

  <div> tags.

To insert an HTML control by dragging it onto the page:

1.  Display the Web page in Design view.

2.  Locate the HTML control to add in the HTML group of the Toolbox.

3.  Drag the control onto the page.

To Add HTML Block Format Tags

You can format text by using HTML block format tags, such as <p> and <h1>, by following these steps:

1.  Display the Web page in Design view, and then place the cursor at the

location in the page that you want to format.

2.  On the Formatting toolbar, choose the desired style from the Block 

Format drop-down list.

3.  Type the text you want to add to the page.

Page 49: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 49/168

Unit 3: Adding and Configuring Server Controls 41

To Add HTML into the Source View

You can add HTML markup to the Web page directly by following these steps:

1.  Switch to Source view and then find the location in the markup where you

want to add HTML markup.

2.  Type the HTML markup.

The Visual Studio 2005 IntelliSense® features help you to create well-formedand valid HTML content by providing guidance on valid element names andattribute names and values. Additionally, the IntelliSense features provide

schema validation features.

The following example renders a heading, a paragraph, and a horizontal line:

<h1>This is the Heading</h1>

<p>This is the paragraph.</p>

<hr />

Page 50: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 50/168

42 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Survey.aspx Page Design–Web Server ControlsThe following illustration shows a model page layout achieved by using Webserver controls for the Survey.aspx prototype. You should use this illustrationas a guide when you are designing the survey page in the lab.

Page 51: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 51/168

Unit 3: Adding and Configuring Server Controls 43

Introduction to ASP.NET Web Server ControlsWhen you create Web Forms pages, you can use the following types of controls:

  HTML server controls: These are HTML elements exposed to the server 

so you can program them. HTML server controls expose an object modelthat maps very closely to the HTML elements that the controls render.

  Web server controls: These are controls with more built-in features than

HTML server controls. Web server controls include not only form-type

controls, such as buttons and text boxes, but also special-purpose controls,

such as a calendar. Web server controls are more abstract than HTML server 

controls in that their object model does not necessarily reflect HTML

syntax.

  Validation controls: These controls incorporate logic that enables you to

test user input. You attach a validation control to an input control to test the

data the user enters into it. Validation controls enable you to check for a

required field, to test against a specific value or pattern of characters, to

verify that a value lies within a range, and so on.  User controls: These are controls that you create as Web Forms pages. You

can embed user controls in other Web Forms pages, which is an easy way tocreate menus, toolbars, and other reusable elements.

You can also create output for mobile devices. To do so, you use the

same Microsoft® ASP.NET page framework, but you create Mobile Web Formsinstead of Web Forms pages and use controls specifically designed for mobile

devices.

You can use all types of controls on the same page. The following sections

 provide more detail about HTML server controls and Web server controls.

In some situations, server controls require client script in order tofunction properly. If a user has disabled scripting in the browser, the controlsmight not function as you intend.

HTML Server Controls

HTML server controls are HTML elements with attributes that make themvisible to—and programmable on—the server. Ordinary HTML elements, suchas <p> tags, on a Web Forms page are not available to server-side code; they

are treated as static text that is passed through to the browser. However, byconverting HTML elements to HTML server controls, you expose them as

elements that server-side ASP.NET code can access.

The object model for HTML server controls maps closely to that of the

corresponding elements. For example, HTML attributes are exposed in HTMLserver controls as properties.

Note

Note

Page 52: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 52/168

44 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Any HTML element on a page can be converted to an HTML server control.Conversion is a simple process involving just a few attributes. At a minimum,you convert an HTML element to a control with the addition of the attribute

runat="server". This attribute tells the ASP.NET page framework that itshould create an instance of the control during parsing for use during server-

side page processing. If you want to reference the control within your code, you

should also assign an ID attribute to it.The ASP.NET page framework provides predefined HTML server controls for 

the HTML elements most commonly used dynamically on a page: forms, the<INPUT> elements, list boxes, tables, images, and so on. Each HTML server 

control typically provides its own set of properties and events.

HTML server controls offer the following features:

  An object model that you can program against on the server. Each server 

control exposes properties that allow you to manipulate the HTML

attributes programmatically in server code.

  A set of events for which you can write event handlers in much the same

way that you would in a client-based form. However, the event is handled in

server-side code.

  The ability to handle events in client script.

  Automatic maintenance of the control’s state. If the form makes a roundtrip

to the server, the values that the user entered into HTML server controls are

automatically maintained when the page is sent back to the browser.

  Interaction with validation controls so that you can easily verify that a user 

has entered appropriate information into a control.

  Data binding for one or more properties of the control.

  Support for HTML 4.0 styles if the Web Forms page is displayed in a

 browser that supports cascading style sheets.

  Pass-through of custom attributes. You can add any attributes you need toan HTML server control and the page framework will read them and render 

them without any change in functionality. This enables you to add browser-

specific attributes to your controls.

Web Server Controls

Web server controls is set of controls designed differently from HTML

controls. They enable you to create a control with complex behavior by simplydragging from the Toolbox in Microsoft Visual Studio® 2005 onto a Web page.

They do not map one-to-one to HTML server controls. Instead, they are abstractcontrols, in which the HTML rendered can be quite different from the model

that you program against. For example, a RadioButtonList Web server controlmight be rendered in a table or as inline text with other HTML.

The Web server controls include traditional form controls, such as buttons andtext boxes, in addition to complex controls such as tables, calendars, and tree-views.

Page 53: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 53/168

Unit 3: Adding and Configuring Server Controls 45

Web server controls provide all of the features described earlier for HTMLserver controls except for one-to-one mapping to HTML elements. In addition,they provide the following additional features:

  A rich object model that provides type-safe programming capabilities.

  Automatic browser detection. The controls can detect browser capabilities

and create appropriate output for both basic and rich (HTML 4.0) browsers.  The ability to define consistent appearances for the controls by using

templates.

  The ability to specify whether a control’s event causes immediate posting to

the server or is instead cached and raised when the form is submitted.

  The ability to pass events from a nested control, such as a button in a table,

to the container control.

When the Web Forms page runs, ASP.NET renders the Web server control onthe page by using appropriate HTML, which often depends not only on the browser type, but also on settings that you have made for the control. For 

example, a TextBox control might render as an <input> tag or a <textarea> tag,depending on its properties.

Page 54: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 54/168

46 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Standard Toolbox ControlsThis document describes controls that are available in the Standard group of theMicrosoft® Visual Studio® 2005 Toolbox. These are Microsoft ASP.NET Webserver controls, which can be added only to ASP.NET Web Forms pages, not

static HTML pages. Web server controls are automatically available for access

and manipulation in server-side code.

The Web server controls enable you to display buttons, lists, images, text boxes,hyperlinks, labels, and tables, as well as more complicated controls that work 

with static and dynamic data and controls that act as containers for other controls.

Standard Toolbox Controls

The Standard section of the Visual Studio 2005 Toolbox contains the followingcontrols:

  AdRotator: This control cycles through a series of clickable ad banners,

and it allows some ads to be weighted more heavily than others. Ads caneither be linked to the control by using an XML file with a predefinedschema or by creating your own custom logic.

  BulletedList: This control contains a number of ListItem controls. Each of 

these is presented in a list with bullet points.

  Button: This control renders a button that the user can click to send a

command or to initiate an action. When a Button control is pressed, the

 page is submitted back to the server, and various events, such as Page.Load

and Button.Click , are fired.

  Calendar: This control renders a calendar that the user can use to view and

 pick date values.

  CheckBox and CheckBoxList: These controls render check boxes withwhich the user can enter true/false or yes/no values. ListItem controls are

used to populate multiple check boxes in a CheckBoxList control.

  DropDownList: This control renders a drop-down list box from which the

user can select an item. You can set the items that appear in the list by

adding ListItem controls.

  FileUpload: This control renders a text box and a browse button. With this

control, users can specify a file to upload to the Web server. You must

implement server-side code to handle this upload and store the file.

  HiddenField: This control can be used to store information in the page that

you do not want the user to see.

  HyperLink : This control renders an HTML <a> tag, which you can use tolink to another Web page.

  Image: This control renders an image on the page. You can manipulate this

image with server-side code before it is displayed on the user’s browser.

  ImageMap: Similar to the Image control, this control renders an image.

However, it also allows you to create HotSpots within the image, which

links to other pages. You add these hotspots with CircleHotSpot, 

RectangleHotSpot, or PolygonHotSpot controls within the ImageMap 

markup.

Page 55: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 55/168

Unit 3: Adding and Configuring Server Controls 47

  Label: This control renders text, or an HTML fragment, on the page. You

can change the displayed text with server-side code.

  LinkButton: This control renders an object that appears as a hyperlink to

the user, but behaves as a button in terms of its programming model.

  ListBox: This control renders a box with a list of items from which the user 

can choose. Like the DropDownList control, this is populated with

ListItem controls.

  Literal: This control renders text to the page without adding any HTML

tags.

  MultiView and View: The MultiView control can be used to switch quickly

 between several displays on a page. The control contains several View

controls, each of which can contain HTML markup or other controls. Onlyone view is displayed at a time. You can display a view by using the

SetActiveView method of the control.

  Panel: This control is used as a container for other controls and tags. By

grouping elements within a Panel control you can, for example, hide or 

show them all in a single line of code.

  PlaceHolder: This control is used to mark a place in the page. You can use

this to easily insert other controls into the page at a particular place at run

time.

  RadioButton and RadioButtonList: These controls render option buttons.

A user can select only one option button control from a group. You can

group RadioButton controls by using the GroupName property. In a

RadioButtonList, all the buttons are automatically grouped. You can create

individual option buttons in a RadioButtonList control with ListItem 

controls.

  Substitution: This control is used to declare a section of the page that will

show dynamic content. If you have a page in which only a small area

changes when the page is reloaded, ASP.NET can cache the majority of it.You can inform ASP.NET not to cache the section that changes by

surrounding it with a Substitution control.

  Table, Table Row, and Table Cell: These controls render the elements of 

an HTML table. By using them in place of a static HTML table, you can

manipulate the table in code before the user sees the page. For example, you

could add rows to the table, one for each of your products.

  TextBox: This control renders an <input> tag with the type attribute set to

textbox, or a <textarea> tag, depending on the properties you set. The user 

can enter text and numeric values into the boxes that are displayed. This

control supports input masks that make it suitable for entering passwords or 

other sensitive information.

  Wizard: This control simplifies the task of building a series of forms tocollect user input. Within the control, you use WizardStep controls to

determine what appears on the page at each step in the procedure.

  XML: You can use this control to render an XML file onto the page. Toformat the data, you can use an XSL transform.

Page 56: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 56/168

48 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Create a Simple Web Page by Using Visual WebDeveloper 

Microsoft®Visual Web Developer ™ is the environment in Microsoft VisualStudio® 2005 that is used to create and work with Microsoft ASP.NET Web

applications. Tasks described in this How-to document include:

  Familiarizing yourself with Visual Web Developer 

  Creating a single-file ASP.NET page in Visual Web Developer 

  Adding controls

When you create a new Web application, Visual Web Developer creates a new

 page named Default.aspx. Visual Web Developer displays the page in Sourceview by default. This view displays the HTML description of the page, as

shown in the following illustration:

To switch to different views, you can use the view tabs feature of the VisualStudio 2005 integrated development environment (IDE). For more information

about the view tabs, refer to the next section of this document.

Page 57: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 57/168

Unit 3: Adding and Configuring Server Controls 49

A Tour of Visual Web Developer 

Before you begin working on a Web page, it is useful to familiarize yourself with the Visual Web Developer development environment. The followingillustration shows you the windows and tools that are available in Visual Web

Developer:

The following list describes the most commonly used windows and tools. (Only

the windows and tools marked in the preceding illustration are listed here.)

  Toolbars. Provide commands for formatting text, finding text, and so on.

Some toolbars are available only when you are working in Design view.

  Solution Explorer . Displays the files and folders in your Web site.

   Document windows. Display the documents you are working on in tabbed

windows. You can switch between documents by clicking tabs.

   Properties window. Allows you to change settings for the page, HTML

elements, controls, and other objects.

  View tabs. Present you with different views of the same document. Designview is a near-WYSIWYG editing surface. Source view is the HTML editor 

for the page. You will work with these views later in this walkthrough. If 

you prefer to open Web pages in Design view, on the Tools menu, click 

Options, select the HTML Designer node, and then change the Start

Pages In option.

  Toolbox. Provides controls and HTML elements that you can drag onto your 

 page. Toolbar elements are grouped by common function.

  Server Explorer . Displays database connections. If Server Explorer is not

visible in Visual Web Developer, on the View menu, click Other Windows 

and then click Server Explorer.

You can rearrange and resize the windows to suit your preferences. The

View menu allows you to display additional windows.Note

Page 58: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 58/168

50 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Adding Existing Items to a Web Application

You can add existing items, such as Web pages, graphics, and XML files, toWeb applications.

To Add an Existing Item to the Web Site1.  Select the Web application (or a subfolder of the application) in Solution

Explorer.

2.  On the Web Site menu, click Add Existing Item.

You can also right-click the Web application in Solution Explorer,and then from the shortcut menu, click Add Existing Item.

3.  Browse to the location of the file (or files) you want to add to the Web

application, and then select the items to add.

4.  Click Open.

Creating a New Web Forms Page

You can use the Default.aspx page as the home page for your Web site.However, for this lab, you will create and work with a new page. You can addmany types of pages and components to your Web site, including plain HTML

 pages, cascading style sheets, Web configuration files, and ASP.NET WebForms.

To Add a New Page to the Web Site1.  Close the Default.aspx page (if it is open).

2.  In Solution Explorer, right-click the Web site (for example, C:\WebSite),

and then click Add New Item.

3.  Under Visual Studio installed templates, click Web Form.

4.  In the Name box, type FirstWebPage.

5.  In the Language list, choose the programming language you prefer to use

(Microsoft Visual Basic® or C#).

When you created the Web site, you specified a default language. However,

each time you create a new page or component for your Web site, you canchange the language from the default. You can use different programming

languages in the same Web site.

6.  Clear the Place code in separate file box.

In this example, you are creating a single-file page with the code and HTMLin the same page. The code for ASP.NET Web Forms can be embedded in

the page or located in a separate class file.

7.  Click Add. Visual Web Developer creates the new page and opens it inSource view.

Note

Page 59: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 59/168

Unit 3: Adding and Configuring Server Controls 51

Adding HTML to the Page

In this part of the example, you will add some static HTML text to the page.

To Add Text to the Page

1.  At the bottom of the document window, click the Design tab to switch toDesign view. Design view displays the page that you are working on in a

WYSIWYG manner. At this point, you do not have any text or controls on

the page, so the page is blank.

2.  On the page, type Welcome to Visual Web Developer.

3.  Switch to Source view. You can see the HTML that you created by typing in

Design view.

Adding and Programming Controls

You can add controls to a Web Form. The following procedure describes howto add Button, TextBox, and Label controls to the page and write code tohandle the Click event for the Button control.

To Add Controls to the Page1.  Click the Design tab to switch to Design view.

2.  Press ENTER a few times to make some room.

3.  In the Toolbox, from the Standard group, drag three controls onto the

 page: a TextBox control, a Button control, and a Label control.

4.  Click on the page directly above the TextBox control, and then type Enter

your name.

This static HTML text is the caption for the TextBox control. You can mix

static HTML and server controls on the same page.

Setting Control Properties

Visual Web Developer offers you various ways to set the properties of controls

on the page. In this part of the example, you will set properties in both Designview and Source view.

To Set Control Properties1.  Select the Button control, and then in the Properties window, set the Text 

 property to Display Name.

2.  Switch to Source view.

Source view displays the HTML for the page, including the elements thatVisual Web Developer has created for the server controls. Controls are

declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute runat="server".

Control properties are declared as HTML attributes. For example, in step 1,

when you set the Text property for the Button control, you were actuallysetting the Text HTML attribute of the control.

Page 60: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 60/168

52 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The controls are inside a <form> element, which also has theattribute runat="server". The runat="server" attribute and the asp:  prefix for control tags marks the controls so that they are processed by

ASP.NET on the Web server when the page runs. Code outside of 

<form runat="server"> and <script runat="server"> elements is

interpreted by the browser as client-side code.

3.  Click to position the insertion point after the text Label in the <asp:Label> 

tag, and then press SPACEBAR.

A drop-down list appears that displays the list of properties you can set for a

Label control. This feature, referred to as IntelliSense®, helps you in Sourceview with the syntax of server controls, HTML elements, and other items on

the page.

4.  Select ForeColor and then type an equals sign. IntelliSense displays a list of 

available colors.

You can display an IntelliSense drop-down list at any time by

 pressing CTRL+J.

5.  Select a color for the Label control’s text, and then click OK .

The ForeColor attribute is set to the color that you have selected.

Note

Note

Page 61: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 61/168

Unit 3: Adding and Configuring Server Controls 53

How to: Set ASP.NET Control PropertiesWhen you set a control’s properties, you define its appearance and behavior.This document describes how to set control properties at design time.

The Web Forms Designer provides the Properties window, with which you can

set the properties of a control. Alternatively, you can set the properties of acontrol by modifying its attributes in the HTML markup for a Web page inSource view.

To Set Server Control Properties by Using the Properties Window

Either:

In Design view, select the control, and then set properties in the Propertieswindow.

Or:

In Source view, place the insertion point in the element tag of the control, andthen set properties in the Properties window.

To Set Server Control Properties by Using ASP.NET Syntax

1.  Switch to Source view.

2.  Find the control you want to edit in the HTML markup.

3.  Add an attribute with the name of the property you want to set, followed by

an equal sign, followed by the desired value in quotation marks.

You must ensure that the attribute and value you enter are supported by thecontrol you are editing. For information about the properties of a specific

control, search for the name of the control class in the Help index of theMicrosoft® Visual Studio® 2005 documentation.

The following example sets the MaxLength property of an HtmlInputText 

control:

<input id="MyTextBox" type=text runat=server maxlength=20 >

The following example sets the TextMode property of a TextBox control:

<asp:textbox text="Hi" runat=Server textMode=multiline />

Page 62: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 62/168

54 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Add Web Server Controls to a Web Forms Pageby Using the Web Forms Designer 

You can add a Web Server control to a Web page by dragging and dropping acontrol from the Standard group of the Toolbox in Microsoft® Visual

Studio® 2005. Web Server controls are automatically configured with therunat="server" attribute, so there is no need to convert them as there is for 

HTML server controls. To make the control more meaningful, it is good practice to edit the ID attribute that Visual Studio automatically assigns.

To Add a Web Server Control to a Web Forms Page

Complete the following procedure in the Design view of an .aspx page inVisual Studio 2005:

1.  From the Standard section in the Toolbox, drag the required control ontothe page.

The Web Forms Designer adds a new Web control to the page and includesthe attribute runat="server", which tells Microsoft ASP.NET to treat theelement as a server-side control. A glyph appears on the control toindicate that it is a server-side control.

2.  Right-click the control, and then click Properties.

3.  In the Properties window, change the (ID) property of the control to a

meaningful value.

Page 63: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 63/168

Unit 3: Adding and Configuring Server Controls 55

Navigation ControlsIn Microsoft® Visual Studio® 2005, the Navigation section in the Toolboxcontains controls that you can use to display the structure of your Web site.This information enables visitors to quickly recognize where they are in your 

site and move to other pages. The navigation controls are Web server controls;

you can write server-side code to control them.

The Navigation section in the Toolbox contains the following controls:

  Menu

Use this control to build a navigation menu for your site.

You can add items to the menu, either by adding MenuItem controls to the

markup, or by binding the control to a web.sitemap XML file. Theweb.sitemap file defines the structure of the menu, along with URL

information for the target of each menu item. Additionally, you can controlhow many levels of a hierarchical structure to display by default. The

following XML shows an example of the contents of a web.sitemap file:

<?xml version="1.0" encoding="utf-8" ?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode url="~/Default.aspx" title="Home" description="">

<siteMapNode url="~/TrailReport.aspx" title="Trails" description=""/>

<siteMapNode url="~/Diags.aspx" title="Diagnostics" description=""/>

<siteMapNode url="~/About.aspx" title="About Us" description=""/>

<siteMapNode url="~/Contact.aspx" title="Contact Us" description="">

<siteMapNode url="~/Feedback.aspx" title="Feedback" description=""/>

<siteMapNode url="~/Survey.aspx" title="Survey" description=""/>

</siteMapNode>

</siteMapNode>

</siteMap>

The following illustration shows the result of binding a Menu control to theexample web.sitemap file:

Page 64: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 64/168

56 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

  SiteMapPath

This control displays the location of the current page in the hierarchy of the

site. It is frequently shown close to the top of the page; visitors can use it toorient themselves quickly. The display is often referred to as a breadcrumbtrail . The control obtains data about the structure of the site from the

web.sitemap file.

The following illustration shows the result of binding a SiteMapPath 

control to the example web.sitemap just described:

  TreeView

This control renders a hierarchical tree of objects. Unlike the Menu control,the TreeView control can be used to display structures other than those of 

Web pages. For example, you could use it to display information from adatabase. You can populate the TreeView control by using TreeNode

objects, or you can bind it to a hierarchical data source such as an XML file.

The following illustration shows the result of binding a TreeView control tothe example web.sitemap just described:

Page 65: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 65/168

Page 66: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 66/168

58 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Determine How an ASP.NET Web Page WasInvoked

You will often find it useful to know how a Web page was invoked: whether byan original request, a postback, a cross-page post from another page, or by

transfer from another page by using the Server.Transfer method. For example,you might want to display a button on the page only when the page is displayed

as a result of a user’s navigation action, not when the page is loaded in responseto a postback. The Page object exposes properties that you can use to determinehow a page was invoked.

To Determine How a Page Was Invoked

Examine the following properties of the Page object:

  Page.IsPostBack 

  Page.PreviousPage

  Page.PreviousPage.IsCrossPagePostBack 

The following table lists the values of these properties in each situation.

Invocation IsPostBack PreviousPage IsCrossPagePostBack  

Original Request False Null False

Post Back True Null False

Cross Page Posting False Reference to the

source page

True

Server Transfer False Reference to the

source page

False

For example, to show a button only if the page was invoked by using a cross- page posting, use the following code:

[Visual Basic]

If PreviousPage.IsCrossPagePostBack = True Then

Button1.Visible = True

End If

[Visual C#]

if (PreviousPage.IsCrossPagePostBack == true)

{

Button1.Visible = true;

}

Page 67: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 67/168

Unit 3: Adding and Configuring Server Controls 59

Cross-Page Posting in an ASP.NET Web PageBy default, buttons and other controls that cause a postback on a Microsoft®ASP.NET Web page submit the page back to itself. Under some circumstances,you might want to post one page to another page—if, for example, you are

creating a multi-page form that collects different information on each page. You

can configure controls to post to a different target page. This is referred to ascross-page posting . The controls that can do this are those that implement theIButtonControl interface, such as the Button control.

Posting to a Different Page

To create a Button control that posts to a different page, use the following

HTML markup, which posts to a page called Processingpage.aspx:

<asp:Button ID="Button1"

runat="server"

Text="Submit to Other Web Form"

PostBackUrl="Processingpage.aspx" />

Retrieving Control Values from the Original Page

In the destination page, such as Processingpage.aspx, you can respond to the

input the user submitted. To do this, access the controls on the submitting page.ASP.NET enables this access by using the Page.PreviousPage object. The

following code reads input from a TextBox control on the PreviousPage object into a Label on the page it posted to:

[Visual Basic]

If Not Page.PreviousPage Is Nothing Then

Dim SourceTextBox As TextBox

SourceTextBox = CType(PreviousPage.FindControl("TextBox1"), _

TextBox)

If Not SourceTextBox Is Nothing Then

Label1.Text = SourceTextBox.Text

End If

End If

[Visual C#]

if (Page.PreviousPage != null)

{

TextBox SourceTextBox =

(TextBox)Page.PreviousPage.FindControl("TextBox1");

if (SourceTextBox != null){

Label1.Text = SourceTextBox.Text;

}

}

Page 68: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 68/168

60 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Retrieving Public Properties from the Original Page

You can access public properties of the original page in much the same way.The following code shows how to define a public, read-only property called

CurrentCity, defined by the original (previous) page:

[Visual Basic]Public ReadOnly Property CurrentCity() As String

Get

Return textCity.Text

End Get

End Property

[Visual C#]

public string CurrentCity

{

get

{

return textCity.Text;

}}

Before you can access the CurrentCity property in the target page, you mustinclude the PreviousPageType directive at the top of the HTML markup, just

under the Page directive. This makes the reference to the previous pagestrongly typed and enables you to refer to its properties directly:

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

The following code assigns the value of the original page’s CurrentCity 

 property to a Label control:

[Visual Basic]

Label1.Text = PreviousPage.CurrentCity

[Visual C#]

Label1.Text = PreviousPage.CurrentCity;

Page 69: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 69/168

Unit 3: Adding and Configuring Server Controls 61

How to: Post an ASP.NET Page to a Different PageBy default, controls on Microsoft® ASP.NET Web pages that cause a postback,such as the Button control, post back to the same page for processing.However, you can configure controls to post to a different page within the same

application. To do this, use the PostBackURL property of the control to specify

the page to which the control should post.

To Specify the Post Page in Design View

1.  In Design view, drag a Button control from the Standard group in the

Toolbox onto the page.

2.  Right-click the new Button control and then click Properties.

3.  In the Properties window, set the PostBackURL property to

processingpage.aspx.

To Specify the Post Page in Source ViewIn Source view, add the following tags to the page markup, within the <form> 

element:

<asp:Button ID="Button1"

runat="server"

Text="Button"

PostBackUrl="processingpage.aspx" />

Page 70: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 70/168

Page 71: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 71/168

 

Unit 4: Creating a Common Layout byUsing Master Pages

Master Pages OverviewThis document contains extracts from the article “ASP.NET Master Pages

Overview,” which you can find in the Microsoft® Visual Studio® 2005Documentation at ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/

MS.VisualStudio.v80.en/dv_aspnetcon/html/4e53eedf-8304-4e7a-aed1-691a2623b28b.htm.

Microsoft ASP.NET master pages allow you to create a consistent layout for 

the pages in your application. A single master page defines the look and feeland standard behavior that you want for all the pages (or a group of pages) in

your application. You can then create individual content pages that contain thecontent you want to display. When users request the content pages, the pages

merge with the master page to produce output that combines the layout of themaster page with the content from the content page.

How Master Pages Work

Master pages actually consist of two pieces, the master page itself and one or 

more content pages.

Master Pages

A master page is an ASP.NET file with the extension .master, such asMasterPage.master, with a predefined layout that can include static text, HTML

elements, and server controls. The master page is identified by a special@ Master directive that replaces the @ Page that is used for ordinary .aspx

 pages. The directive looks like the following:

[Visual Basic]

<%@ Master Language="VB" %>

[C#]<%@ Master Language="C#" %>

Page 72: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 72/168

64 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The @ Master directive can contain most of the same directives that an @

Page directive can. For example, the following master page directive includesthe name of a code-behind file and assigns a class name to the master page:

[Visual Basic]

<%@ Master Language="VB" CodeFile="MasterPage.master.vb"

AutoEventWireup="false" Inherits="MasterPage" %>

[C#]

<%@ Master Language="C#" CodeFile="MasterPage.master.cs"

AutoEventWireup="false" Inherits="MasterPage" %>

In addition to the @ Master directive, the master page also contains all the top-

level HTML elements for a page, such as <html>, <head>, and <form>. For example, on a master page you might use an HTML table for the layout, an<img> tag for your company logo, static text for the copyright notice, and

server controls to create standard navigation for your site. You can use anyHTML and ASP.NET elements as part of your master page. On the master page

you can also include one or more ContentPlaceHolder controls that define

regions where replaceable content will appear.

Content Pages

You define the content for the placeholders by creating individual content pages, which are ASP.NET pages (.aspx files and, optionally, code-behindfiles) that are bound to a specific master page. The binding is established in the

content page’s @ Page directive by including a MasterPageFile attribute that points to the master page to be used. For example, a content page might have

the following @ Page directive, which binds it to the Master1.master page:

[Visual Basic]

<%@ Page Language="VB" MasterPageFile="~/MasterPages/Master1.master" %>

[C#]

<%@ Page Language="C#" MasterPageFile="~/MasterPages/Master1.master" %>

In the content page, you create the content by adding Content controls andmapping them to ContentPlaceHolder controls on the master page. For 

example, the master page might have content placeholders calledContentPlaceholder1 and ContentPlaceholder2. In the content page, you can

create two Content controls, one mapped to ContentPlaceholder1 and the other to ContentPlaceholder2.

After creating Content controls, you add text and controls to them. In a content

 page, anything not inside the Content controls (except script blocks) results in

an error. You can perform any tasks in a content page that you do in anASP.NET page. For example, you can generate content for a Content control by using server controls and database queries or other dynamic mechanisms.

You can create multiple master pages to define different layouts for parts of 

your site, and a different set of content pages for each master page.

Page 73: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 73/168

Unit 4: Creating a Common Layout by Using Master Pages 65

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created bycopying existing code, text, and control elements repeatedly; using framesets;using include files for common elements; using ASP.NET user controls; and so

on. Advantages of master pages include:

  They allow you to centralize the common functionality of your pages so that

you can make updates in just one place.

  They make it easy to create one set of controls and code and apply the

results to a set of pages. For example, you can use controls on the master 

 page to create a menu that applies to all pages.

  They give you fine-grained control over the layout of the final page by

allowing you to control how the placeholder controls are rendered.

  They provide an object model that allows you to customize the master page

from individual content pages.

Run-Time Behavior of Master PagesWhen a content page is requested in the browser, ASP.NET processes the

request in the following sequence:

1.  ASP.NET fetches the page.

2.  ASP.NET determines whether the content page references a master page.

3.  If so, ASP.NET fetches the master page associated with the content page.

4.  ASP.NET merges the content into the content placeholders on the master  page.

5.  ASP.NET renders results to the browser.

Page 74: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 74/168

66 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The process is illustrated in the following diagram.

From the user’s perspective, the combined master and content pages are a

single, discrete page. The URL of the page is that of the content page.

From a programming perspective, the two pages act as separate containers for 

their respective controls. However, you can reference public master pagemembers from code in the content page.

Page 75: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 75/168

Unit 4: Creating a Common Layout by Using Master Pages 67

How to: Create a Master PageThe process of adding a master page to a Web application is similar to the process of adding a Web Form.

To Add a New Master Page to the Web Site1.  In Solution Explorer, right-click the Web site and then click Add New

Item.

2.  Under Visual Studio installed templates, click Master Page.

3.  In the Name box, type SiteMaster.Master .

4.  In the Language list, select your preferred programming language.

5.  Click Add.

Microsoft® Visual Web Developer ™ creates the new master page and opens it inSource view.

Designing the Master Page

When you create a new master page by using Microsoft Visual Studio® 2005, itcontains a single ContentPlaceholder control. This control provides a location

where content from referencing pages will be merged at run time. You can addadditional ContentPlaceholder controls to the master page.

ContentPlaceholder controls are identified by their ID attributes—referencing pages will include Content controls with attributes that map to the

ContentPlaceholder control IDs on the master page.

You can also add any HTML markup, HTML controls, and Web server controls

to the page, although these user interface elements should be inserted outside of 

the ContentPlaceholder controls. You can add server-side code to the master  page; this code will run on all referencing pages at run time.

Page 76: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 76/168

68 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Configure Content PagesThe process of adding a content page to a Web application is similar to the process of adding a Web Form.

To Add a New Content Page to the Web Site1.  In Solution Explorer, right-click the Web site and then click Add New

Item.

2.  Under Visual Studio i

3.  nstalled templates, click Web Form.

4.  In the Name box, type Content.aspx.

5.  In the Language list, select your preferred programming language.

6.  Select the Select master page check box.

7.  Click Add.

8.  In the Select a Master Page dialog box, select the master page that thiscontent page will reference and then click OK .

Microsoft® Visual Web Developer ™ creates the new content page and

opens it in Source view.

Configuring an Existing Web Form as a Content Page

If you have an existing Web Form that you want to use as a content page, you

can configure it to reference a master page by setting the MasterPageFile  property of the page. You can do this either by using the Properties window or  by adding the MasterPageFile page attribute directly to the markup in Source

view. When you configure an existing Web Form as a content page, you mustadd the appropriate Content controls manually. You must also remove all

elements outside of the Content controls (or move them inside the Content controls).

The following example shows how to use the MasterPageFile attribute:

[Visual Basic]

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb"

Inherits="_Default" MasterPageFile="~/SiteMaster.master" %>

[C#]

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"

Inherits="_Default" MasterPageFile="~/SiteMaster.master" %>

Page 77: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 77/168

Unit 4: Creating a Common Layout by Using Master Pages 69

Designing the Content Page

The Content controls that map to ContentPlaceholder controls on the master  page provide locations for the content that is merged with the master page atrun time. ContentPlaceholder controls on the master page are identified by

their ID attributes—the Content controls on the content page include the

ContentPlaceholderID attribute, which maps the Content control to theContentPlaceholder control on the master page.

You can add any HTML markup, HTML controls, and Web server controls to

the content page, although these user interface elements must be placed inside the Content controls. You can also add server-side code to the content page to

 provide page-specific processing features.

Page 78: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 78/168

70 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Create Nested Master PagesThis document is a copy of the article “Nested Master Pages,” which you canfind in the Microsoft® Visual Studio® 2005 Documentation atms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en

/dv_aspnetcon/html/ec29afad-b7f5-4c58-a4db-b538dbfcea1b.htm.

Master pages can be nested, with one master page referencing another as itsmaster. Nested master pages allow you to create componentized master pages.For example, a large site might contain an overall master page that defines the

look of the site. Different site content partners can then define their own childmaster pages that reference the site master and that in turn define the look for 

that partner’s content.

As with any master page, a child master page has the extension .master. Thechild master page typically contains content controls that are mapped to content

 placeholders on the parent master page. In this respect, the child master page islaid out like any content page. However, the child master page also has content

 placeholders of its own to display content supplied by its own child pages. The

following three page listings show a simple nested master page configuration.This is the parent.master master file:

[C#]

<%@ Master Language="C#" %>

<HTML>

<BODY>

<form id="Form1" runat="server">

<h1>Parent Master</h1>

<p><font color="red">This is Parent-master content.</font></P>

<asp:ContentPlaceHolder ID="MainContent" runat="server" />

</form>

</BODY>

</HTML>

This is the child master file:

[C#]

<%@ Master Language="C#" MasterPageFile="Parent.master"%>

<asp:Content id="Content1" ContentPlaceholderID="MainContent" runat="server">

<asp:panel runat="server" id="panelMain" backcolor="lightyellow">

<h2>Child master</h2>

<asp:panel runat="server" id="panel1" backcolor="lightblue">

<p>This is childmaster content.</p>

<asp:ContentPlaceHolder ID="ChildContent" runat="server" />

</asp:panel>

<asp:panel runat="server" id="panel2" backcolor="pink"><p>This is childmaster content.</p>

<asp:ContentPlaceHolder ID="ChildFooter" runat="server" />

</asp:panel>

</asp:panel>

</asp:Content>

Page 79: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 79/168

Unit 4: Creating a Common Layout by Using Master Pages 71

This is a child file that references the child master page:

[C#]

<%@ Page Language="C#" MasterPageFile="Child.Master"%>

<asp:Content id="pageContent" ContentPlaceholderID="ChildContent" runat="server">

<asp:Label runat="server" id="Label1" text="Child label1" font-bold="true" />

<br>

</asp:Content>

<asp:Content id="footerContent" ContentPlaceholderID="ChildFooter" runat=server>

<asp:Label runat="server" id="Label2" text="Child label2" font-bold=true/>

</asp:Content>

Page 80: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 80/168

Page 81: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 81/168

 

Unit 5: Managing State for a WebApplication

ASP.NET State Management OverviewThe information in this document is adapted from the article “ASP.NET State

Management,” which you can find in the Microsoft® Visual Studio® 2005documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/0218d965-5d30-445b-b6a6-8870e70e63ce.htm.

A new instance of the Web page class is created each time the page is posted to

the server. In traditional Web programming, this would ordinarily mean that allinformation that is associated with the page—along with the controls on the

 page—would be lost with each roundtrip. For example, if a user entersinformation into a text box, that information would be lost in the roundtrip from

the browser or client device to the server.

To overcome this inherent limitation of traditional Web programming, the

Microsoft ASP.NET framework includes several options to help you preservedata on both a per-page basis and an application-wide basis. These features are

as follows:

  View state

  Control state

  Hidden form fields

  Cookies

  Query strings

  Application state

  Session state

View state, control state, hidden form fields, cookies, and query strings all

involve storing data on the client in various ways. For instance, application andsession state both store data in memory on the server. Each option has distinct

advantages and disadvantages, depending on the scenario.

Page 82: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 82/168

74 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Client-Based State Management Options

The following sections describe options for state management that involvestoring information either in the page or on the client computer. For theseoptions, no information is maintained on the server between roundtrips.

View StateThe System.Web.UI.Control.ViewState property provides a dictionary object

for retaining values between multiple requests for the same page. This is thedefault method that the page uses to preserve page- and control-property values

 between roundtrips.

When the page is processed, the current state of the page and controlsis hashed into a string and saved in the page as a hidden field, or 

multiple hidden fields if the amount of data stored in the

System.Web.UI.Control.ViewState property exceeds the specified value in

the System.Web.UI.Page.MaxPageStateFieldLength property. When the page is posted back to the server, the page parses the view-state string at page

initialization and restores property information in the page.

Control StateSometimes you need to store control-state data for a control to work properly.For example, if you have written a custom control that has different tabs thatshow different information, the control needs to know which tab is selected

 between roundtrips if it is to work as expected. The

System.Web.UI.Control.ViewState property can be used for this purpose, but

ViewState can be turned off at a page level by developers, effectively breakingyour control. To solve this, the Microsoft ASP.NET page framework exposes a

new feature in ASP.NET version 2.0 called control state.

The System.Web.UI.PageStatePersister.ControlState property allows you to

 persist property information that is specific to a control and cannot be turned off as can the System.Web.UI.Control.ViewState property.

Hidden Form FieldsASP.NET allows you to use HTML-standard hidden fields in a form. A hiddenfield does not render visibly in the browser, but you can set its properties just as

you can with a standard control. When a page is submitted to the server, thecontent of a hidden field is sent in the HTTP form collection along with thevalues of other controls. A hidden field acts as a repository for any page-

specific information that you want to store directly in the page.

It is easy for a malicious user to see and modify the contents of a hidden

field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly.

Note

Page 83: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 83/168

Unit 5: Managing State for a Web Application 75

A hidden field stores a single variable in its value property and must beexplicitly added to the page. After adding a hidden field to the page, you insertyour value into the hidden field. ASP.NET provides the

System.Web.UI.HtmlControls.HtmlInputHidden control, which offershidden-field functionality.

CookiesA cookie is a small amount of data that is stored either in a text file on the clientfile system or in memory in the client browser session. It contains site-specific

information that the server sends to the client along with page output. Cookiescan be temporary (with specific expiration times and dates) or persistent.

You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser 

requests a page, the client sends the information in the cookie along with therequest information. The server can read the cookie and extract its value. A

typical use is to store a token (perhaps encrypted) indicating that the user hasalready been authenticated in your application.

The browser can send the data back only to the server that originally

created the cookie. However, malicious users have ways to access cookies andread their contents. It is recommended that you do not store sensitive

information, such as a user name or password, in a cookie. Instead, store atoken in the cookie that identifies the user and then use the token to look up thesensitive information on the server.

Query StringsA query string is information that is appended to the end of a page URL. Atypical query string might look like the following example:

http://www.contoso.com/listwidgets.aspx?category=basic&price=100

In this URL path, the query string starts with the question mark (?) and includestwo attribute-value pairs, one called category and the other called price.

Query strings provide a simple but limited way of maintaining stateinformation. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another 

 page where it will be processed. However, some browsers and client devicesimpose a 255-character limit on the length of the URL.

Information that is passed in a query string can be tampered with

 by a malicious user. Do not rely on query strings to convey important or sensitive data.

For query string values to be available during page processing, you must submitthe page by using an HTTP GET command. That is, you cannot take

advantage of a query string if a page is processed in response to an HTTP

POST command.

Note

Security Note

Page 84: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 84/168

76 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Server-Based State Management Options 

ASP.NET offers you a variety of ways to maintain state information on theserver rather than persisting information on the client. With server-based statemanagement, you can decrease the amount of information sent to the client to

 preserve state; however, this approach can use costly resources on the server.

The following sections describe two server-based state management features:application state and session state.

Application StateASP.NET allows you to save values by using application state—which is aninstance of the System.Web.HttpApplicationState class—for each active Web

application. Application state is a global storage mechanism that is accessiblefrom all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server roundtrips and

 between requests for pages.

Application state is stored in a key/value dictionary that is created during each

request to a specific URL. You can add your application-specific information tothis structure to store it between page requests.

Once you add your application-specific information to application state, theserver manages it.

Session StateASP.NET allows you to save values by using session state—which is aninstance of the System.Web.SessionState.HttpSessionState class—for each

active Web application session.

Session state is similar to application state, except that it is scoped to the current

 browser session. If different users are using your application, each user session

will have a different session state. In addition, if a user leaves your applicationand then returns later, the second user session will have a different session statefrom the first.

Session state has a key-value dictionary structure for storing session-specific

information that needs to be maintained between server roundtrips and betweenrequests for pages.

You can use session state to accomplish the following tasks:

  Uniquely identify browser or client-device requests and map them to an

individual session instance on the server.

  Store session-specific data on the server for use across multiple browser or 

client-device requests within the same session.

  Raise appropriate session management events. In addition, you can write

application code that makes use of these events.

Once you add your application-specific information to session state, the server manages this object. Depending on the options you specify, session information

can be stored in cookies, an out-of-process server, or a computer runningMicrosoft SQL Server ™.

Page 85: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 85/168

Unit 5: Managing State for a Web Application 77

What’s New in ASP.NET State ManagementThis document is a copy of the article “What’s New in ASP.NET StateManagement,” which you can find in the Microsoft® Visual Studio® 2005documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/ba1da7de-269e-

418f-9739-5c307ba4afb7.htm.

Microsoft ASP.NET version 2.0 retains much of the functionality of ASP.NETversion 1.1, including automatic page-state persistence using view state and

database support for session state and application state. Additionally,ASP.NET 2.0 contains two new features: view-state chunking and control state.

View-State Chunking

View state provides an easy way to automatically persist field and control dataon the page without having to manually request it and then re-populate during

roundtrips to the server. It also allows you to store custom data on the page in

the System.Web.UI.Control.ViewState property.However, view-state data can, in some cases, become very large. Because view-

state data is stored in hidden fields, some proxies and firewalls will preventaccess to the page that contains them. For this reason, the ASP.NET 2.0 page

framework introduces a feature called view-state chunking. If the amount of view-state data becomes too large, view-state chunking will automatically split

the data into chunks and put the data into multiple hidden-form fields.

To enable view-state chunking, set the

System.Web.UI.Page.MaxPageStateFieldLength property to the maximumsize (in bytes) that you want to allow in a single view-state field. When the pageis posted back to the server, the page parses the view-state string at page

initialization and restores property information in the page. The default is –1,

which means that there is no maximum size and the view state will not be broken up into chunks.

Control State

Sometimes you need to store control-state data for a control to work properly.

For example, if you have written a custom control that has different tabs thatshow different information, somehow the control needs to know which tab is

selected between roundtrips to be able to work as expected. TheSystem.Web.UI.Control.ViewState property can be used for this purpose, but

ViewState can be turned off at a page level by developers, effectively breaking

your control. To solve this, the ASP.NET page framework exposes a new

feature in ASP.NET version 2.0, called control state.

The System.Web.UI.PageStatePersister.ControlState property allowsyou to persist property information that is specific to a control and cannot be turned off (unlike the System.Web.UI.Control.ViewState property).

To use control state, your control must call the

System.Web.UI.Page.RegisterRequiresControlState method during

initialization and then override the System.Web.UI.Control.SaveControlState  and System.Web.UI.Control.LoadControlState methods.

Page 86: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 86/168

78 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

ASP.NET ViewStateMicrosoft® ASP.NET enables you to persist the contents of server controls between repeated requests for the same page by a Web application. For example, when a user types data into a Web form and submits the form back to

the Web server, the server processes the values supplied by the user and then

redisplays the page. The page should still contain the values entered by the user.This persisted information is referred to as the ViewState of the Web form.

The ASP.NET runtime implements ViewState by hashing the values in the

fields on a Web form and storing the result in a hidden field on the page. Thefield is not visible in the browser but the user can see it by viewing the page

source. In a typical Web application, it is not necessary to maintain ViewStateinformation for every field, so ASP.NET enables you to selectively configure it

for individual pages and controls.

Some proxy servers and firewalls block access to pages that contain largehidden fields. Because ViewState data is preserved in hidden fields, this can

 prevent access to ASP.NET pages on which there is a lot of ViewState

information to retain. To avoid this problem, you can divide the ViewState intoseveral hidden fields. You can do this by using view-state chunking.

 To enable or disable ViewState for a control

1.  Using Microsoft Visual Studio®, display the Web form containing the

control in Design view.

2.  Select the control to configure.

3.  In the Properties window, set the EnableViewState property to true to

 persist state information for the control; set it to false to disable view-state

 persistence.

You can enable or disable ViewState for a control in Source view byadding EnableViewState="true" or EnableViewState="false" to themarkup for the control.

 To enable or disable ViewState for a page

1.  In Visual Studio, display the Web form in Source view.

1.  Locate the <%@ Page %> directive at the top of the page markup.

2.  To enable ViewState, add EnableViewState="true" to the directive.

To disable ViewState, add EnableViewState="false" to the directive.

 To examine the ViewState information in the markup sent to thebrowser

1.  Browse to the Web page by using Microsoft Internet Explorer.

2.  On the View menu, click Source.

 Notepad opens and displays the source markup for the Web form.

3.  On the Edit menu, click Find.

4.  In the Find What box, type __VIEWSTATE and then click Find Next.

 Notepad locates the hidden field that contains the ViewState data.

Note

Page 87: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 87/168

Unit 5: Managing State for a Web Application 79

 To use view-state chunking

1.  In Visual Studio, in Solution Explorer, right-click the page to configure, and

then click View Code.

2.  In the Code and Text Editor window, find the Page_Load method.

3.  Add a statement that sets the MaxPageStateFieldLengthproperty of the

 page to the maximum length of each chunk, as follows:

[Visual Basic]

MaxPageStateFieldLength = 250

[C#]

MaxPageStateFieldLength = 250;

Page 88: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 88/168

80 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Initializing the ASP.NET Application and Session ObjectsMicrosoft® ASP.NET provides two objects that can be used to store smallamounts of data that can be accessed from any page in a Web application.

The Application object is created when the application is started. There is a

single Application object for the whole application. Different users running thesame Web application share the same Application object.

The Session object is created when a user begins a session in a Webapplication. Each user has his or her own Session object. You can access the

Session object for the current user only when writing code.

You can handle the following Application and Session object events:

  Application_Start  

This event occurs when the first user visits a page in the Web application.

  Application_End 

This event occurs if the application stops, perhaps because of a system

reboot.

  Application_Error  

This event occurs if the application throws an unhandled exception.

  Session_Start 

This event occurs when any user begins a session in the Web application.

  Session_End 

This event occurs when a user session ends, usually because the session has

timed out since the user last made a request. This event fires only if your application uses the InProc session-state mode.

To write code to handle these events, you must add a Global.asax file to theWeb application.

 To handle the Application and Session events

1.  Using Microsoft Visual Studio® 2005, examine Solution Explorer. If there is

no Global.asax file, right-click the project and then click Add New Item.

2.  In the Add New Item dialog box, click Global Application Class and then

click Add.

Visual Studio adds a new Global.asax file to your application and displays itin the Code and Text Editor window.

3.  Visual Studio 2005 generates the event handlers for each of the events listed

earlier. Add your code to the appropriate event handler.

Page 89: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 89/168

Unit 5: Managing State for a Web Application 81

How to: Save Values in Session StateThis document is a copy of the article “How to: Save Values in Session State,”which you can find in the Microsoft® Visual Studio® 2005 documentation atms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/

MS.VisualStudio.v80.en/dv_aspnetcon/html/a6cb2e3a-df49-4b12-9d9a-

eed45541c165.htm.

This example uses the HttpSessionState object to persist values within anindividual session. 

[Visual Basic]

Dim firstName As String = "John"

Dim lastName As String = "Smith"

Dim city As String = "Seattle"

Session("FirstName") = firstName

Session("LastName") = lastName

Session("City") = city

[C#]

string firstName = "Jeff";

string lastName = "Smith";

string city = "Seattle";

Session["FirstName"] = firstName;

Session["LastName"] = lastName;

Session["City"] = city;

Page 90: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 90/168

82 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Read Values from Session StateThis document contains extracts from the article “How to: Read Values fromSession State,” which you can find in the Microsoft® Visual Studio® 2005documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/2ef449bc-5c17-

4785-b7cf-378c601af8f5.htm.

This example accesses the HttpSessionState.Itemproperty to retrieve thevalues in session state.

[Visual Basic]

Dim firstName as String = CType(Session.Item("FirstName"), String)

Dim lastName as String = CType(Session.Item("LastName"), String)

Dim city as String = CType(Session.Item("City"), String)

[C#]

string firstName = (string)(Session["First"]);

string lastName = (string)(Session["Last"]);

string city = (string)(Session["City"]);

 No exception is thrown if you attempt to get a value out of session state thatdoes not exist. To be sure that the value you want is in session state, check first

for the existence of the object with a test such as the following:

[Visual Basic]

If Session.Item("FirstName") Is Nothing Then

' No such value in session state,

' take appropriate action.

End If

[C#]

if (Session["City"] == null)

// No such value in session state,

// take appropriate action.

If you attempt to use a nonexistent session-state entry in some other way (for example, to examine its type), a System.NullReferenceException exception is

thrown.

Session values are of type System.Object. In Microsoft Visual Basic®, if you

set Option Strict On, you must cast from type System.Object to theappropriate type when getting values out of session state, as shown in the

example. In C#, you should always cast to the appropriate type when readingsession values.

Page 91: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 91/168

Unit 5: Managing State for a Web Application 83

How to: Save Values in Application StateThis document contains extracts from the article “How to: Save Values inApplication State,” which you can find in the Microsoft® Visual Studio® 2005documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/1e0caf13-e8f0-

46d5-9ca0-8b53e4b1c08e.htm.

Application state is a data repository that is available to all classes within aMicrosoft ASP.NET application. Application state is stored in memory on the

server and is faster than storing and retrieving in a database. Unlike sessionstate, which is specific to a single user session, application state applies to all

users and sessions. Therefore, application state is a useful place to store smallamounts of often-used data that does not change from one user to another.

Application state is stored in the System.Web.HttpApplicationState class, a

new instance of which is created the first time a user accesses a URL resourcewithin an application. The System.Web.HttpApplicationState class is exposed

through the System.Web.UI.Page.Application property.

Application state stores data as System.Object data types. Thus, even thoughyou do not have to serialize the data when persisting it to application state, you

must convert the data back to the appropriate type when retrieving it.

 To write a value to application state

•  In your application, set the value of the variable in the

System.Web.HttpApplicationState class. The following code exampleshows how you can set the application variable Message to “Hello, world.”

[Visual Basic]

Application("Message") = "Hello, world."

[C#]

Application["Message"] = "Hello, world.";

 To write a value to application state when the application starts

•  In your application, set the value of the application state variable of theApplication_Start handler in the Global.asax file. Just as in a regular .aspx

 page, the System.Web.HttpApplicationState class is exposed through theSystem.Web.UI.Page.Application object. The following code exampleshows how you can set the application variable Message to “Hello, world.”,

and initialize the variable PageRequestCount to 0.

[Visual Basic]

Application("Message") = "Hello, world."

Application("PageRequestCount") = 0

[C#]

Application["Message"] = "Hello, world.";

Application["PageRequestCount"] = 0;

Page 92: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 92/168

84 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Read Values from Application StateThis document is a copy of the article “How To: Read Values from ApplicationState,” which you can find in the Microsoft® Visual Studio® 2005Documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS. VisualStudio.v80.en/dv_aspnetcon/html/21142bde-d4f2-

4e80-b1b3-6113b4477c47.htm.

Application state is a data repository that is available to all classes within aMicrosoft ASP.NET application. Application state is stored in memory on the

server and is faster than storing and retrieving in a database. Unlike sessionstate, which is specific to a single user session, application state applies to all

users and sessions. Therefore, application state is a useful place to store smallamounts of often-used data that does not change from one user to another.

Application state is stored in the System.Web.HttpApplicationState class, a

new instance of which is created the first time a user accesses a URL resourcewithin an application. 

 To read a value from application state•  Determine whether the application variable exists and then convert the

variable to the appropriate type when you access it. The following code

example retrieves the AppStartTime value and converts it to a variablecalled appStateTime of type System.DateTime.

[Visual Basic]

If (Not Application("AppStartTime") _

Is Nothing) Then

Dim myAppStartTime As DateTime = _

CDate(Application("AppStartTime"))

End If

[C#]if (Application["AppStartTime"] != null)

{

DateTime myAppStartTime =

(DateTime)Application["AppStartTime"];

}

Application state stores data as System.Object data types. Thus, even though

you do not have to serialize the data when persisting it to application state, youmust convert the data back to the appropriate type when retrieving it.

If you attempt to use a non-existent application-state entry in some other way(for example, to examine its type), a System.NullReferenceException  

exception is thrown.

Page 93: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 93/168

Unit 5: Managing State for a Web Application 85

How to: Implement Out-of-Process Session StateThe information in this document is adapted from the article “Session StateModes,” which you can find in the Microsoft® Visual Studio® 2005documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS. VisualStudio.v80.en/dv_aspnetcon/html/0bb0a3a3-650f-

4c47-a0c5-b08b9b591bb4.htm.

Microsoft ASP.NET session state supports several different storage options for session variables. Each option is identified by a value of the

System.Web.SessionState.SessionStateMode enumeration. The following listdescribes the available session-state modes:

  InProc mode, which is the default and stores session state in memory on the

Web server.

  StateServer mode, which stores session state in a separate process called the

ASP.NET state service. This ensures that session state is preserved if the

Web application is restarted and also makes session state available to

multiple Web servers in a Web farm.

  SQLServer mode, which stores session state in a Microsoft SQL Server ™ 

database. This ensures that session state is preserved if the Web application

is restarted and also makes session state available to multiple Web servers in

a Web farm.

  Custom mode, which allows you to specify a custom storage provider.

You can specify the mode you want ASP.NET session state to use by supplying

one of the System.Web.SessionState.SessionStateMode enumeration valuesfor the mode attribute of the <sessionState> element in the Web.config file for 

your application.

 To enable InProc mode

•  Open the Web.config file for your application. Add the following markup

within the <system.web> tags

<sessionState mode="InProc"></sessionState>

Before you enable StateServer mode, you must have decided which server willhost the state information and have its IP address or host name. You must also

ensure that the ASPNET State Service is running on that server.

 To enable StateServer mode

1.  Open the Web.config file for your application. Add the following markup

within the <system.web> tags:<sessionState mode="StateServer" stateConnectionString="tcpip=MyStateServer:42424"

cookieless="false" timeout="20"/>

2.  Replace MyStateServer with the IP address or host name of the server you

have selected to host the session-state data.

Before using SQLServer mode, you must have a computer running SQL Server 

to run the database. Install the database on this server in the following way:

Page 94: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 94/168

86 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

 To enable SQLServer mode

1.  Locate the Aspnet_regsql.exe tool, which is usually in the following folder:

Systemroot\Microsoft.NET\Framework\versionnumber\

2.  Run the tool. The following example installs the database on a server called

MySqlServer.Aspnet_regsql –S MySqlServer –E –ssadd –sstype p

Once the database has been installed, you must configure your applicationto use it. This is done in the following way:

3.  In Visual Studio, open the Web.config file.

4.  Add the following markup within the <system.web> tags:

<sessionState mode="SQLServer" sqlConnectionString="

Integrated Security=SSPI;data source=MySqlServer;" />

Page 95: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 95/168

Unit 5: Managing State for a Web Application 87

How to: Store and Retrieve State Data in the CacheObject

To cache an item, you specify its value and a key name for it. You can also usethe Cache.Insert and Cache.Add methods, which provide greater control. For 

example, with these methods you can specify a timeout value after which theitem is removed from cache.

The Microsoft® ASP.NET runtime automatically removes items from the cache

when system resources become scarce. Items can also expire or be removed for other reasons. When you retrieve values from the cache, you must bear this in

mind. If you try to access a cached item that has been removed, ASP.NET willreturn a null reference.

 To add a value to the cache by specifying a key name

•  Add the value to the Cache object, using the key name as the indexer.

The following code caches the value in the Text property of a TextBox

control called txtExample:[Visual Basic]

Cache("TextItem1") = txtExample.Text

[C#]

Cache["TextItem1"] = txtExample.Text;

 To add a value to the cache by using the Insert method

•  Specify the key name as the first argument and the value being cached asthe second argument.

The following code performs the same task as the previous example byusing the Insert method of the Cache object:

[Visual Basic]

Cache.Insert("TextItem1", txtExample.Text)

[C#]

Cache.Insert("TextItem1", txtExample.Text);

Page 96: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 96/168

88 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

 To retrieve values from the cache

•  Reference the Cache object, using the key name as the indexer, as shown in

the following example.

When you attempt to retrieve values from the cache you should bear 

in mind that they may have been removed by scavenging. You should also

ensure that values are of the expected type.

[Visual Basic]

If Not Cache("TextItem1") Is Nothing Then

txtExample.Text = CStr(Cache("TextItem1"))

End If

[C#]

if (Cache["TextItem1"] != null)

{

txtExample.Text = (string)Cache["TextItem1"];

}

Note

Page 97: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 97/168

Unit 5: Managing State for a Web Application 89

How to: Define Dependencies Between Cached ItemsThe information in this document is adapted from the article “How to: AddItems to the Cache,” which you can find in the Microsoft® Visual Studio® 2005Documentation at ms-

help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudi

o.v80.en/dv_aspnetcon/html/80b8105b-4c44-4583-a9d6-b891a957242c.htm.

 To add an item that has a dependency on a file to the cache

•  You can add an item with a dependency to the cache by using thedependencies parameter in the Cache.Add or Cache.Insert method. The

following example demonstrates using the Insert method to add an itemwith a dependency on an XML file to the cache. 

[Visual Basic]

Cache.Insert("MyData1", connectionString, new CacheDependency

(Server.MapPath("~\myConfig.xml")))

[C#]

Cache.Insert("MyData1", connectionString, new CacheDependency(Server.MapPath("~\myConfig.xml")));

 To add an item that has a dependency on another cached item to the

cache

•  You can also add an item that depends on another object in the cache to the

cache, as shown in the following example: 

[Visual Basic]

Dim sDependencies As String(1)

sDependencies(0) = "OriginalItem"

Dim dependency As CacheDependency = New CacheDependency(Nothing, sDependencies)

Cache.Insert("DependentItem", "This item depends on OriginalItem", dependency)

[C#]

string[] sDependencies = new string[1];

sDependencies[0] = "OriginalItem";

CacheDependency dependency = new CacheDependency(null, sDependencies);

Cache.Insert("DependentItem", "This item depends on OriginalItem", dependency);

Page 98: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 98/168

90 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Delete Cached DataThis document is a copy of the article “How to: Delete Items from the Cache,”which you can find in the Microsoft® Visual Studio® 2005 documentation atms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/

html/80b8105b-4c44-4583-a9d6-b891a957242c.htm.

There are several reasons for an item to be removed from an application’scache. You can set expiration policies that determine the total amount of time

the item remains in the cache (absolute expiration). You can also set expiration policies that are based on the amount of time that must pass following the

 previous time the item is accessed (sliding expiration). You can also specifyfiles, directories, or keys that the item is dependent on. The item is removed

from the cache when those dependencies change. The server itself can removean item from the cache when it needs to free memory (scavenging). You havecontrol over the priorities of cached items when this occurs. Any of these

methods for removing items from the cache are determined when you writecode to add the item to the cache by using either the Cache.Add or 

Cache.Insert method.

Additionally, you can explicitly remove items from the cache by using the

Cache.Remove method. You can use this method in event-handler code to

respond to user input or some other input from your application.

 To delete an item from the cache by using the Cache.Remove method

•  The Remove method has one parameter that allows you to specify the key

of the item you want to remove. For example, the following code removesan item assigned the MyData1 key.

[Visual Basic]

Cache.Remove("MyData1")

[C#]

Cache.Remove("MyData1");

Page 99: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 99/168

Unit 5: Managing State for a Web Application 91

How to: Implement Deletion Notifications in Cached DataThis document is a copy of the article “How to: Notify an Application When anItem is Deleted from the Cache,” which you can find in the Microsoft® VisualStudio® 2005 documentation at ms-help://MS.VSCC.v80/

MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/

dv_aspnetcon/html/38c33aa0-afe9-40ba-a1a4-1ebab95286ef.htm.

Microsoft ASP.NET provides the CacheItemRemovedCallback delegate. Itdefines the signature to use when you write event handlers to respond when an

item is deleted from the cache. ASP.NET also provides the

CacheItemRemovedReason enumeration, which you can use to make event

handlers dependent upon the reason the item is deleted.

 To notify an application when an item is deleted from the cache

1.  Create a local variable that raises the event for the

CacheItemRemovedCallback delegate. For example, the following code

creates an onRemove local variable of type CacheItemRemovedCallback .

[Visual Basic]Private onRemove As CacheItemRemovedCallback = Nothing

[C#]

private static CacheItemRemovedCallback onRemove = null;

The variable must be of this type to be used in the onRemoveCallback   parameter of the Cache.Add or Cache.Insert method in step four.

2.  Create an event handler to respond when the item is removed from the

cache. For example, the following code sets the static Boolean 

itemRemoved to true, and the static CacheItemRemovedReason reason to

the value passed when the item is removed from the cache.

[Visual Basic]

Shared itemRemoved As boolean = false

Shared reason As CacheItemRemovedReason

Public Sub RemovedCallback(key As String, value As Object, callbackreason As

CacheItemRemovedReason)

itemRemoved = true

reason = callbackreason

End Sub

[C#]

static bool itemRemoved = false;

static CacheItemRemovedReason reason;public void RemovedCallback(string key, object value, CacheItemRemovedReason

callbackreason)

{

itemRemoved = true;

reason = callbackreason;

}

Note

Page 100: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 100/168

92 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

This event handler must use the same signature as theCacheItemRemovedCallback delegate. This code assumes that you havecreated two static variables: itemRemoved of type Boolean and reason of 

type CacheItemRemovedReason .

3.  Create an instance of the CacheItemRemovedCallback delegate that callsthe event handler. The following code calls the method created in step 2.

[Visual Basic]

onRemove = New CacheItemRemovedCallback(this.RemovedCallback)

[C#]

onRemove = new CacheItemRemovedCallback(this.RemovedCallback);

4.  Add the item to the cache by using either the Cache.Add method or the

Cache.Insert method. You must specify the local variable, created in step 1,

in the onRemoveCallback parameter. The following code uses the Insert 

method to add an item to the cache with a key of MyData1 and a value of 

Source. It defines the onRemove variable in the onRemoveCallback  

 parameter.

[Visual Basic]

Cache.Insert("MyData1", Source, Nothing,

DateTime.Now.AddMinutes(2),

NoSlidingExpiration,

CacheItemPriority.High, onRemove)

[C#]

Cache.Insert("MyData1", Source, null,

DateTime.Now.AddMinutes(2),

NoSlidingExpiration,

CacheItemPriority.High, onRemove);

When the item added in step 4 is removed from the cache for any reason,

the RemovedCallback method is called, and the code within it can beaccessed to render new content to a requesting client or to notify your application in a way that you choose as appropriate.

Note

Page 101: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 101/168

Page 102: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 102/168

94 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Providers

A provider is a class that can communicate with a specific type of database or data store. For example, one provider might be able to communicate with aMicrosoft SQL Server ™ database, and another provider might be able to

communicate with a Microsoft Office Access database.

In ASP.NET, you can choose from a number of providers that between themcan communicate with a wide variety of data stores. The providers include:

  The .NET Framework Data Provider for SQL Server in the

System.Data.SqlClient namespace.

  The .NET Framework Data Provider for OLE DB in the

System.Data.OleDb namespace.

  The .NET Framework Data Provider for ODBC in the System.Data.Odbc 

namespace.

  The .NET Framework Data Provider for Oracle in the

System.Data.OracleClient namespace.

You can indicate your provider in the Web.config file as part of a connectionstring, as a property of a specific data source control instance on your page, or  both.

Connection Strings

A connection string provides the necessary information so that an underlying provider can make a connection with a particular database using the necessary

authentication information. You can store a connection string in the Web.configfile and reference it in your page’s data source control.

Depending on the provider, a connection string usually supplies the server or location of the database server, the particular database to use, and theauthentication information. As with the provider, you can indicate the

connection string within the Web.config file or as a property of a specific datasource control instance on your page.

Connection String Storage

For organizational purposes, it is good practice to place connection strings in

the Web.config file. Within the <configuration> element, you can create achild element named <connectionStrings> and place your connection stringsthere:

<connectionStrings><add name="AppConnString"

connectionString=" Server=MyDataServer;User ID=dbuser;

Password=dbpass;Database=Northwind;Persist Security Info=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

In this example, the name and provider are both supplied, and any data sourcecontrol can use values from the Web.config file. One advantage to this process

is that you can easily change the server name, database, or authenticationinformation without editing individual Web pages.

Page 103: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 103/168

Unit 6: Accessing and Displaying Data 95

Retrieving Connection Strings Programmatically

You can programmatically retrieve connection strings from the Web.config fileat run time and use them in conjunction with data source controls or ADO.NETobjects. The following examples show how to retrieve a connection string and

use it to open an ADO.NET Connection object:

'[Visual Basic]

Dim dbString As String = _

ConfigurationManager.ConnectionStrings _

("AppConnString").ConnectionString

Dim sqlConn As System.Data.SqlClient.SqlConnection = _

New System.Data.SqlClient.SqlConnection(dbString)

sqlConn.Open()

If sqlConn.State.ToString() = "Open" Then

'Perform data operations

End If

//[Visual C#] 

string dbString =ConfigurationManager.ConnectionStrings

["AppConnString"].ConnectionString;

System.Data.SqlClient.SqlConnection sqlConn = new

System.Data.SqlClient.SqlConnection(dbString);

sqlConn.Open();

if (sqlConn.State.ToString() == "Open")

{

//Perform data operations

}

Data Source Controls

A data source control such as SqlDataSource pulls together all the elements of connecting to a database (provider, connection string, and query) to retrieve or manipulate data. For example, the SqlDataSource control in the following

example is configured to connect to a database and pull all records from aCustomer table:

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"

SelectCommand="SELECT * from Customers"

ConnectionString="<%$ ConnectionStrings:AppConnString %>"

ProviderName="<%$ ConnectionStrings:AppConnString.ProviderName %>" />

In this example, the provider and connection string are contained within the

Web.config file, while the SQL query is stated as an attribute of the control

declaration.

Page 104: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 104/168

96 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Products.aspx Page DesignThe following illustration shows a model page layout for the Products.aspx prototype. You should use this illustration as a guide when you are designingthe Products page in the lab.

Page 105: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 105/168

Page 106: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 106/168

98 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

You can create parameterized commands that include placeholders for values to be supplied at run time. The following example shows a typical parameterizedSQL Select command:

Select CustomerID, CompanyName From Customers Where city = @city

You can create parameter objects that specify where the command should get

 parameter values at run time, such as from another control, from a query string,and so on. Alternatively, you can specify parameter values programmatically.

The data source control executes the commands when the corresponding Select,Update, Delete, or Insert method is called. The Select method is calledautomatically when you call the DataBind method of the page or of a control

 bound to the data source control. You can also call any of the four methodsexplicitly when you want the data source control to execute a command. Some

controls, such as the GridView command, can call the methods automatically,without requiring that you call the methods or that you explicitly call the

DataBind method.

Format of Returned DataThe SqlDataSource control can return data in two forms—as a DataSet or as adata reader—which you can select by setting the DataSourceMode property of the data source control. A DataSet contains all the data in memory, allowing

you to manipulate the data in various ways after retrieving it. A data reader  provides a read-only cursor that can fetch individual records. As a rule, you

would choose to return a DataSet if you wanted to filter, sort, or page throughdata after retrieving it or if you wanted to maintain a cache. In contrast, you

would use a data reader if you simply wanted to return the data and load it (bindit) into a control on the page. For example, using a data reader is ideal for returning data that you want to display in a ListBox, DropDownList, or 

GridView control.

CachingThe SqlDataSource control can cache data that it has retrieved, which can

enhance the performance of your applications by avoiding expensive queries.Caching is practical in almost any situation in which the data is not highly

volatile.

Caching is not enabled by default, but you can set it by setting EnableCaching to true. The caching mechanism is based on time; you can set the

CacheDuration property to the number of seconds to cache data. The datasource control maintains a separate cache for each combination of connection,

Select query, parameters, and cache settings.

The SqlDataSource control can also take advantage of the cache dependency

feature of SQL Server (if available in your version of SQL Server). This featureallows you to specify a database and table. The data in the cache is maintained

until SQL Server reports a change in the specified table. This type of cachingallows you to create high-performance data access in your Web applications,

 because you can minimize data retrieval to only those times when it isnecessary to get refreshed data.

Page 107: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 107/168

Unit 6: Accessing and Displaying Data 99

Sorting and Filtering

If you have cached data and have specified a DataSet as the format for datareturned by a Select query, you can also filter the data without rerunning thequery. The SqlDataSource control supports a FilterExpression property that

allows you to specify selection criteria that are applied to the data maintained

 by the data source control. You can also parameterize the filter expression bycreating special FilterParameters objects that provide values at run time to thefilter expression.

To Add and Configure an SqlDataSource Control on a Web Page

The following steps describe the process of adding and configuring an

SqlDataSource control on a Web Page so that it retrieves a list of customersfrom the Northwind database, by using the NWind connection that has beenconfigured in the Web.config file:

1.  Drag an SqlDataSource control from the Data group in the Toolbox onto

the Design view of a Web page.2.  Click Configure Data Source in the Smart Tag of the SqlDataSource 

control.

3.  Click NWind in the Which data connection should your application use

to connect to the database? list.

 NWind is the name used to identify the database connection in the

Web.config file.

4.  Click Next.

5.  Click Specify a custom SQL statement or stored procedure and then

click Next.6.  On the Select tab, type the following SQL code in the SQL statement text

 box:

Select CustomerID, CompanyName From Customers

ORDER BY CompanyName

This SQL statement retrieves a list of customer IDs and company

names from the database, sorted alphabetically by customer name.

7.  Click Next.

8.  Click Test Query and review the results.

9.  Click Finish.

Note

Note

Page 108: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 108/168

100 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Access Data by Using ASP.NET Data-BoundControls

This document is an extract from the article “Types of ASP.NET Data BoundControls,” which you can find in the Microsoft® Visual Studio® 2005

Documentation at ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_aspnetcon/html/37c9e9bb-e119-41e0-a20d-

 b1691ed076bd.htm

Microsoft ASP.NET features several different types of data-bound controls,offering you flexibility in the presentation of data on your page.

In the latest release of ASP.NET, the GridView, DetailsView, and FormView controls support editing, updating, and deleting data. In addition, the

DetailsView also supports insertion of new data. The GridView control alsosupersedes the DataGrid from previous versions of ASP.NET; it supports all

the functionality of the DataGrid control and provides additional features.

List of ControlsIn this section, you are introduced to each of the data-bound controls in

ASP.NET with an explanation of the control’s purpose and functionality.

FormViewThe FormView control is a data-bound container allowing you to create afreeform layout for viewing and editing data with individual controls. For example, you could tie a FormView control to a user’s profile, allowing the

user to both see and edit his or her profile using simple controls like the

TextBox and DropDownList and to use the binding support of FormView to

update the data automatically.

You can use the control’s EditItemTemplate to tailor how your data isdisplayed on the form when the user is editing data. Binding syntax is used to

 bind a particular form control, such as a TextBox, to a data field. A user’schanges to the data can be automatically updated in the database using

FormView.

GridViewThe GridView control displays multiple rows of data in a grid (table) on the page, with a row in the grid for each data record and a column for each data

field you are displaying. The GridView control supports automatic paging andsorting. You can configure the control to allow users to edit or delete rows; the

user’s action is transmitted to the GridView control’s data source, which performs the appropriate database action. You can customize the appearance of data in a column, and the control provides events that you can handle to modify

data as it is displayed or after the user has edited it.

The GridView control supersedes the DataGrid control that performed

similar functions in earlier versions of ASP.NET. The DataGrid control is stillavailable for backward compatibility with existing Web applications.

Note

Page 109: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 109/168

Unit 6: Accessing and Displaying Data 101

DetailsViewThe DetailsView control displays one or more records from a data source, one

record at a time. If the data source provides more than one record, theDetailsView control can page through individual records. You can configure

the DetailsView control to allow users to view, edit, delete, and insert records.

DetailsView is useful when used in conjunction with a list-based data displaysuch as GridView. For example, you could click on a name in a GridView andthen dynamically display a DetailsView to show a record for that particular 

name.

DataListThe DataList control displays multiple records, typically in a table. Unlike the

GridView control, the DataList control does not provide a predeterminedlayout for the data. For example, the DataList control does not inherentlydisplay data in a rows and columns. Instead, you define the layout for the data

using templates. Templates contain controls, such as the Label control, that you bind to individual fields in the data record. The DataList control therefore

 provides a freeform way to lay out the display of multiple rows within a table-like structure. You can configure the DataList control to allow users to select,

edit, and delete records.

The DataList control is another list-type control that displays your entire result

set based on templates that you may edit and configure. The DataList may becustomized through properties to customize the control and set data

 presentation options such as the direction of the data display and a different presentation for alternating rows of data.

Repeater The Repeater control is similar to the DataList control in that it also allowsyou to create a freeform layout for displaying multiple records. With the

Repeater control, you use your own HTML and controls surrounding the datarow you want to display, and the repeater control will repeat the markup andcontrols for each row of data in your result set. Its functionality is similar to

scripting a for loop around presentation code but is simpler to use, as thecontrol manages the data presentation. Data-binding syntax is used to populate

controls contained within the repeater. For example:

<asp:Repeater ID="Repeater1" Runat="server" DataSourceID="SqlDataSource1">

<ItemTemplate>

<font color="red"><asp:Label ID="Label1" Runat="server"

text='<%# Bind("ContactName") %>' /></font>

<br />

</ItemTemplate>

</asp:Repeater>

The preceding repeater control iterates through the result set, rendering theContactName from each row in the context of the HTML contained within the

control.

Page 110: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 110/168

102 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

DropDownList and ListBoxYou can bind data to both the ListBox and DropDownList because of their 

inheritance of the ListControl. For example, you can bind a DropDownList toyour query using one column for a value, and another column for display:

<asp:DropDownList ID="DropDownList1" Runat="server"

DataSourceID="SqlDataSource1"DataValueField="CustomerID" DataTextField="ContactName">

</asp:DropDownList>

In this DropDownList, the DataValueField property shows a customer IDstring, while the DataTextField property shows a user-friendly contact name.

TreeViewThe TreeView control is a hierarchical data-bound control and may be used inconjunction with an XmlDataSource or a SiteMapDataSource. The inherently

hierarchical data from either of these two sources is used to create astraightforward expandable and collapsible tree for the user.

MenuThe Menu control features hierarchical data-binding and may be bound to an

XmlDataSource or a SiteMapDataSource . The hierarchical data from either of these sources is used to construct the primary selection, depth, and submenus

of the Menu control.

Control and DataSource Considerations

Your choice of data-bound control may rest on whether it supports your data

source. The following two lists contain details of which controls support whichdata sources. For example, TreeView and the Menu control can only use

hierarchical data sources. The rest of the data-bound controls may use either hierarchical or standard data sources.

These DataSource controls support the IDataSource interface:

  ObjectDataSource

  SqlDataSource 

  AccessDataSource  

These DataSource controls support the IHierarchicalDataSource interface in

addition to the IDataSource interface:

  XmlDataSource 

  SiteMapDataSource 

Page 111: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 111/168

Unit 6: Accessing and Displaying Data 103

Most data-bound controls require the IDataSource interface, which allDataSource controls support. Some controls require the

IHierarchicalDataSource interface, which only two DataSource controls

support.

Controls that can use any DataSource:

  FormView

  GridView 

  DetailsView 

  DataList 

  Repeater 

  BulletedList 

Controls that may only use hierarchical-supporting DataSource controls:

  TreeView 

  Menu 

Page 112: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 112/168

104 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Access and Display Data by Using the GridViewControl

This resource describes how to access and display data by using a GridView control. The GridView control can accept parameters that filter the data

displayed. In the following example, a parameter will be supplied at run time bythe selected value in a DropDownList control named ddCustomerID. The

data will be retrieved from the Northwind database; the data source for theGridView control will connect to the database by using a connection stringfrom the Web.config file.

To Add a GridView Control to a Web Page

1.  Drag a GridView control from the Data group in the Toolbox onto a Web

 page.

A Smart Tag appears for the GridView control.

2.  In the Choose Data Source list, click New data source.The Data Source Configuration Wizard appears.

3.  Click Database in the Where will the application get data from? section.

4.  Type dsCustomers in the Specify an ID for the data source box.

5.  Click OK .

The Configure Data Source dialog box appears.

6.  Click NWind in the Which data connection should your application use

to connect to the database? list.

 NWind is the name used to identify the database connection in theWeb.config file.

7.  Click Next.

8.  Click Specify a custom SQL statement or stored procedure and then

click Next.

9.  On the Select tab, type the following SQL code in the SQL statement text

 box:

SELECT CustomerID, CompanyName, Address, City

FROM Customers WHERE (CustomerID = @CustomerID)

This SQL statement retrieves customer details from the Customer 

table in the Northwind database. The WHERE clause of the selectstatement includes a parameter named @CustomerID. The value of this parameter will be determined at run time by referencing the selected item in

the ddCustomerID DropDownList control.

10. Click Next.

11. Click Control in the Parameter source list.

12. Click ddCustomerID in the ControlID list.

13. Click Next.

Note

Note

Page 113: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 113/168

Unit 6: Accessing and Displaying Data 105

14. Click Test Query.

The Parameter Values Editor dialog box appears.

15. Click Int32 in the Type list and then enter 1 in the Value box.

16. Click OK and review the results.

17. The details of the customer with a CustomerID of 1 are displayed.

18. Click Finish.

To Configure the Columns of the GridView Control

1.  On the Smart Tag menu for the GridView control, select the Enable

Selection check box.

Enabling selection specifies that the user can select a row in the

GridView control at run time. It adds a column to the GridView controlthat the user can click to select a row.

2.  Click Edit Columns and then remove the CustomerID column.

3.  Move the Select field below the CompanyName, Address, and City fields in

the Selected fields list.

4.  Set the HeaderText property of the CompanyName field to Customers.

5.  Set the following properties of the Select field:

•  HeaderText: <Clear this property>

•  SelectText: [>]

•  ShowSelectButton: True

Note

Page 114: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 114/168

106 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Access Objects as Data by UsingObjectDataSource Controls

This document contains extracts of the article “Walkthrough: Data Binding to aCustom Business Object,” which you can find in the Microsoft® Visual Studio® 

2005 Documentation at ms-help://MS.VSCC.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/a806fa2c-fe6a-405f-869c-

74e804a642ea.htm.

Many Web applications are built by using multiple tiers, with one or morecomponents in the middle tier to provide data access. Microsoft Visual Web

Developer ™ includes a wizard that helps you create a data component that youcan use as a middle-tier data object.

However, you might also want to build a custom business object, rather thanrelying on the data component created by the wizard. Creating a custom

 business object allows you to implement your own business logic. Thiswalkthrough illustrates how to create a basic business object that you can use as

a data source for Microsoft ASP.NET Web pages.

Creating an XML File for Business Data

In the following procedure, you will create a simple XML file for the businesscomponent data.

 To create the XML file

1.  In Solution Explorer, right-click App_Data and then click Add New Item.

Be sure you create the XML file in the App_Data folder. TheApp_Data folder has permissions set on it that will allow the Web page to

read and write data to the XML file.

2.  Under Visual Studio installed templates, click XML file.

3.  In the Name box, type Authors.xml.

4.  Click Add.

A new XML file is created containing only the XML directive.

5.  Copy the following XML data and then paste it into the file, overwriting

what is already in the file.

The XML file includes schema information that identifies the database

structure of the data, including a primary-key constraint for the key.

Business components can work with data in any way that is suitablefor your application. This walkthrough uses an XML file.

Note

Note

Page 115: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 115/168

Unit 6: Accessing and Displaying Data 107

<?xml version="1.0" standalone="yes"?>

<dsPubs xmlns="http://www.tempuri.org/dsPubs.xsd">

<xs:schema id="dsPubs" targetNamespace="http://www.tempuri.org/dsPubs.xsd"

xmlns:mstns="http://www.tempuri.org/dsPubs.xsd"

xmlns="http://www.tempuri.org/dsPubs.xsd"

xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-

com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"><xs:element name="dsPubs" msdata:IsDataSet="true">

<xs:complexType>

<xs:choice minOccurs="0" maxOccurs="unbounded">

<xs:element name="authors">

<xs:complexType>

<xs:sequence>

<xs:element name="au_id" type="xs:string" />

<xs:element name="au_lname" type="xs:string" />

<xs:element name="au_fname" type="xs:string" />

<xs:element name="au_phone" type="xs:string" />

</xs:sequence>

</xs:complexType>

</xs:element></xs:choice>

</xs:complexType>

<xs:unique name="Constraint1" msdata:PrimaryKey="true">

<xs:selector xpath=".//mstns:authors" />

<xs:field xpath="mstns:au_id" />

</xs:unique>

</xs:element>

</xs:schema>

<authors>

<au_id>172-32-1176</au_id>

<au_lname>West</au_lname>

<au_fname>Paul</au_fname>

<au_phone>408 555-0123</au_phone></authors>

<authors>

<au_id>213-46-8915</au_id>

<au_lname>Gray</au_lname>

<au_fname>Chris</au_fname>

<au_phone>415 555-0120</au_phone>

</authors>

</dsPubs>

6.  Save the Authors.xml file and then close it.

Page 116: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 116/168

Page 117: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 117/168

Unit 6: Accessing and Displaying Data 109

6.  Copy the following code, and then paste it into the file, overwriting what is

already in the file:

Visual Basic Copy Code

Imports Microsoft.VisualBasic

Imports System

Imports System.Web

Imports System.DataNamespace PubsClasses

Public Class AuthorClass

Private dsAuthors As DataSet = _

New System.Data.DataSet("ds1")

Private filePath As String = _

HttpContext.Current.Server.MapPath("~/Data/authors.xml")

Public Sub New()

dsAuthors.ReadXml(filePath, Data.XmlReadMode.ReadSchema)

End Sub

Public Function GetAuthors() As DataSet

Return dsAuthors

End Function

End Class

End Namespace

C# Copy Code

using System;

using System.Web;

using System.Data;

namespace PubsClasses

{

public class AuthorClass

{

private DataSet dsAuthors = new DataSet("ds1");private String filePath =

HttpContext.Current.Server.MapPath("~/App_Data/Authors.xml");

public AuthorClass()

{

dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema);

}

public DataSet GetAuthors ()

{

return dsAuthors;

}

}

}

Make sure the value of the filePath variable references the name of the XML file that you created previously.

When the class is instantiated, it reads the XML file and translates it into a

DataSet. The GetAuthors method for the class returns the DataSet.

7.  Save the file.

Note

Page 118: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 118/168

110 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Displaying Data by Using the Business Component

You can now invoke the business component in a Web page and display itsdata. To reference the component, you use an ObjectDataSource control,which is specifically designed to work with objects.

 To create an ObjectDataSource control that references the component

1.  Switch to or open the Default.aspx page.

If you do not have a Default.aspx page, you can use another page.Alternatively, you can add a new page to the Web site. In Solution Explorer,

right-click the name of your Web site, click Add New Item, and then add aWeb Form.

2.  Switch to Design view.

3.  In the Toolbox, from the Data folder, drag an ObjectDataSource control

onto the page.

4.  In the Properties window, set ID to AuthorsObjectDataSource .

5.  Right-click the ObjectDataSource control and then click Show Smart

Tag.

6.  On the Common ObjectDataSource Tasks menu, click Configure Data

Source.

The Configure Data Source Wizard appears.

7.  In the Enter the name of your business object list, click 

PubsClasses.AuthorClass .

This is the type name (namespace and class name) of the class that you

created previously.

8.  Click Next.9.  On the Select tab, in the Choose a method list, click GetAuthors.

The GetAuthors method is defined in the business class that you created previously. It returns a DataSet containing the data from the Authors.xmlfile.

10. Click Finish.

The configuration information you have entered specifies that to get datafrom the component, the component’s GetAuthors method should becalled.

Note

Page 119: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 119/168

Unit 6: Accessing and Displaying Data 111

You can now get data from the component by using the ObjectDataSource control. You will display the data in a GridView control on the page.

 To display data from the component

1.  In the Toolbox, from the Data folder, drag a GridView control onto the

 page.

2.  Right-click the GridView control and then click Show Smart Tag.

3.  On the Common GridView Tasks menu, in the Choose Data Source box,

click AuthorsObjectDataSource .

4.  Press CTRL+F5 to run the page.

The GridView control with the XML data in it is displayed.

Inserting Data by Using the Business ComponentAs with other data source controls, such as the SqlDataSource control, the

ObjectDataSource control supports updating (inserting, updating, and

deleting). In this section, you will modify the business component with amethod that inserts an author record. Then you will change the page so thatusers can type new author information and modify the ObjectDataSource 

control to perform the insertion.

During this part of the walkthrough, the Authors.xml file you created

 previously will be updated. It is important that the application have permissionto write to the file at run time; if it does not, the Web page will display an error 

when you try to update the file. If you created the Authors.xml file in theApp_Data folder, permissions are set automatically.

 To modify the business component to allow inserts

1.  Switch to the BusinessObject file.

2.  Add the following method as the final member of AuthorClass:

Visual Basic

Public Sub InsertAuthor(ByVal au_id As String, _

ByVal au_lname As String, _

ByVal au_fname As String, ByVal au_phone As String)

Dim workRow As DataRow = dsAuthors.Tables(0).NewRow

workRow.BeginEdit()

workRow(0) = au_id

workRow(1) = au_lname

workRow(2) = au_fname

workRow(3) = au_phoneworkRow.EndEdit()

dsAuthors.Tables(0).Rows.Add(workRow)

dsAuthors.WriteXml(filePath,

Data.XmlWriteMode.WriteSchema)

End Sub

Note

Page 120: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 120/168

112 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

C#

public void InsertAuthor (String au_id, String au_lname,

String au_fname, String au_phone)

{

DataRow workRow = dsAuthors.Tables[0].NewRow ();

workRow.BeginEdit ();

workRow[0] = au_id;workRow[1] = au_lname;

workRow[2] = au_fname;

workRow[3] = au_phone;

workRow.EndEdit ();

dsAuthors.Tables[0].Rows.Add (workRow);

dsAuthors.WriteXml (filePath, XmlWriteMode.WriteSchema);

}

Pay close attention to the names of the variables used to pass author 

information into the method (au_id, au_lname, au_fname, and au_phone).They must match the column names defined in the schema of the XML file

you created previously.

The new method takes four values to insert, which you will provide in the page as parameters. The method creates a new row in the DataSet and thenwrites the updated DataSet out as an XML file.

3.  Save the file.

The next step is to change the page so that users can enter new author 

information. For the following procedure, you will use the DetailsView control.

 To add a control for inserting data

1.  Switch to or open the Default.aspx page.

2.  Switch to Design view.

3.  In the Toolbox, from the Data folder, drag a DetailsView control onto the

 page.

The exact layout of the page is not important.

4.  On the Common DetailsView Tasks menu, in the Choose Data Source 

 box, click AuthorsObjectDataSource .

If the Common DetailsView Tasks menu is not visible, right-click 

the control, and then click Show Smart Tag..

5.  In the Properties window, set AutoGenerateInsertButton to true.

This causes the DetailsView control to render a New button that users canclick to put the control into data-entry mode.

Note

Note

Note

Page 121: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 121/168

Unit 6: Accessing and Displaying Data 113

Finally, you must configure the ObjectDataSource control to specify whataction the control should take to insert data.

 To configure the data source control for inserting data

•  Right-click AuthorsObjectDataSource , click Properties, and then set

InsertMethod to InsertAuthor.

This is the name of the method that you added to the business component.

You can now insert new authors into the XML file.

 To test insertion

1.  Press CTRL+F5 to run the Default.aspx page.

2.  In the DetailsView control, click New.

The control is redisplayed with text boxes.

3.  Enter new author information, and then click Insert.

The new author information is added to the XML file. The GridView 

control immediately reflects the new record.

Page 122: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 122/168

114 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Access XML Data by Using XmlDataSourceControls

This document is an extract from the article “XmlDataSource Class,” whichyou can find in the Microsoft® Visual Studio® 2005 Documentation at

ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref/html/T_System_Web_UI_WebControls_XmlDataSource.htm.

The following code example demonstrates how to use an XmlDataSource 

control with a TreeView control to display XML data. The XmlDataSource loads XML data from the XML file identified by the DataFile property.

Visual Basic

<%@ Page Language="VB" %>

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

<HTML>

<BODY>

<form runat="server">

<asp:xmldatasource

id="XmlDataSource1"

runat="server"

datafile="books.xml" />

<!-- TreeView uses hierachical data, so the

XmlDataSource uses an XmlHierarchicalDataSourceView

when a TreeView is bound to it. -->

<asp:treeview

id="TreeView1"

runat="server"

datasourceid="XmlDataSource1">

<databindings>

<asp:treenodebinding datamember="book" textfield="title"/>

</databindings></asp:TreeView>

</form>

</BODY>

</HTML>

Page 123: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 123/168

Unit 6: Accessing and Displaying Data 115

C#

<%@ Page Language="C#" %>

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

<HTML>

<BODY>

<form runat="server">

<asp:xmldatasourceid="XmlDataSource1"

runat="server"

datafile="books.xml" />

<!-- TreeView uses hierachical data, so the

XmlDataSource uses an XmlHierarchicalDataSourceView

when a TreeView is bound to it. -->

<asp:treeview

id="TreeView1"

runat="server"

datasourceid="XmlDataSource1">

<databindings>

<asp:treenodebinding datamember="book" textfield="title"/>

</databindings></asp:TreeView>

</form>

</BODY>

</HTML>

The XML file in the code example has the following data:

<books>

<languagebooks>

<book title="Pure JavaScript" author="Wyke, Gilliam, and Ting"/>

<book title="Effective C++: 50 Specific Ways to Improve Your Programs and

Designs" author="Scott Meyers"/>

<book title="Assembly Language: Step-By-Step" author="Jeff Duntemann"/><book title="Oracle PL/SQL Best Practices" author="Steven Feuerstein"/>

</languagebooks>

<securitybooks>

<book Title="Counter Hack: A Step-by-Step Guide to Computer Attacks and

Effective Defenses" author="Ed Skoudis"/>

</securitybooks>

</books>

Page 124: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 124/168

Page 125: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 125/168

 

Unit 7: Controlling Access to a WebApplication

How to Configure Authentication for a Web ApplicationMicrosoft® ASP.NET uses authentication providers to implement authentication

for Web applications. An authentication provider is a core module that containsthe code necessary to authenticate credentials. An authentication provider 

handles many of the common tasks involved. The ASP.NET authentication providers are:

•  Windows Authentication. When your application uses Windows

Authentication, Internet Information Services (IIS) validates credentialsagainst Microsoft Windows® accounts stored in Active Directory® 

directory service or the Security Account Manager (SAM). The users musthave valid Windows accounts. IIS prompts the user for details, if necessary.

Basic, Digest or Windows Integrated authentication is used, depending onthe configuration of IIS and the capabilities of the browser.

•   Passport Authentication. When your application uses PassportAuthentication, users can use their MSN® Passport to access your site.

•   Forms Authentication. When your application uses Forms Authentication,

you can create a custom ASP.NET page to collect the credentials from the

user. If users attempt to access a page for which they are not authorized,they will be automatically redirected to the login page. You can store user credentials in a variety of locations, including Microsoft SQL Server ™ andMicrosoft Office Access databases.

This document describes how to configure each of these providers.

Configuring Windows Authentication

To use Windows Authentication, you configure ASP.NET and IIS and createuser accounts for each user you need to identify.

 To configure the ASP.NET application

1.  Open the Web.config file in the root folder of your application.

2.  Locate the <system.web> and </system.web> tags. Add the following

element between these tags:

<authentication mode="Windows" />

Page 126: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 126/168

118 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

 To configure the IIS Web site

1.  Click Start, right-click My Computer, and then click Manage.

2.  In the Computer Management console, expand Services and Applications

and then click Internet Information Services.

3.  In the Internet Information Services console, select the Web site or virtual

directory that hosts your application.

4.  Right-click the Web site and then click Properties.

5.  In the Web Site properties dialog box, click the Directory Security tab.

6.  In the Anonymous access and authentication control section, click Edit.

7.  In the Authenticated access section of the Authentication Methods dialog

 box, choose the Basic or Integrated Windows Authentication option as

appropriate. Clear the Enable Anonymous Access check box.

8.  Click OK twice to apply your configuration and close the dialog boxes.

9.  Close the Computer Management console.

Configuring Passport AuthenticationTo implement Passport Authentication, you must first register with the

Microsoft Passport Service on the Microsoft Passport Network Web site. Youshould also download the .NET Passport SDK from the same location.

 To configure Passport Authentication for your ASP.NET application

1.  Open the Web.config file in the root folder of your application.

2.  Locate the <system.web> and </system.web> tags. Add the following

element between these tags:

<authentication mode="Passport" />

Configuring Forms AuthenticationForms authentication requires a login page to collect credentials from the user 

and compare them against stored credentials. For more information on login pages, see the resource document “How to: Implement a Login Page and Add

Login Controls.”

After you have created the login page you must configure the application to use

it. This involves modifying the Web.config file.

 To configure Forms Authentication for your ASP.NET Application

1.  Open the Web.config file in the root folder of your application.

2.  Locate the <system.web> and </system.web> tags. Add the following

element between these tags:

<authentication mode="Forms">

<forms name="MainLogon" loginUrl="/logon.aspx" />

</authentication>

Page 127: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 127/168

Unit 7: Controlling Access to a Web Application 119

You frequently store accounts in a database or some other external location.However, it is possible to keep a list of users in the Web.config file itself. Thisis appropriate when the number of users is small and fixed.

 To configure Forms Authentication with credentials stored in the

Web.config file

1.  Open the Web.config file in the top folder of your application.

2.  Locate the <system.web> and </system.web> tags. Add the following

elements between them:

<authentication mode="Forms">

<forms name="MainLogon" loginUrl="/logon.aspx">

<credentials passwordFormat="SHA1">

<user name="Kim"

password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>

<user name="John"

password="BA56E5E0366D003E98EA1C7F04ABF8FCB3753889"/>

</credentials>

</forms>

</authentication>

In this example, the passwords have been hashed by using a one-way algorithmso that the password is held in the file in a non-reversible format.

Page 128: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 128/168

120 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Configure Authorization for a Web ApplicationThere are two ways to configure authorization for a Microsoft® ASP.NET Webapplication:

   File Authorization. This is available only if your application uses Microsoft

Windows® Authentication. You can set permissions on files and directories by using Access Control Lists (ACLs).

  URL Authorization. This is available regardless of which authentication

 provider you are using. You use the Web.config file in each directory of the

application to assign permissions for the contents of the directory.

This document discusses using URL Authorization.

 To configure URL Authorization for a directory in an ASP.NET

application

1.  In Microsoft Visual Studio®, if there is no Web.config file in the directory,

right-click the directory in Solution Explorer and then click Add New Item.

2.  In the Add New Item dialog box, click Web Configuration File and then

click Add. A new Web.config file is added and displayed.

3.  Locate the <system.web> and </system.web> tags. Add the following

markup between these tags:

<authorization>

<allow users="Kim"/>

<allow roles="Admins"/>

<deny users="John"/>

<deny users="?"/>

</authorization>

This example demonstrates how to assign authorizations to users, such as Kim,or roles, such as Admins. Use of <allow> tags permit access and <deny> tags prevent access. Authorizations appearing earlier in the list take precedence over 

those that appear later.

There are two special characters that can be used:

  “?” indicates anonymous users.

  “*” indicates all users. If you place this entry at the bottom of the list, it

 becomes the default authorization for any users not mentioned above it.

If you are using Windows Authentication, you must apply an authorization toa Windows account by specifying the full name, for example, LON-DEV-01\

Student.

Page 129: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 129/168

Unit 7: Controlling Access to a Web Application 121

 To configure URL Authorization for a single file in an ASP.NET

application

1.  In Visual Studio, if there is no Web.config file in the directory holding thefile, right-click the directory in Solution Explorer and then click Add New

Item.

2.  In the Add New Item dialog box, click Web Configuration File and thenclick Add. A new Web.config file is added and displayed.

3.  Locate the <configuration> and </configuration> tags. Add the

following markup between these tags:

<location path="SecuredFile.aspx">

<system.web>

<authorization>

<allow users="Joe"/>

<deny users="*"/>

</authorization>

</system.web>

</location>

Page 130: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 130/168

122 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Introduction to MembershipThis document is a copy of the article “Introduction to Membership,” whichyou can find in the Microsoft® Visual Studio® 2005 documentation atms-help://MS.VSCC.v80/MS.MSDN.v80/

MS.VisualStudio.v80.en/dv_aspnetcon/html/79184d17-f4c7-4c9f-a073-

cec4f5543980.htm.

Microsoft ASP.NET membership gives you a built-in way to validate and storeuser credentials. ASP.NET membership, therefore, helps you manage user 

authentication in your Web sites. You can use ASP.NET membership withASP.NET Forms authentication or with the ASP.NET login controls to create a

complete system for authenticating users.

ASP.NET membership supports facilities for:

  Creating new users and passwords.

  Storing membership information (user names, passwords, and supporting

data) in Microsoft SQL Server ™, Microsoft Office Access, or in an

alternative data store.  Authenticating users who visit your site. You can authenticate users

 programmatically, or you can use the ASP.NET login controls to create a

complete authentication system that requires little or no code.

  Managing passwords, which includes creating, changing, or resetting them;maintaining password expiration dates, and so on. Depending on which

membership options you choose, the membership system can also provide

an automated password reminder system that uses a user-supplied question

and response.

  Exposing a unique identification for authenticated users that you can use in

your own applications and that also integrates with the ASP.NET

 personalization and role management (authorization) systems.

  Specifying a custom membership provider, which allows you to substitute

your own code to manage membership and maintain membership data in a

custom data store.

Membership, Roles, and the User ProfileAlthough membership is a self-standing feature in ASP.NET for authentication,

it can be integrated with ASP.NET role management to provide authorizationservices for your site. Membership can also be integrated with the user profile

to provide application-specific customization that can be tailored to individualusers.

Page 131: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 131/168

Unit 7: Controlling Access to a Web Application 123

How Membership Works

To use membership, you must first configure it for your site. In summary, youfollow these steps:

1.  Specify membership options as part of your Web site configuration. By

default, membership is enabled. You can also specify the membership provider you want to use. (In practical terms, this means that you are

specifying the type of database you want to keep membership information

in.) The default provider uses an Access database. You can also choose touse SQL Server to store membership information, or you can specify a

custom provider.

2.  Configure your application to use Forms authentication (as distinct from

Microsoft Windows® Authentication or Passport authentication). You

typically specify that some pages or folders in your application are protected

and are accessible only to authenticated users.

3.  Define user accounts for membership. You can do this in a variety of ways.

You can use the Web Site Administration Tool, which provides a wizard-

like interface for creating new users. Alternatively, you can create a “newuser” ASP.NET Web page where you collect a user name and a password

(and optionally an e-mail address) and then use a membership function

named CreateUser to create a new user in the membership system.

You can now use membership to authenticate users in your application. Mostoften, you will provide a login form, which might be a separate page or a

special area on your home page. You can create the login form by hand usingASP.NET TextBox controls, or you can use ASP.NET login controls. Becauseyou have configured the application to use Forms authentication, ASP.NET will

automatically display the login page if an unauthenticated or unauthorized user requests a protected page.

The ASP.NET login controls encapsulate virtually all of the logicrequired to prompt users for credentials and validate the credentials in themembership system.

If you use login controls, they will automatically use the membership system tovalidate a user. If you have created a login form by hand, you can prompt theuser for a user name and password and then call ValidateUser to perform the

validation. When the user is validated, information about the user is persisted(for example, using an encrypted cookie if the user’s browser accepts cookies).

The login controls perform this task automatically. If you have created a loginform by hand, you can call methods of the FormsAuthenticationclass to

create the cookie and write it to the user’s computer. If a user has forgotten his

or her password, code in the login page can call membership functions that helpthe user remember the password or create a new one.

Each time the user requests another protected page, ASP.NET Formsauthentication checks whether the user is authenticated and then either allows

the user to view the page or redirects the user to the login page. By default, theauthentication cookie remains valid for the user’s session.

Note

Page 132: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 132/168

124 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

After a user has been authenticated, the membership system makes available anobject that contains information about the current user. For example, you canget properties of the membership user object to determine the user’s name or e-

mail address, when the user last logged into your application, and so on.

An important aspect of the membership system is that you never need toexplicitly perform any low-level database functions to get or set user 

information. For example, you create a new user by calling the membershipCreateUser method. The membership system handles the details of creating the

necessary database records to store the user information. When you call the

ValidateUser method to check a user’s credentials, the membership system

does all the database lookup for you.

Anonymous Users in the Membership System

The membership system allows your application to accept and work with

anonymous users, defined as those who have not been authenticated.Anonymous identification is not enabled by default, but when it is enabled,unauthenticated users are assigned a temporary ID in the membership system.

The ID allows you to track users who are online at your site, even if they havenot been authenticated. In addition, the ID for the anonymous user allows the

membership system to associate data, such as profile information, with theanonymous user, and provides an ID that can be used with the profile for that

user. The anonymous user’s ID is stored in a cookie, much as a formsauthentication ticket, except that the membership system does not consider the

user to be logged in. If the user’s browser does not accept cookies, theanonymous identification can be embedded in the URL of requested pages.

If an anonymous user logs in, the anonymous identification information isdiscarded and the user is treated thereafter as an authenticated user. If you are

using personalization, the user’s personalization values can be migrated so thatthey are retained as part of the user’s logged-in user identity.

Membership Configuration and ManagementYou configure the membership system in your application’s Web.config file.

The easiest way to configure and manage membership is with the Web SiteAdministration Tool, which provides a wizard-based interface. As part of 

membership configuration, you specify:

  What membership provider to use. (This typically also specifies what

database to store membership information in.)

  Password options such as encryption and whether to support password

recovery based on a user-specific question.

  Users and passwords. If you are using the Web Site Administration Tool,you can create and manage users directly. Otherwise, you must call

membership functions to create and manage users programmatically.

Page 133: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 133/168

Unit 7: Controlling Access to a Web Application 125

How to: Configure an ASP.NET Application to UseMembership

This document contains extracts from the article “Configuring an ASP.NETApplication to Use Membership,” which you can find in the Microsoft® Visual

Studio® 2005 documentation at ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/

dv_aspnetcon/html/283c397e-3a2d-458f-84e3-df94460ab052.htm.

Microsoft ASP.NET Membership is configured using the <membership>element in the Web.config file for your application. The <membership>

element is a sub-element of the <system.web> section. You can also enableASP.NET Membership for an application by directly editing the Web.config

file for that application, or you can use the Web Site Administration Tool,which provides a wizard-based interface. As part of membership configuration,you specify:

  What membership provider to use. (This typically also specifies what

database to store membership information in.)

  Password options such as encryption and whether to support password

recovery based on a user-specific question.

  Users and passwords. If you are using the Web Site Administration Tool,

you can create and manage users directly. Otherwise, you must call

membership functions to create and manage users programmatically.

Specifying the Default Provider  You specify the default membership provider using the defaultProvider 

attribute of the <membership> element. The machine configuration specifies aSqlMembershipProvider instance named AspNetSqlProvider that is

identified as the default provider if you do not specify a default provider explicitly. AspNetSqlProvider connects to the aspnetdb database in the localcomputer running Microsoft SQL Server ™.

You need to set up the database used by SqlMembershipProvider

 before using it in an application.

You can also specify the default provider instance and options for that provider 

 by configuring a provider in the <membership> section. You use the<providers> element to identify a provider to add to the collection of providersavailable for the application. You can identify your provider instance as the

default provider using the value of the name attribute as the defaultProvider 

value. When you specify a provider instance, you must also specify a validconnection string for that instance using the <connectionStrings> section of the configuration. For example, the following Web.config file identifies a

SqlMembershipProvider instance that connects to a computer running SQLServer that is not the local server:

Note

Page 134: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 134/168

126 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

<configuration>

<connectionStrings>

<add name="MySqlConnection"

connectionString="Data Source=MySqlServer;

Initial Catalog=aspnetdb;

Integrated Security=SSPI;" />

</connectionStrings><system.web>

<authentication mode="Forms" >

<forms loginUrl="login.aspx" name=".ASPXFORMSAUTH" />

</authentication>

<authorization>

<deny users="?" />

</authorization>

<membership defaultProvider="SqlProvider"

userIsOnlineTimeWindow="15">

<providers>

<clear />

<add name="SqlProvider"

type="System.Web.Security.SqlMembershipProvider"connectionStringName="MySqlConnection"

applicationName="MyApplication"

enablePasswordRetrieval="false"

enablePasswordReset="true"

requiresQuestionAndAnswer="true"

requiresUniqueEmail="true"

passwordFormat="Hashed" />

</providers>

</membership>

</system.web>

</configuration>

Page 135: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 135/168

Page 136: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 136/168

128 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

To update the details stored for the current user 

The following code modifies the details of the current user and saves them.

[Visual Basic]

Dim userCurrent As MembershipUser = Membership.GetUser()

userCurrent.UserName = txtUsername.TextuserCurrent.Email = txtEmail.Text

userCurrent.Comment = "The user has modified his or her details"

Membership.UpdateUser(userCurrent)

[C#]

MembershipUser userCurrent = Membership.GetUser();

userCurrent.UserName = txtUsername.Text;

userCurrent.Email = txtEmail.Text;

userCurrent.Comment = "The user has modified his or her details";

Membership.UpdateUser(userCurrent);

To change a user passwordThe following code changes a user’s password:

[Visual Basic]

Dim userCurrent As MembershipUser = Membership.GetUser()

Dim sOldPassword As String = txtOldPassword.Text

Dim sNewPassword As String = txtNewPassword.Text

If userCurrent.ChangePassword(sOldPassword, sNewPassword) Then

lblMessage.Text = "Your password has been changed."

Else

lblMessage.Text = "The password could not be changed. Please try again later."

End If

[C#]

MembershipUser userCurrent = Membership.GetUser();

string sOldPassword = txtOldPassword.Text;

string sNewPassword = txtNewPassword.Text;

if (userCurrent.ChangePassword(sOldPassword, sNewPassword)){

lblMessage.Text = "Your password has been changed.";

} else {

lblMessage.Text = "The password could not be changed. Please try again later.";

}

Page 137: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 137/168

Page 138: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 138/168

Page 139: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 139/168

Unit 7: Controlling Access to a Web Application 131

TopLevel.master 

Page 140: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 140/168

132 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Implement a Login Page and Add Login ControlsIf you are using Forms authentication, you must create a login page that prompts the user for a user name and password. You can create this page byusing the Login Web server control.

The name of the page must match the loginUrl attribute of the <forms>element in the Web.config file. By default, Microsoft® ASP.NET Membershipis configured to use a login page called login.aspx.

The Login Web server control is designed to work with ASP.NET

Membership. Therefore, you must have configured Membership before usingthis control. For details see “How to: Configure an ASP.NET Application to

Use Membership.”

 To create the login page and add a Login control

1.  In Microsoft Visual Studio®, add a new Web form to the Web application.

Ensure that the name of this file matches the loginUrl attribute of the

<forms> element specified in the application’s Web.Config file.

2.  In Design view, drag a Login control onto the page from the Login section

of the Toolbox, or in Source view, add the following markup to the page:

<asp:Login ID="Login1" runat="server"></asp:Login>

 To add a PasswordRecovery control to the page

•  In Design view, drag a PasswordRecovery control onto the page from the

Login section of the Toolbox, or in Source view, add the following markupto the page:

<asp:PasswordRecovery ID="PasswordRecovery1" runat="server">

</asp:PasswordRecovery>

 To add a LoginStatus control to the page

•  In Design view, drag a LoginStatus control onto the page from the Login

section of the Toolbox, or in Source view, add the following markup to the

 page:

<asp:LoginStatus ID="LoginStatus1" runat="server" />

The LoginStatus control indicates whether the current user is authenticatedor anonymous.

 To add a LoginName control to the page

•  In Design view, drag aLoginName

control onto the page from theLogin

 

section of the Toolbox, or in Source view, add the following markup to the page:

<asp:LoginName ID="LoginName1" runat="server" />

The LoginName control shows the user name of the current authenticateduser.

Page 141: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 141/168

Unit 7: Controlling Access to a Web Application 133

 To add a LoginView control to the page, including templates for logged-

in and anonymous users

•  In Source view, add the following markup to the page:

<asp:LoginView ID="LoginView1" Runat="server">

<LoggedInTemplate> Welcome,

<asp:LoginName ID="LoginName1" Runat="server" /> <br /><asp:HyperLink ID="HyperLink3" Runat="server"

NavigateUrl="~/MemberPages/ChangePassword.aspx">

Change Password

</asp:HyperLink>

</LoggedInTemplate>

<AnonymousTemplate>

Click Login to sign in.<br />

<asp:HyperLink ID="HyperLink2" Runat="server"

NavigateUrl="~/Register.aspx">

Register

</asp:HyperLink>

<asp:HyperLink ID="HyperLink4" Runat="server"

NavigateUrl="~/Recovery.aspx">Forgot your password?

</asp:HyperLink>

</AnonymousTemplate>

</asp:LoginView>

Page 142: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 142/168

134 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Create a Membership ManagementAdministrative User Interface

If you are using Microsoft® ASP.NET Forms authentication and URLauthorization, you can assign permissions to individual users or to roles. A role 

is a group of users. Any permission you assign to a role automatically applies toall the members of that role.

To use roles, you must first configure the ASP.NET Roles Provider in the

Web.config file. You can set up the membership of each role by using theASP.NET Administration Tool. This document shows you how to perform

these tasks programmatically. For details on granting permissions, see “How to:Configure Authorization for a Web Application.”

 To configure the ASP.NET Roles Provider

1.  In Microsoft Visual Studio®, open the Web.config file in the root folder of 

your application.

2.  Add the following markup to the <system.web> section:<roleManager cacheRolesInCookie="true" enabled="true"

defaultProvider="SQLProvider">

<providers>

<add name="SqlProvider"

type="System.Web.Security.SqlRoleProvider"

connectionStringName="RolesConnection"

applicationName="MyApplication" />

</providers>

</roleManager>

This example uses the ASP.NET SQL Server Roles Provider. To use this

 provider, you must have created the ASP.NET Roles database in SQL by usingthe aspnet_regsql.exe tool.

To list the users in a role

The following code lists all the members of a role called Moderators, and allusers who are not members of this role:

[Visual Basic]

Dim allUsers As MembershipUserCollection = _

Membership.GetAllUsers()

Dim currentUser As MembershipUser

For Each currentUser In allUsers

If Roles.IsUserInRole(currentUser.UserName, _

"Moderators") Then

lblMembers.Text &= currentUser.UserName & "<br>"

Else

lblNonMembers.Text &= currentUser.UserName & "<br>"

End If

Next

Page 143: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 143/168

Page 144: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 144/168

Page 145: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 145/168

 

Unit 8: Deploying a Web Application

Features of the Copy Web Site UtilityThis document is a copy of the article “Copying Web Sites with the Copy Web

Tool,” which you can find in the Microsoft® Visual Studio® 2005documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/

MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/fb4e125f-6238-48c0-a03c-4854bf9895e8.htm.

The Copy Web tool allows you to copy files between the current Web site and

another site. The Copy Web tool is similar to an FTP utility, but differs in the

following ways:

  It allows you to connect to and copy files between any types of Web sites

you can create in Visual Studio, including local Web sites, IIS Web sites,Remote (Microsoft Office FrontPage®) Web sites, and FTP sites.

  It supports a synchronization feature. This examines the files on both sites

and makes sure that all files on both sites are up to date.

You can use the Copy Web tool to move files from your local computer to a

staging server or to a production server. The Copy Web tool is especially usefulin situations in which you cannot open files from the remote site to edit them.

You can use the Copy Web tool to copy the files to your local computer, edit

them, and then copy them back to the remote site. You can also use the tool tocopy files from a staging server to the production server when you have

finished your development.

Source and Remote Sites

The Copy Web tool copies files between a source site and a remote site. These

terms are used to distinguish the two sites that the tool is working with. Theterms are used with specific meanings:

  The source site is the site that you currently have open in Visual Studio.

  The remote site is the site that you want to copy files to. A remote site can

 be a location on another computer that you can access using FrontPageServer Extensions or FTP. In those cases, the site is literally remote.

However, the remote site can also be another site on your own computer.

For example, you can publish from a file system Web site on your computer 

to a local IIS Web site that is also on your computer. In that case, although

the site is local to your computer, it is the “remote site” for purposes of the

Copy Web tool.

Page 146: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 146/168

138 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The source site is not necessarily the source for copying. You can copyfrom the remote site to the source site.

Synchronizing Sites

In addition to copying files, the Copy Web tool allows you to synchronize sites.

Synchronizing examines the files on the local and remote sites and makes surethat all files on both sites are up to date. For example, if a file on the remote siteis more current than the version of the same file on the local site, synchronizing

the files copies the remote file to your local site.

The Copy Web tool does not merge files that have the same name but

different content. In that case, synchronization gives you the opportunity tospecify which version of a file you want to keep.

Synchronization makes the tool well suited to a multi-developer environment in

which developers keep copies of the Web site on their local computers.Individual developers can copy their latest changes to a shared remote server and at the same time update the local computer with changed files from other 

developers. A new developer on a project can also quickly get copies of all thefiles for a Web site by creating a local Web site on his or her own computer and

then synchronizing with the site on the shared server.

File Status

To synchronize files, the Copy Web tool needs information about the state of 

the files on both sites. Therefore, the tool maintains information consisting of the files’ timestamps plus additional information required to perform

synchronization. For example, the tool maintains a list of when the files werelast checked, which enables the tool to determine information such as if a filehas been deleted.

When you connect to (or refresh) a site, the tool compares the timestamps of thefiles on both sites and the information it has stored for both sites and reports the

state of each file. The following table shows the status of the files.

Status Description

Unchanged The file has not changed since the last time the file was copied.

Changed The file has a timestamp that is newer than the timestamp taken when

the file was last copied.

  New The file has been added since the last time the site was copied.

Deleted The file has been removed since the last time the site was copied. If 

you select Show Deleted Files in the Copy Web tool, an entry for the

file is displayed in the window.

Note

Note

Page 147: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 147/168

Unit 8: Deploying a Web Application n 139

How to: Deploy a Web Site by Using the Copy Web SiteUtility

This document is a copy of the article “How to: Copy Web Site Files with theCopy Web Tool,” which you can find in the Microsoft® Visual Studio® 2005

documentation at ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/fb4e125f-6238-

48c0-a03c-4854bf9895e8.htm.

You can use the Copy Web tool in Visual Studio to copy files from a local siteto a remote site or vice versa. You can copy selected files individually or copy

all files at once. Additionally, you can synchronize two sites, which copies filesas required to be sure that both sites have identical copies of all files.

You must have sufficient permissions to be able to read, write, create,and delete files on the remote site. If you are unsure of your permissions, check 

with the administrator for the remote site.

To Connect to a Remote Site

1.  On the Website menu, choose Copy Web Site.

The Copy Web window is displayed with files from the currently open Website in the Source Web Site list.

2.  From the Connect to list, select the site to connect to as the remote site. If 

the site you want to connect to is not in the list, select Connect to and then

use the Open Web Site dialog box to connect to the site you want to copy

files to or from.

When the Copy Web tool opens the remote site, it examines the files on

 both sites and indicates their status (New, Unchanged, Changed, or Deleted). If there are two different versions of a file, one on the source siteand one on the remote site, an arrow points from the newer version to the

older version.

To see files that have been deleted, select the Show Deleted Files check 

 box. The names of deleted files have a glyph next to them indicating that theyhave been deleted.

Note

Note

Page 148: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 148/168

140 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Removing a Connection

Connection information is persisted in Visual Studio. (The connection is liveonly while you are working with a site.) If you do not need to connect to aremote site any more, you can remove the connection information.

 To remove a connection to a remote site

1.  From the Connect to list, select the connection to remove.

2.  Click Disconnect from currently selected remote site.

Copying Files

 To copy files

1.  Select the file or files you want to copy.

2.  Click the copy button between the Source Web Site and Remote Web Site 

lists, using the button that indicates the direction in which you want to copy.

To copy the recent version of a file to the site with the older version, selectthe synchronize button.

The status pane at the bottom of the window displays the results of the copy

operation.

Files that have not changed are not copied.Note

Page 149: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 149/168

Unit 8: Deploying a Web Application n 141

Features of the Publish Web Site UtilityThis document contains extracts from the article “Publishing Web Sites,” whichyou can find in the Microsoft® Visual Studio® 2005 documentation atms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/

MS.VisualStudio.v80.en/dv_vwdcon/html/c8048c31-012b-4718-b8ac-

06a2dd41c137.htm.

Microsoft Visual Web Developer ™ allows you to publish your Web sites, whichcompiles the sites and copies the output to a location you specify, such as a

 production server. Publishing accomplishes the following tasks:

  Precompiles each page, the source code in the App_Code folder, and so on

  Creates executable output and writes it to a target folder 

The Publish Web utility is not available in Visual Web Developer Express Edition.

Publishing offers the following advantages over simply copying the Web site toa target Web server:

  The precompilation finds any compilation errors throughout the site and

identifies errors in the configuration file.

  Initial response speed for individual pages is faster because the pages arealready compiled. (If you copy pages to a site instead of precompiling them,

the pages are compiled and the compiled code is loaded on first request.)

   No source code is deployed with the site, providing you with some security

for your files. You can publish the site with markup protection, which

compiles .aspx files, or without markup protection, which copies .aspx files

to the site as is and allows you to change their layout after deployment.

Precompilation

The first step in publishing is to precompile the Web site. Precompilation for  publishing, which is somewhat different than precompiling in place (building),

 performs essentially the same compilation process that normally occurs when a page is compiled dynamically upon being requested in a browser. The

 precompiler produces assemblies from the pages (both the markup and thecode). It also compiles files in the App_Code, App_GlobalResources,

App_LocalResources, and App_Themes folders.

You can compile both single-file ASP.NET pages and code-behind pages.

Precompilation vs. Building

The precompilation step in publishing differs from the compilation that occurswhen you build a Web site while testing it. Building compiles the site or the

current page and any of its dependent files and then runs it. The build process isa form of testing, and does not produce output that you can deploy.

Precompilation during publishing, on the other hand, creates output in aspecified folder that you can, in turn, deploy to a production server.

Note

Page 150: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 150/168

142 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Writing Precompilation Output

When the precompilation process is finished, the resulting output is written to afolder that you specify. You can write the output to any folder that is accessibleto you in the file system by using FTP, or across HTTP. You must have

appropriate permissions to be able to write to the target site.

The publishing process deploys only the files in your Web site foldersand subfolder. It does not deploy the machine.config file. Therefore, theconfiguration of the target Web server might be different than it is on your 

computer, which might affect the behavior of your application.

You can specify a target folder on a staging server or production server, or youcan write the output to a folder on your local computer. If you specify a folder 

on a production server, you can precompile and deploy in one step. If youchoose to write the output to a folder that is not part of a Web site, you cancopy the output to the server in a separate step.

The output of the compilation process includes the compiled assemblies for anycode or pages. If you choose the option to allow the precompiled site to be

updateable, the code-behind classes, if any, for your .aspx, .asmx, and .ashxfiles are compiled into assemblies. However, the .aspx, .asmx, and .ashx filesthemselves are copied as-is to the target folder so that you can make changes to

their layout after deploying the site. For updateable precompiled sites, the codein single-file pages is not compiled into an assembly, but is instead deployed as

source code.

Static files are not compiled; instead, they are copied as is to the output folder.

Static files include graphics, .htm or .html files, text files, and so on.

If an error occurs during precompilation, it is reported to you in the Outputwindow and in the Error List window. Errors during precompilation will

 prevent the site from being compiled and published.

Note

Page 151: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 151/168

Unit 8: Deploying a Web Application n 143

How to: Precompile and Deploy a Web Site by Using thePublish Web Site Utility

This document contains extracts from the article “How to: Publish a Web Site,”which you can find in the Microsoft® Visual Studio® 2005 documentation at

ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_vwdcon/html/d0a1a20f-15be-4940-9485-

cb8e4aa8181b.htm.

Publishing a Web site compiles the executable files in the Web site into objectcode and then writes the output to a folder that you specify.

 To publish a Web site

1.  On the Build menu, click Publish Web Site.

2.  The Publish Web Site dialog box appears.

3.  Type the path of the folder you want to publish to, or click the ellipsis

 button (…) to browse for local IIS Web sites, remote Web sites, or FTP

locations.

You can write the Web site output to a local or shared folder, to an FTP site, or 

to a Web site that you access with a URL. You must have create and write permissions in the target folder.

If you want to be able to change the layout (but not the code) for aspx files after 

 publishing the site, select Allow this precompiled site to be updateable.

Page 152: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 152/168

144 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Features of Windows Installer Setup ProjectsThis document contains extracts from the article “Setup Projects,” which youcan find on the MSDN® Web site.

Setup projects allow you to create installers to distribute an application. The

resulting Microsoft® Windows® Installer .msi file contains the application, anydependent files, information about the application such as registry entries, andinstructions for installation. When the .msi file is distributed and run on another computer, you can be assured that everything necessary for installation is

included; if for any reason the installation fails (for example, the targetcomputer does not have the required operating system version), the installation

will be rolled back and the computer returned to its preinstallation state.

There are two types of setup projects in Microsoft Visual Studio®: Setup projects and Web Setup projects. The distinction between Setup projects and

Web Setup projects is where the installer will be deployed: Setup projectsinstall files into the file system of a target computer; Web Setup projects install

files into a virtual directory of a Web server.

In addition, a Setup Wizard is available to simplify the process of creating aSetup project or a Web Setup project.

Page 153: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 153/168

Unit 8: Deploying a Web Application n 145

How to: Create a Windows Installer Package for Deploying a Web Application

The simplest way to create a Microsoft® Windows® Installer Package for deploying a Web application is to create a Web Setup project in the Microsoft

Visual Studio® 2005 integrated development environment (IDE) and then addthe project output of the Web application to be deployed to the Web Setup

 project.

 To create a Web Setup project

1.  Using Visual Studio 2005, open the solution containing the Web site to be

deployed.

2.  On the File menu, point to Add and then click New Project.

The Add New Project dialog box appears.

3.  Expand the Other Project Types node in the Project types tree view and

then click Setup and Deployment.

4.  In the Templates section of the Add New Project dialog box, click WebSetup Project.

5.  Provide a meaningful name and choose a location for the new project, and

then click OK .

 To add Web site output to a Web Setup project

1.  In Solution Explorer, right-click the new Web Setup project that you have

 just added to the solution.

2.  Point to Add on the shortcut menu and then click Project Output.

The Add Project Output Group dialog box appears.

3.  Click Content Files.

4.  Ensure that the Web site project is selected in the Project drop-down list,

and that (Active) is selected in the Configuration drop-down list.

5.  Click OK .

 To set properties of the Web Setup project

•  Click the Web Setup project in Solution Explorer, and then use theProperties window to set the following properties:

•  Author: <Type your company name> 

•  Description: <Type a brief description> 

•  Manufacturer: <Type your company name> 

•  Product Name: <Type the name of the Web application> 

•  Title: Setup Application for <type the name of the Web application> 

Page 154: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 154/168

146 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

 To define the user interface for a Web Setup project

1.  In Solution Explorer, right-click the Web Setup project, point to View on

the shortcut menu, and then click User Interface.

The User Interface designer appears.

2.  Right-click the Start node in the Install section of the tree-view and then

click Add Dialog on the shortcut menu.

The Add Dialog dialog box appears.

3.  Click License Agreement and then click OK .

4.  Drag the License Agreement node into the tree-view so that it appears

directly below the Welcome item.

5.  Use the Properties window to set the LicenseFile property to a rich-text

format file that contains the license agreement for your Web application.

 To build the Windows Installer package

•  Right-click the Web Setup project in Solution Explorer, and then click 

Build.

After the Windows Installer package has been created, you can copy theinstaller files that it creates to the destination Web server and then run the package to install the Web site.

You can add other features to the Windows Installer, such as custom

actions, launch conditions, file-type associations, and registry settings. For more details of these features, review the Visual Studio 2005 documentation.

Note

Page 155: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 155/168

 

Unit 9: Making Web ApplicationsAvailable to Mobile Devices

How to: Detect and Redirect Mobile DevicesMobile devices typically have much smaller screens than conventional desktop

and laptop computers, which means that they might not display in a usable wayan ordinary Web Form designed to be displayed by a desktop computer. Also,

some mobile devices have gray-scale or two-tone screens and might havelimited network connectivity. To support mobile devices, it is therefore sensible

to create two versions of each Web form, one for desktop computers and onefor mobile devices.

When a mobile device makes a request to a Web Form, it should be detected

and redirected to the Mobile Web Form. Use the HttpBrowserCapabilities  class to determine the source of a request. The Request.Browser method

returns an HttpBrowserCapabilities object for the browser that requested the page.

 To redirect a mobile device to a Mobile Web Forms page

•  Insert the following code into the Web Form designed for desktop

computers. This example redirects mobile devices to a page calleddefault.aspx, in the Mobile subfolder.

[Visual Basic]

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _

Handles Me.Load

If Request.Browser.IsMobileDevice Then

Response.Redirect("Mobile/default.aspx")

End If

End Sub

[C#]

protected void Page_Load(object sender, EventArgs e) {

if (Request.Browser.IsMobileDevice)

Response.Redirect("Mobile/default.aspx");

}

Page 156: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 156/168

148 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

Some mobile devices do not permit you to use relative URLs such asMobile/default.aspx. You can ensure that requests for these devices areredirected correctly by configuring the Web application as follows.

 To configure the Web application to redirect with fully qualified URLs

•  Insert the following markup into the Web.config file:

<system.web>

<httpRuntime useFullyQualifiedRedirectUrl="true" />

</system.web>

Page 157: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 157/168

Unit 9: Making Web Applications Available to Mobile Devices 149

How to: Browse Mobile Web Pages with Specific DeviceEmulators

Microsoft® Visual Studio® 2005 includes Microsoft Device Emulator 1.0 tohelp developers write applications for mobile devices such as Pocket PCs and

mobile phones. Device Emulator can be used to simulate devices runningMicrosoft Windows® CE 5.0, Microsoft Pocket PC 2003 SE, and Microsoft

Smartphone 2003 SE.

This article explains how to browse a Microsoft ASP.NET application on adevelopment computer, with an emulator installed on the same computer, using

Microsoft ActiveSync® 4.0 to make the connection. The host computer and theemulator must already have been configured, as described in “How to:

Configure Device Emulator 1.0 to Connect to an ASP.NET Application.”

To browse an application with the Device Emulator, you must know the IP

address of the host computer.

 To obtain the IP address of the host computer

1.  On the host computer, open a command prompt.

2.  Type the following command:

Ipconfig

3.  The computer’s IP address, subnet mask, and default gateway address are

returned.

 To browse to a Web page by using the Pocket PC 2003 SE Emulator

1.  If ActiveSync is not already running and visible in the notification area, start

it from the Programs menu.

2.  In Visual Studio, on the Tools menu, click Device Emulator Manager.3.  In the Device Emulator Manager, select Pocket PC 2003 SE Emulator.

4.  On the Actions menu, click Connect. The emulator starts.

5.  In the Device Emulator Manager, on the Actions menu, click Cradle.

ActiveSync connects to the emulator and synchronizes.

6.  Once the synchronization is complete, in the emulator, click Start, and then

click Internet Explorer.

7.  In the Address box, type the address

http:// x.x.x.x / page.aspx

where x.x.x.x is the IP address you obtained for the host computer, and

 page.aspx is the file name of the page you want to browse to.

Page 158: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 158/168

150 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

 To browse to a Web page by using the Smartphone 2003 SE Emulator

1.  If ActiveSync is not already running and visible in the notification area, start

it from the Programs menu.

2.  In Visual Studio, on the Tools menu, click Device Emulator Manager.

3.  In the Device Emulator Manager, select Smartphone 2003 SE Emulator.

4.  On the Actions menu, click Connect. The emulator starts.

5.  In the Device Emulator Manager, on the Actions menu, click Cradle.

ActiveSync connects to the emulator and synchronizes.

6.  When the synchronization is complete, in the emulator, click the left buttonto open the Start menu.

7.  Use the down button to move to Microsoft Internet Explorer. Click the

center button to open Internet Explorer.

8.  Click the right button to open the menu. Click the center button to open the

Address Bar.

9.  In the Address Bar, type the address

http:// x.x.x.x / page.aspx

where x.x.x.x is the IP address of the host computer and page.aspx is the filename of the page you want to display.

10.  Use the left button to choose Go. The Web page appears.

Page 159: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 159/168

Unit 9: Making Web Applications Available to Mobile Devices 151

How to: Design and Implement a Mobile Web FormMicrosoft® Visual Studio® 2005 provides the Microsoft ASP.NET MobileDesigner for designing and creating Mobile Web Forms.

You can add a Mobile Web Form to any Visual Studio ASP.NET project.

 To add a Mobile Web Form to a Web project

1.  Right-click the project and then click Add New Item.

2.  In the Add New Item dialog box, select Mobile Web Form. Give the new

 page the name of your choice and then click Add.

The page is added and displayed in the Visual Studio Source view.

Every Mobile Web Form includes one or more <mobile:Form> tags. Each of these tags defines a form that can be displayed by the page. Only one form—the

active form—will be displayed at a time by the mobile device.

 To add a second <mobile:Form> to the page

•  In Design view, drag a Form control from the Mobile Web Forms section

of the Toolbox onto the page.

- or -

•  Add the following markup to the page:

<mobile:Form ID="SecondForm" Runat="server">

</mobile:Form>

 To activate the second form when the user presses a button

1.  In Design view, drag a Command control from the MobileWeb Forms 

section of the Toolbox onto the page.

2.  Double-click the Command object to create the default click event handler.

3.  Add the following code to this handler:

[Visual Basic]

Me.ActiveForm = SecondForm

[C#]

this.ActiveForm = SecondForm;

Within a single form you can use pagination to present a lot of information over 

several screens. This is useful, for example, if you have a long list of products,and the device can display only 10 lines at a time.

Page 160: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 160/168

152 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

 To use pagination with a list of items

1.  In Design view, select the form in which you want to use pagination.

2.  In the Properties window, set the Paginate property to true, set the

PagerStyle.NextPageTextproperty to Next, and then set the

PagerStyle.PreviousPageTextproperty to Previous.

3.  In Design view, drag a List control from the Mobile Web Forms section of the Toolbox onto the form.

4.  Select the new list object. In the Properties window, set the ItemsPerPage 

 property to 10. Add items to the Items collection.

When the form is displayed, if there are more than 10 items in the list, Next and 

Previous links appear, enabling the user to navigate through the list.

Page 161: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 161/168

Unit 9: Making Web Applications Available to Mobile Devices 153

Mobile ControlsMicrosoft® ASP.NET 2.0 includes a wide variety of controls for use on MobileWeb Form pages. These controls are optimized for use on many types of mobiledevices, such as phones and Pocket PCs. The controls adapt to the capabilities

of the device displaying the Web page. For example, they render differently on

gray-scale and color displays.

The following controls are available:

  Form: This control contains child controls for displaying information or 

gathering user input. Each page can have multiple forms, but only one form

is active at a time.

  Panel: Use this control to group other child controls. The child controls

inherit default property values from the parent panel. You can also use a

 panel to modify several controls in a single operation.

  Label: This control displays text on the page. If the label has an ID, it can be programmatically modified as the page is rendered.

  TextBox: Use this control to gather input from the user.  TextView: This control is similar to a Label control but is designed to

support longer text strings. This control supports pagination, and long text

strings will automatically be spread over several pages, as long as the form

has been configured to enable this feature.

  Command: This control is the equivalent of a Button control on a Web

Form.

  Link : This control represents a link to another control on the Mobile Form

or any other URL.

  PhoneCall: This control allows users with telephony devices to place a call

to a number you specify. If the device is not able to place calls, alternate text

can been displayed.  Image: This control displays an image on the page.

  List: This control displays a list of text items. You can bind a List control to

a data source, such as a database table or array, to display items at run time.

Alternatively, you can populate the list at design time by using the Items 

collection.

  SelectionList: This control enables the user to select one or more items

from a list. You can determine which item the user has selected by using the

SelectionList.Selection.Text  property.

  ObjectList: This control displays a list of items such as the List control.

However, each item can be any type of object, including an instance of a

custom class. This control is useful when you need to store information thatis more complex than simple text and values.

  DeviceSpecific: This control enables you to display different content,

depending on the capabilities of the device. See the resource “How to:Design Device Specific Features for a Mobile Web Form” for more details.

Page 162: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 162/168

154 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

  StyleSheet: Use this control to format a Mobile Form page or control in

much the same way as a StyleSheet on a static HTML Web page.

  Calendar: This control enables the user to select a day, week, or month of 

the year. You can set which of these is selected by using the SelectionMode 

 property and determine the value the user selected by using the

SelectedDate property.

  AdRotator: This control displays a randomly selected advertisement.

  Validation Controls: Use these controls to check the validity of user input

on a Mobile Form. The RequiredFieldValidator , for example, ensures that

the user does not leave a field blank. If the validation test is not satisfied

when the user submits the form, a message is displayed describing the error.

Page 163: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 163/168

Unit 9: Making Web Applications Available to Mobile Devices 155

How to: Design Device Specific Features for a MobileWeb Form

Mobile devices can vary greatly in their capabilities. For example, some devicescan send e-mail messages, some can place phone calls, some have color 

screens, and some have gray-scale screens. When you are designing a Web page and you do not know what type of device the user will use, you should

cater to all possible types of devices.

Microsoft® ASP.NET Mobile Forms enable you to specify different propertiesfor a tag, depending on the capabilities of the device. You can do this by using

the DeviceSpecific/Choice construct.

 To specify different attribute values based on filters

1.  In Source view, locate the control that should change depending on the

device used to view it.

2.  Add <DeviceSpecific> and <Choice> tags. The following example

shows how to display different images for different types of devices in animage control:

<mobile:Image runat=server>

<DeviceSpecific>

<Choice Filter="isColor" ImageURL="colorTree.gif" />

<Choice Filter="isWML11" ImageURL="tree.wbmp"/>

<Choice ImageURL="monoTree.gif"/>

</DeviceSpecific>

</mobile:Image>

Page 164: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 164/168

156 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

The Filter attribute in each <Choice> tag can be used in one of two ways. Itcan either specify the name of a method on the Mobile Form—which you mustwrite—or the name of a device filter in the Web.config file.

 To use a method on the Mobile Form as a filter

•  If the Filter attribute specifies the name of a method in the Mobile Form,

the method must return a Boolean value and match the signature shown bythe following example:

[Visual Basic]

Public Function isColor(ByVal capabilities As MobileCapabilities, _

ByVal optionalArgument As String) As Boolean

If capabilities.IsColor Then

isColor = True

Else

isColor = False

End If

End Function

[C#]public bool isColor(System.Web.Mobile.MobileCapabilities capabilities,

string optionalArgument) {

if (capabilities.IsColor)

return true;

return false;

}

If the Filter attribute does not specify the name of a method on the page, itmust specify the name of a filter defined in the Web.config file. These filters

can be of two types: comparison filters, in which a capability is checked against

the Argument attribute of the Choice element; and evaluator delegate filters,which specify a class and method used to perform the test.

 To use a Comparison Filter in the Web.config file

1.  Edit the Web.config file.

2.  Add the following markup to the file:

<system.web>

<deviceFilters>

<filter name="TestIsColor" compare="IsColor" argument="true" />

</deviceFilters>

</system.web>

Page 165: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 165/168

Unit 9: Making Web Applications Available to Mobile Devices 157

This example tests for the IsColor capability. For more information, see the“Device Capability Names” section later in this resource.

 To use an Evaluator Delegate Filter in the Web.config file

1.  Edit the Web.config file.

2.  Add the following markup to the file:<system.web>

<deviceFilters>

<filter name="TestColorDepth" type=”MyNameSpace.MyClass "

method="TestDepth" />

</deviceFilters>

</system.web>

Device Capability Names

When using Comparison Filters, you must specify a capability from the

Capabilities Dictionary for the compare attribute. Capabilities you can test for 

include the following:

  CanInitiateVoiceCalls : The device can place telephone calls.

  CanSendMail: The device can send e-mail messages.

  HasBackButton: The browser has a Back button for displaying the

 previous page.

  IsColor: The device has a color display.

  IsMobileDevice: The device is a Pocket PC, mobile phone, or other mobile

device.

  MobileDeviceManufacturer : The name of the device manufacturer.

  MobileDeviceModel: The model name of the device. This, with the

MobileDeviceManufacturer capability, enables you to add features that are

specific to particular piece of client hardware.

  ScreenCharactersHeight and ScreenCharactersWidth: The maximum

size of the device screen, specified in characters.

  ScreenPixelsHeight and ScreenPixelsWidth: The maximum size of the

 page, specified in pixels.

  SupportsBodyColor: The device can display a background color for the

 page.

  SupportsBold: The device can display text in bold format.

  SupportsFontColor: The device can display colored fonts.

  SupportsItalic: The device can display text in italic format.

Page 166: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 166/168

158 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005

How to: Configure Microsoft Device Emulator 1.0 toConnect to an ASP.NET Application

Microsoft® Visual Studio® 2005 includes Microsoft Device Emulator 1.0 tohelp developers write applications for mobile devices such as PDAs and

mobile phones. Device Emulator can be used to simulate devices runningMicrosoft Windows® CE 5.0, Microsoft Pocket PC 2003 SE, and Microsoft

Smartphone 2003 SE.

Device Emulator can connect only to Microsoft ASP.NET applications runningin IIS, not in the ASP.NET Development Web server. Therefore, you must

configure IIS to host your application:

 To configure IIS to host your ASP.NET application

1.  On your development computer, open a command  prompt. Type the

following command to start the IIS management console as Administrator:

Runas /user:administrator "mmc %windir%\system32\inetsrv\iis.msc"

2.  In the IIS management console, in the Web Sites section, right-click theDefault Web Site object and then click Properties.

3.  In the Default Web Site Properties dialog box, click the Home Directory 

tab.

4.  In the Local Path box, type the path to the folder where your ASP.NET

application has been saved and then click OK .

Microsoft ActiveSync® 4.0 is used to make a connection from the DeviceEmulator to the Web site as if the device were cradled. Therefore, the network 

adapter in the Device Emulator is not necessary:

 To disable the network adapter in the Device Emulator 

1.  In Visual Studio, on the Tools menu, click Options.

2.  In the Options dialog box, expand Device Tools and then click Devices.

3.  In the Devices list, select the emulator you want to use and then click 

Properties.

4.  In the Emulator Properties dialog box, click Emulator Options.

5.  On the Network tab, clear all check boxes and then click OK three times.

1.  The connection must be made with the DMA protocol.

 To configure ActiveSync to use DMA

1.  Open ActiveSync from the Start menu.

2.  On the File menu, click Connection Settings.

3.  Select the Allow connections to one of the following check box. Select

DMA from the list.

Page 167: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 167/168

Unit 9: Making Web Applications Available to Mobile Devices 159

If you are using the Pocket PC 2003 SE Emulator, you must configure thedevice to connect to the Work network for connections to the Internet.

 To configure options in the Pocket PC 2003 SE Emulator

1.  In the Pocket PC Emulator, click Start and then click Settings.

2.  On the Connections tab, double-click Connections.3.  On the Advanced tab, click Select Networks.

4.  Select My Work Network in both drop-down lists.

5.  Click OK in the top-right corner twice and then close the Connections dialog box.

 To make a connection to the Device Emulator with ActiveSync

1.  If ActiveSync is not already running, open it from the Program menu.

2.  In Visual Studio, on the Tools menu, click Device Emulator Manager.

3.  In the Device Emulator Manager, right-click the emulator you want to use

and then click Connect. The emulator starts.4.  In the Device Emulator Manager, on the Actions menu, click Cradle.

5.  The ActiveSync Connection Wizard starts and guides you through making aconnection to the host computer.

If Microsoft Office Outlook ® is not installed, do not configure

ActiveSync to synchronize the Inbox in the Connection Wizard. Note

Page 168: ASP.net Stage1

8/9/2019 ASP.net Stage1

http://slidepdf.com/reader/full/aspnet-stage1 168/168

 

THIS PAGE INTENTIONALLY LEFT BLANK