+ All Categories
Home > Documents > Visual Web Developer 2005 Express Edition

Visual Web Developer 2005 Express Edition

Date post: 10-Mar-2015
Category:
Upload: pipercub2006
View: 155 times
Download: 4 times
Share this document with a friend
244
Microsoft ® Visual Web Developer 2005 Express Edition Build a Web Site
Transcript
Page 1: Visual Web Developer 2005 Express Edition

Microsoft®

Visual Web Developer™ 2005Express Edition

Build a Web Site

A01622124.indd iA01622124.indd i 9/16/05 1:01:57 PM9/16/05 1:01:57 PM

Page 2: Visual Web Developer 2005 Express Edition

PUBLISHED BYMicrosoft PressA Division of Microsoft CorporationOne Microsoft WayRedmond, Washington 98052-6399

Copyright © 2006 by Microsoft Corporation

All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher.

Library of Congress Control Number 2005933641

Printed and bound in the United States of America.

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

Distributed in Canada by H.B. Fenn and Company Ltd.

A CIP catalogue record for this book is available from the British Library.

Microsoft Press books are available through booksellers and distributors worldwide. For further information about international editions, contact your local Microsoft Corporation offi ce or contact Microsoft Press International directly at fax (425) 936-7329. Visit our Web site at www.microsoft.com/learning/. Send comments to [email protected].

Microsoft, Active Directory, FrontPage, Intellisense, Microsoft Press, MSDN, SharePoint, Visual Basic, Visual C#, Visual J#, Visual Studio, Visual Web Developer, Windows, and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fi ctitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.

This book expresses the author s views and opinions. The information contained in this book is provided with out any express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.

Acquisitions Editor: Ben RyanProject Editor: Sandra HaynesEditorial and Production: Custom Editorial Productions, Inc.

Body Part No. X11-78002

A01622124.indd iiA01622124.indd ii 9/16/05 1:01:59 PM9/16/05 1:01:59 PM

