asp net stage1

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

Upload: jud10

Post on 14-Apr-2015

61 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASP Net Stage1

Toolkit

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

Page 2: ASP Net Stage1

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 any license 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

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 online and electronic documentation), training materials, and any other associated media and printed materials. This EULA applies to updates, supplements, add-on components, and Internet-based services components of the Licensed Content that Microsoft may 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 you or made available to you through the use of the Licensed Content. This EULA also governs any product support services relating to the Licensed Content except as may be included in another agreement between you and Microsoft. An amendment or addendum to this EULA may accompany the Licensed Content.

2. GENERAL GRANT OF LICENSE. Microsoft grants you the following rights, conditioned on your compliance with all the terms and conditions of this EULA. Microsoft grants you a limited, non-exclusive, royalty-free license to install and use the Licensed Content solely in conjunction with your participation as a student in an Authorized Training Session (as defined 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 Device for 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 Microsoft Certified Technical Education Center, an IT Academy, via a Microsoft Certified Partner, or such other entity as Microsoft may designate from time to time in writing, by a Microsoft Certified Trainer (for more information on these entities, please visit www.microsoft.com). WITHOUT LIMITING THE FOREGOING, COPYING OR REPRODUCTION OF THE LICENSED CONTENT TO ANY SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY 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 technical inaccuracies or typographical errors. Changes are periodically made to the content. Microsoft may make improvements and/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 to represent 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 not republished or posted on any network computer or broadcast in any media; (c) any reproduction will include either the Document’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 to exercise the foregoing rights, you agree to comply with all other terms and conditions of this EULA, including without limitation Sections 3.4, 3.5, and 6.

Page 4: ASP Net Stage1

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

3.5 Reproduction/Redistribution Licensed Content. Except as expressly provided in this EULA, you may not reproduce 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 in this EULA. The Licensed Content is protected by copyright and other intellectual property laws and treaties. Microsoft or its suppliers 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, as delivered to you. The Licensed Content is licensed, not sold.

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

6. LIMITATIONS ON SALE, RENTAL, ETC. AND CERTAIN ASSIGNMENTS. You may not provide commercial hosting 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 technical information 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 you and 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. The third party sites are not under the control of Microsoft, and Microsoft is not responsible for the contents of any third party sites, 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-on components, or Internet-based services components, of the Licensed Content that Microsoft may provide to you or make available 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 discontinue any 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 solicitations issued on or after December 1, 1995 is provided with the commercial license rights and restrictions described elsewhere herein. All software provided to the U.S. Government pursuant to solicitations issued prior to December 1, 1995 is provided with “Restricted Rights” as provided for in FAR, 48 CFR 52.227-14 (JUNE 1987) or DFAR, 48 CFR 252.227-7013 (OCT 1988), as applicable.

11. EXPORT RESTRICTIONS. You acknowledge that the Licensed Content is subject to U.S. export jurisdiction. You agree 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 and Licensed 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 must agree to all the EULA terms.

13. “NOT FOR RESALE” LICENSED CONTENT. Licensed Content identified as “Not For Resale” or “NFR,” may not 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 comply with the terms and conditions of this EULA. In such event, you must destroy all copies of the Licensed Content and all of its component parts.

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

Page 5: ASP Net Stage1

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, OF RESULTS, OF WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE, ALL WITH REGARD TO THE LICENSED CONTENT, AND THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT OR OTHER SERVICES, INFORMATION, SOFTWARE, AND RELATED CONTENT THROUGH THE LICENSED CONTENT, OR OTHERWISE ARISING OUT OF THE USE OF THE LICENSED CONTENT. also, there is no warranty or condition of title, quiet enjoyment, quiet possession, correspondence to description or non-infringement with regard to the LICENSED 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 maximum extent 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 any way 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 arising out of the use of the LICENSED CONTENT, or otherwise under or in connection with any provision of this EULA, even in the 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 LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.

17. LIMITATION OF LIABILITY AND REMEDIES. NOTWITHSTANDING ANY DAMAGES THAT YOU MIGHT INCUR FOR ANY REASON WHATSOEVER (INCLUDING, WITHOUT LIMITATION, ALL DAMAGES REFERENCED HEREIN AND ALL DIRECT OR GENERAL DAMAGES IN CONTRACT OR ANYTHING ELSE), THE ENTIRE LIABILITY OF MICROSOFT AND ANY OF ITS SUPPLIERS UNDER ANY PROVISION OF THIS EULA AND YOUR EXCLUSIVE REMEDY HEREUNDER SHALL BE LIMITED TO THE GREATER OF THE ACTUAL DAMAGES YOU INCUR IN REASONABLE RELIANCE ON THE LICENSED CONTENT UP TO THE AMOUNT ACTUALLY 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 APPLICABLE LAW, 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 the laws 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 arise hereunder, you consent to the jurisdiction of the federal and provincial courts sitting in Toronto, Ontario. If you acquired this Licensed 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 EULA which is included with the Licensed Content) are the entire agreement between you and Microsoft relating to the Licensed Content 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 the extent 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 the address information enclosed in this Licensed Content to contact the Microsoft subsidiary serving your country or visit Microsoft 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 services de soutien technique (le cas échéant) sont fournis TELS QUELS ET AVEC TOUS LES DÉFAUTS par Microsoft et ses fournisseurs, 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, des ré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 du Contenu Sous Licence et de la prestation des services de soutien technique ou de l’omission de la ’une telle prestation des services 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

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

