Toolkit
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.
1 2 3 4 5 6 7 8 9 QWE 9 8 7 6 5
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.
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
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.
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
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.
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
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
iv 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
Note 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.
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.
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.
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.
4 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Unit 1: Creating a Web Application 5
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.
Unit 1: Creating a Web Application 7
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.
Note You can rearrange and resize the windows to suit your preferences. The
View menu allows you to display additional windows.
8 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
This static HTML text is the caption for the TextBox control. You can mix
static HTML and server controls on the same page.
10 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
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.
[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.
Note 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#).
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.
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.
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:
16 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
Optional Attribute
Attribute Description
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.
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.
Important 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.
Note 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>
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>
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.
Unit 2: Programming a Web
Application
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
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;
}
}
Unit 2: Programming a Web Application 23
[Visual Basic]
Server.Transfer("Destination.aspx")
[Visual C#]
Server.Transfer("Destination.aspx");
24 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
Unit 2: Programming a Web Application 25
[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;
Note 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.
26 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
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
Unit 2: Programming a Web Application 27
Note 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.
28 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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
[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;
}
}
<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>
32 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[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;
}
34 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[Visual C#]
protected void Button1_Click(object sender, EventArgs e)
{
Page.Header.Title = "Your name is " + TextBox1.Text;
}
Unit 2: Programming a Web Application 35
[Visual C#]
private void Page_Error(Object sender, System.EventArgs e)
{
Response.Write(Server.GetLastError().Message);
Server.ClearError();
}
Note 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.
36 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Note 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.
Unit 3: Adding and Configuring Server
Controls
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.
Unit 3: Adding and Configuring Server Controls 39
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.
40 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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 />
42 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
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.
46 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
48 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Unit 3: Adding and Configuring Server Controls 49
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.
Note You can rearrange and resize the windows to suit your preferences. The
View menu allows you to display additional windows.
50 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
Note 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.
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.
Unit 3: Adding and Configuring Server Controls 53
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 >
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:
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:
Unit 3: Adding and Configuring Server Controls 57
Note 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.
The following table lists the values of these properties in each situation.
Invocation IsPostBack PreviousPage IsCrossPagePostBack
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;
}
Unit 3: Adding and Configuring Server Controls 59
[Visual C#]
if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
60 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[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;
Unit 3: Adding and Configuring Server Controls 61
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#" %>
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.
Unit 4: Creating a Common Layout by Using Master Pages 65
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.
Unit 4: Creating a Common Layout by Using Master Pages 67
Microsoft® Visual Web Developer™ creates the new master page and opens it in
Source view.
Microsoft® Visual Web Developer™ creates the new content page and
opens it in Source view.
[C#]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" MasterPageFile="~/SiteMaster.master" %>
Unit 4: Creating a Common Layout by Using Master Pages 69
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.
74 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Note 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.
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.
Note 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.
Security Note 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.
76 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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™.
Unit 5: Managing State for a Web Application 77
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.
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.
Note 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.
[C#]
MaxPageStateFieldLength = 250;
80 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
To write code to handle these events, you must add a Global.asax file to the
Web application.
[C#]
string firstName = "Jeff";
string lastName = "Smith";
string city = "Seattle";
Session["FirstName"] = firstName;
Session["LastName"] = lastName;
Session["City"] = city;
82 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[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.
Unit 5: Managing State for a Web Application 83
[C#]
Application["Message"] = "Hello, world.";
[C#]
Application["Message"] = "Hello, world.";
Application["PageRequestCount"] = 0;
84 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[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.
Unit 5: Managing State for a Web Application 85
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.
<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.
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:
86 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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;" />
Unit 5: Managing State for a Web Application 87
[C#]
Cache["TextItem1"] = txtExample.Text;
[C#]
Cache.Insert("TextItem1", txtExample.Text);
88 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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"];
}
Unit 5: Managing State for a Web Application 89
[C#]
Cache.Insert("MyData1", connectionString, new CacheDependency
¬(Server.MapPath("~\myConfig.xml")));
[C#]
string[] sDependencies = new string[1];
sDependencies[0] = "OriginalItem";
CacheDependency dependency = new CacheDependency(null, sDependencies);
Cache.Insert("DependentItem", "This item depends on OriginalItem", dependency);
90 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[C#]
Cache.Remove("MyData1");
Unit 5: Managing State for a Web Application 91
[C#]
private static CacheItemRemovedCallback onRemove = null;
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;
}
92 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
[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.
Unit 6: Accessing and Displaying Data
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.
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.
Unit 6: Accessing and Displaying Data 95
//[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
}
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.
96 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
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.
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.
Unit 6: Accessing and Displaying Data 99
Note 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
Note 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.
100 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Note 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.
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.
102 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Note 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)
Note 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.
Note 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.
Note 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.
Note Business components can work with data in any way that is suitable
for your application. This walkthrough uses an XML file.
Unit 6: Accessing and Displaying Data 107
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.
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
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;
}
}
}
Note 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.
110 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
Note 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.
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.
Note 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.
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);
}
Note 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.
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.
114 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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>
Unit 7: Controlling Access to a Web
Application
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.
120 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.
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.
Note 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.
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.
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:
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>
Unit 7: Controlling Access to a Web Application 127
This document shows how to use some of these methods in a Web application.
Note 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.”
[C#]
MembershipUser userNew = Membership.CreateUser("Joe", "Pa$$w0rd",
"joe@contoso.com");
if (userNew == null) {
lblMessage.Text = "User was not successfully added";
} else {
lblMessage.Text = "User was successfully added";
}
128 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
[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);
[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.";
}
Unit 7: Controlling Access to a Web Application 129
MemberUpdate.aspx
130 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
MembersLogin.aspx
Unit 7: Controlling Access to a Web Application 131
TopLevel.master
132 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
The LoginName control shows the user name of the current authenticated
user.
Unit 7: Controlling Access to a Web Application 133
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.
[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>";
}
}
[C#]
if (!Roles.RoleExists("Moderators"))
Roles.CreateRole("Moderators");
Roles.AddUserToRole("Sam", "Moderators");
[C#]
Roles.RemoveUserFromRole("Bob", "Administrators");
Unit 8: Deploying a Web Application
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.
Note 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.
Note 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.
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.
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.
Note 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.
Note 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.
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.
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.
Note 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.
Note 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.
Unit 8: Deploying a Web Application n 143
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.
144 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
Note 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.
Unit 9: Making Web Applications
Available to Mobile Devices
[C#]
protected void Page_Load(object sender, EventArgs e) {
if (Request.Browser.IsMobileDevice)
Response.Redirect("Mobile/default.aspx");
}
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.
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.
[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.
152 2543B: Core Web Application Technologies with Microsoft® Visual Studio® 2005
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.
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.
154 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.
[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.
This example tests for the IsColor capability. For more information, see the
“Device Capability Names” section later in this resource.
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.