Page 3: Visual Web Developer 2005 Express Edition
Page 4: Visual Web Developer 2005 Express Edition
Page 5: Visual Web Developer 2005 Express Edition
Page 6: Visual Web Developer 2005 Express Edition
Page 7: Visual Web Developer 2005 Express Edition
Page 8: Visual Web Developer 2005 Express Edition
Page 9: Visual Web Developer 2005 Express Edition
Page 10: Visual Web Developer 2005 Express Edition
Page 11: Visual Web Developer 2005 Express Edition
Page 12: Visual Web Developer 2005 Express Edition
Page 13: Visual Web Developer 2005 Express Edition
Page 14: Visual Web Developer 2005 Express Edition
Page 15: Visual Web Developer 2005 Express Edition
Page 16: Visual Web Developer 2005 Express Edition
Page 17: Visual Web Developer 2005 Express Edition
Page 18: Visual Web Developer 2005 Express Edition
Page 19: Visual Web Developer 2005 Express Edition
Page 20: Visual Web Developer 2005 Express Edition
Page 21: Visual Web Developer 2005 Express Edition
Page 22: Visual Web Developer 2005 Express Edition
Page 23: Visual Web Developer 2005 Express Edition
Page 24: Visual Web Developer 2005 Express Edition
Page 25: Visual Web Developer 2005 Express Edition
Page 26: Visual Web Developer 2005 Express Edition
Page 27: Visual Web Developer 2005 Express Edition
Page 28: Visual Web Developer 2005 Express Edition
Page 29: Visual Web Developer 2005 Express Edition
Page 30: Visual Web Developer 2005 Express Edition
Page 31: Visual Web Developer 2005 Express Edition
Page 32: Visual Web Developer 2005 Express Edition
Page 33: Visual Web Developer 2005 Express Edition
Page 34: Visual Web Developer 2005 Express Edition
Page 35: Visual Web Developer 2005 Express Edition
Page 36: Visual Web Developer 2005 Express Edition
Page 37: Visual Web Developer 2005 Express Edition
Page 38: Visual Web Developer 2005 Express Edition
Page 39: Visual Web Developer 2005 Express Edition
Page 40: Visual Web Developer 2005 Express Edition
Page 41: Visual Web Developer 2005 Express Edition
Page 42: Visual Web Developer 2005 Express Edition
Page 43: Visual Web Developer 2005 Express Edition
Page 44: Visual Web Developer 2005 Express Edition
Page 45: Visual Web Developer 2005 Express Edition
Page 46: Visual Web Developer 2005 Express Edition
Page 47: Visual Web Developer 2005 Express Edition
Page 48: Visual Web Developer 2005 Express Edition
Page 49: Visual Web Developer 2005 Express Edition
Page 50: Visual Web Developer 2005 Express Edition
Page 51: Visual Web Developer 2005 Express Edition
Page 52: Visual Web Developer 2005 Express Edition
Page 53: Visual Web Developer 2005 Express Edition
Page 54: Visual Web Developer 2005 Express Edition
Page 55: Visual Web Developer 2005 Express Edition
Page 56: Visual Web Developer 2005 Express Edition
Page 57: Visual Web Developer 2005 Express Edition
Page 58: Visual Web Developer 2005 Express Edition
Page 59: Visual Web Developer 2005 Express Edition
Page 60: Visual Web Developer 2005 Express Edition
Page 61: Visual Web Developer 2005 Express Edition
Page 62: Visual Web Developer 2005 Express Edition
Page 63: Visual Web Developer 2005 Express Edition
Page 64: Visual Web Developer 2005 Express Edition
Page 65: Visual Web Developer 2005 Express Edition
Page 66: Visual Web Developer 2005 Express Edition
Page 67: Visual Web Developer 2005 Express Edition
Page 68: Visual Web Developer 2005 Express Edition
Page 69: Visual Web Developer 2005 Express Edition
Page 70: Visual Web Developer 2005 Express Edition
Page 71: Visual Web Developer 2005 Express Edition
Page 72: Visual Web Developer 2005 Express Edition
Page 73: Visual Web Developer 2005 Express Edition
Page 74: Visual Web Developer 2005 Express Edition
Page 75: Visual Web Developer 2005 Express Edition
Page 76: Visual Web Developer 2005 Express Edition
Page 77: Visual Web Developer 2005 Express Edition
Page 78: Visual Web Developer 2005 Express Edition
Page 79: Visual Web Developer 2005 Express Edition
Page 80: Visual Web Developer 2005 Express Edition
Page 81: Visual Web Developer 2005 Express Edition
Page 82: Visual Web Developer 2005 Express Edition
Page 83: Visual Web Developer 2005 Express Edition
Page 84: Visual Web Developer 2005 Express Edition
Page 85: Visual Web Developer 2005 Express Edition
Page 86: Visual Web Developer 2005 Express Edition
Page 87: Visual Web Developer 2005 Express Edition
Page 88: Visual Web Developer 2005 Express Edition
Page 89: Visual Web Developer 2005 Express Edition
Page 90: Visual Web Developer 2005 Express Edition
Page 91: Visual Web Developer 2005 Express Edition
Page 92: Visual Web Developer 2005 Express Edition
Page 93: Visual Web Developer 2005 Express Edition
Page 94: Visual Web Developer 2005 Express Edition
Page 95: Visual Web Developer 2005 Express Edition
Page 96: Visual Web Developer 2005 Express Edition
Page 97: Visual Web Developer 2005 Express Edition
Page 98: Visual Web Developer 2005 Express Edition
Page 99: Visual Web Developer 2005 Express Edition
Page 100: Visual Web Developer 2005 Express Edition
Page 101: Visual Web Developer 2005 Express Edition
Page 102: Visual Web Developer 2005 Express Edition
Page 103: Visual Web Developer 2005 Express Edition
Page 104: Visual Web Developer 2005 Express Edition
Page 105: Visual Web Developer 2005 Express Edition
Page 106: Visual Web Developer 2005 Express Edition
Page 107: Visual Web Developer 2005 Express Edition
Page 108: Visual Web Developer 2005 Express Edition
Page 109: Visual Web Developer 2005 Express Edition
Page 110: Visual Web Developer 2005 Express Edition
Page 111: Visual Web Developer 2005 Express Edition
Page 112: Visual Web Developer 2005 Express Edition
Page 113: Visual Web Developer 2005 Express Edition
Page 114: Visual Web Developer 2005 Express Edition
Page 115: Visual Web Developer 2005 Express Edition
Page 116: Visual Web Developer 2005 Express Edition
Page 117: Visual Web Developer 2005 Express Edition
Page 118: Visual Web Developer 2005 Express Edition
Page 119: Visual Web Developer 2005 Express Edition
Page 120: Visual Web Developer 2005 Express Edition
Page 121: Visual Web Developer 2005 Express Edition
Page 122: Visual Web Developer 2005 Express Edition
Page 123: Visual Web Developer 2005 Express Edition
Page 124: Visual Web Developer 2005 Express Edition
Page 125: Visual Web Developer 2005 Express Edition
Page 126: Visual Web Developer 2005 Express Edition
Page 127: Visual Web Developer 2005 Express Edition
Page 128: Visual Web Developer 2005 Express Edition
Page 129: Visual Web Developer 2005 Express Edition
Page 130: Visual Web Developer 2005 Express Edition
Page 131: Visual Web Developer 2005 Express Edition
Page 132: Visual Web Developer 2005 Express Edition
Page 133: Visual Web Developer 2005 Express Edition
Page 134: Visual Web Developer 2005 Express Edition
Page 135: Visual Web Developer 2005 Express Edition
Page 136: Visual Web Developer 2005 Express Edition
Page 137: Visual Web Developer 2005 Express Edition
Page 138: Visual Web Developer 2005 Express Edition
Page 139: Visual Web Developer 2005 Express Edition
Page 140: Visual Web Developer 2005 Express Edition
Page 141: Visual Web Developer 2005 Express Edition
Page 142: Visual Web Developer 2005 Express Edition
Page 143: Visual Web Developer 2005 Express Edition
Page 144: Visual Web Developer 2005 Express Edition
Page 145: Visual Web Developer 2005 Express Edition
Page 146: Visual Web Developer 2005 Express Edition
Page 147: Visual Web Developer 2005 Express Edition
Page 148: Visual Web Developer 2005 Express Edition
Page 149: Visual Web Developer 2005 Express Edition
Page 150: Visual Web Developer 2005 Express Edition
Page 151: Visual Web Developer 2005 Express Edition
Page 152: Visual Web Developer 2005 Express Edition
Page 153: Visual Web Developer 2005 Express Edition
Page 154: Visual Web Developer 2005 Express Edition
Page 155: Visual Web Developer 2005 Express Edition
Page 156: Visual Web Developer 2005 Express Edition
Page 157: Visual Web Developer 2005 Express Edition
Page 158: Visual Web Developer 2005 Express Edition
Page 159: Visual Web Developer 2005 Express Edition
Page 160: Visual Web Developer 2005 Express Edition
Page 161: Visual Web Developer 2005 Express Edition
Page 162: Visual Web Developer 2005 Express Edition
Page 163: Visual Web Developer 2005 Express Edition
Page 164: Visual Web Developer 2005 Express Edition
Page 165: Visual Web Developer 2005 Express Edition
Page 166: Visual Web Developer 2005 Express Edition
Page 167: Visual Web Developer 2005 Express Edition
Page 168: Visual Web Developer 2005 Express Edition
Page 169: Visual Web Developer 2005 Express Edition
Page 170: Visual Web Developer 2005 Express Edition
Page 171: Visual Web Developer 2005 Express Edition
Page 172: Visual Web Developer 2005 Express Edition
Page 173: Visual Web Developer 2005 Express Edition
Page 174: Visual Web Developer 2005 Express Edition
Page 175: Visual Web Developer 2005 Express Edition
Page 176: Visual Web Developer 2005 Express Edition
Page 177: Visual Web Developer 2005 Express Edition
Page 178: Visual Web Developer 2005 Express Edition
Page 179: Visual Web Developer 2005 Express Edition
Page 180: Visual Web Developer 2005 Express Edition
Page 181: Visual Web Developer 2005 Express Edition
Page 182: Visual Web Developer 2005 Express Edition
Page 183: Visual Web Developer 2005 Express Edition
Page 184: Visual Web Developer 2005 Express Edition
Page 185: Visual Web Developer 2005 Express Edition
Page 186: Visual Web Developer 2005 Express Edition
Page 187: Visual Web Developer 2005 Express Edition
Page 188: Visual Web Developer 2005 Express Edition
Page 189: Visual Web Developer 2005 Express Edition
Page 190: Visual Web Developer 2005 Express Edition
Page 191: Visual Web Developer 2005 Express Edition
Page 192: Visual Web Developer 2005 Express Edition
Page 193: Visual Web Developer 2005 Express Edition
Page 194: Visual Web Developer 2005 Express Edition
Page 195: Visual Web Developer 2005 Express Edition
Page 196: Visual Web Developer 2005 Express Edition
Page 197: Visual Web Developer 2005 Express Edition
Page 198: Visual Web Developer 2005 Express Edition
Page 199: Visual Web Developer 2005 Express Edition

CW-1

Chapter 17Controlling Access to Your Site

17 The sample site for this chap-ter resides in a folder named ContosoMagic17.

NOT E

Configuring Web Site Security, 184

Adding Login Controls to Your Site, 193

Hiding Menu Options for Secured Pages, 197

Publishing Security Settings, 199

For most Web pages, popularity is the best sign of success. The more people access your page, the grander the achievement.

For certain pages, however, it’s critical to block, rather than attract, visitors. For example, you may want visitors to identify themselves before accessing certain pages. In other cases, such as the Add Products and Update Products pages in Chapter 15, you’ll want to strictly control which visitors have access. ASP.NET 2.0 has built-in features that satisfy such requirements. What’s more, Microsoft Visual Web Developer™ makes these features very easy to use. You can finish the entire job using only the graphical interface, and without writing any program code.

C17622124.indd 1 9/11/05 4:53:45 PM

Page 200: Visual Web Developer 2005 Express Edition

CW-2 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

Configuring Web Site Security

Controlling security for an ASP.NET Web site involves two quite different tasks. This section describes the first task, which is configuring the Web site with the security features and rules you want. The section “Adding Login Controls to Your Site” will describe the second task, which is creating Web pages that handle logins, password changes, self-registrations, and other security features that visitors use.