EXCLUSION DES DOMMAGES ACCESSOIRES, INDIRECTS ET DE CERTAINS AUTRES DOMMAGES. DANS LA MESURE MAXIMALE PERMISE PAR LES LOIS APPLICABLES, EN AUCUN CAS MICROSOFT OU SES FOURNISSEURS NE SERONT RESPONSABLES DES DOMMAGES SPÉCIAUX, CONSÉCUTIFS, ACCESSOIRES OU INDIRECTS 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 PERTE D’EXPLOITATION, DE BLESSURES CORPORELLES, DE LA VIOLATION DE LA VIE PRIVÉE, DE L’OMISSION DE REMPLIR 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 CE SOIT) SE RAPPORTANT DE QUELQUE MANIÈRE QUE CE SOIT À L’UTILISATION DU CONTENU SOUS LICENCE OU À L’INCAPACITÉ DE S’EN SERVIR, À LA PRESTATION OU À L’OMISSION DE LA ’UNE TELLE PRESTATION DE SERVICES DE SOUTIEN TECHNIQUE OU À LA FOURNITURE OU À 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 DE L’UTILISATION DU CONTENU SOUS LICENCE OU AUTREMENT AUX TERMES DE TOUTE DISPOSITION DE LA U PRÉSENTE CONVENTION EULA OU RELATIVEMENT À UNE TELLE DISPOSITION, MÊME EN CAS DE FAUTE, DE DÉLIT CIVIL (Y COMPRIS LA NÉGLIGENCE), DE RESPONSABILITÉ STRICTE, DE VIOLATION DE CONTRAT OU DE VIOLATION DE GARANTIE DE MICROSOFT OU DE TOUT FOURNISSEUR ET MÊME SI MICROSOFT OU TOUT FOURNISSEUR 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 DOMMAGES SUSMENTIONNÉS ET TOUS LES DOMMAGES DIRECTS OU GÉNÉRAUX OU AUTRES), LA SEULE RESPONSABILITÉ ’OBLIGATION INTÉGRALE DE MICROSOFT ET DE L’UN OU L’AUTRE DE SES FOURNISSEURS AUX TERMES DE TOUTE DISPOSITION DEU LA PRÉSENTE CONVENTION EULA ET VOTRE RECOURS EXCLUSIF À L’ÉGARD DE TOUT CE QUI PRÉCÈDE SE LIMITE AU PLUS ÉLEVÉ ENTRE LES MONTANTS SUIVANTS : LE MONTANT QUE VOUS AVEZ RÉELLEMENT PAYÉ POUR LE CONTENU SOUS LICENCE 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 SI TOUT 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 province d’Ontario, Canada. Vous consentez Chacune des parties à la présente reconnaît irrévocablement à la compétence des tribunaux fédéraux et provinciaux siégeant à Toronto, dans de la province d’Ontario et consent à instituer tout litige qui pourrait dé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 de succursale Microsoft desservant votre pays, dont l’adresse est fournie dans ce produit, ou visitez écrivez à : Microsoft sur le World Wide Web à http://www.microsoft.com

Page 7: ASP Net Stage1

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.NET Pages......................................................................................................................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 the Web 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 the Web 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

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

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: local Internet 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 are stored in a folder under the default IIS folder for Web sites (Inetpub\wwwroot). Visual Studio 2005 also creates the appropriate IIS configuration so that the Web 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 any accessible 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 a network share. You do not need to run IIS on your computer. Instead, you can test 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 directory that points to the Web site.

Note

Note

Page 10: ASP Net Stage1

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 by using an FTP server. This is a typical scenario if your Web site is located on a hosting site.

You can connect from within Visual Studio 2005 to any FTP server on which you have read/write privileges. You can then create and edit Web pages on that server. If the FTP server is configured with ASP.NET and an IIS virtual root that 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 installed and 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 run the 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 Visual Studio 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

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 containing your 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

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

How to: Create a File System Web Site In a file-system Web site, you store the files for your application in a folder on your 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 you to 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 overwrite any files with the same name that are already in the folder.

Page 13: ASP Net Stage1

Unit 1: Creating a Web Application 5

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

Page 14: ASP Net Stage1

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

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

Microsoft® Visual Web Developer™ is the environment in Microsoft Visual Studio® 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 Source view 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 Visual Studio 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

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 following illustration 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. The View menu allows you to display additional windows.

Note

Page 16: ASP Net Stage1

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, to Web applications.

To add an existing item to the Web site 1. 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 add many types of pages and components to your Web site, including plain HTML pages, cascading style sheets, Web configuration files, and ASP.NET Web Forms.

To add a new page to the Web site 1. 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 can change 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 HTML in 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 in Source view.

Note

Page 17: ASP Net Stage1

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 to

Design 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 how to add a Button, TextBox, and Label control to the page and how to write code to handle the Click event for the Button control.

To add controls to the page 1. 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.

Page 18: ASP Net Stage1

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 controls on the page. In this part of the example, you will set properties in both Design view and Source view.

To set control properties 1. 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 that Visual 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 you set 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 the attribute 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 Source view 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. The ForeColor attribute is set to the color that you have selected.

Note

Note

Page 19: ASP Net Stage1

Unit 1: Creating a Web Application 11

ASP.NET Web Page Code Model A 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 programming code are in the same physical .aspx file. The programming code is contained in a <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

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 consist of 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 from the 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 the code 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 support creating code-behind files for ASP.NET pages.

For example, if you are working with a page named SamplePage, the HTML markup 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

Unit 1: Creating a Web Application 13

