- •Preface
- •Who Should Read This Book
- •Organization and Presentation
- •Contacting the Authors
- •Acknowledgments
- •Contents
- •Introduction
- •Why Microsoft .NET?
- •The Microsoft .NET Architecture
- •Internet Standards
- •The Evolution of ASP
- •The Benefits of ASP.NET
- •What Is .NET?
- •.NET Experiences
- •.NET Clients
- •.NET Services
- •.NET Servers
- •Review
- •Quiz Yourself
- •Installation Requirements
- •Installing ASP.NET and ADO.NET
- •Installing the .NET Framework SDK
- •Testing Your Installation
- •Support for .NET
- •Review
- •Quiz Yourself
- •Designing a Database
- •Normalization of Data
- •Security Considerations
- •Review
- •Quiz Yourself
- •Creating a Database
- •Creating SQL Server Tables
- •Creating a View
- •Creating a Stored Procedure
- •Creating a Trigger
- •Review
- •Quiz Yourself
- •INSERT Statements
- •DELETE Statements
- •UPDATE Statements
- •SELECT Statements
- •Review
- •Quiz Yourself
- •The XML Design Specs
- •The Structure of XML Documents
- •XML Syntax
- •XML and the .NET Framework
- •Review
- •Quiz Yourself
- •ASP.NET Events
- •Page Directives
- •Namespaces
- •Choosing a Language
- •Review
- •Quiz Yourself
- •Introducing HTML Controls
- •Using HTML controls
- •How HTML controls work
- •Intrinsic HTML controls
- •HTML Control Events
- •The Page_OnLoad event
- •Custom event handlers
- •Review
- •Quiz Yourself
- •Intrinsic Controls
- •Using intrinsic controls
- •Handling intrinsic Web control events
- •List Controls
- •Rich Controls
- •Review
- •Quiz Yourself
- •Creating a User Control
- •Adding User Control Properties
- •Writing Custom Control Methods
- •Implementing User Control Events
- •Review
- •Quiz Yourself
- •Common Aspects of Validation Controls
- •Display property
- •Type Property
- •Operator Property
- •Using Validation Controls
- •RequiredFieldValidator
- •RegularExpressionValidator
- •CompareValidator
- •RangeValidator
- •CustomValidator
- •ValidationSummaryx
- •Review
- •Quiz Yourself
- •Maintaining State Out of Process for Scalability
- •No More Cookies but Plenty of Milk!
- •Out of Process State Management
- •Review
- •Quiz Yourself
- •Introducing the Key Security Mechanisms
- •Web.config and Security
- •Special identities
- •Using request types to limit access
- •New Tricks for Forms-based Authentication
- •Using the Passport Authentication Provider
- •Review
- •Quiz Yourself
- •ASP.NET Updates to the ASP Response Model
- •Caching with ASP.NET
- •Page Output Caching
- •Absolute cache expiration
- •Sliding cache expiration
- •Fragment Caching
- •Page Data Caching
- •Expiration
- •File and Key Dependency and Scavenging
- •Review
- •Quiz Yourself
- •A Brief History of Microsoft Data Access
- •Differences between ADO and ADO.NET
- •Transmission formats
- •Connected versus disconnected datasets
- •COM marshaling versus text-based data transmission
- •Variant versus strongly typed data
- •Data schema
- •ADO.NET Managed Provider Versus SQL Managed Provider
- •Review
- •Quiz Yourself
- •Review
- •Quiz Yourself
- •Creating a Connection
- •Opening a Connection
- •Using Transactions
- •Review
- •Quiz Yourself
- •Building a Command
- •Connection property
- •CommandText property
- •CommandType property
- •CommandTimeout property
- •Appending parameters
- •Executing a Command
- •ExecuteNonQuery method
- •Prepare method
- •ExecuteReader method
- •Review
- •Quiz Yourself
- •Introducing DataReaders
- •Using DataReader Properties
- •Item property
- •FieldCount property
- •IsClosed property
- •RecordsAffected property
- •Using DataReader Methods
- •Read method
- •GetValue method
- •Get[Data Type] methods
- •GetOrdinal method
- •GetName method
- •Close method
- •Review
- •Quiz Yourself
- •Constructing a DataAdapter Object
- •SelectCommand property
- •UpdateCommand, DeleteCommand, and InsertCommand properties
- •Fill method
- •Update method
- •Dispose method
- •Using DataSet Objects
- •DataSetName property
- •CaseSensitive property
- •Review
- •Quiz Yourself
- •Constructing a DataSet
- •Tables property
- •TablesCollection Object
- •Count property
- •Item property
- •Contains method
- •CanRemove method
- •Remove method
- •Add method
- •DataTable Objects
- •CaseSensitive property
- •ChildRelations property
- •Columns property
- •Constraints property
- •DataSet property
- •DefaultView property
- •ParentRelations property
- •PrimaryKey property
- •Rows property
- •Dispose method
- •NewRow method
- •Review
- •Quiz Yourself
- •What Is Data Binding?
- •Binding to Arrays and Extended Object Types
- •Binding to Database Data
- •Binding to XML
- •TreeView Control
- •Implement the TreeView server control
- •Review
- •Quiz Yourself
- •DataGrid Control Basics
- •Binding a set of data to a DataGrid control
- •Formatting the output of a DataGrid control
- •Master/Detail Relationships with the DataGrid Control
- •Populating the Master control
- •Filtering the detail listing
- •Review
- •QUIZ YOURSELF
- •Updating Your Data
- •Handling the OnEditCommand Event
- •Handling the OnCancelCommand Event
- •Handling the OnUpdateCommand Event
- •Checking that the user input has been validated
- •Executing the update process
- •Deleting Data with the OnDeleteCommand Event
- •Sorting Columns with the DataGrid Control
- •Review
- •Quiz Yourself
- •What Is Data Shaping?
- •Why Shape Your Data?
- •DataSet Object
- •Shaping Data with the Relations Method
- •Review
- •Quiz Yourself
- •OLEDBError Object Description
- •OLEDBError Object Properties
- •OLEDBError Object Methods
- •OLEDBException Properties
- •Writing Errors to the Event Log
- •Review
- •Quiz Yourself
- •Introducing SOAP
- •Accessing Remote Data with SOAP
- •SOAP Discovery (DISCO)
- •Web Service Description Language (WSDL)
- •Using SOAP with ASP.NET
- •Review
- •Quiz Yourself
- •Developing a Web Service
- •Consuming a Web Service
- •Review
- •Quiz Yourself
- •ASP and ASP.NET Compatibility
- •Scripting language limitations
- •Rendering HTML page elements
- •Using script blocks
- •Syntax differences and language modifications
- •Running ASP Pages under Microsoft.NET
- •Using VB6 Components with ASP.NET
- •Review
- •Quiz Yourself
- •Preparing a Migration Path
- •ADO and ADO.NET Compatibility
- •Running ADO under ASP.NET
- •Early Binding ADO COM Objects in ASP.NET
- •Review
- •Quiz Yourself
- •Answers to Part Reviews
- •Friday Evening Review Answers
- •Saturday Morning Review Answers
- •Saturday Afternoon Review Answers
- •Saturday Evening Review Answers
- •Sunday Morning Review Answers
- •Sunday Afternoon Review Answers
- •What’s on the CD-ROM
- •System Requirements
- •Using the CD with Windows
- •What’s on the CD
- •The Software Directory
- •Troubleshooting
- •ADO.NET Class Descriptions
- •Coding Differences in ASP and ASP.NET
- •Retrieving a Table from a Database
- •Displaying a Table from a Database
- •Variable Declarations
- •Statements
- •Comments
- •Indexed Property Access
- •Using Arrays
- •Initializing Variables
- •If Statements
- •Case Statements
- •For Loops
- •While Loops
- •String Concatenation
- •Error Handling
- •Conversion of Variable Types
- •Index
128 |
Saturday Afternoon |
<deny users=”*” /> </authorization>
<system.Web>
</configuration>
Using request types to limit access
You can also limit access to resources based upon the request type, GET, POST, and HEAD. The following example lets everyone do a POST, but only Jason can perform a GET request:
<?xml version=”1.0” encoding=”utf-8” ?> <configuration>
<system.Web>
<authorization>
<allow verb=”GET” users=”Jason” /> <allow verb=”POST” users=”*” /> <deny verb=”GET” users=”*”/>
</authorization>
<system.Web>
</configuration>
When it is determined that a user should be denied, then the default 401 code is displayed.
New Tricks for Forms-based Authentication
The most common type of authentication that you will want to implement with ASP.NET is forms-based cookie authentication. In this approach, we use a simple Web form combined with a modification to the Web.config file to provide user authentication.
Let’s look at an example of using forms-based authentication to validate users against a database.
The first step is to create the Web.config file as shown in the following example:
<?xml version=”1.0” encoding=”utf-8” ?> <configuration>
<system.Web>
<authentication mode=”Forms”>
<forms name=”CookieFormApplication” loginUrl=”login.aspx” /> </authentication>
<authorization> <deny users=”?” />
</authorization>
<sessionState mode=”InProc” cookieless=”false” timeout=”20”/> </system.Web>
</configuration>
In this example we are setting the authentication mode to use forms based authentication, establishing that all non-authenticated users should be denied access and that users will be redirected to the login.aspx to obtain authentication.
We will use an xml file, users.xml, to validate the users during the login session. The following example shows the format of the xml file used to validate the users credentials.
Session 13—Authentication and Authorization |
129 |
<Users>
<User>
<UserEmail>joe@smith.com</UserEmail>
<UserPassword>jsmith</UserPassword>
</User>
<User>
<UserEmail>bill@johnson.com</UserEmail>
<UserPassword>bjohnson</UserPassword>
</User>
</Users>
Once you have created the users.xml file, populate it with some sample user name/ password pairs for testing. Next, you can create the login.aspx form. The login.aspx form will collect the user name and password of the user and then compare these values against the xml file. If they match, an authentication cookie will be sent to the user.
Should the username not be found in the XML file then the user is redirected to another page that allows them to add a new username/password to the xml file. Listing 13-2 provides a sample of the login.aspx form.
Listing 13-2 Example of login.aspx using forms-based authentication
<%@ Import Namespace=”System.XML” %> <%@ Import Namespace=”System.IO” %>
<%@ Import Namespace=”System.Web.Security “ %> <%@ Import Namespace=”System.Data.SqlClient” %> <%@ Import Namespace=”System.Data.OleDB” %> <%@ Import Namespace=”System.Data” %>
<%@ Page Language=”vb” debug=”True”%> <HTML>
<HEAD>
<TITLE>Session 13 Cookie Authentication </TITLE> <SCRIPT LANGUAGE=”VB” RUNAT=”Server”>
Sub btnLogin_Click(ByVal Sender As Object, ByVal E As EventArgs)
Select Case ValidateUserXML(txtusername.text,txtpassword.text) Case “Success”
FormsAuthentication.RedirectFromLoginPage (txtusername.text, chkPersistForms.Checked)
Case “PasswordFailed”
lblMessage.Text = “Sorry your password verification for the user “ & txtusername.text &” failed.”
Case “NoSuchUser”
Response.Redirect(“adduser/adduser.aspx?username=” & txtusername.text) End Select
End Sub
Sub btnAddNewUser_Click(ByVal Sender As Object, ByVal E As EventArgs) Response.Redirect(“adduser/adduser.aspx?username=Enter User Name”)
End Sub
Function ValidateUserXML(ByVal username as String, ByVal password as String) as String
Dim cmd as String
Continued
130 |
Saturday Afternoon |
Listing 13-2 |
Continued |
cmd = “UserEmail=’” & username & “‘“ Dim ds as New DataSet
Dim fs as new FileStream(Server.MapPath(“users.xml”),FileMode.Open,FileAccess.Read)
Dim reader as new StreamReader(fs) Dim pass as string
Dim user as string ds.ReadXml(reader) fs.Close()
Dim users as DataTable Users = ds.tables(0) Dim Matches() as DataRow
Matches = Users.Select(cmd)
If Matches.length >0 Then Dim row as DataRow row = matches(0)
pass = row.item(“UserPassword”) user = row.item(“userEmail”) if pass = password then
Return “Success”
else
Return “PasswordFailed”
end if
Else
Return “NoSuchUser” End If
End Function
</SCRIPT>
</HEAD>
<BODY>
<FORM ID=”WebForm1” METHOD=”postPOST” RUNAT=”server”> <P>
<STRONG>Session 13 Forms Authentication</STRONG> </P>
<P>
Please enter your username and password information below and then select the Login Button.
</P>
<P>
<ASP:LABEL ID=”lblMessage” RUNAT=”SERVER”></ASP:LABEL> </P>
<P>
<ASP:TEXTBOX ID=”txtUserName” RUNAT=”SERVER” TOOLTIP=”Please enter your Username here”></ASP:TEXTBOX>
</P>
<P>
Password
<ASP:TEXTBOX ID=”txtPassword” RUNAT=”SERVER” TEXTMODE=”Password” TOOLTIP=”Please enter your password here.”></ASP:TEXTBOX>
</P>
Session 13—Authentication and Authorization |
131 |
<P>
<ASP:CHECKBOX ID=”chkPersistForms” RUNAT=”SERVER” TEXT=”Select to Persist Cookies”></ASP:CHECKBOX>
</P>
<P>
<ASP:BUTTON ID=”btnLogin” RUNAT=”SERVER” TEXT=”Login” ONCLICK=”btnLogin_Click”></ASP:BUTTON>
<ASP:BUTTON ID=”btnAddUser” RUNAT=”SERVER” TEXT=”Add New User” ONCLICK=”btnAddNewUser_Click”></ASP:BUTTON>
</P>
</FORM>
</BODY>
</HTML>
The login form displays a login page to the user. When the user selects the Login button, the btnLogin_Click() method is called. btnLogin_Click() calls a function that compares the e-mail address entered to the e-mail field to the users.xml file. If a valid e-mail is found, then the password of the user is tested. Once a match is discovered, then the
FormsAuthentication.RedirectFromLoginPage () method is called to redirect the user back to the originally requested page or resource while also writing the authentication cookie to the browser.
To test this functionality out, create another file called default.aspx as shown below, establish a virtual directory for all of the above described files (default.aspx, login.aspx, users.xml, Web.config) and browse to the default.aspx page:
<%@ Page Language=”vb”%> <HEAD>
<SCRIPT Language = “VB” Runat=”Server”>
Sub btnLogout_Click(ByVal Sender As Object, ByVal E As EventArgs) FormsAuthentication.Signout
Response.Redirect(“default.aspx”) End Sub
</SCRIPT>
<HTML>
<BODY>
<H1> You successfully logged in and gained access</H1>
<FORM Runat=”Server”>
<asp:Button id=btnLogout runat=”SERVER” Text=”LogOut” OnClick=”btnLogout_Click”>
</asp:Button>
</P>
</FORM>
</BODY>
</HTML>
And that does it — you have tested the user name and password against an xml file, authenticated the user, and forwarded the user to the appropriate resource. When you compare this approach against a similar scenario in ASP 3.0, it is clear that ASP.NET is streamlining these basic functions for the developer.