To configure security settings for your site, open the site in Visual Web Developer and choose ASP.NET Configuration from the Website menu. This displays the Web Site Administration Tool page shown in Figure 17-1.

Figure 17-1This is the home page for configur-ing Web site security on Visual Web Developer’s built-in Web server.

C17622124.indd 2 9/11/05 4:53:47 PM

Page 201: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-3

ASP.NET provides a Security Setup Wizard that makes it easy to configure your site the first time. Before running that wizard, however, you should configure the site’s SMTP e-mail settings and its authentication provider.

Configuring SMTP E-Mail Settings

A site’s SMTP e-mail settings specify the server, From address, and security settings for any security-related e-mail that ASP.NET sends.

TO CONFIGURE SMTP E-MAIL SETTINGS:

1 Click the Application tab or the Application Configuration link on the Web Site Administration Tool’s home page.

2 When the page reappears with the Application tab selected, click the Configure SMTP E-Mail Settings link that appears in the middle of the page.

3 When a page displaying the Configure SMTP Settings box shown in Figure 17-2 appears, configure these settings:

■ Server Name Enter the DNS name or IP address of the SMTP e-mail server that will relay any security-related e-mail to Web visitors.

■ Server Port Specify the port number where the SMTP server listens. Normally this is 25, but some administrators choose another number.

■ From Specify the e-mail address that will appear in the From: line of any security-related messages from your site. This doesn’t need to be a real address, but it does need to satisfy any rules that the e-mail server enforces.

■ Authentication: None Select this button if the SMTP server accepts e-mail without knowing the send-er’s identity.

■ Authentication: Basic Select this button if the SMTP server accepts e-mail only from senders who sup-ply a valid user name and password. Then, specify the user name and password in the appropriate boxes.

■ Authentication: NTLM Select this button if the SMPT server accepts e-mail only from processes that run under a known Microsoft Windows® login account. This will be the account that runs ASP.NET pro-cesses for your web site.

C17622124.indd 3 9/11/05 4:53:47 PM

Page 202: Visual Web Developer 2005 Express Edition

CW-4 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

4 Click the Save button and then, when the confirmation message appears, click the OK button.SMTP e-mail servers use a variety

of methods to block unsolicited mass mailings (spam). For exam-ple, they may only accept e-mail with known addresses (or at least known domains) listed in the From field, or e-mail from IP addresses on your company’s or connectivity provider’s network.

NOT E

Figure 17-2This page specifies the SMTP e-mail server and related settings ASP.NET should use when sending security-related e-mail.

Configuring an Authentication Provider

This setting controls the type of database that stores the login accounts, roles, role member-ships, and other administrative data for your site. This is fairly simple because Visual Web Developer doesn’t support very many choices.

C17622124.indd 4 9/11/05 4:53:48 PM

Page 203: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-5

TO CONFIGURE AN AUTHENTICATION PROVIDER

1 On the Web Site Administration Tool home page, click either the Provider tab or the Provider Configuration link.

2 To use the same type of database for all your security data:

■ Click the link titled Select A Single Provider For All Site Management Data.

■ When a page with a Provider box appears, select the provider you want. In all probability, the only choice will be AspNetSqlProvider.

■ Click the Test link to verify that the provider is installed and working. A Provider Management box should report, “Successfully established a connection to the database.” Click the OK button to close this box.

■ To save the configuration, click the Back button at the bottom of the Web page.

3 To use different types of databases for some security data:

■ Click the link titled Select A Different Provider For Each Feature (Advanced). This will display a page with two boxes titled Membership Provider and Role Provider.

■ The Membership Provider box specifies the type of database to use for storing login accounts. The only choice will be AspNetSqlMembershipProvider, which corresponds to Microsoft® SQL Server™.

■ The Role Provider box specifies the type of database to use for storing security groups. Select AspNetSqlRoleProvider (which uses SQL Server) or AspNetWindowsTokenRoleProvider (which uses Windows groups).

■ Click Back to save the configuration.

As a practical matter, you should probably select a single provider (SQL Server) for all site management data unless your site resides on an intranet and you plan to use both Windows accounts and Windows security groups for controlling access.

Running the Security Setup Wizard

This wizard configures most of the security settings for your site, including an initial set of login accounts and access rules.

C17622124.indd 5 9/11/05 4:53:49 PM

Page 204: Visual Web Developer 2005 Express Edition

CW-6 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

Figure 17-3This page specifies whether to authenticate visitors by using Windows accounts or by using custom accounts stored in a SQL Server database.

TO RUN THE SECURITY SETUP WIZARD

1 On the Web Site Administration Tool’s home page, click either the Security tab or the Security link.

2 When a page with the Security tab highlighted appears, click the link titled Use The Security Setup Wizard To Configure

Security Step By Step.

3 When the wizard’s Welcome page appears, read the introductory information and then click the Next button.

4 On the Select Access Method page shown in Figure 17-3, select either:

■ From The Internet if you want your site to have its own database of login accounts. This is the usual choice for sites located on the Internet.

■ From A Local Area Network if you want to use existing Windows login accounts for controlling access to your site. This is the usual choice for sites on a company intranet.

After making your selection, click the Next button.

C17622124.indd 6 9/11/05 4:53:50 PM

Page 205: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-7

5 If you chose From A Local Area Network in step 4, skip to step 6.

If you chose From The Internet, a Data Store wizard page will appear. Read the information it presents and then click the Next button. (To change any set-tings this page mentions, refer to the previous sec-tion titled, “Configuring an Authentication Provider.”)

6 When the Define Roles page initially appears, it will contain a single check box titled Enable

Roles For This Web Site. If you want some registered

visitors to have different privileges than others, select this check box. If all registered visitors will have the same privileges, clear it. Click the Next button to continue.

7 If you enabled roles in step 6, the Define Roles page will change to resemble Figure 17-4. For

each role you plan to use, enter its name in the New Role Name box and then click the Add Role button. Each role you create will appear in the Existing Roles box. When you’re done, click the Next button.

Figure 17-4Use this wizard page to create any security groups (roles) that your site needs.

C17622124.indd 7 9/11/05 4:53:51 PM

Page 206: Visual Web Developer 2005 Express Edition

CW-8 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

8 When the Add New Users wizard page shown in Figure 17-5 appears, fill out the Create User

form and click the Create User button once for each login account you want the site to have. Keep these points in mind:

■ The User Name field is a login name, not a legal name. Specify a value like bzighetti or barzig, rather than Barbara Zighetti.

■ Passwords must be at least eight characters long and contain at least one letter, one numeric digit, and one special character.

■ If a visitor forgets his or her password but can correctly answer the security question, ASP.NET

will reset the password and send the new pass-word to the given e-mail address.

■ The Active User check box in the lower left corner determines whether the visitor can log in. To pre-vent an account from logging in, clear this box.

■ If you wish, you can create additional login accounts later, or let visitors create their own accounts.

Once you’ve created all the login accounts you need, click the Next button.

Figure 17-5This page can create as many new login accounts as you want. Enter the data for each account and then click the Create User button.

C17622124.indd 8 9/11/05 4:53:52 PM

Page 207: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-9

9 On the Add New Access Rules page shown in Figure 17-5, perform the following steps for each folder you want to secure:

a. Under the Select A Directory For This Rule heading, expand the folder tree as necessary and then select the folder you want to configure.

b. Under the Rule Applies To heading, specify who the rule should affect. Table 17-1 explains the available options.

c. Under the Permission heading, select the Allow option if you want the rule to grant access to any visitors who match the rule. If you want the rule to block access to any matching visitors, select the Deny option.

d. To save the rule, click the Add This Rule button.

You can create as many rules as you like, whether for the same folder or different folders. Figure 17-6, for example, shows three rules all assigned to the secure folder.

Figure 17-6This Web page creates and modifies access rules for any folder you select.

Don’t create access rules that block anonymous visitors from your site’s root folder. That would make your login page inaccessible.

T I P

C17622124.indd 9 9/11/05 4:53:53 PM

Page 208: Visual Web Developer 2005 Express Edition

CW-10 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

10 Click the Next button to display the last wizard page, then click the Finish button to redisplay the Security tab of the Web Site Administration Tool.

You can rerun the wizard any time but the links at the bottom of the security page provide a more direct path to specific functions. In addition, the Create Or Manage Roles link assigns login accounts to roles, a function the wizard doesn’t include.

TO ASSIGN LOGIN ACCOUNTS TO ROLES

1 On the Security tab of the Web Site Administration Tool, click the Create Or Manage Roles link.

2 On the resulting page, click the Manage link that appears to the right of the role you want to configure.

3 When the Web page shown in Figure 17-7 appears, display a list of user names by either:

■ Using the Search By drop-down list, the For text box, and the Find User button, or

■ Clicking one of the first initial links (A-Z and All)

4 Select or clear the User Is In Role checkbox for each account as necessary.

5 Click the Back button to select another role or return to the Security page.

Table 17-1Options for Applying Access Rules Option Description

Role All users in a given role. Use the drop-down list to select which role.

User A specific user. Enter the user name in the accompanying text box.

All Users All users who have accounts.

Anonymous Users Users who don’t have accounts or haven’t logged in.

C17622124.indd 10 9/11/05 4:53:54 PM

Page 209: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-11

Adding Login Controls to Your Site

Once you’ve configured the security settings and access rules for your site, you’ll need to create Web pages that visitors can use to login, change their password from time to time, recover a forgotten password, or even (if you decide to permit it) self-register.

ASP.NET 2.0 includes a set of Web server controls that make creating these pages very easy. To use these controls in Visual Web Developer, just drag the one you want from the Toolbox’s Login group and drop it on an open ASP.NET Web page. Table 17-2 lists these controls.Toollbox Name Tag Name

Figure 17-7This Web page controls which login accounts belong to a given role.

C17622124.indd 11 9/11/05 4:53:55 PM

Page 210: Visual Web Developer 2005 Express Edition

CW-12 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

A site that requires logging in should always contain these two pages:

■ login.aspx When an anonymous visitor requests a secure page, ASP.NET will automati-cally redirect the request to a page named login.aspx located in the site’s root folder. The Login link that a LoginStatus control displays also points to login.aspx. If your site doesn’t contain a login.aspx page, your visitors will get a 404 Not Found error instead of a login prompt.

Table 17-2ASP.NET 2.0 Login Controls Toolbox Name Tag Name Description

Login <asp:login> Displays a standard login form.

LoginView <asp:loginview> Displays one of several custom login forms based on the visitor’s current login status: anonymous, logged-in, logged-in and member of a certain role, and so forth. The Web developer has to design and configure these templates.

CreateUserWizard <asp:CreateUserWizard> Displays a form that creates new login accounts.

ChangePassword <asp:ChangePassword> Displays a form that changes a login account’s password.

PasswordRecovery <asp:passwordrecovery> Displays a form that resets a visitor’s password and sends it to the visitor by e-mail.

LoginName <asp:loginname> If the current visitor is logged in, displays the login name. Otherwise displays nothing.

LoginStatus <asp:loginstatus> Displays a Login link if the current visitor is anonymous. Displays a Logout link if the visitor is logged in.

C17622124.indd 12 9/11/05 4:53:55 PM

Page 211: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-13

■ default.aspx If a visitor requests a page but lacks permission to display it, ASP.NET will redirect the visitor to the site’s login.aspx page. Then, if the login succeeds, ASP.NET redirects the visitor to the secure page he or she originally requested.

If, however, the visitor follows a hyperlink or Favorites entry to the login.aspx page, and if the login is successful, ASP.NET redirects the visitor to the site’s home page: default.aspx in the site’s root folder. This is one of many good reasons to name your site’s home page default.aspx.

Figure 17-8 shows a login page for the Contoso Magic Web site. This page uses three controls from the Login group:

■ A Login form in the center of the page. After dragging this control from the Toolbox and dropping it onto the page, the only change was a CssClass attribute that provides the colored background and the dotted border. The tag for this control is:

<asp:Login ID=”Login1” runat=”server” CssClass=”formbox” />

Chapter 10 explained how to create CSS classes like formbox.

■ A LoginStatus control just below the breadcrumb trail. By adding this control to the site’s master page, the developer added a Login/Logout link to every page. All settings are the default values. The tag is:

<asp:LoginStatus ID=”LoginStatus1” runat=”server” />

■ A LoginName control at the right, under the date message, displays the text You Are Logged In As: and the current login name (if any). The tag is:

<asp:LoginName ID=”LoginName1” runat=”server”

FormatString=”You are logged in as: {0}.” />

The LoginName control displays the contents of the FormatString attribute only when the current visitor is logged in. In the usual ASP.NET way, it replaces {0} with the first (and in this case only) available parameter: the current username. If no one is logged in, the control displays nothing.

Like the LoginStatus control, this LoginStatus control appears in the sample site’s master page. This, however, isn’t a requirement. You can add either of these controls to any page, user control, custom control, or master page you want.

C17622124.indd 13 9/11/05 4:53:56 PM

Page 212: Visual Web Developer 2005 Express Edition

CW-14 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

LoginStatus Control

Login Control

LoginName Control

Figure 17-9 shows the forms that the CreateUserWizard, ChangePassword, and PasswordRecovery controls display by default. A CSS class provides the background color and the dotted border. To use these controls, simply drag them onto a Web page, save the page, and then add it to your menu system. In the sample site, these pages and the login page are all under a main menu item named Security.

Figure 17-8This is the login form for the Contoso Magic site. A Login Web server con-trol with default settings (except for a CSS class) provides the login form. Everything else comes from a master page.

C17622124.indd 14 9/11/05 4:53:57 PM

Page 213: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-15

For simplicity, this section showed how to use the various Login controls with most or all defaults in effect. In fact, however, these controls are highly configurable. They provide dozens of properties, methods, and events. Whatever you want to change—such as colors, fonts, on-screen titles, error messages, field editing, or visibility under various conditions—you can probably find a property that does what you want. If you can’t find the property you need in the Properties window, display the control’s Help page.

Hiding Menu Options for Secured Pages

For many sites, it makes perfect sense that if a visitor can access a certain page, that page ought to appear in the site’s menu system. Conversely, if a visitor can’t access a certain page, that page should be absent from the site’s menu system.