In the code-behind model, the example used in the preceding section for the single-file page is split into two parts. The HTML markup is in one file (in this example, 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 the code-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

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 file that 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 the full 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, but can 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 be from another class that derives from System.Web.UI.Page. In addition, the .aspx file contains an Inherits attribute that points to the code-behind partial class. 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 generated class is compiled into an assembly that runs in order to render output to the browser.

Page 23: ASP Net Stage1

Unit 1: Creating a Web Application 15

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

Page 24: ASP Net Stage1

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 run time, 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 and HTML 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 Pages Code-behind pages offer advantages that make them suitable for Web applications with a significant amount of code or in which multiple developers are 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 code file. 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 the output is the same for both models.

Page 25: ASP Net Stage1

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, the Default.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 Visual Studio 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, load the 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

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

<customErrors> Element The customErrors element provides information about how custom error messages are handled for a Microsoft® ASP.NET application. It can be defined in 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 Attribute Attribute 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

Unit 1: Creating a Web Application 19

Installation Defaults When the Microsoft .NET Framework is installed, the machine.config file specifies 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 cause run-time errors when they are used in response to another error, the standard ASP.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 does not have access to the details of the error.

Example The following configuration example specifies the error-handling pages to use for 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

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

<compilation> Element The <compilation> element in the system.web section of a configuration file enables 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 different optional 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 the Web application by using the integrated Visual Studio 2005 debugging tools. The numRecompilesBeforeAppRestart setting defines how many recompiles can be performed before Microsoft ASP.NET unloads and then reloads the Web application. An application restart will result in loss of Application state and Session state (if the in-process state option is used), so it is important to understand the implication of this setting for your Web application.

Page 29: ASP Net Stage1

Unit 2: Programming a Web Application

How to Determine Which Web Server Control Raised an Event

When an event handler is called, you can determine which control raised the event. 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

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

Unit 2: Programming a Web Application 23

The HttpServerUtility Transfer Method You can use the HttpServerUtility.Transfer method to halt the code running on 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

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

How to: Pass Values Between ASP.NET Web Pages If 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 techniques depend on how you perform the redirection. Options include the following:

Appending information to the URL of the target page by using a query string. 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

Unit 2: Programming a Web Application 25

Using the Query String The following code demonstrates how to pass query string parameters called productname 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 the query 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

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

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

You can bind several control events to the same event handler method. These events 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 the Command 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 the HTML 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 Properties window 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 by separating 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

Unit 2: Programming a Web Application 27

If you use a Handles clause to bind an event and method, do not include the 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 the event 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

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

The Button.Command Event The Button.Command event fires when the user clicks a Button control on a Microsoft® 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 have a 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 a CommandArgument of Ascending, whereas the other button may specify Descending as its CommandArgument property.

Example The following code example demonstrates how to use a Command event handler 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

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

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

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

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

How to: Detect Browser Capabilities Different browsers (and even different versions of the same browser) support different features. In Microsoft® ASP.NET pages, you frequently need to know about 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 specific capabilities in mind, such as a text-only version of a Web page for browsers running 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 the type 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

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

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

How to: Access Page Header Information The HTML page header section of a Microsoft® ASP.NET page contains useful information that you can access programmatically. For example, you can examine 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 property when 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 page header:

[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

Unit 2: Programming a Web Application 35

How to: Handle Page-Level Errors In a Microsoft® ASP.NET Web application, you can catch and handle errors at three levels:

At the method level by using Try…Catch blocks for performing structured exception handling.

At the page level by using the Page.Error event. Use this technique to provide more general error handling. Any error on the page—except for those within Try…Catch blocks—will raise this event.

At the application level by:

• Using the web.config file and a generalized error handling page. Any errors within your entire application that are not handled by the previous methods will display the error handling page.

• Using the Application_Error event in a global.asax file.

Handling Page-Level Errors The following code shows a Page_Error event handler for an ASP.NET page that will handle all errors for the page that are not caught by Try…Catch blocks elsewhere in the page:

[Visual Basic] Private Sub Page_Error(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles MyBase.Error Response.Write(Server.GetLastError().Message) Server.ClearError() End Sub

[Visual C#] private void Page_Error(Object sender, System.EventArgs e) { Response.Write(Server.GetLastError().Message); Server.ClearError(); }

You should be careful not to display sensitive information in error pages. For example, displaying code, Microsoft SQL Server™ error information, or platform version numbers can give malicious users information that they can exploit to attack your Web site.

Note

Page 44: ASP Net Stage1

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

How to: Handle Application-Level Errors You can handle errors at the Web-application level in either of the following ways:

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 Web site 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 custom error 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 will display 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 that they can use to attack your Web site.

Note

Page 45: ASP Net Stage1

Unit 3: Adding and Configuring Server Controls

Survey.aspx Page Design—HTML Controls The following illustration shows a model page layout achieved by using HTML controls for the survey.aspx prototype. You should use this illustration as a guide when you are designing the survey page in the lab.

Page 46: ASP Net Stage1

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

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

You can add an HTML control to a Web page by dragging a control from the HTML group in the Toolbox in Microsoft® Visual Studio® 2005. By default, an HTML control generates static HTML text. To make this control accessible to server-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 in Visual 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 HTML markup for this control. A glyph appears on the control to indicate that it is a server-based control.

Page 47: ASP Net Stage1

Unit 3: Adding and Configuring Server Controls 39

HTML Controls for ASP.NET Web Pages This document describes controls in the HTML section in the Toolbox. You can add 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 that is passed through to the browser. However, by converting HTML elements to HTML server controls, you expose them as objects that you can program in server-side code.

HTML Controls The following HTML controls can be added to Web pages from the Toolbox in Microsoft 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 table itself, 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

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

How to: Add HTML Markup to Web Pages You can use Microsoft® Visual Studio® 2005 to add any HTML markup to a static Web page or to a dynamic Microsoft ASP.NET page. You can add HTML controls 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

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-formed and valid HTML content by providing guidance on valid element names and attribute 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

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

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

Page 51: ASP Net Stage1

Unit 3: Adding and Configuring Server Controls 43

Introduction to ASP.NET Web Server Controls When 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 model that 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 to create 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 Forms instead 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 to function properly. If a user has disabled scripting in the browser, the controls might not function as you intend.

HTML Server Controls HTML server controls are HTML elements with attributes that make them visible to—and programmable on—the server. Ordinary HTML elements, such as <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, by converting 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 HTML server controls as properties.

Note

Note

Page 52: ASP Net Stage1

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 it should 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 to

an 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 simply dragging 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 abstract controls, in which the HTML rendered can be quite different from the model that you program against. For example, a RadioButtonList Web server control might be rendered in a table or as inline text with other HTML.

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

Page 53: ASP Net Stage1

Unit 3: Adding and Configuring Server Controls 45

Web server controls provide all of the features described earlier for HTML server 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 on the 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

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

Standard Toolbox Controls This document describes controls that are available in the Standard group of the Microsoft® Visual Studio® 2005 Toolbox. These are Microsoft ASP.NET Web server 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 following controls:

AdRotator: This control cycles through a series of clickable ad banners, and it allows some ads to be weighted more heavily than others. Ads can either be linked to the control by using an XML file with a predefined schema 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 with which 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 to link 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

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. Only one 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 to collect 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. To format the data, you can use an XSL transform.

Page 56: ASP Net Stage1

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

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

Microsoft®Visual Web Developer™ is the environment in Microsoft Visual Studio® 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 Source view 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 Visual Studio 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

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 following illustration 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. 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. The View menu allows you to display additional windows.

Note

Page 58: ASP Net Stage1

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, to Web applications.

To Add an Existing Item to the Web Site 1. 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 add many types of pages and components to your Web site, including plain HTML pages, cascading style sheets, Web configuration files, and ASP.NET Web Forms.

To Add a New Page to the Web Site 1. 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 can change 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 HTML in 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 in Source view.

Note

Page 59: ASP Net Stage1

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 to

Design 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 how to add Button, TextBox, and Label controls to the page and write code to handle the Click event for the Button control.

To Add Controls to the Page 1. 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 Design view and Source view.

To Set Control Properties 1. 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 that Visual 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 actually setting the Text HTML attribute of the control.

Page 60: ASP Net Stage1

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

The controls are inside a <form> element, which also has the attribute 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 Source view 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

Unit 3: Adding and Configuring Server Controls 53

How to: Set ASP.NET Control Properties When 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 a control by modifying its attributes in the HTML markup for a Web page in Source view.

To Set Server Control Properties by Using the Properties Window Either:

In Design view, select the control, and then set properties in the Properties window.

Or:

In Source view, place the insertion point in the element tag of the control, and then 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 the control 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 the Microsoft® 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

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

How to: Add Web Server Controls to a Web Forms Page by Using the Web Forms Designer

You can add a Web Server control to a Web page by dragging and dropping a control from the Standard group of the Toolbox in Microsoft® Visual Studio® 2005. Web Server controls are automatically configured with the runat="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 in Visual Studio 2005:

1. From the Standard section in the Toolbox, drag the required control onto the page. The Web Forms Designer adds a new Web control to the page and includes the attribute runat="server", which tells Microsoft ASP.NET to treat the element as a server-side control. A glyph appears on the control to indicate 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

Unit 3: Adding and Configuring Server Controls 55

Navigation Controls In Microsoft® Visual Studio® 2005, the Navigation section in the Toolbox contains 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. The web.sitemap file defines the structure of the menu, along with URL information for the target of each menu item. Additionally, you can control how 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 the example web.sitemap file:

Page 64: ASP Net Stage1

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 to orient themselves quickly. The display is often referred to as a breadcrumb trail. 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 a database. 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 to the example web.sitemap just described:

Page 65: ASP Net Stage1

Unit 3: Adding and Configuring Server Controls 57

The Button.OnClientClick Property Use the Button.OnClientClick property to specify client-side script to be run when the Button object is clicked. The code that you add to this property is added to the onclick attribute of the control.

Write client-side code in a scripting language that you know the target browser supports. JavaScript is the most widely supported language and is used in the examples in this document.

To Add Client-Side Code to the Button.OnClientClick Property 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, type the following text in the OnClientClick

property: alert("You clicked the button");

To Add Client-Side Code to the Button.OnClientClick Property in Source View

Add the following markup to the page, somewhere within the <form> element:

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick='alert("You clicked the button");' />

Note

Page 66: ASP Net Stage1

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

How to: Determine How an ASP.NET Web Page Was Invoked

You will often find it useful to know how a Web page was invoked: whether by an 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 response to a postback. The Page object exposes properties that you can use to determine how 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

Unit 3: Adding and Configuring Server Controls 59

Cross-Page Posting in an ASP.NET Web Page By 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 as cross-page posting. The controls that can do this are those that implement the IButtonControl 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

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 must include the PreviousPageType directive at the top of the HTML markup, just under the Page directive. This makes the reference to the previous page strongly 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

Unit 3: Adding and Configuring Server Controls 61

How to: Post an ASP.NET Page to a Different Page By 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 View In 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
Page 71: ASP Net Stage1

Unit 4: Creating a Common Layout by Using Master Pages

Master Pages Overview This document contains extracts from the article “ASP.NET Master Pages Overview,” 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/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 feel and 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 the content 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 the master 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 as MasterPage.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

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 includes the 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 any HTML 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-behind files) 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 and mapping them to ContentPlaceHolder controls on the master page. For example, the master page might have content placeholders called ContentPlaceholder1 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 an ASP.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

Unit 4: Creating a Common Layout by Using Master Pages 65

Advantages of Master Pages Master pages provide functionality that developers have traditionally created by copying 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 Pages When 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

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 page members from code in the content page.

Page 75: ASP Net Stage1

Unit 4: Creating a Common Layout by Using Master Pages 67

How to: Create a Master Page The 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 Site 1. 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 in Source view.

Designing the Master Page When you create a new master page by using Microsoft Visual Studio® 2005, it contains a single ContentPlaceholder control. This control provides a location where content from referencing pages will be merged at run time. You can add additional 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

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

How to: Configure Content Pages The 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 Site 1. 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 this

content 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 must add 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

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 at run 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 the ContentPlaceholder 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

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

How to: Create Nested Master Pages This document is a copy of the article “Nested Master Pages,” 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/ec29afad-b7f5-4c58-a4db-b538dbfcea1b.htm.

Master pages can be nested, with one master page referencing another as its master. 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 child master 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. The child master page typically contains content controls that are mapped to content placeholders on the parent master page. In this respect, the child master page is laid 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

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
Page 81: ASP Net Stage1

Unit 5: Managing State for a Web Application

ASP.NET State Management Overview The information in this document is adapted from the article “ASP.NET State Management,” 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_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 all information that is associated with the page—along with the controls on the page—would be lost with each roundtrip. For example, if a user enters information 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 preserve data 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 and session 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

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 involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between roundtrips.

View State The System.Web.UI.Control.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default 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 controls is 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 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 that show 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 breaking your 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 Fields ASP.NET allows you to use HTML-standard hidden fields in a form. A hidden field 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, the content of a hidden field is sent in the HTTP form collection along with the values 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

Unit 5: Managing State for a Web Application 75

A hidden field stores a single variable in its value property and must be explicitly added to the page. After adding a hidden field to the page, you insert your value into the hidden field. ASP.NET provides the System.Web.UI.HtmlControls.HtmlInputHidden control, which offers hidden-field functionality.

Cookies A cookie is a small amount of data that is stored either in a text file on the client file 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. Cookies can 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 the request 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 has already 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 and read their contents. It is recommended that you do not store sensitive information, such as a user name or password, in a cookie. Instead, store a token in the cookie that identifies the user and then use the token to look up the sensitive information on the server.

Query Strings A query string is information that is appended to the end of a page URL. A typical 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 includes two attribute-value pairs, one called category and the other called price.

Query strings provide a simple but limited way of maintaining state information. 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 devices impose 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 submit the 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

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 the server rather than persisting information on the client. With server-based state management, 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 State ASP.NET allows you to save values by using application state—which is an instance of the System.Web.HttpApplicationState class—for each active Web application. Application state is a global storage mechanism that is accessible from 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 to this structure to store it between page requests.

Once you add your application-specific information to application state, the server manages it.

Session State ASP.NET allows you to save values by using session state—which is an instance 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 application and then returns later, the second user session will have a different session state from the first.

Session state has a key-value dictionary structure for storing session-specific information that needs to be maintained between server roundtrips and between requests 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 running Microsoft SQL Server™.

Page 85: ASP Net Stage1

Unit 5: Managing State for a Web Application 77

What’s New in ASP.NET State Management This document is a copy of the article “What’s New in ASP.NET State Management,” 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_aspnetcon/html/ba1da7de-269e-418f-9739-5c307ba4afb7.htm.

Microsoft ASP.NET version 2.0 retains much of the functionality of ASP.NET version 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 data on 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 prevent access 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 maximum size (in bytes) that you want to allow in a single view-state field. 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. 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 that show different information, somehow the control needs to know which tab is selected between roundtrips to be able 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 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 allows you 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

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

ASP.NET ViewState Microsoft® 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. The field 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 ViewState information 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 large hidden 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 into several 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 by adding EnableViewState="true" or EnableViewState="false" to the markup 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 the browser

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

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 MaxPageStateFieldLength property of the

page to the maximum length of each chunk, as follows: [Visual Basic] MaxPageStateFieldLength = 250

[C#] MaxPageStateFieldLength = 250;

Page 88: ASP Net Stage1

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

Initializing the ASP.NET Application and Session Objects Microsoft® ASP.NET provides two objects that can be used to store small amounts 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 the same Web application share the same Application object.

The Session object is created when a user begins a session in a Web application. 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 the Web 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 it in 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

Unit 5: Managing State for a Web Application 81

How to: Save Values in Session State This 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 at ms-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 an individual 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

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

How to: Read Values from Session State This document contains extracts from the article “How to: Read Values from Session State,” 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_aspnetcon/html/2ef449bc-5c17-4785-b7cf-378c601af8f5.htm.

This example accesses the HttpSessionState.Item property to retrieve the values 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 that does 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 the appropriate type when getting values out of session state, as shown in the example. In C#, you should always cast to the appropriate type when reading session values.

Page 91: ASP Net Stage1

Unit 5: Managing State for a Web Application 83

How to: Save Values in Application State This document contains extracts from the article “How to: Save Values in Application State,” 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_aspnetcon/html/1e0caf13-e8f0-46d5-9ca0-8b53e4b1c08e.htm.

Application state is a data repository that is available to all classes within a Microsoft ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving in a database. Unlike session state, 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 small amounts 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 resource within 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 though you 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 example shows 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 the Application_Start handler in the Global.asax file. Just as in a regular .aspx page, the System.Web.HttpApplicationState class is exposed through the System.Web.UI.Page.Application object. The following code example shows 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

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

How to: Read Values from Application State This document is a copy of the article “How To: Read Values from Application State,” 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_aspnetcon/html/21142bde-d4f2-4e80-b1b3-6113b4477c47.htm.

Application state is a data repository that is available to all classes within a Microsoft ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving in a database. Unlike session state, 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 small amounts 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 resource within 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 variable called 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, you must 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

Unit 5: Managing State for a Web Application 85

How to: Implement Out-of-Process Session State The information in this document is adapted from the article “Session State Modes,” 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_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 list describes 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 values for 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 will host 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

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 application to 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

Unit 5: Managing State for a Web Application 87

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

To cache an item, you specify its value and a key name for it. You can also use the Cache.Insert and Cache.Add methods, which provide greater control. For example, with these methods you can specify a timeout value after which the item 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 will return 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 as the second argument. The following code performs the same task as the previous example by using 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

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

Unit 5: Managing State for a Web Application 89

How to: Define Dependencies Between Cached Items The information in this document is adapted from the article “How to: Add Items to the Cache,” 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_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 the dependencies parameter in the Cache.Add or Cache.Insert method. The following example demonstrates using the Insert method to add an item with 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

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

How to: Delete Cached Data This 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 at ms-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’s cache. 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 specify files, directories, or keys that the item is dependent on. The item is removed from the cache when those dependencies change. The server itself can remove an item from the cache when it needs to free memory (scavenging). You have control over the priorities of cached items when this occurs. Any of these methods for removing items from the cache are determined when you write code 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 removes an item assigned the MyData1 key. [Visual Basic] Cache.Remove("MyData1")

[C#] Cache.Remove("MyData1");

Page 99: ASP Net Stage1

Unit 5: Managing State for a Web Application 91

How to: Implement Deletion Notifications in Cached Data This document is a copy of the article “How to: Notify an Application When an Item is Deleted from the Cache,” 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_aspnetcon/html/38c33aa0-afe9-40ba-a1a4-1ebab95286ef.htm.

Microsoft ASP.NET provides the CacheItemRemovedCallback delegate. It defines 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

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

This event handler must use the same signature as the CacheItemRemovedCallback delegate. This code assumes that you have created two static variables: itemRemoved of type Boolean and reason of type CacheItemRemovedReason.

3. Create an instance of the CacheItemRemovedCallback delegate that calls the 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 be accessed 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

Unit 6: Accessing and Displaying Data

How to: Create and Retrieve Database Connections This document contains extracts from the article “Connecting to Databases,” 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/3a95463b-0fd1-44c0-b6a5-3c36002be1dc.htm.

Microsoft ASP.NET gives you flexibility in how you connect to databases. Using data-source controls enables you to encapsulate data-access logic in a control that you can configure by specifying connection and query information. Alternatively, you can write the data-access logic yourself.

Using Data Source Controls in a Web Page To connect to a database in ASP.NET, you should do the following (in addition to using custom objects, Microsoft ADO.NET, or other processes):

Determine which provider you need. A provider is a class that communicates with a specific type of database.

Construct a connection string that includes the information that the provider needs to open a specific database.

Add a data source control, such as SqlDataSource, to the page and configure it with the name of the provider, a connection string (or a reference to a connection string stored elsewhere), and query information (typically, an SQL statement).

You can specify provider and connection information as individual properties of data source controls, or you can define provider and connection string information centrally in the configuration file for the Web application (Web.config). This allows you to share information across multiple data control instances by referencing the configuration values.

Coding Data Access Yourself If it is not practical in your application to use data source controls, you can code data access yourself by using ADO.NET classes. You might code data access yourself if you have complex data access requirements that are not possible with data source controls, or if you want to create a separate component that performs data access outside of your Web pages.

Page 102: ASP Net Stage1

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 a Microsoft 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 them can 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 connection string, 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.config file 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 the authentication information. As with the provider, you can indicate the connection string within the Web.config file or as a property of a specific data source 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 a child element named <connectionStrings> and place your connection strings there:

<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 source control can use values from the Web.config file. One advantage to this process is that you can easily change the server name, database, or authentication information without editing individual Web pages.

Page 103: ASP Net Stage1

Unit 6: Accessing and Displaying Data 95

Retrieving Connection Strings Programmatically You can programmatically retrieve connection strings from the Web.config file at run time and use them in conjunction with data source controls or ADO.NET objects. 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 a Customer 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

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

Products.aspx Page Design The following illustration shows a model page layout for the Products.aspx prototype. You should use this illustration as a guide when you are designing the Products page in the lab.

Page 105: ASP Net Stage1

Unit 6: Accessing and Displaying Data 97

How to: Access Data by Using SqlDataSource Controls This document contains extracts from the article “SQL DataSource Web Server Control Overview,” 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/34779c84-3512-49d9-8e6f-643aaae216ce.htm.

Microsoft ASP.NET includes a set of data source controls that allow you to interact with different types of data sources. All data source controls provide the same basic functionality, regardless of what underlying data source they interact with. For example, all data source controls support a Select method that retrieves data.

The data source control model is extensible, so you can also create your own data source controls that interact with different data sources or that provide additional functionality for an existing data source.

SqlDataSource Control The SqlDataSource control allows you to retrieve and update data using SQL commands. The SqlDataSource control works with Microsoft SQL Server™, OLE DB, ODBC, and Oracle databases, depending on the data provider configured for your application. By default, the control works with SQL Server.

Connections When you configure a SqlDataSource control, you specify a connection string in the ConnectingString property that includes information that the control needs to connect to a database. The contents of a connection string differ depending on what type of database the data source control is accessing. For example, the SqlDataSource control (and any other data source control that interacts with SQL Server) requires a server name, a database (catalog) name, and information about how to authenticate the user.

Instead of setting connection strings at design time as part of the data source control, you can store them centrally as part of your application’s configuration settings. In that case, you can programmatically retrieve the connection string and assign it to the data source control when the page runs.

Commands You can specify up to four commands (SQL queries) for the SqlDataSource control: SelectCommand, UpdateCommand, DeleteCommand, and InsertCommand. Each command is a separate property of the data source control. For each command property, you specify a SQL statement that the data source control should execute. If the data source control connects to a database that supports stored procedures, you can specify the name of a stored procedure in place of the SQL statement for a command.

Page 106: ASP Net Stage1

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 parameterized SQL 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 called automatically 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 methods explicitly 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 Data The SqlDataSource control can return data in two forms—as a DataSet or as a data 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 through data 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 (bind it) 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.

Caching The 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 data source 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 feature allows 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 caching allows you to create high-performance data access in your Web applications, because you can minimize data retrieval to only those times when it is necessary to get refreshed data.

Page 107: ASP Net Stage1

Unit 6: Accessing and Displaying Data 99

Sorting and Filtering If you have cached data and have specified a DataSet as the format for data returned by a Select query, you can also filter the data without rerunning the query. 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 by creating special FilterParameters objects that provide values at run time to the filter 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 customers from the Northwind database, by using the NWind connection that has been configured 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

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

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

This document is an extract from the article “Types of ASP.NET Data Bound Controls,” 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 also supersedes the DataGrid from previous versions of ASP.NET; it supports all the functionality of the DataGrid control and provides additional features.

List of Controls In 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.

FormView The FormView control is a data-bound container allowing you to create a freeform 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 is displayed 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’s changes to the data can be automatically updated in the database using FormView.

GridView The 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 and sorting. 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 still available for backward compatibility with existing Web applications.

Note

Page 109: ASP Net Stage1

Unit 6: Accessing and Displaying Data 101

DetailsView The 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, the DetailsView 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 display such as GridView. For example, you could click on a name in a GridView and then dynamically display a DetailsView to show a record for that particular name.

DataList The DataList control displays multiple records, typically in a table. Unlike the GridView control, the DataList control does not provide a predetermined layout for the data. For example, the DataList control does not inherently display 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 be customized 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 allows you to create a freeform layout for displaying multiple records. With the Repeater control, you use your own HTML and controls surrounding the data row you want to display, and the repeater control will repeat the markup and controls 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 the control 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 the ContactName from each row in the context of the HTML contained within the control.

Page 110: ASP Net Stage1

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

DropDownList and ListBox You can bind data to both the ListBox and DropDownList because of their inheritance of the ListControl. For example, you can bind a DropDownList to your 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 ID string, while the DataTextField property shows a user-friendly contact name.

TreeView The TreeView control is a hierarchical data-bound control and may be used in conjunction with an XmlDataSource or a SiteMapDataSource. The inherently hierarchical data from either of these two sources is used to create a straightforward expandable and collapsible tree for the user.

Menu The 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 which data 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

Unit 6: Accessing and Displaying Data 103

Most data-bound controls require the IDataSource interface, which all DataSource 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

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

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

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 by the selected value in a DropDownList control named ddCustomerID. The data will be retrieved from the Northwind database; the data source for the GridView control will connect to the database by using a connection string from 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 the Web.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 select statement 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

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 control that 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

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

How to: Access Objects as Data by Using ObjectDataSource Controls

This document contains extracts of the article “Walkthrough: Data Binding to a Custom 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 more components in the middle tier to provide data access. Microsoft Visual Web Developer™ includes a wizard that helps you create a data component that you can use as a middle-tier data object.

However, you might also want to build a custom business object, rather than relying on the data component created by the wizard. Creating a custom business object allows you to implement your own business logic. This walkthrough 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 business component 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. The App_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 suitable for your application. This walkthrough uses an XML file.

Note

Note

Page 115: ASP Net Stage1

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

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

Creating a Component The next step is to create a class to act as your business component. You will keep the component in the App_Code folder of your Web site. In a real application, you can keep the component in any convenient store, including the Global Assembly Cache (GAC). If your Web site does not already have a directory called App_Code, you must create one.

To create an App_Code folder

1. In Solution Explorer, right-click the name of your Web site, and then click New Folder.

2. Name the folder App_Code.

The folder must be named App_Code.

You can now add the component to your site.

To create the business component

1. In Solution Explorer, right-click App_Code and then click Add New Item. The Add New Item dialog box appears.

Be sure to create the new item in the App_Code folder.

2. Under Visual Studio installed templates, click Class. 3. In the Language box, click the programming language you prefer. 4. In the Name box, type BusinessObject. 5. Click Add.

Visual Web Developer creates the new class file and opens the code editor.

Note

Note

Page 117: ASP Net Stage1

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.Data Namespace 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

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 its data. 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 a Web 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.xml file.

10. Click Finish. The configuration information you have entered specifies that to get data from the component, the component’s GetAuthors method should be called.

Note

Page 119: ASP Net Stage1

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 Component As 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 a method that inserts an author record. Then you will change the page so that users 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 permission to 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 the App_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_phone workRow.EndEdit() dsAuthors.Tables(0).Rows.Add(workRow) dsAuthors.WriteXml(filePath, Data.XmlWriteMode.WriteSchema) End Sub

Note

Page 120: ASP Net Stage1

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 then writes 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 can click to put the control into data-entry mode.

Note

Note

Note

Page 121: ASP Net Stage1

Unit 6: Accessing and Displaying Data 113

Finally, you must configure the ObjectDataSource control to specify what action 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

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

How to: Access XML Data by Using XmlDataSource Controls

This document is an extract from the article “XmlDataSource Class,” which you 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

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

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
Page 125: ASP Net Stage1

Unit 7: Controlling Access to a Web Application

How to Configure Authentication for a Web Application Microsoft® ASP.NET uses authentication providers to implement authentication for Web applications. An authentication provider is a core module that contains the 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 credentials against Microsoft Windows® accounts stored in Active Directory® directory service or the Security Account Manager (SAM). The users must have valid Windows accounts. IIS prompts the user for details, if necessary. Basic, Digest or Windows Integrated authentication is used, depending on the configuration of IIS and the capabilities of the browser.

• Passport Authentication. When your application uses Passport Authentication, 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™ and Microsoft 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 create user 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

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 Authentication To implement Passport Authentication, you must first register with the Microsoft Passport Service on the Microsoft Passport Network Web site. You should 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 Authentication Forms 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

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. This is 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 algorithm so that the password is held in the file in a non-reversible format.

Page 128: ASP Net Stage1

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

How to: Configure Authorization for a Web Application There are two ways to configure authorization for a Microsoft® ASP.NET Web application:

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 to a Windows account by specifying the full name, for example, LON-DEV-01\ Student.

Page 129: ASP Net Stage1

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 the file, 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 <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

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

Introduction to Membership This document is a copy of the article “Introduction to 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/79184d17-f4c7-4c9f-a073-cec4f5543980.htm.

Microsoft ASP.NET membership gives you a built-in way to validate and store user credentials. ASP.NET membership, therefore, helps you manage user authentication in your Web sites. You can use ASP.NET membership with ASP.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 Profile Although membership is a self-standing feature in ASP.NET for authentication, it can be integrated with ASP.NET role management to provide authorization services for your site. Membership can also be integrated with the user profile to provide application-specific customization that can be tailored to individual users.

Page 131: ASP Net Stage1

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, you follow 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 to use 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 “new user” 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. Most often, 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 using ASP.NET TextBox controls, or you can use ASP.NET login controls. Because you 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 logic required to prompt users for credentials and validate the credentials in the membership system.

If you use login controls, they will automatically use the membership system to validate a user. If you have created a login form by hand, you can prompt the user 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 login form by hand, you can call methods of the FormsAuthentication class 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 help the user remember the password or create a new one.

Each time the user requests another protected page, ASP.NET Forms authentication 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, the authentication cookie remains valid for the user’s session.

Note

Page 132: ASP Net Stage1

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

After a user has been authenticated, the membership system makes available an object that contains information about the current user. For example, you can get 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 to explicitly perform any low-level database functions to get or set user information. For example, you create a new user by calling the membership CreateUser 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 have not been authenticated. In addition, the ID for the anonymous user allows the membership system to associate data, such as profile information, with the anonymous 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 forms authentication ticket, except that the membership system does not consider the user to be logged in. If the user’s browser does not accept cookies, the anonymous identification can be embedded in the URL of requested pages.

If an anonymous user logs in, the anonymous identification information is discarded and the user is treated thereafter as an authenticated user. If you are using personalization, the user’s personalization values can be migrated so that they are retained as part of the user’s logged-in user identity.

Membership Configuration and Management You configure the membership system in your application’s Web.config file. The easiest way to configure and manage membership is with 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.

Page 133: ASP Net Stage1

Unit 7: Controlling Access to a Web Application 125

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

This document contains extracts from the article “Configuring an ASP.NET Application 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 enable ASP.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 a SqlMembershipProvider 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 local computer 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 providers available 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 valid connection 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 SQL Server that is not the local server:

Note

Page 134: ASP Net Stage1

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

Unit 7: Controlling Access to a Web Application 127

How to: Manage Users by Using Membership The Microsoft® ASP.NET Membership class provides a range of methods for managing the members of a Web site:

The CreateUser and DeleteUser methods for adding and removing users The UpdateUser method for altering user details The ValidateUser method for checking credentials against those in the

account store The FindUserByEmail and FindUserByName methods for searching

through lists of users

This document shows how to use some of these methods in a Web application.

Before you can use the Membership class, you must have configured your ASP.NET application to use a membership provider. For details, see “How To: Configure an ASP.NET Application to Use Membership.”

To add a new user to a Web application The following code creates a new user and sets the UserName, Password, and Email properties:

[Visual Basic] Dim userNew As MembershipUser = Membership.CreateUser("Joe", "Pa$$w0rd", _ "[email protected]") If userNew Is Nothing Then lblMessage.Text = "User was not successfully added" Else lblMessage.Text = "User was successfully added" End If

[C#] MembershipUser userNew = Membership.CreateUser("Joe", "Pa$$w0rd", "[email protected]"); if (userNew == null) { lblMessage.Text = "User was not successfully added"; } else { lblMessage.Text = "User was successfully added"; }

Note

Page 136: ASP Net Stage1

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.Text userCurrent.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 password The 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

Unit 7: Controlling Access to a Web Application 129

Login and Membership Page Design The following examples will help you design the Web pages in this lab. The illustrations show the pages in Microsoft® Visual Studio® Design view.

MemberUpdate.aspx

Page 138: ASP Net Stage1

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

MembersLogin.aspx

Page 139: ASP Net Stage1

Unit 7: Controlling Access to a Web Application 131

TopLevel.master

Page 140: ASP Net Stage1

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

How to: Implement a Login Page and Add Login Controls If 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 by using 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 Membership is 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 using this 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 markup to 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 authenticated or anonymous.

To add a LoginName control to the page

• In Design view, drag a LoginName control onto the page from the Login 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 authenticated user.

Page 141: ASP Net Stage1

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

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

How to: Create a Membership Management Administrative User Interface

If you are using Microsoft® ASP.NET Forms authentication and URL authorization, 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 to all 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 the ASP.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 using the aspnet_regsql.exe tool.

To list the users in a role The following code lists all the members of a role called Moderators, and all users 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

Unit 7: Controlling Access to a Web Application 135

[C#] MembershipUserCollection allUsers = Membership.GetAllUsers(); foreach (MembershipUser userCurrent in allUsers) { if (Roles.IsUserInRole(userCurrent.UserName, "Moderators")) { lblMembers.Text += userCurrent.UserName + "<br>"; } else { lblNonMembers.Text += userCurrent.UserName + "<br>"; } }

To add users to a role The following code adds a user called Sam to a role called Moderators. Note that the code checks that the role exists before adding the user.

[Visual Basic] If Not Roles.RoleExists("Moderators") Then Roles.CreateRole("Moderators") End If Roles.AddUserToRole("Sam", "Moderators")

[C#] if (!Roles.RoleExists("Moderators")) Roles.CreateRole("Moderators"); Roles.AddUserToRole("Sam", "Moderators");

To remove users from a role The following code removes a user called Bob from a role called Administrators:

[Visual Basic] Roles.RemoveUserFromRole("Bob", "Administrators")

[C#] Roles.RemoveUserFromRole("Bob", "Administrators");

Page 144: ASP Net Stage1
Page 145: ASP Net Stage1

Unit 8: Deploying a Web Application

Features of the Copy Web Site Utility This document is a copy of the article “Copying Web Sites with the Copy 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.

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 useful in 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 to copy 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. The terms 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 FrontPage Server 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

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

The source site is not necessarily the source for copying. You can copy from 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 sure that all files on both sites are up to date. For example, if a file on the remote site is 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 to specify 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 the files 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 were last checked, which enables the tool to determine information such as if a file has been deleted.

When you connect to (or refresh) a site, the tool compares the timestamps of the files 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

Unit 8: Deploying a Web Application n 139

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

This document is a copy of the article “How to: Copy Web Site Files with the Copy 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 site to 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 files as 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 Web site 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 site and 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 they have been deleted.

Note

Note

Page 148: ASP Net Stage1

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

Removing a Connection Connection information is persisted in Visual Studio. (The connection is live only while you are working with a site.) If you do not need to connect to a remote 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, select the 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

Unit 8: Deploying a Web Application n 141

Features of the Publish Web Site Utility This document contains extracts from the article “Publishing Web Sites,” 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/c8048c31-012b-4718-b8ac-06a2dd41c137.htm.

Microsoft Visual Web Developer™ allows you to publish your Web sites, which compiles 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 to a 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 are already 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 the code). 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 occurs when 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 is a form of testing, and does not produce output that you can deploy. Precompilation during publishing, on the other hand, creates output in a specified folder that you can, in turn, deploy to a production server.

Note

Page 150: ASP Net Stage1

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 a folder that you specify. You can write the output to any folder that is accessible to 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 folders and subfolder. It does not deploy the machine.config file. Therefore, the configuration 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 you can 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 you choose to write the output to a folder that is not part of a Web site, you can copy the output to the server in a separate step.

The output of the compilation process includes the compiled assemblies for any code 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 .ashx files are compiled into assemblies. However, the .aspx, .asmx, and .ashx files themselves 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 code in 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 Output window and in the Error List window. Errors during precompilation will prevent the site from being compiled and published.

Note

Page 151: ASP Net Stage1

Unit 8: Deploying a Web Application n 143

How to: Precompile and Deploy a Web Site by Using the Publish 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 object code 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

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

Features of Windows Installer Setup Projects This document contains extracts from the article “Setup Projects,” which you can 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, any dependent files, information about the application such as registry entries, and instructions 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 target computer 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 projects install 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 a Setup project or a Web Setup project.

Page 153: ASP Net Stage1

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 add the 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 Web Setup 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 the Properties 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

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 the installer 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

Unit 9: Making Web Applications Available to Mobile Devices

How to: Detect and Redirect Mobile Devices Mobile devices typically have much smaller screens than conventional desktop and laptop computers, which means that they might not display in a usable way an ordinary Web Form designed to be displayed by a desktop computer. Also, some mobile devices have gray-scale or two-tone screens and might have limited network connectivity. To support mobile devices, it is therefore sensible to create two versions of each Web form, one for desktop computers and one for 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 called default.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

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

Some mobile devices do not permit you to use relative URLs such as Mobile/default.aspx. You can ensure that requests for these devices are redirected 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

Unit 9: Making Web Applications Available to Mobile Devices 149

How to: Browse Mobile Web Pages with Specific Device Emulators

Microsoft® Visual Studio® 2005 includes Microsoft Device Emulator 1.0 to help developers write applications for mobile devices such as Pocket PCs and mobile phones. Device Emulator can be used to simulate devices running Microsoft 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 a development computer, with an emulator installed on the same computer, using Microsoft ActiveSync® 4.0 to make the connection. The host computer and the emulator 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

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 button

to 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 file name of the page you want to display.

10. Use the left button to choose Go. The Web page appears.

Page 159: ASP Net Stage1

Unit 9: Making Web Applications Available to Mobile Devices 151

How to: Design and Implement a Mobile Web Form Microsoft® Visual Studio® 2005 provides the Microsoft ASP.NET Mobile Designer 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

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.NextPageText property to Next, and then set the PagerStyle.PreviousPageText property 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

Unit 9: Making Web Applications Available to Mobile Devices 153

Mobile Controls Microsoft® ASP.NET 2.0 includes a wide variety of controls for use on Mobile Web Form pages. These controls are optimized for use on many types of mobile devices, 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 that is 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

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

Unit 9: Making Web Applications Available to Mobile Devices 155

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

Mobile devices can vary greatly in their capabilities. For example, some devices can 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 properties for 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 an image 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

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. It can either specify the name of a method on the Mobile Form—which you must write—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 by the 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, it must 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

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

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

How to: Configure Microsoft Device Emulator 1.0 to Connect to an ASP.NET Application

Microsoft® Visual Studio® 2005 includes Microsoft Device Emulator 1.0 to help developers write applications for mobile devices such as PDAs and mobile phones. Device Emulator can be used to simulate devices running Microsoft Windows® CE 5.0, Microsoft Pocket PC 2003 SE, and Microsoft Smartphone 2003 SE.

Device Emulator can connect only to Microsoft ASP.NET applications running in 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 the Default 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 Device Emulator 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

Unit 9: Making Web Applications Available to Mobile Devices 159

If you are using the Pocket PC 2003 SE Emulator, you must configure the device 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 a

connection 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

THIS PAGE INTENTIONALLY LEFT BLANK