- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •System Requirements
- •Code Samples
- •Installing the Code Samples
- •Using the Code Samples
- •Support for This Book
- •Questions and Comments
- •Beginning Programming with the Visual Studio 2008 Environment
- •Writing Your First Program
- •Using Namespaces
- •Creating a Graphical Application
- •Chapter 1 Quick Reference
- •Understanding Statements
- •Identifying Keywords
- •Using Variables
- •Naming Variables
- •Declaring Variables
- •Working with Primitive Data Types
- •Displaying Primitive Data Type Values
- •Using Arithmetic Operators
- •Operators and Types
- •Examining Arithmetic Operators
- •Controlling Precedence
- •Using Associativity to Evaluate Expressions
- •Associativity and the Assignment Operator
- •Incrementing and Decrementing Variables
- •Declaring Implicitly Typed Local Variables
- •Chapter 2 Quick Reference
- •Declaring Methods
- •Specifying the Method Declaration Syntax
- •Writing return Statements
- •Calling Methods
- •Specifying the Method Call Syntax
- •Applying Scope
- •Overloading Methods
- •Writing Methods
- •Chapter 3 Quick Reference
- •Declaring Boolean Variables
- •Using Boolean Operators
- •Understanding Equality and Relational Operators
- •Understanding Conditional Logical Operators
- •Summarizing Operator Precedence and Associativity
- •Using if Statements to Make Decisions
- •Understanding if Statement Syntax
- •Using Blocks to Group Statements
- •Cascading if Statements
- •Using switch Statements
- •Understanding switch Statement Syntax
- •Following the switch Statement Rules
- •Chapter 4 Quick Reference
- •Using Compound Assignment Operators
- •Writing while Statements
- •Writing for Statements
- •Understanding for Statement Scope
- •Writing do Statements
- •Chapter 5 Quick Reference
- •Coping with Errors
- •Trying Code and Catching Exceptions
- •Handling an Exception
- •Using Multiple catch Handlers
- •Catching Multiple Exceptions
- •Using Checked and Unchecked Integer Arithmetic
- •Writing Checked Statements
- •Writing Checked Expressions
- •Throwing Exceptions
- •Chapter 6 Quick Reference
- •The Purpose of Encapsulation
- •Controlling Accessibility
- •Working with Constructors
- •Overloading Constructors
- •Understanding static Methods and Data
- •Creating a Shared Field
- •Creating a static Field by Using the const Keyword
- •Chapter 7 Quick Reference
- •Copying Value Type Variables and Classes
- •Understanding Null Values and Nullable Types
- •Using Nullable Types
- •Understanding the Properties of Nullable Types
- •Using ref and out Parameters
- •Creating ref Parameters
- •Creating out Parameters
- •How Computer Memory Is Organized
- •Using the Stack and the Heap
- •The System.Object Class
- •Boxing
- •Unboxing
- •Casting Data Safely
- •The is Operator
- •The as Operator
- •Chapter 8 Quick Reference
- •Working with Enumerations
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •Working with Structures
- •Declaring a Structure
- •Understanding Structure and Class Differences
- •Declaring Structure Variables
- •Understanding Structure Initialization
- •Copying Structure Variables
- •Chapter 9 Quick Reference
- •What Is an Array?
- •Declaring Array Variables
- •Creating an Array Instance
- •Initializing Array Variables
- •Creating an Implicitly Typed Array
- •Accessing an Individual Array Element
- •Iterating Through an Array
- •Copying Arrays
- •What Are Collection Classes?
- •The ArrayList Collection Class
- •The Queue Collection Class
- •The Stack Collection Class
- •The Hashtable Collection Class
- •The SortedList Collection Class
- •Using Collection Initializers
- •Comparing Arrays and Collections
- •Using Collection Classes to Play Cards
- •Chapter 10 Quick Reference
- •Using Array Arguments
- •Declaring a params Array
- •Using params object[ ]
- •Using a params Array
- •Chapter 11 Quick Reference
- •What Is Inheritance?
- •Using Inheritance
- •Base Classes and Derived Classes
- •Calling Base Class Constructors
- •Assigning Classes
- •Declaring new Methods
- •Declaring Virtual Methods
- •Declaring override Methods
- •Understanding protected Access
- •Understanding Extension Methods
- •Chapter 12 Quick Reference
- •Understanding Interfaces
- •Interface Syntax
- •Interface Restrictions
- •Implementing an Interface
- •Referencing a Class Through Its Interface
- •Working with Multiple Interfaces
- •Abstract Classes
- •Abstract Methods
- •Sealed Classes
- •Sealed Methods
- •Implementing an Extensible Framework
- •Summarizing Keyword Combinations
- •Chapter 13 Quick Reference
- •The Life and Times of an Object
- •Writing Destructors
- •Why Use the Garbage Collector?
- •How Does the Garbage Collector Work?
- •Recommendations
- •Resource Management
- •Disposal Methods
- •Exception-Safe Disposal
- •The using Statement
- •Calling the Dispose Method from a Destructor
- •Making Code Exception-Safe
- •Chapter 14 Quick Reference
- •Implementing Encapsulation by Using Methods
- •What Are Properties?
- •Using Properties
- •Read-Only Properties
- •Write-Only Properties
- •Property Accessibility
- •Understanding the Property Restrictions
- •Declaring Interface Properties
- •Using Properties in a Windows Application
- •Generating Automatic Properties
- •Initializing Objects by Using Properties
- •Chapter 15 Quick Reference
- •What Is an Indexer?
- •An Example That Doesn’t Use Indexers
- •The Same Example Using Indexers
- •Understanding Indexer Accessors
- •Comparing Indexers and Arrays
- •Indexers in Interfaces
- •Using Indexers in a Windows Application
- •Chapter 16 Quick Reference
- •Declaring and Using Delegates
- •The Automated Factory Scenario
- •Implementing the Factory Without Using Delegates
- •Implementing the Factory by Using a Delegate
- •Using Delegates
- •Lambda Expressions and Delegates
- •Creating a Method Adapter
- •Using a Lambda Expression as an Adapter
- •The Form of Lambda Expressions
- •Declaring an Event
- •Subscribing to an Event
- •Unsubscribing from an Event
- •Raising an Event
- •Understanding WPF User Interface Events
- •Using Events
- •Chapter 17 Quick Reference
- •The Problem with objects
- •The Generics Solution
- •Generics vs. Generalized Classes
- •Generics and Constraints
- •Creating a Generic Class
- •The Theory of Binary Trees
- •Building a Binary Tree Class by Using Generics
- •Creating a Generic Method
- •Chapter 18 Quick Reference
- •Enumerating the Elements in a Collection
- •Manually Implementing an Enumerator
- •Implementing the IEnumerable Interface
- •Implementing an Enumerator by Using an Iterator
- •A Simple Iterator
- •Chapter 19 Quick Reference
- •What Is Language Integrated Query (LINQ)?
- •Using LINQ in a C# Application
- •Selecting Data
- •Filtering Data
- •Ordering, Grouping, and Aggregating Data
- •Joining Data
- •Using Query Operators
- •Querying Data in Tree<TItem> Objects
- •LINQ and Deferred Evaluation
- •Chapter 20 Quick Reference
- •Understanding Operators
- •Operator Constraints
- •Overloaded Operators
- •Creating Symmetric Operators
- •Understanding Compound Assignment
- •Declaring Increment and Decrement Operators
- •Implementing an Operator
- •Understanding Conversion Operators
- •Providing Built-In Conversions
- •Creating Symmetric Operators, Revisited
- •Adding an Implicit Conversion Operator
- •Chapter 21 Quick Reference
- •Creating a WPF Application
- •Creating a Windows Presentation Foundation Application
- •Adding Controls to the Form
- •Using WPF Controls
- •Changing Properties Dynamically
- •Handling Events in a WPF Form
- •Processing Events in Windows Forms
- •Chapter 22 Quick Reference
- •Menu Guidelines and Style
- •Menus and Menu Events
- •Creating a Menu
- •Handling Menu Events
- •Shortcut Menus
- •Creating Shortcut Menus
- •Windows Common Dialog Boxes
- •Using the SaveFileDialog Class
- •Chapter 23 Quick Reference
- •Validating Data
- •Strategies for Validating User Input
- •An Example—Customer Information Maintenance
- •Performing Validation by Using Data Binding
- •Changing the Point at Which Validation Occurs
- •Chapter 24 Quick Reference
- •Querying a Database by Using ADO.NET
- •The Northwind Database
- •Creating the Database
- •Using ADO.NET to Query Order Information
- •Querying a Database by Using DLINQ
- •Creating and Running a DLINQ Query
- •Deferred and Immediate Fetching
- •Joining Tables and Creating Relationships
- •Deferred and Immediate Fetching Revisited
- •Using DLINQ to Query Order Information
- •Chapter 25 Quick Reference
- •Using Data Binding with DLINQ
- •Using DLINQ to Modify Data
- •Updating Existing Data
- •Adding and Deleting Data
- •Chapter 26 Quick Reference
- •Understanding the Internet as an Infrastructure
- •Understanding Web Server Requests and Responses
- •Managing State
- •Understanding ASP.NET
- •Creating Web Applications with ASP.NET
- •Building an ASP.NET Application
- •Understanding Server Controls
- •Creating and Using a Theme
- •Chapter 27 Quick Reference
- •Comparing Server and Client Validations
- •Validating Data at the Web Server
- •Validating Data in the Web Browser
- •Implementing Client Validation
- •Chapter 28 Quick Reference
- •Managing Security
- •Understanding Forms-Based Security
- •Implementing Forms-Based Security
- •Querying and Displaying Data
- •Understanding the Web Forms GridView Control
- •Displaying Customer and Order History Information
- •Paging Data
- •Editing Data
- •Updating Rows Through a GridView Control
- •Navigating Between Forms
- •Chapter 29 Quick Reference
- •What Is a Web Service?
- •The Role of SOAP
- •What Is the Web Services Description Language?
- •Nonfunctional Requirements of Web Services
- •The Role of Windows Communication Foundation
- •Building a Web Service
- •Creating the ProductsService Web Service
- •Web Services, Clients, and Proxies
- •Talking SOAP: The Easy Way
- •Consuming the ProductsService Web Service
- •Chapter 30 Quick Reference
Chapter 29
Protecting a Web Site and Accessing Data with Web Forms
After completing this chapter, you will be able to:
Restrict access to a Web site by using Microsoft ASP.NET Login controls and
Forms-based authentication.
Create Web forms that present data from a database using a GridView control.
Build Web applications that need to display potentially large volumes of data while minimizing resource use.
Update a database from a Web form.
Build applications that can pass data between Web forms.
In the previous two chapters, you have seen how to build a Web site that enables the user to enter information and validate the data that was entered. You’ve also seen in earlier chapters how to build a non-Web-based application that displays and updates data from a database.
In this chapter, you’ll learn about creating Web applications that display data from a database and that can update the database with any changes made by the user. You will see how to do this in an efficient manner that minimizes use of shared resources, such as the network and the database.
Security is always an important issue, especially when building applications that can be accessed over the Internet, when a Web application accesses sensitive resources such as your company’s databases. Therefore, you will start by learning how to configure a Web forms application to use Forms-based security to verify the identity of the user.
Managing Security
Applications built by using the Microsoft .NET Framework have a range of mechanisms available for ensuring that the users who run those applications have the appropriate user rights. Some of the techniques rely on authenticating users based on some form of identifier and password, whereas others are based on the integrated security features of the Microsoft Windows operating system. If you are creating a Web application that will be accessed over the Internet, using Windows security is probably not an option—users are unlikely to be members of any Windows domain recognized by the Web application and might be running
597
598 |
Part VI Building Web Applications |
|
an operating system other than Windows, such as UNIX. Therefore, the best option to use in |
|
this environment is Forms-based security. |
Understanding Forms-Based Security
With Forms-based security, you can verify the identity of a user by displaying a login form that prompts the user for an ID and a password. After the user has been authenticated, the various Web forms that make up the application can be accessed, and the user’s security credentials can be examined by the code running in any page if additional authorization is needed. (A user might be able to log in to the system but might not have access to every part of the application.)
To use ASP.NET Forms-based security, you must configure the Web application by making some changes to the web.config file, and you must also supply a login form to validate the user. This login form will be displayed whenever the user tries to gain access to any page in the application if the user has not already been validated. The user will be able to proceed to the requested page only if the logic in the login form successfully verifies the user’s identity.
Important To the uninitiated, it might seem that ASP.NET Forms-based security is excessive. It’s not. Don’t be tempted to simply create a login form that acts as an entry point to your application and assume that users will always access your application through it. Browsers can cache forms and URLs locally on users’ computers. Another user might be able to gain access to the browser cache depending on how the computer itself is configured, find the URLs of the sensitive parts of your application, and navigate directly to them, bypassing your login form. You have control over your Web server (hopefully), but you have almost no control over the user’s computer. The ASP.NET Forms-based mechanism is robust, and assuming that your Web server is well protected, it should be adequate for most of your applications.
Implementing Forms-Based Security
In the first set of exercises in this chapter, you will create and configure a Web application that implements Forms-based security. The application will ultimately enable a user to view and modify customer information in the Northwind database.
Create the Northwind Web site
1.Start Microsoft Visual Studio 2008 if it is not already running.
2.If you are using Visual Studio 2008 Professional Edition or Enterprise Edition, on the File menu, point to New, and then click Web Site.
3.If you are using Microsoft Visual Web Developer 2008 Express Edition, on the File menu, click New Web Site.
Chapter 29 Protecting a Web Site and Accessing Data with Web Forms |
599 |
4.In the New Web Site dialog box, click the ASP.NET Web Site template. Select File System in the Location drop-down list box, and specify the \Microsoft Press\Visual CSharp Step By Step\Chapter 29\Northwind folder under your Documents folder. Set the Language to Visual C#, and then click OK.
5.In Solution Explorer, right-click Default.aspx, click Rename, and rename the form to
CustomerData.aspx.
6.Right-click CustomerData.aspx, and click Set As Start Page.
7.In the Code and Text Editor window displaying the HTML source code for the Web form, click the Design button.
8.Using the Toolbox, add a Label control from the Standard category to the Web form. Set the Text property of the label to This form will be implemented later.
In the next exercises, you will build a login form to authenticate the user and configure Forms-based security for the Web application. When configured to use Forms-based security, the ASP.NET runtime will redirect to the login form attempts made by an unauthenticated user to access the application.
Implementing a login form for Forms-based security is such a common task that Microsoft has implemented a set of Login controls to simplify matters. You will use one of these controls now.
Build the login form
1.On the Website menu, click Add New Item.
2.In the Add New Item dialog box, ensure that the Web Form template is selected, and type LoginForm.aspx for the name. Verify that the Language drop-down list box is set to Visual C#, the Place code in separate file check box is selected, and the Select master page check box is cleared, and then click Add to create the form.
The new Web form is created, and the HTML code for the form is displayed in the Code and Text Editor window.
3.Click the Design button to display LoginForm.aspx in the Design View window.
4.In the Properties window, set the Title property of the DOCUMENT object to Northwind Traders – Log In.
5.In the Toolbox, expand the Login category. Add a Login control to the Web form.
The Login control is a composite control that is composed of several labels, two text boxes for the user to type a name and a password, the Remember me next time check
box, and a button to click to log in. You can configure most of these items by using the Properties window for this control, and you can also modify the style of the control.
600 |
Part VI Building Web Applications |
6.In the Common Login Tasks menu displayed by the Login control, click Auto Format on the Login Tasks menu that appears.
Tip If the Common Login Tasks menu is not displayed, click the Login control, and then click the smart tag icon on the top edge of the control, near the right-hand corner.
The Auto Format dialog box appears. You can use this dialog box to change the look and feel of the Login control by selecting a predefined scheme. You can also define your own layout by creating a template using the Convert to Template command on the
Common Login Tasks menu for the Login control.
7.In the Auto Format dialog box, click the Classic scheme, and then click OK. Click the smart tag icon on the Login control to hide the Login Tasks menu.
8.In the Properties window, change the properties of the Login control by using the values in the following table.
Property |
Value |
DisplayRememberMe |
False |
|
|
FailureText |
Invalid User Name or Password. Please enter a valid User |
|
Name and Password. |
|
|
TitleText |
Northwind Traders – Log In |
|
|
DestinationPageUrl |
~/CustomerData.aspx |
|
|
The Login control should look like this:
When the user clicks the Log In button, the user must be authenticated. If the user name
and password are valid, the user should be allowed to proceed to the form specified by the DestinationPageUrl property; otherwise, the error message stored in the FailureText property of the Login control should be displayed and the user prompted to log in again. How do you
perform these tasks? You have at least two options:
Write code that handles the Authenticate event for the Login control. This event is
raised whenever the user clicks the Log In button. You can examine the values in the UserName and Password properties, and if they are valid, allow the user to proceed to the page identified by the DestinationPageUrl property. This strategy is highly customi-
zable but requires that you maintain your own secure list of user names and passwords to authenticate against.
Chapter 29 Protecting a Web Site and Accessing Data with Web Forms |
601 |
Use the built-in features of Visual Studio 2008 with the ASP.NET Web Site Administration Tool to manage user names and passwords, and let the Login control perform its default processing to validate users when the user clicks the Log In button. The ASP.NET Web Site Administration Tool maintains its own database of user names and passwords, and it provides a wizard to help you add users to your Web site.
You will use the second option in the following exercise. (You can investigate the first option on your own time.)
Configure Web site security, and activate Forms-based security
1.On the Website menu, click ASP.NET Configuration.
The ASP.NET Configuration command opens Windows Internet Explorer and starts a Web application called the ASP.NET Web Site Administration Tool, which uses its own instance of the ASP.NET Development Server, independent from your Web application.
By using this tool, you can add and manage users for your Web site, specify application settings that you want to be stored in the application configuration file, and specify how security information such as user names and passwords are stored. By default, the ASP.NET Web Site Administration Tool stores security information in a local Microsoft SQL Server database called ASPNETDB.MDF that it creates in the App_Data folder of your Web site. You can configure the ASP.NET Web Site Administration Tool to store security information elsewhere, but that is beyond the scope of this book.
2. In the ASP.NET Web Site Administration Tool, click the Security tab.
602 Part VI Building Web Applications
The Security page appears. You can use this page to manage users, specify the authentication mechanism that the Web site uses, define roles for users (roles are a convenient mechanism for assigning rights to groups of users), and specify access rules for controlling access to the Web site.
Note The first time you click the Security tab, the ASP.NET Web Site Administrator Tool creates the ASPNETDB.MDF database, so it might take a little time for Internet Explorer to display the next page.
3.In the Users section, click the Select authentication type link.
A new page appears, asking how users will access your Web site. You have two options available: From the internet and From a local network. The From a local network option is selected by default. This option configures the Web site to use Windows authentication; all users must be members of a Windows domain that your Web site can access.
The Northwind Web site will be available over the Internet, so this option is probably not very useful.
4.Click From the internet, and then click Done.
This option configures the application to use Forms-based security. You will make use of the login form you created in the preceding exercise to prompt the user for a name and password.
You return to the Security page.
5.In the Users section, notice that the number of existing users that can access your Web site is currently zero. Click the Create User link.
6.In the Create User page, add a new user with the values shown in the following table.
Prompt |
Response |
User Name |
John |
|
|
Password |
Pa$$w9rd |
|
|
Confirm Password |
Pa$$w9rd |
|
|
john@northwindtraders.com |
|
|
|
Security Question |
What was the name of your first pet |
|
|
Security Answer |
Thomas |
|
|
Note You must supply values for all fields in this screen. The E-mail, Security Question, and Security Answer fields are used by the PasswordRecovery control to recover or reset a user’s password. The PasswordRecovery control is available in the Login category of the Toolbar, and you can add it to a login page to provide assistance to a user who has
forgotten his or her password.
Chapter 29 Protecting a Web Site and Accessing Data with Web Forms |
603 |
7.Ensure that the Active User box is selected, and then click Create User.
The message “Complete. Your account has been successfully created” appears on a new page.
8.Click Continue.
The Create User page reappears so that you can add more users.
9.Click Back to return to the Security page. Verify that the number of existing users is now set to 1.
Note You can use the Manage users link on this page to change the e-mail addresses of
users and add descriptions, and remove existing users. You can let users change their passwords and recover their passwords if they forget them by adding the ChangePassword and PasswordRecovery controls to the login page of the Web site. For more information, see
the topic “Walkthough: Creating a Web Site with Membership and User Login” in the Microsoft Visual Studio 2008 documentation.
10.In the Access Rules section, click Create access rules.
The Add New Access Rule page appears. You use this page to specify which users can access which folders in the Web site.
11.Under Select a directory for this rule, ensure that the Northwind folder is selected by clicking it.
12.Under Rule applies to, ensure that user is selected, and type John.
13.Under Permission, click Allow, and then click OK.
This rule grants John access to the Web site. The Security screen reappears.
14.In the Access Rules section, click Create access rules again.
15.On the Add New Access Rule page, under Select a directory for this rule, ensure that the Northwind folder is selected. Under Rule applies to, click Anonymous users. Under Permission, ensure that Deny is selected, and then click OK.
This rule ensures that users who have not logged in will not be able to access the Web site. The Security screen reappears.
16.Close the Internet Explorer window displaying the ASP.NET Web Site Administration Tool, and return to Visual Studio 2008.
17.Click the Refresh button on the Solution Explorer toolbar.
The database file ASPNETDB.MDF appears in the App_Data folder.
18.Double-click the web.config file in the project folder to display it in the Code and Text Editor window.
604 |
Part VI Building Web Applications |
This file was updated by the ASP.NET Web Site Administration Tool and should contain an <authorization> and an <authentication> element in the <web.config> section that
look like this:
<system.web>
...
<authorization>
<allow users=”John” /> <deny users=”?” />
</authorization>
...
<authentication mode=”Forms” />
...
</system.web>
The <authorization> element specifies the users who are granted and denied
access to the Web site (“?” indicates anonymous users). The mode attribute of the <authentication> element indicates that the Web site uses Forms-based authentication.
19.Modify the <authentication> element, replace the terminating delimiter (/>) with an ordinary closing delimiter (>), and add a <forms> child element, as shown here in bold type. Make sure you add a closing </authentication> element:
<authentication mode=”Forms”>
<forms loginUrl=”LoginForm.aspx” timeout=”5” cookieless=”AutoDetect” protection=”All” />
</authentication>
The <forms> element configures the parameters for Forms-based authentication. The attributes shown here specify that if an unauthenticated user attempts to gain access to any page in the Web site, the user will be redirected to the login page, LoginForm.aspx. If the user is inactive for 5 minutes, she will have to log in again when next accessing a page in the Web site.
In many Web sites that use Forms-based authentication, information about the user is stored in a cookie on the user’s computer. However, most browsers allow users to
specify that they don’t want to use cookies. (Cookies can be abused by malicious Web sites and are frequently considered a security risk.) By inserting cookieless=”AutoDetect”,
you can specify that the Web site can use cookies if the user’s browser has not disabled them; otherwise, the user information is passed back and forth between the Web site and the user’s computer as part of each request. The user information includes the user
name and the password. Obviously, you don’t want this to be clearly visible to everyone. You can use the protection attribute to encrypt this information, which is what this
example does.
20.On the Debug menu, click Start Without Debugging.
Internet Explorer opens. The start page for the application is CustomerData.aspx, but because you have not yet logged in you are directed to LoginForm.aspx instead.