Logical as this might seem, it’s not the default ASP.NET behavior. If you want menu options to appear and disappear in sync with the current visitor’s permissions, you need to perform two tasks.

■ Add roles attributes to your web.sitemap file.

■ Set the securityTrimmingEnabled property of the XmlSiteMapProviderObject to true. This requires copying 10 lines of fairly messy XML code from the sample files and pasting them into your web.config file.

The procedure for adding roles attributes to your web.sitemap file is fairly simple.

Figure 17-9These forms come from CreateUserWizard, ChangePassword, and PasswordRecovery Web server controls.

C17622124.indd 15 9/11/05 4:53:58 PM

Page 214: Visual Web Developer 2005 Express Edition

CW-16 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

TO ADD ROLES ATTRIBUTES TO YOUR WEB.SITEMAP FILE

1 Open your site in Visual Web Developer, then open the web.sitemap file.

2 For each menu option (that is, each siteMapNode tag) that should appear only for visitors in a certain role, add a roles attribute like the one shown below in green.

<siteMapNode url=”” title=”Product Updates”

description=”Update the Products Database”

roles=”Administrator” >

</siteMapNode>

If the menu item should appear for visitors in more than one role, specify a list of roles separated by com-mas, such as

roles=”friends,romans,countrymen”

3 Add the following roles attribute to each remaining menu option at the same level. The asterisk role (*) means everybody.

roles=”*”

4 Save the web.sitemap file and test the site.

At this point, you should notice that blocked menu items are still visible.

TO MAKE BLOCKED MENU ITEMS DISAPPEAR

1 Open your site in Visual Web Developer, then open the web.config file.

2 Add the following lines of XML code either just after the <system.web> tag or just before the </system.web> tag. (The line breaks on line 6 are for readability.)

C17622124.indd 16 9/11/05 4:53:58 PM

Page 215: Visual Web Developer 2005 Express Edition

Chapter 17: Controlling Access to Your Site CW-17

01 <siteMap defaultProvider=”XmlSiteMapProvider” enabled=”true”>

02 <providers>

03 <clear />

04 <add name=”XmlSiteMapProvider”

05 description=”SiteMap provider which reads in .sitemap XML files.”

06 type=”System.Web.XmlSiteMapProvider, System.Web,

Version=2.0.0.0, Culture=neutral,

PublicKeyToken=b03f5f7f11d50a3a”

07 siteMapFile=”web.sitemap”

08 securityTrimmingEnabled=”true” />

09 </providers>

10 </siteMap>

This block of code appears in the web.config file for the ContosoMagic17 sample site. To save typing, you may wish to open that file, copy the block of code, and paste it into your own web.config file.

3 Save the web.sitemap file and test the site.

The important part of this code appears on line 8, which activates a feature named securityTrimmingEnabled. Unfortunately, the XmlSiteMapProvider object can only enable or disable this feature when it initially loads. Therefore, the <clear /> tag on line 3 unloads any existing site map providers and the <add> tag beginning on line 4 reloads the XmlSiteMapProvider object with securityTrimmingEnabled in effect.

Publishing Security Settings

Physically, the security settings this chapter explains reside in two places: the site’s web.config file and its AspNetSqlProvider database. This database resides in the site’s App_Data folder and its file name is ASPNETDB.MDF.

C17622124.indd 17 9/11/05 4:53:58 PM

Page 216: Visual Web Developer 2005 Express Edition

CW-18 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

When you publish a site for the first time, you can publish these files right along with everything else. Then, if your site is fully ASP.NET 2.0 compliant, your security settings should take effect immediately. Of course, the usual precautions about publishing web.config files and databases remain in effect. As the previous chapter explained, they may require some adjustment depending on your provider’s configuration.

On an ongoing basis, the security settings (and certainly the user databases) of the two sites will almost certainly diverge. As a result, you’ll probably need to administer the security settings on your production site separately from any working copies.

In Summary…

ASP.NET 2.0 provides powerful—yet easy-to-use features—for controlling access to a Web site. You can use either Windows login accounts or custom accounts stored in a SQL Server database to authenticate visitors to your site. Similarly, if you choose to use roles, these can be either Windows security groups or custom roles stored in SQL Server.

ASP.NET 2.0 also provides Web server controls that display login, change password, recover password, and create user forms. By using these controls, you can create Web pages that provide the corresponding functions with very little effort.

Controlling access to pages and controlling the visibility of menu items are two separate tasks. To control the visibility of menu items, you have to add roles attributes to your web.sitemap file and add a few lines of XML to your web.config file.

Although you can initially publish security settings from a working copy of your site to a production copy, this usually isn’t practical over time. Copying the site’s security database, for example, would overwrite the target site’s list of login accounts and passwords. Instead, you should administer the security settings for each site separately.

The next chapter will explain how to use Web Parts in an ASP.NET 2.0 site. Web Parts are special server controls that administrators and visitors, subject to security, can add, rearrange, remove, and configure themselves using only a browser.

C17622124.indd 18 9/11/05 4:53:59 PM

Page 217: Visual Web Developer 2005 Express Edition

CW-19

Introducing Web Part Controls and Terms, 202

Creating Your Own Web Part Page, 207

Chapter 18Displaying Web Parts

18ASP.NET server controls provide tremendous flexibility, productivity, and ease of use for Web developers, but no special flexibility for Web visitors—unless, that is, the server controls are Web Parts.

Like other kinds of server controls, Web Parts are independent software components that execute on the Web server as part of a complete Web page. As with Web user controls and Web custom controls, you can develop Web Parts once and use them in many different pages and many different contexts. The key advantage of Web Parts is that Web visitors, subject to limitations you set, can show, hide, configure, and rearrange Web Parts any way they like.

Prior to ASP.NET 2.0, Web Parts required special programming and worked only in Microsoft® Windows® SharePoint® Services. Now, however, any server control can be a Web Part, and any ASP.NET Web page can display one. This chapter will explain how you can easily use Web Parts on your own site.

A word of warning: using Web Parts to their fullest does require writing a small amount of program code.

C18622124.indd 19 9/11/05 4:55:42 PM

Page 218: Visual Web Developer 2005 Express Edition

CW-20 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

Introducing Web Part Controls and Terms

Any page that displays a Web Part must be an ASP.NET 2.0 page (with an .aspx filename extension) and must contain a WebPartManager control. This control displays no output of its own, but it coordinates many Web Part features. Physically, it must appear before any other Web Part controls on the same page.

A WebPartZone control encloses an area where Web Parts can appear. Any page that contains a WebPartManager control can contain any number of zones.

Web Parts are special server controls that reside within Web Part zones. Web Parts normally require special programming but ASP.NET 2.0 provides a GenericWebPart control that can display any server control as a Web Part.

The page shown in Figure 18-1 illustrates these concepts. The following points are important:

■ Because Web Part features are working, a WebPartManager control must be present, even though it displays nothing of its own.

■ There are two Web Part zones: one titled Left Sleeve and one titled Right Sleeve.

■ The Left Sleeve zone contains three Web Parts named Cards, Cell Phone, and Dove.

■ The Right Sleeve zone contains three Web Parts named Watch, Rabbit, and Keys.

■ The visitor has already clicked the drop-down arrow for the Dove Web Part and selected Minimize. As a result, only the Web Part’s title bar appears.

■ The visitor has now clicked the drop-down arrow for the Rabbit Web Part. This displays a popup menu with these choices:

■ Minimize makes the Web Part display only its title bar.

■ Close completely removes the Web Part from view.

Any page that contains Web Parts is a Web Part Page.

N O T E

The sample pages for this chapter reside in the ContosoMagic17 Web site. To create your own account for logging in, open the site in Microsoft Visual Web Developer™, choose ASP.NET Configuration from the Website menu, then click Security and Create Users. To use an account that comes with the sample files, specify UserName: visitor and Password: vwd$2005.

T I P

C18622124.indd 20 9/11/05 4:55:43 PM

Page 219: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-21

If a visitor hasn’t logged in, he or she can only see Web Parts in their default state. That is, Web Parts appear with the visibility, position, and maximized/minimized state that the Web developer specified when designing the page.

In order to minimize, restore, close, or otherwise modify Web Parts, visitors must first log in as Chapter 17 described. This is because ASP.NET stores each visitor’s Web Part settings in that visitor’s profile. (An ASP.NET 2.0 profile is a block of data within each login account that stores visitor preferences.) This has two benefits:

■ Web Part preferences persist across logins, regardless of time interval. As long as the login account exists, so will the saved Web Part preferences.

■ Each visitor has his or her own set of Web Part prefer-ences. When a visitor reconfigures a Web Part it doesn’t affect any other visitor’s view of that Web Part or the Web Part Page that contains it.

Figure 18-1The six objects that appear horizontally on this page are Web Parts that visitors can configure to suit their needs and interests. No dove picture appears because the visitor minimized that Web Part.

C18622124.indd 21 9/11/05 4:55:44 PM

Page 220: Visual Web Developer 2005 Express Edition

CW-22 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

At any given moment, a WebPartManager control (and therefore all Web Parts on the same page) can be in any of four modes. These are:

■ Browse Visitors can minimize, restore, or close any Web Part on the page. They do this by clicking the drop-down arrow that appears in the top right corner of any Web Part and then choosing the command they want. Figure 18-1 shows this mode in effect.

■ Design Visitors have all the capabilities of Browse mode, plus the ability to rearrange Web Parts within or across any zones in the same page. They do this by dragging the Web Part’s title bar and dropping it where they want it. Figure 18-2 shows a visitor drag-ging the Watch Web Part out of the Right Sleeve zone and dropping it into the Left Sleeve zone.

Figure 18-2Visitors who invoke Design mode can rearrange any Web Parts the page contains. ASP.NET stores such changes in the visitor’s profile and saves them from session to session.

Closing a Web Part removes it from memory, and from view. To restore a closed Web Part, the visi-tor must enter Catalog mode.

N O T E

C18622124.indd 22 9/11/05 4:55:46 PM

Page 221: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-23

■ Edit Visitors have all the capabilities of Browse and Design modes plus an additional command named Edit on the drop-down menu for each Web Part. Choosing this option displays an Editor Zone like the one shown at the right in Figure 18-3. Visitors can make any changes they want, then click the OK button or the Apply button to save them.

To quit without saving, the visitor clicks the Cancel button at the bottom of the zone or the Close link in the top right corner.

Figure 18-3Pages in Edit mode display an Edit Zone where visitors can customize aspects of individual Web Parts.

A Web Part’s Chrome Type refers to the style of its title bar and border (i.e. to its trim). A Web Part’s Direction refers to its lin-guistic direction. In English and Spanish, for example, words and letters appear from left to right. In Hebrew and Arabic, the words and letters appear from right to left.

T I P

C18622124.indd 23 9/11/05 4:55:47 PM

Page 222: Visual Web Developer 2005 Express Edition

CW-24 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

■ Catalog Visitors have all the capabilities of Browse and Design modes. In addition, the page displays a Catalog Zone like the one at the right in Figure 18-4. This zone displays check boxes for any Web Parts that the developer includes on the page, but that the visi-tor subsequently closes (by opening the popup menu and choosing Close).

To restore a closed Web Part, the visitor selects its check box in the Catalog Zone, selects a zone in the Add-To drop-down list, and then clicks the Add button. If necessary, the visitor then switches to Design mode and moves the newly-visible Web Part into place.

Figure 18-4In Catalog mode, a Web Part Page displays a Catalog Zone that lists Web Parts no longer on display, and pro-vides a means of restoring them.

C18622124.indd 24 9/11/05 4:55:48 PM

Page 223: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-25

Web Parts can, of course, do far more than display pictures of magical props. In one common scenario, the catalog zone for a corporate home page offers dozens or hundreds of Web Parts, each with its own specialty: corporate news feeds, industry news feeds, stock prices, corporate metrics, and many other choices. Each employee then configures the home page to display the information that interests or concerns him or her the most.

Creating Your Own Web Part Page

Preparing the Sleeve Trick page (tricks/sleeves.aspx in the ContosoMagic17 sample files) isn’t difficult but it does involve some repetitive work and a bit of program code that ties the var-ious components together. The next few sections explain, in a general way, how to create this Web Part Page.

Gathering Web Parts

Constructing a Web Part Page is rather pointless unless you have some Web Parts to display. You can buy purchase Web Parts commercially or ask your IT department to program Web Parts, but in most cases the fastest and easiest way of obtaining Web Parts is to write them yourself as Web user controls.The Web Parts in the Sleeve Trick page are all very simple Web User controls. Here, for example, is the complete source code listing for the cards.ascx control (using C# syntax):

01 <%@ Control Language=”C#” ClassName=”cards” %>

02 <script runat=”server”>

03 protected void Page_Init(control sender, EventArgs e)

04 {

05 GenericWebPart gwp = Parent as GenericWebPart;

06 if (gwp != null)

07 {

08 gwp.Title = “Cards”;

09 gwp.TitleIconImageUrl = “../images/haticon.gif”;

If you’ve forgotten how to cre-ate Web user controls, refer to Chapter 8, “Creating and Using Web User Controls.”

M O R E I N F O

C18622124.indd 25 9/11/05 4:55:49 PM

Page 224: Visual Web Developer 2005 Express Edition

CW-26 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

10 gwp.CatalogIconImageUrl = “../images/haticon.gif”;

11 }

12 }

13 </script>

14 <img border=0 src=”../images/cards.gif” />

Here are the important features of this code:

■ The @ Control directive on line 1 specifies options for the user control. The program-ming language will be C# and compiling the control will create a class (a type of object) named cards.

■ The <img > tag that appears on line 14 displays the picture of a deck of cards.

The statements on lines 1 and 14 are all the statements you really need. However, the resulting Web Part would display the word Untitled in its title bar, and would contain no icons in its title bar or in Catalog mode. The code on lines 2 through 13 corrects these visual shortcomings. Here’s a brief explanation of this code:

■ The tags on lines 2 and 13 mark the beginning and end of some program code that will run on the Web server.

■ Line 3 defines a function named Page_Init. Because it has this name, ASP.NET will run it automatically when ASP.NET initializes the rest of the Web page. The function parameters sender and e satisfy ASP.NET requirements.

■ The curly braces ({ }) on lines 4 and 12 mark the beginning and end of the Page_Init function’s source code.

■ Line 5 is more complex. When you use a Web user control as a Web Part, ASP.NET loads a GenericWebPart control and tells that control to load the Web user control you want. In that situation, the statement on line 5:

GenericWebPart gwp = Parent as GenericWebPart;

establishes the variable gwp as a pointer to the parent GenericWebPart control.

C18622124.indd 26 9/11/05 4:55:49 PM

Page 225: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-27

If, however, you’re using the same Web user control in an ordinary ASP.NET Web page, the control’s parent won’t be a GenericWebPart control; it will most likely be a Page control or another Web user control. Because it can’t make the gwp variable point to a GenericWebPart control, ASP.NET will set the variable to null.

■ Line 6 determines whether the gwp variable contains something other than null. If so:

■ Line 8 sets the GenericWebPart control’s Title property.

■ Line 9 sets the GenericWebPart control’s TitleIconImageUrl property so it points to the icon that should appear in the Web Part’s title bar.

■ Line 10 sets the GenericWebPart control’s CatalogIconImageUrl property so it points to the icon that should identify the Web Part in Catalog mode.

All six controls that the Sleeve Trick example uses as Web Parts follow the same pattern. To avoid confusion with image URL paths, all six user controls and the Sleeve Tricks Web page itself will reside in the same folder: tricks.

Creating a Blank Web Part Page

The process for creating a Web Part Page is the same as for creating any other ASP.NET page.

TO CREATE A WEB PART PAGE

1 Right-click the tricks folder and select Add New Item.

2 Select the Web Form template, then specify the other options as you like. The example uses Name: sleeves.aspx, Language: C#, Place Code In Separate File: cleared, and Select Master Page: checked.

The page also uses the same master page as the rest of the site.

3 Drag a WebPartManager control from the WebParts group of the Toolbox and drop it onto the body of the Web page. Then, set its ID to wpmSleeves.

C18622124.indd 27 9/11/05 4:55:50 PM

Page 226: Visual Web Developer 2005 Express Edition

CW-28 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

Adding Web Part Zones

When they get to the browser, Web Part Zones are DIVs. As such, they normally cause a line break and then appear flush left. The usual way of overriding this behavior is by placing the Web Part Zones in table cells.

TO ADD WEB PART ZONES

1 Add a one-row, three-column HTML table below the WebPartManager control. Make sure this table appears physically after the WebPartManager control you added in the previous section.

2 Add a two-row, three-column HTML table inside the left cell of the table you created in step 1.

3 Type Left Sleeve into the top left cell of the table you created in step 2. Then, type Right Sleeve into the top-right cell of the same table. Format these cells as headings. (The middle column is only for

spacing.)

4 Drag a WebPartZone control out of the WebParts group of the Toolbox and drop it into the bottom left cell of the table from step 2. Give this WebPartZone control an ID of Left and set its

LayoutOrientation property to Horizontal.

5 Repeat step 4, this time dragging the WebPartZone control into the bottom right cell and giving it an ID of Right. Again, set the LayoutOrientation property to Horizontal.

6 Drag three of your Web Parts or Web user controls out of Server Explorer and drop them in the Left Web Part Zone. Then, drag the rest of your Web Parts or Web user controls into the Right

Web Part Zone.

7 Save the page and browse it. The Web Parts should appear, but unless you log into the site, you won’t be able to modify them from the browser.

8 Log into the site, then try using the drop-down arrows on each Web Part. Initially, the popup menu options should be Minimize and Close.

C18622124.indd 28 9/11/05 4:55:51 PM

Page 227: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-29

■ Choosing Minimize should hide the entire Web Part except for its title bar, and should change its popup menu commands to Restore and Close.

■ Choosing Close should hide the entire Web Part with no way (for now) of getting it back. The next section will explain how to modify the page so visitors can restore closed Web Parts.

Adding Editor and Catalog Zones

For Edit mode to work, your page must contain an Editor zone that contains an Editor Web Part. Similarly, for Catalog mode to work, your page must contain a Catalog zone that con-tains a Catalog Web Part.

TO ADD EDITOR AND CATALOG ZONES AND WEB PARTS

1 Drag an EditorZone control out of the WebParts group of the Toolbox and drop it into the rightmost cell of the table you created in step 1 of the previous section.

2 Drag an AppearanceEditorPart control out of the WebParts group of the Toolbox and drop it onto the EditorZone control from step 1.

3 Drag a CatalogZone control out of the WebParts group of the Toolbox and drop it into the same cell as the EditorZone control from step 1. (The order doesn’t matter. These two controls will never

be visible at the same time.)

4 Drag a PageCatalogPart control out of the WebParts group of the Toolbox and drop it onto the CatalogZone control from step 3.

If you find that Web Part popup menus don’t appear with the font, border, colors, and other proper-ties you want, select the Web Part Zone, open the MenuPopupStyle group in the Properties window, and specify the formatting you want.

T I P

C18622124.indd 29 9/11/05 4:55:51 PM

Page 228: Visual Web Developer 2005 Express Edition

CW-30 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

Switching Display Modes

To switch your Web Part Page between Browse, Design, Edit, and Catalog modes, you need to programmatically change the WebPartManager control’s DisplayMode property to one of four values:

WebPartManager.BrowseDisplayMode

WebPartManager.DesignDisplayMode

WebPartManager.EditDisplayMode

WebPartManager.CatalogDisplayMode

The sample page uses a drop-down list to trigger these property changes. To create this control, proceed as follows.

TO CREATE A DROP-DOWN LIST

1 Drag a DropDownList control out of the Standard group of the Toolbox and drop it onto any conve-nient spot on the Web page. Give this control an ID of ddlMode.

2 Drag a Literal control out of the Standard group of the Toolbox and drop it near the DropDownList control from step 1. This control will display any error messages that result from attempting to switch

Web Part modes. Give this control an ID of litMode and set its EnableViewState property to false. (Disabling view state automatically clears the previous message during each form submission).

3 Select the DropDownList control from step 1, then locate its Items property in the Properties window.

4 Click the word Collection to the right of Items, then click the resulting ellipsis (…) button.

5 When the ListItem Collection Editor dialog box appears:

■ Click the Add button, then type Browse in the Text box and 0 in the Value box.

■ Click the Add button, then type Design in the Text box and 1 in the Value box.

■ Click the Add button, then type Edit in the Text box and 2 in the Value box.

■ Click the Add button, then type Catalog in the Text box and 3 in the Value box.

C18622124.indd 30 9/11/05 4:55:52 PM

Page 229: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-31

6 Click the OK button, then switch to Source view and check your work. The code should look like this:

<asp:DropDownList ID=”ddlMode” runat=”server”>

<asp:ListItem Value=”0”>Browse</asp:ListItem>

<asp:ListItem Value=”1”>Design</asp:ListItem>

<asp:ListItem Value=”2”>Edit</asp:ListItem>

<asp:ListItem Value=”3”>Catalog</asp:ListItem>

</asp:DropDownList>

Make any corrections you need, then return to Design view.

7 With the drop-down list still selected, locate its AutoPostBack property in the Properties window. To cause a form submission every time the visitor selects a different item, set the AutoPostBack property

to True.

8 Double-click the drop-down list. This will switch the display into Source view and display an empty function that looks like this:

protected void ddlMode_SelectedIndexChanged(control sender, EventArgs e)

{

}

9 Enter the following program code inside the function you created in step 8:

01 try

02 {

03 switch (ddlMode.SelectedValue)

04 {

05 case “1”:

06 wpmSleeves.DisplayMode = WebPartManager.DesignDisplayMode;

07 break;

08 case “2”:

09 wpmSleeves.DisplayMode = WebPartManager.EditDisplayMode;

C18622124.indd 31 9/11/05 4:55:52 PM

Page 230: Visual Web Developer 2005 Express Edition

CW-32 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

10 break;

11 case “3”:

12 wpmSleeves.DisplayMode = WebPartManager.CatalogDisplayMode;

13 break;

14 default:

15 wpmSleeves.DisplayMode = WebPartManager.BrowseDisplayMode;

16 break;

17 }

18 }

19 catch (Exception ex)

20 {

21 litMode.Text = ex.Message;

22 }

23 CheckDisplayMode();

In this code:

■ A try block starts on lines 1 and 2 and ends on line 18. This captures any exceptions (i.e. serious errors) that the WebPartManager control might raise. These occur, for example, when a visitor who’s not logged in tries to enter Design, Edit, or Catalog mode.

■ A switch block starts on lines 3 and 4 and ends on line 17. This block tests the current selection in the ddlMode drop-down list box and sets the DisplayMode property of the WebPartManager control named wpmSleves accordingly.

■ The catch block on lines 19 through 22 immediately follows the try block, and runs only if the try block detects an exception. This block receives an Exception object named ex and displays that object’s Message property in the Literal control named litMode. You created this control in step 2.

■ The CheckDisplayMode() statement on line 23 runs a function that queries the WebPartManager con-trol’s DisplayMode property and resets the ddlMode drop-down list accordingly. This is necessary because when change of mode fails, the WebPartManager and the drop-down list will be out of sync. The next step will explain how to write this function.

C18622124.indd 32 9/11/05 4:55:53 PM

Page 231: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-33

10 Add the following function after the code from steps 8 and 9 and just before the </script> that follows it.

01 private void CheckDisplayMode()

02 {

03 if (wpmSleeves.DisplayMode == WebPartManager.BrowseDisplayMode)

04 {

05 ddlMode.SelectedIndex = 0;

06 return;

07 }

08 if (wpmSleeves.DisplayMode == WebPartManager.DesignDisplayMode)

09 {

09 ddlMode.SelectedIndex = 1;

10 return;

11 }

12 if (wpmSleeves.DisplayMode == WebPartManager.EditDisplayMode)

13 {

14 ddlMode.SelectedIndex = 2;

15 return;

16 }

17 if (wpmSleeves.DisplayMode == WebPartManager.CatalogDisplayMode)

18 {

19 ddlMode.SelectedIndex = 3;

20 };

21 }

This is the function that line 23 from step 9 calls. Lines 3 through 7 determine if the WebPartManager con-trol wpmSleeves is in Display mode and if so, it makes sure that the first item (index 0) in the drop-down list, ddlMode, is selected. Lines 8 through 11 determine if the WebPartManager control is in Design mode, and so forth.

C18622124.indd 33 9/11/05 4:55:53 PM

Page 232: Visual Web Developer 2005 Express Edition

CW-34 Microsoft Visual Web Developer 2005 Express Edition: Build a Web Site Now!

11 Note that the WebPartManager control might change mode for reasons other than the Web visitor changing the drop-down list box. Suppose, for example, that the page is in Edit or Catalog mode. If

the visitor clicks the Close button in the AppearanceEditorPart or PageCatalogPart control (whichever is visi-ble), the WebPartManager control will revert to Browse mode, and the ddlMode drop-down list should revert to Browse as well. To make this happen, proceed as follows:

■ Return to Design mode in Visual Web Developer.

■ Select the WebPartManager control.

■ In the Properties window, click the Events button (the lightning bolt icon).

■ In the resulting list of events, double-click DisplayModeChanged.

This will switch Visual Web Developer to Source mode and add the lines shown below in normal weight. Add the line shown in green.

protected void wpmSleeves_DisplayModeChanged(control sender,

WebPartDisplayModeEventArgs e)

{

CheckDisplayMode();

}

Now, whenever the WebPartManager control’s DisplayMode property changes, this function will run the CheckDisplayMode function from step 10. That function, of course, synchronizes the drop-down list to the current DisplayMode.

This completes the coding for the Sleeve Trick page. Once this page is working, you can add it to the web.sitemap file just as you did for any other page in the site.

By now, you should know how you keep visitors from adding unauthorized Web Parts to a page: Don’t add those Web Parts when you develop the page. The only Web Parts visitors can add are those you include when you develop a page.

Similarly, it’s easy to keep visitors from using display modes you don’t want them to access: Avoid writing any program code that switches to those modes.

C18622124.indd 34 9/11/05 4:55:54 PM

Page 233: Visual Web Developer 2005 Express Edition

Chapter 18: Displaying Web Parts CW-35

In Summary…

Web Parts are independent units of content that, like any other server control, you can include in many different Web pages. Web Parts, however, have special capabilities so that each visitor can add, configure, rearrange, or hide any Web Part the developer provides. In this way, visitors can customize the site to their own needs and preferences.

Any ASP.NET page that contains Web Parts is a Web Part Page. Each Web Part Page must contain one WebPartManager control and at least one WebPartZone control. The WebPartZone controls contain the Web Parts.

WebPartManager controls (and therefore Web Part Pages) support four display modes: Browse (which can minimize, restore, and close Web Parts); Design (which can also rearrange Web Parts); Edit (which can also modify Web Part properties); and Catalog (which can reinstate closed Web Parts). Letting visitors switch among these modes requires writing a small amount of program code.

Visual Web Developer 2005 Express Edition is a powerful, sophisticated, yet easy-to use development environment for Web pages. It supports a wide range of today’s best and newest Web techniques including WYSIWYG editing, site management, cascading style sheets, drop-down or fly-out menus, site maps, breadcrumbs, database integration, login security, and visitor customization. It takes full advantage of ASP.NET 2.0 and Microsoft SQL Server™, both of which are widely available at a reasonable cost.

Of course, no piece of software can create Web sites on its own. The concept, the design, the structure, and the hard work are still yours to contribute. Hopefully, Visual Web Developer will provide the best possible channel between your thoughts, your efforts, and extraordinary results. Good luck with your site and I hope we meet again.

C18622124.indd 35 9/11/05 4:55:54 PM

Page 234: Visual Web Developer 2005 Express Edition

C18622124.indd 36 9/11/05 4:55:54 PM

Page 235: Visual Web Developer 2005 Express Edition
Page 236: Visual Web Developer 2005 Express Edition
Page 237: Visual Web Developer 2005 Express Edition
Page 238: Visual Web Developer 2005 Express Edition
Page 239: Visual Web Developer 2005 Express Edition
Page 240: Visual Web Developer 2005 Express Edition
Page 241: Visual Web Developer 2005 Express Edition
Page 242: Visual Web Developer 2005 Express Edition
Page 243: Visual Web Developer 2005 Express Edition
Page 244: Visual Web Developer 2005 Express Edition

Recommended