ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object...

126
Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Transcript of ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object...

Page 1: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Object Innovations Course 416

Student Guide Revision 2.2

ASP.NET Using C#

Page 2: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC ii All Rights Reserved

ASP.NET Using C# Rev. 2.2 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners. Copyright ©2006 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

Page 3: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 Introduction to ASP.NET Chapter 2 Web Forms Architecture Chapter 3 ASP.NET and HTTP Chapter 4 Web Applications Using Visual Studio Chapter 5 State Management and Web Applications Chapter 6 Server Controls Chapter 7 Caching in ASP.NET Chapter 8 ASP.NET Configuration and Security Fundamentals Chapter 9 Debugging, Diagnostics and Error Handling Chapter 10 More Server Controls Chapter 11 Data Access in ASP.NET 2.0 Chapter 12 Personalization and Security Chapter 13 HTTP Pipeline Chapter 14 Database Programming Using ADO.NET Chapter 15 Introduction to Web Services Appendix A Learning Resources Appendix B Configuring IIS for ASP.NET 2.0

Page 4: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• The course software installs to the root directory c:\OIC\AspCs.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The CaseStudy directory contains case studies in multiple steps.

− The Demos directory is provided for doing in-class demonstrations led by the instructor.

• Data files install to the directory c:\OIC\Data.

• Log files are written to the directory c:\OIC\Logs.

Page 5: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1 Introduction to ASP.NET ................................................................................ 1 Web Application Fundamentals.......................................................................................... 3 Setting up the Web Examples ............................................................................................. 4 Creating a Virtual Directory ............................................................................................... 7 Home Page for ASP.NET Examples .................................................................................. 9 From ASP to ASP.NET .................................................................................................... 10 Limitations of ASP ........................................................................................................... 11 Benefits of ASP.NET........................................................................................................ 12 ASP Example .................................................................................................................... 13 ASP.NET Example ........................................................................................................... 15 An Echo Program.............................................................................................................. 16 ASP.NET Features............................................................................................................ 20 Compiled Code ................................................................................................................. 22 Server Controls ................................................................................................................. 23 Browser Independence...................................................................................................... 24 Separation of Code and Content ....................................................................................... 25 State Management............................................................................................................. 26 Lab 1 ................................................................................................................................. 27 Summary ........................................................................................................................... 28

Chapter 2 Web Forms Architecture ............................................................................... 31 Web Forms Architecture................................................................................................... 33 Code-Behind Version of Echo Example........................................................................... 34 HelloCodebehind.aspx...................................................................................................... 35 HelloCodebehind.aspx.cs.................................................................................................. 36 Page Class ......................................................................................................................... 37 Inheriting from Page Class ............................................................................................... 38 Web Forms Page Life Cycle ............................................................................................. 40 View State......................................................................................................................... 43 Web Forms Event Model .................................................................................................. 44 Page Processing ................................................................................................................ 46 Page Events....................................................................................................................... 47 Page Properties ................................................................................................................. 48 Sample Program................................................................................................................ 49 Page Directive................................................................................................................... 53 Tracing .............................................................................................................................. 55 Code-Behind in ASP.NET 2.0 .......................................................................................... 57 ASP.NET 2.0 Code-Behind Example............................................................................... 58 ASP.NET 2.0 Code-Behind Page ..................................................................................... 59 Lab 2 ................................................................................................................................. 60 Summary ........................................................................................................................... 61

Chapter 3 ASP.NET and HTTP ...................................................................................... 65

Page 6: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC vi All Rights Reserved

Classical Web Programming............................................................................................. 67 Active Server Pages Object Model ................................................................................... 68 Request and Response Objects ......................................................................................... 69 Request and Response Example ....................................................................................... 70 HTML Code...................................................................................................................... 71 ASP Code.......................................................................................................................... 72 Request/Response in ASP.NET........................................................................................ 73 HttpRequest Class............................................................................................................. 74 Properties of HttpRequest ................................................................................................. 75 Using HttpRequest Class .................................................................................................. 76 HTTP Collections ............................................................................................................. 77 HttpResponse Class .......................................................................................................... 79 Redirect ............................................................................................................................. 80 HttpUtility ......................................................................................................................... 81 Echo Program in ASP.NET .............................................................................................. 82 Echo.aspx .......................................................................................................................... 83 EchoBack.aspx.................................................................................................................. 84 GET and POST Compared................................................................................................ 85 QueryString and Forms Collections ................................................................................. 86 Lab 3 ................................................................................................................................. 87 Summary ........................................................................................................................... 88

Chapter 4 Web Applications Using Visual Studio......................................................... 91 Using Visual Studio .......................................................................................................... 93 Visual Web Developer...................................................................................................... 94 Visual Web Developer Demo ........................................................................................... 95 Using Components in ASP.NET 2.0............................................................................... 101 Compilation Error ........................................................................................................... 102 Shadow Copying............................................................................................................. 105 Shadow Copy Demonstration ......................................................................................... 106 Temporary Copy of the Component ............................................................................... 109 ASP.NET Applications ................................................................................................... 111 Sessions........................................................................................................................... 112 Global.asax ..................................................................................................................... 113 Web Application Life Cycle ........................................................................................... 114 Application Life Cycle Example .................................................................................... 115 Global.asax ..................................................................................................................... 116 Log Class ........................................................................................................................ 117 Sample Log File.............................................................................................................. 118 StringStore Class............................................................................................................. 119 Data Binding ................................................................................................................... 120 Data Binding Code Example .......................................................................................... 121 Session Data.................................................................................................................... 122 Sessions Using IIS .......................................................................................................... 123 Absolute Positioning....................................................................................................... 125 Adding Global.asax File ................................................................................................. 126

Page 7: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC vii All Rights Reserved

Lab 4 ............................................................................................................................... 127 Summary ......................................................................................................................... 128

Chapter 5 State Management and Web Applications ................................................. 135 Session and Application State......................................................................................... 138 Example Program............................................................................................................ 139 Session Object................................................................................................................. 140 Page_Load....................................................................................................................... 141 Session Variable Issues................................................................................................... 143 Session State and Cookies .............................................................................................. 144 Session State Timeout..................................................................................................... 145 Session State Store.......................................................................................................... 146 Application State............................................................................................................. 147 Implementing Application State ..................................................................................... 148 Global.asax ..................................................................................................................... 149 Users.aspx.cs................................................................................................................... 150 Multithreading Issues...................................................................................................... 151 Bouncing the Web Server ............................................................................................... 152 Lab 5A ............................................................................................................................ 153 Cookies ........................................................................................................................... 154 Cookies and ASP.NET.................................................................................................... 155 HttpCookie Properties..................................................................................................... 156 Example – Exposing Cookies ......................................................................................... 157 Acme Travel Agency Case Study ................................................................................... 163 Lab 5B............................................................................................................................. 165 Summary ......................................................................................................................... 166

Chapter 6 Server Controls ............................................................................................. 179 Server Controls in ASP.NET .......................................................................................... 181 HTML Server Controls ................................................................................................... 182 Using HTML Server Controls ........................................................................................ 183 HTML vs. Web Forms Server Controls.......................................................................... 184 Server Control Examples ................................................................................................ 185 HTML Controls Example ............................................................................................... 186 Code for Login................................................................................................................ 187 HTML Controls in Visual Studio ................................................................................... 188 Using HTML Controls.................................................................................................... 189 Web Controls .................................................................................................................. 190 Validation Controls......................................................................................................... 191 Required Field Validation............................................................................................... 193 Regular Expression Validation ....................................................................................... 194 Rich Controls .................................................................................................................. 195 Copying a Web Site ........................................................................................................ 196 Lab 6 ............................................................................................................................... 197 User Controls .................................................................................................................. 198 Using a User Control ...................................................................................................... 199

Page 8: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC viii All Rights Reserved

Copyright.ascx ................................................................................................................ 200 Copyright.ascx.cs............................................................................................................ 201 User Control Example..................................................................................................... 202 Summary ......................................................................................................................... 203

Chapter 7 Caching in ASP.NET.................................................................................... 207 Introduction..................................................................................................................... 209 What is Caching? ............................................................................................................ 210 Need for Caching (Why Cache?).................................................................................... 211 Data to be Cached – Time Frame ................................................................................... 212 ASP vs. ASP.NET Response Model............................................................................... 213 Caching in ASP.NET...................................................................................................... 214 Three Types of Caching in ASP.NET............................................................................. 215 Output Caching ............................................................................................................... 216 @ OutputCache Directive............................................................................................... 217 Simple Output Caching Example.................................................................................... 218 @ OutputCache – Attributes in Detail............................................................................ 221 VaryByParam in Detail................................................................................................... 222 HttpCachePolicy Class ................................................................................................... 224 HttpCachePolicy Class – Example ................................................................................. 225 Page Fragment Caching .................................................................................................. 227 Common Mistakes in Using Fragment Caching............................................................. 228 Fragment Caching Example............................................................................................ 229 Data Caching or Application Caching ............................................................................ 230 Add an Item to the Cache Object.................................................................................... 231 Insert and Add Methods.................................................................................................. 232 Application Caching – Example ..................................................................................... 233 Expiration........................................................................................................................ 235 Problems in Caching ....................................................................................................... 236 Lab 7 ............................................................................................................................... 237 Summary ......................................................................................................................... 238

Chapter 8 ASP.NET Configuration and Security Fundamentals .............................. 243 One-minute Introduction to XML! ................................................................................. 245 ASP.NET Configuration - Overview.............................................................................. 246 Multi-level Configuration ............................................................................................... 247 Configuration Hierarchy ................................................................................................. 248 Example of Configuration Hierarchy.............................................................................. 249 Web.Config File Structure .............................................................................................. 250 Web.Config Sections ...................................................................................................... 251 Application Settings........................................................................................................ 252 ASP.NET Security – Overview ...................................................................................... 253 Role-Based Security and CAS........................................................................................ 254 Types and Steps .............................................................................................................. 255 Steps in Enabling Role-Based Security .......................................................................... 256 Three Ways to Authenticate ........................................................................................... 257

Page 9: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC ix All Rights Reserved

Forms Authentication Example ...................................................................................... 258 Forms Authentication – Default.aspx ............................................................................. 260 Forms Authentication – Web.Config.............................................................................. 263 Features of Forms Authentication................................................................................... 264 Forms Authentication Classes ........................................................................................ 265 Customizing Forms Authentication ................................................................................ 266 Authentication Source..................................................................................................... 267 Forms Authentication – Analysis ................................................................................... 268 Windows Authentication ................................................................................................ 269 Windows Authentication – Analysis .............................................................................. 270 Windows Authentication Example ................................................................................. 271 Example Corrected.......................................................................................................... 272 Passport Authentication .................................................................................................. 273 Passport Authentication - Analysis................................................................................. 274 Authorization .................................................................................................................. 275 Lab 8 ............................................................................................................................... 276 Summary ......................................................................................................................... 277

Chapter 9 Debugging, Diagnostics and Error Handling............................................. 285 ASP.NET Diagnostics..................................................................................................... 287 Debugging Using Visual Studio ..................................................................................... 288 Calculator Example......................................................................................................... 289 Debugging Calculator ..................................................................................................... 290 Application-Level Tracing.............................................................................................. 292 Tracing Calculator .......................................................................................................... 293 Using the Page Cache ..................................................................................................... 296 An ASP.NET Page Without Visual Studio..................................................................... 297 Attaching to VS Debugger.............................................................................................. 298 Preparing to Debug ......................................................................................................... 300 Trace Messages............................................................................................................... 301 Tracing the Calculator Page............................................................................................ 302 Conditional Tracing ........................................................................................................ 303 Trace Category................................................................................................................ 304 Trace Warning ................................................................................................................ 305 Exceptions in Trace ........................................................................................................ 306 Errors in ASP.NET ......................................................................................................... 307 Uncaught Exception........................................................................................................ 308 Custom Error Pages ........................................................................................................ 309 Lab 9 ............................................................................................................................... 310 Summary ......................................................................................................................... 311

Chapter 10 More Server Controls................................................................................. 313 ASP.NET 2.0 Control Improvements ............................................................................. 315 New Controls in ASP.NET 2.0 ....................................................................................... 316 Master Pages ................................................................................................................... 317 Master Page Demonstration............................................................................................ 318

Page 10: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC x All Rights Reserved

Using a Menu Control..................................................................................................... 321 Creating Content Pages................................................................................................... 323 TreeView Control ........................................................................................................... 324 Master Page Application................................................................................................. 325 Visual Studio 2005 Solutions ......................................................................................... 326 Lab 10 ............................................................................................................................. 327 Summary ......................................................................................................................... 328

Chapter 11 Data Access in ASP.NET 2.0...................................................................... 333 Data Access in ASP.NET 2.0 ......................................................................................... 335 AcmePub Database ......................................................................................................... 336 Creating a Connection .................................................................................................... 337 Using Database Explorer ................................................................................................ 338 Performing Queries......................................................................................................... 339 Data Access Demonstration............................................................................................ 340 Data Entry Demonstration .............................................................................................. 345 SQL Generation Options ................................................................................................ 346 Enable Edit and Delete ................................................................................................... 347 Editing Records............................................................................................................... 348 GridView Control ........................................................................................................... 349 DetailsView Control ....................................................................................................... 350 Storing the Connection String......................................................................................... 351 Protecting the Configuration String................................................................................ 352 Lab 11A .......................................................................................................................... 353 FormView Control .......................................................................................................... 354 Master/Detail Web Pages................................................................................................ 355 Data Binding ................................................................................................................... 358 Template Editing............................................................................................................. 359 Using XML Data............................................................................................................. 361 Example Program............................................................................................................ 362 XML Data Source Demo ................................................................................................ 363 Multiple-Tier Data Access.............................................................................................. 366 Object Data Source ......................................................................................................... 368 Lab 11B........................................................................................................................... 371 Summary ......................................................................................................................... 372

Chapter 12 Personalization and Security ..................................................................... 381 Themes............................................................................................................................ 383 Control Skins .................................................................................................................. 384 Sample Skin File ............................................................................................................. 385 Applying Themes............................................................................................................ 386 Example of Themes ........................................................................................................ 387 Security in ASP.NET 2.0 ................................................................................................ 389 ASP.NET Membership ................................................................................................... 390 Login Controls ................................................................................................................ 391 Membership Demonstration............................................................................................ 392

Page 11: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC xi All Rights Reserved

Web Site Administration Tool ........................................................................................ 393 Access Rules ................................................................................................................... 395 Login Controls Demo ..................................................................................................... 397 Running the Membership Demo..................................................................................... 398 Lab 12A .......................................................................................................................... 400 Profile Properties ............................................................................................................ 401 Profile Demonstration..................................................................................................... 402 Using ASP.NET Profile Properties................................................................................. 403 Web Parts ........................................................................................................................ 405 Web Parts Control Set..................................................................................................... 406 UI Structural Components .............................................................................................. 407 Web Parts Demonstration ............................................................................................... 408 Lab 12B........................................................................................................................... 416 Summary ......................................................................................................................... 417

Chapter 13 HTTP Pipeline............................................................................................. 427 Web Applications............................................................................................................ 429 ASP.NET Request Processing ........................................................................................ 430 ASP.NET Architecture with IIS 5.0 ............................................................................... 431 Pipeline Processing ......................................................................................................... 432 Pipeline Architecture ...................................................................................................... 433 Customizing the HTTP Pipeline ..................................................................................... 434 Customizing Applications............................................................................................... 435 Customizing a Welcome Application ............................................................................. 436 Logger Class ................................................................................................................... 441 Custom Handlers............................................................................................................. 443 IHttpHandler Interface.................................................................................................... 444 Custom Handler Example ............................................................................................... 445 Custom Handler Configuration....................................................................................... 447 Custom Handler Demonstration ..................................................................................... 448 Entry in Configuration File............................................................................................. 449 Extension Mapping in IIS ............................................................................................... 450 .ashx Files ....................................................................................................................... 454 string.ashx ....................................................................................................................... 455 Custom Modules ............................................................................................................. 456 Example: DemoModule .................................................................................................. 457 Using DemoModule........................................................................................................ 458 Lab 13 ............................................................................................................................. 459 Summary ......................................................................................................................... 460

Chapter 14 Database Programming Using ADO.NET................................................ 465 ADO.NET ....................................................................................................................... 467 ADO.NET Architecture .................................................................................................. 468 .NET Data Providers....................................................................................................... 470 Programming with ADO.NET Interfaces ....................................................................... 471 .NET Namespaces........................................................................................................... 472

Page 12: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC xii All Rights Reserved

Connected Data Access .................................................................................................. 473 Sample Database............................................................................................................. 474 Example: Connecting to SQL Server.............................................................................. 475 ADO.NET Class Libraries .............................................................................................. 476 Using Commands............................................................................................................ 477 Creating a Command Object........................................................................................... 478 ExecuteNonQuery........................................................................................................... 479 Using a Data Reader ....................................................................................................... 480 Data Reader: Code Example........................................................................................... 481 Data Bound Controls ...................................................................................................... 482 DataGrid in Visual Studio 2005...................................................................................... 483 Binding a DataReader to a DataGrid .............................................................................. 484 Lab 14A .......................................................................................................................... 486 Disconnected Datasets .................................................................................................... 487 Data Adapters ................................................................................................................. 488 Command Builder ........................................................................................................... 489 Sample Application: Disconnected................................................................................. 490 Main Program ................................................................................................................. 491 Creating a Data Adapter and Generating Commands..................................................... 492 Filling the Dataset ........................................................................................................... 493 Displaying the Data Set .................................................................................................. 494 Adding a Row to the Data Set ........................................................................................ 495 Deleting a Row ............................................................................................................... 496 Changing a Row.............................................................................................................. 497 Updating the Database .................................................................................................... 498 Creating a Dataset Manually........................................................................................... 499 Using XML Data............................................................................................................. 500 XML Schema and Data................................................................................................... 501 Using XML with a DataSet ............................................................................................ 503 XMLExample ................................................................................................................. 504 Lab 14B........................................................................................................................... 505 Summary ......................................................................................................................... 506

Chapter 15 Introduction to Web Services .................................................................... 515 ASP.NET and Web Services........................................................................................... 517 Industry Standards .......................................................................................................... 518 Web Services and Remoting........................................................................................... 519 XML................................................................................................................................ 520 XML Namespaces........................................................................................................... 521 Uniform Resource Identifier ........................................................................................... 522 XML Schema .................................................................................................................. 523 SOAP .............................................................................................................................. 525 WSDL ............................................................................................................................. 526 Web Services Architecture ............................................................................................. 527 A Simple Web Service.................................................................................................... 528 The Add Web Service Example...................................................................................... 529

Page 13: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC xiii All Rights Reserved

Simple IE Client Program............................................................................................... 530 HTTP GET Web Service ................................................................................................ 531 Client IE Web Form........................................................................................................ 532 SOAP Web Service......................................................................................................... 534 SOAP Description........................................................................................................... 535 Viewing WSDL .............................................................................................................. 537 Demo: Creating a Client Program................................................................................... 538 Anonymous Access......................................................................................................... 542 Visual Studio Web Service Demo .................................................................................. 543 Hello World Web Service............................................................................................... 544 WS-I Basic Profile 1.0 .................................................................................................... 545 Test Client....................................................................................................................... 546 Providing a Namespace................................................................................................... 547 Running the Test Client .................................................................................................. 548 Lab 15A .......................................................................................................................... 549 Lab 15B........................................................................................................................... 550 Summary ......................................................................................................................... 551

Appendix A Learning Resources................................................................................... 557

Appendix B Configuring IIS for ASP.NET 2.0 ............................................................ 561 ASP.NET Versions Side-by-Side ................................................................................... 562 Configuring for ASP.NET 2.0 ........................................................................................ 563 Installing ASP.NET ........................................................................................................ 567

Page 14: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC xiv All Rights Reserved

Page 15: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Introduction to ASP.NET

Page 16: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 2 All Rights Reserved

Introduction to ASP.NET

Objectives

After completing this unit you will be able to:

• Review the fundamentals of Web applications and set up a testbed using Internet Information Services and ASP.NET.

• Explain the benefits of ASP.NET and outline its improvements over ASP.

• Describe the two programming models provided by ASP.NET, Web Forms and Web services.

• Create a simple Web Forms application using the .NET Framework SDK.

• Outline the principal features of ASP.NET.

Page 17: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 3 All Rights Reserved

Web Application Fundamentals

• A Web application consists of document and code pages in various formats.

• The simplest kind of document is a static HTML page, which contains information that will be formatted and displayed by a Web browser.

− An HTML page may also contain hyperlinks to other HTML pages.

− A hyperlink (or just “link”) contains an address, or a Uniform Resource Locator (URL), specifying where the target document is located.

• The resulting combination of content and links is sometimes called “hypertext” and provides easy navigation to a vast amount of information on the World Wide Web.

Page 18: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 4 All Rights Reserved

Setting up the Web Examples

• All the example programs for this chapter are in the chapter folder Chap01 underneath the root folder \OIC\AspCs.

• To run the examples, you will need to have Internet Information Services (IIS) installed on your system. IIS is installed by default with Windows 2000 Server.

− You will have to explicitly install it with Windows 2000 Workstation or Windows XP.

− Once installed, you can access the documentation on IIS through Internet Explorer via the URL http://localhost, which will redirect you to the starting IIS documentation page.

• The management tool for IIS is a Microsoft Management Console (MMC) “snap-in,” the Internet Services Manager, which you can find under Administrative Tools in the Control Panel.

Page 19: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 5 All Rights Reserved

Setting up the Web Examples (Cont’d)

• The figure shows the main window of the Internet Services Manager.

− You can Start and Stop the Web server and perform other tasks by right-clicking on Default Web Site.

− Choosing Properties from the context menu will let you perform a number of configurations on the Web server.

• The home directory for the default web site is \Inetpub\wwwroot on the drive where Windows is installed.

− You can change this home directory using Internet Services Manager.

Page 20: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 6 All Rights Reserved

Setting up the Web Examples (Cont’d)

• You can access Web pages stored at any location on your hard drive by creating a “virtual directory.”

− An easy way to create one is from Windows Explorer. Right-click over the desired directory, choose Properties ..., select the Web Sharing tab, click on the Add button, and enter the desired alias, which will be the name of the virtual directory.

• The figure on the next page illustrates creating an alias AspCs, or virtual directory, for the folder \OIC\AspCs.

− You should perform this operation now on your own system in order that you may follow along as the course examples are discussed.

Page 21: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 7 All Rights Reserved

Creating a Virtual Directory

Page 22: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 8 All Rights Reserved

Setting up the Web Examples (Cont’d)

• Once a virtual directory has been created, you can access files in it by including the virtual directory in the path of the URL.

− In particular, you can access the file default.htm using the URL http://localhost/AspCs/.

− The file default.htm contains a home page for all the ASP.NET example programs for this chapter. See the figure on the next page.

Page 23: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 9 All Rights Reserved

Home Page for ASP.NET Examples

Page 24: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 10 All Rights Reserved

From ASP to ASP.NET

• ASP has been a very successful tool for creating Web applications, but there are some significant limitations.

• ASP.NET is not an incremental enhancement to ASP but a whole new programming environment, built on the robust foundation of the .NET Framework.

• ASP.NET is not upwardly compatible with ASP but can run side-by-side with ASP.

− ASP pages have the extension .asp and ASP.NET pages have the extension .aspx.

− A Web site can consist of a mixture of various page types, including .html, .asp, .aspx, and so forth. ASP and ASP.NET pages will be processed separately by the appropriate runtime.

• ASP.NET introduces a new programming model, Web Forms, for building Web applications.

• ASP.NET also introduces another programming model, Web services.

− Web services make it possible for a Web site to expose functionality via an API that can be called remotely by other applications.

• The core infrastructure functionality of ASP.NET applies to both Web Forms and Web services.

Page 25: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 11 All Rights Reserved

Limitations of ASP

• ASP uses scripted languages, such as VBScript and JScript.

− Scripted languages are interpreted and thus slower.

− Scripted languages lack strong data types and object-oriented features.

• ASP leads to intermingled HTML and script code.

− This mixture of HTML and code makes it hard to partition Web page development between designers, concerned with Web page appearance, and programmers, concerned with implementing logical functionality.

• Extensive coding is required with ASP, with limited ability to simply reuse existing components.

− Server-side includes and COM components can be used, but these do not provide a clean, general approach to code reuse.

• Dealing with browser differences has to be handled in code, leading to considerable complexity if you truly want to be browser-independent.

− New devices such as PDAs and cell phones make this problem worse.

Page 26: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 12 All Rights Reserved

Benefits of ASP.NET

• You can use compiled, object-oriented languages with ASP.NET, including C# and Visual Basic.

− All the power of the .NET Framework is available to you, including the extensive class library.

• Code and presentation elements can be cleanly separated.

− Code can be provided in a separate section of a Web page from user interface elements.

− The separation can be carried a step further by use of separate “code behind” files.

• ASP.NET comes with an extensive set of server controls that provide significant functionality out of the box.

• Server controls transparently handle browser compatibility issues.

− A special set of Mobile Controls can emit either HTML or WML, depending on the characteristics of the client device.

• Configuration is handled by XML files without need of any registry settings, and deployment can be done simply by copying files.

• Visual Studio provides a very powerful and easy-to-use environment for developing and debugging Web applications.

Page 27: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 13 All Rights Reserved

ASP Example

• Our example1 displays data from a database.

− See OIC\AspCs\Chap01\Acme.asp.

− The Access database is OIC\Data\SimpleAcme.mdb.

• The example illustrates both the power and limitations of ASP.

− The language is VBScript.

− ADO is used for accessing the database, reading the data into a recordset.

− Code and HTML elements are interspersed.

− Code has to be provided to build up the HTML table.

Note that we sometimes show long strings as simply wrapping to successive lines. They appear on a single line in code files.

1 Based on Professional ASP.NET by Richard Anderson, et al., Wrox Press, 2001, p. 22.

Page 28: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 14 All Rights Reserved

ASP Example (Cont’d)

<%@ language="vbscript" %> <html> <head></head> <body> Hello, ASP <% Dim rs Dim fld Set rs = Server.CreateObject("ADODB.Recordset") rs.Open "select * from Model", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/OIC/Data/SimpleAcme.mdb" If Not rs.EOF Then Response.Write "<table border='1'><tr>" For Each fld In rs.Fields Response.Write "<td>" & fld.Name & "</td>" Next Response.Write "</tr>" While Not rs.EOF Response.Write "<tr>" For Each fld In rs.Fields Response.Write "<td>" & fld.Value & "</td>" Next Response.Write "</tr>" rs.MoveNext Wend Response.Write "</table>" End If %> </body> </html>

Page 29: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 15 All Rights Reserved

ASP.NET Example

• We do the same example in ASP.NET.

− See Chap01\Acme.aspx.

− The DataGrid server control creates an HTML table.

<!-- Acme.aspx --> <%@ Page Language="C#" Debug="true" %> <%@ Import Namespace="System.Data.OleDb" %> <HTML> <HEAD> <SCRIPT RUNAT="SERVER"> void Page_Load(object source, EventArgs e) { string connstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/OIC/Data/SimpleAcme.mdb"; OleDbConnection conn = new OleDbConnection(connstr); conn.Open(); OleDbCommand cmd = new OleDbCommand( "select * from Account", conn); DataGrid1.DataSource = cmd.ExecuteReader(); DataGrid1.DataBind(); } </SCRIPT> </HEAD> <BODY> Hello, ASP.NET <asp:DataGrid id="DataGrid1" runat="server"/> </FORM> </BODY> </HTML>

• This page is an example of a Web Form.

Page 30: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 16 All Rights Reserved

An Echo Program

• We examine the next example, Hello.aspx, in detail.

− The example is complete in one file and contains embedded server code. ASP.NET pages have a .aspx extension.

• The source code consists of HTML along with some C# script code. There are also some special tags for “server controls,” recognized by ASP.NET.

<!-- Hello.aspx --> <%@ Page Language="C#" %> <HTML> <HEAD> <SCRIPT RUNAT="SERVER"> void cmdEcho_Click(object source, EventArgs e) { lblGreeting.Text="Hello, " + txtName.Text; } </SCRIPT> </HEAD> <BODY> <FORM RUNAT="SERVER">Your name:&nbsp; <asp:textbox id=txtName Runat="server"></asp:textbox> <p><asp:button id=cmdEcho onclick=cmdEcho_Click Text="Echo" runat="server" tooltip="Click to echo your name"> </asp:button></p> <asp:label id=lblGreeting runat="server"></asp:label> <P></P> </FORM> </BODY> </HTML>

Page 31: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 17 All Rights Reserved

An Echo Program (Cont’d)

• You can run the program using the URL http://localhost/AspCs/Chap01/Hello.aspx or by clicking on the link Chap01/Hello.aspx in the home page of the examples programs.

− The page shows a text box where you can type in your name, and there is an “Echo” button.

− Clicking the button will echo your name back, with a “Hello” greeting.

− The simple form is again displayed, so you could try out other names.

− If you slide the browser’s mouse cursor over the button, you will see the tool tip “Click to echo your name” displayed in a yellow box.

Page 32: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 18 All Rights Reserved

An Echo Program (Cont’d)

• The figure illustrates a run of this example.

• This little program would not be completely trivial to implement with other Web application tools, including ASP.

• The key user interface feature of such an application is its thoroughly forms-based nature.

− The user is presented with a form and interacts with the form.

− The server does some processing, and the user continues to see the same form.

− This UI model is second nature in desktop applications but is not so common in Web applications.

− Typically, the Web server will send back a different page.

Page 33: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 19 All Rights Reserved

An Echo Program (Cont’d)

• This kind of application could certainly be implemented using a technology like ASP, but the code would be a little ugly.

• The server would need to synthesize a new page that looked like the old page, creating the HTML tags for the original page, plus extra information sent back (such as the greeting shown at the bottom in our echo example).

− A mechanism is needed to remember the current data that is displayed in the controls in the form.

• Another feature of this Web application is that it does some client-side processing too— the Echo button’s tooltip displayed in a yellow box is performed by the browser.

− Such rich client-side processing can be performed by some browsers, such as Internet Explorer, but not others.

• As can be seen by the example code, with ASP.NET it is very easy to implement this kind of Web application.

• We will study the code in detail later.

− For now, just observe how easy it is!

Page 34: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 20 All Rights Reserved

ASP.NET Features

• ASP.NET provides a programming model and infrastructure that facilitates developing new classes of Web applications.

• Part of this infrastructure is the .NET runtime and framework.

• Server-side code is written in .NET compiled languages.

• Two main programming models are supported by ASP.NET.

• Web Forms helps you build form-based Web pages. A WYSIWYG development environment enables you to drag controls onto Web pages.

− Special “server-side” controls present the programmer with an event model similar to what is provided by controls in ordinary Windows programming.

• Web services make it possible for a Web site to expose functionality via an API that can be called remotely by other applications.

− Data is exchanged using standard Web protocols and formats such as HTTP and XML, which will cross firewalls.

• This module is focused on Web Forms, with an introduction to Web services in the last chapter.

Page 35: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 21 All Rights Reserved

ASP.NET Features (Cont’d)

• Both Web Forms and Web services can take advantage of the facilities provided by .NET, such as the compiled code and .NET runtime.

• In addition, ASP.NET itself provides a number of infrastructure services, including:

− state management

− security

− configuration

− caching

− tracing.

Page 36: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 22 All Rights Reserved

Compiled Code

• Web Forms (and Web services) can be written in any .NET language that runs on top of the common language runtime, including C#, Visual Basic, JScript.NET, and Visual C++.

− This code is compiled, and thus offers better performance than ASP pages with code written in an interpreted scripting language such as VBScript.

• All of the benefits, such as a managed execution environment, are available to this code, and of course the entire .NET Framework Class Library is available.

− Legacy unmanaged code can be called through the .NET interoperability services.

Page 37: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 23 All Rights Reserved

Server Controls

• ASP.NET provides a significant innovation known as “server controls.” These controls have special tags such as <asp:textbox>.

• Server-side code interacts with these controls, and the ASP.NET runtime generates straight HTML that is sent to the Web browser.

− The result is a programming model that is easy to use and yet produces standard HTML that can run in any browser.

Page 38: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 24 All Rights Reserved

Browser Independence

• Although the World Wide Web is built on standards, the unfortunate fact of life is that browsers are not compatible and have special features.

− A Web page designer then has the unattractive options of either writing to a lowest common denominator of browser, or else writing special code for different browsers.

− Server controls help remove some of this pain.

• ASP.NET takes care of browser compatibility issues when it generates code for a server control.

− If the requesting browser is upscale, the generated HTML can take advantage of these features, otherwise the generated code will be vanilla HTML.

− ASP.NET takes care of detecting the type of browser.

Page 39: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 25 All Rights Reserved

Separation of Code and Content

• Typical ASP pages have a mixture of scripting code interspersed with HTML elements.

• In ASP.NET there can be a clean separation between code and presentation content.

− The server code can be isolated within a single <SCRIPT RUNAT="SERVER"> ... /SCRIPT> block or, even better, placed within a “code behind” page.

• We will discuss "code-behind" pages in the next chapter.

Page 40: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 26 All Rights Reserved

State Management

• HTTP is a stateless protocol.

• Thus, if a user enters information in various controls on a form, and sends this filled-out form to the server, the information will be lost if the form is displayed again, unless the Web application provides special code to preserve this state.

− ASP.NET makes this kind of state preservation totally transparent.

− There are also convenient facilities for managing other types of session and application state.

Page 41: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 27 All Rights Reserved

Lab 1

A Mortgage Calculator Web Page

You have received a consulting contract to add useful functionality to a realtor’s Web site. In this lab you will implement the first feature, which is a Web page that can be used to calculate a mortgage payment.

Detailed instructions are contained in the Lab 1 write-up at the end of the chapter.

Suggested time: 30 minutes

Page 42: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 28 All Rights Reserved

Summary

• ASP.NET is a unified Web development platform that greatly simplifies the implementation of sophisticated Web applications.

• ASP.NET supports two programming models, Web Forms and Web services.

• Server controls present the programmer with an event model similar to what is provided by controls in ordinary Windows programming.

• Other features of ASP.NET include:

− Compiled code

− Browser independence

− Separation of code and content

− State management

− Security

− Configuration

− Tracing

− Caching

Page 43: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 29 All Rights Reserved

Lab 1

A Mortgage Calculator Web Page

Introduction You have received a consulting contract to add useful functionality to a realtor’s web site. In this lab you will implement the first feature, which is a Web page that can be used to calculate a mortgage payment. The screen capture shows the completed Web page with a sample calculation.

Suggested Time: 30 minutes Root Directory: OIC\AspCs Directories: Labs\Lab1 (do your work here) Chap01\Hello.aspx (starter file) Chap01\MortgageCalculator (C# mortgage calculator) Files: Chap01\Mortgage.aspx (answer)

Page 44: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 1

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 30 All Rights Reserved

1. As a starter file, copy the file Hello.aspx into Labs\Lab1 and rename as Mortgage.aspx. You should now be able to access the “echo” page through the URL http://localhost/AspCs/Labs/Lab1/Mortgage.aspx.

2. Create the user interface for your Web mortgage calculator by making two copies of the textbox for the name in Hello. Rename the three textboxes, one button and one label appropriately. Rename the button handler to match the new name of the button.

3. Examine the code for the C# console program in the MortgageCalculator folder. Run this program a couple of times to generate some test data for use in testing your Web mortgage calculator.

4. Implement the event handler for the Calculate button by copying in code from the MortgageCalculator project. For the Web version you will obtain a numerical value by using the Convert class. For example,

decimal amount; // amount of mortgage ... amount = Convert.ToDecimal(txtAmount.Text); 5. After you have calculated calcPymt, display it formatted as currency in the label

lblPayment . You can do the formatting by the String.Format method.

lblPayment.Text = String.Format("{0, 8:C}", calcPymt); 6. Save your file and test it in the browser. Try out the test data obtained from running

the console version of the program.

Page 45: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 135 All Rights Reserved

Chapter 5

State Management and Web Applications

Page 46: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 136 All Rights Reserved

State Management and Web Applications

Objectives

After completing this unit you will be able to:

• Discuss the issue of state management in creating a Web application.

• Explain the concept of a session and use the HttpSessionState class to manage session state.

• Use the HttpApplicationState class to manage application state.

• Use cookies to save small amounts of information persistently on clients.

• Implement a multiple page Web application using the features of ASP.NET discussed so far in this course.

Page 47: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 137 All Rights Reserved

State Management and Dynamic Web Sites

• Static Web sites work well with the stateless HTTP protocol.

− Each request is for a static Web page and is independent of every other request.

• With dynamic Web sites the issue of state becomes important.

• As an example, consider the common feature of a shopping basket.

− The items previously selected must be remembered as the user goes from page to page on the Web site.

Page 48: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 138 All Rights Reserved

Session and Application State

• Session state is information that is associated with a single browser instance visiting a Web site.

− The Web server identifies and classifies requests coming from a single browser client into a logical application session on the server.

− Session data is stored on the server for use across multiple browser requests.

− Session lifetime management events are raised that can be handled in application code.

• Application state enables sharing of global information across multiple sessions and requests within an ASP.NET application.

− Application state persists across requests from multiple browsers and does not disappear until there are no active browser clients (and a time interval has elapsed).

− Application lifetime management events are raised that can be handled in application code.

− There are multithreading issues with application state.

Page 49: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 139 All Rights Reserved

Example Program

• The example program illustrates individual session data stored for each user.

− See StateDemo.

Page 50: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 140 All Rights Reserved

Session Object

• You can store session information for individual users in the built-in Session object, an instance of the class HttpSessionState.

− You can conveniently access this object through the Session property of the Page class.

− The HttpSessionState class provides a key-value dictionary that you can use for storing arbitrary objects. A string is used as the key.

• Our example provides an illustration of the use of two session variables.

− UserName is a String representing the name of the user.

− ItemList is an ArrayList representing the list of items in the user’s shopping cart.

− These variables are initialized in the Session_Start method of the Global class.

<%@ Application Language="C#" %> <script runat="server"> ... void Session_Start(object sender, EventArgs e) { Session["ItemList"] = new ArrayList(); Session["UserName"] = ""; } ... </script>

Page 51: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 141 All Rights Reserved

Page_Load

• The Page_Load method of the code-behind file for Default.aspx contains logic for storing the user name in a label control.

− The user name is retrieved from the session variable UserName. Note the cast to type string.

− If the user name is blank, there is a redirection to a login page, where the user name will be entered.

protected void Page_Load(object sender, EventArgs e) { string name = (string)Session["UserName"]; if (name == "") Response.Redirect("Login.aspx"); if (!IsPostBack) lblShopper.Text = name; ...

Page 52: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 142 All Rights Reserved

Event Handler for Add Button

• The event handler for the Add button contains code to add an item to the ArrayList of items.

− This list is stored as the session variable ItemList.

− Note the cast to type ArrayList.

− A helper method displays the list of items in a listbox by data binding, as discussed in Chapter 4.

... protected void btnAdd_Click(object sender, EventArgs e) { ArrayList list = (ArrayList)Session["ItemList"]; list.Add(txtItem.Text); ShowItems(); } private void ShowItems() { ArrayList list = (ArrayList)Session["ItemList"]; listItems.DataSource = list; DataBind(); }

Page 53: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 143 All Rights Reserved

Session Variable Issues

• There are some interesting issues in the implementation of session variables.

− Typically cookies are used to identify which requests belong to a particular session. What if the browser does not support cookies, or the user has disabled cookies?

− There is overhead in maintaining session state for many users. Will session state “expire” after a certain time period?

− A common scenario in high-performance Web sites is to use a server farm. How can your application access its data if a second request for a page is serviced on a different machine from that on which the first request was serviced?

• We examine cookies later in this chapter.

Page 54: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 144 All Rights Reserved

Session State and Cookies

• Although by default ASP.NET uses cookies to identify which requests belong to a particular session, it is easy to configure ASP.NET to run cookieless.

• In this mode the Session ID, normally stored within a cookie, is instead embedded within the URL.

• You will learn how to configure an application in the chapter on ASP.NET Configuration and Security.

Page 55: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 145 All Rights Reserved

Session State Timeout

• By default session state times out after 20 minutes.

− This means that if a given user is idle for that period of time, the session is torn down; a request from the client will now be treated as a request from a new user, and a new session will be created.

− Again, it is easy to configure the timeout period, as we will discuss in the chapter on configuration.

Page 56: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 146 All Rights Reserved

Session State Store

• ASP.NET cleanly solves the Web farm problem, and many other issues, through a session state model that separates storage from the application’s use of the stored information.

− Thus different storage scenarios can be implemented without affecting application code.

− The .NET state server does not maintain “live” objects across requests.

− Instead, at the end of each Web request, all objects in the Session collection are serialized to the session state store.

− When the same client returns to the page, the session objects are deserialized.

• By default, the session state store is an in-memory cache.

− It can be configured to be memory on a specific machine, or to be stored in an SQL Server database.

− In these cases the data is not tied to a specific server, and so session data can be safely used with Web farms.

Page 57: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 147 All Rights Reserved

Application State

• Application state is global information that is shared across all users of a Web application.

− For example, the application may keep a list of all logged in users. This list would be stored in application state.

− Our example program StateDemo furnishes an illustration. A Web page Users.aspx is provided to display a list of currently logged in users.

− You can demonstrate that the data is shared across browser sessions by bringing up another browser session and logging in. Then click the Refresh button in the first browser window. Both browser windows should then show the same list of logged in users.

Page 58: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 148 All Rights Reserved

Implementing Application State

• There are several ways to implement application state.

− Use the built-in Application object that you can access through the Application property of the Page class.

− Use the built-in Cache object.

− Use an external data store.

• We illustrate the first approach in the StateDemo program.

− The list of users is stored as an application variable.

• We will discuss the Cache object in the chapter on Caching in ASP.NET.

Page 59: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 149 All Rights Reserved

Global.asax

<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { Application["UserList"] = new ArrayList(); } ... void Session_Start(object sender, EventArgs e) { Session["ItemList"] = new ArrayList(); Session["UserName"] = ""; } ... </script>

Page 60: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 150 All Rights Reserved

Users.aspx.cs

public partial class Users : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ShowUsers(); } private void ShowUsers() { listUsers.Items.Clear(); ArrayList list = (ArrayList)Application["UserList"]; foreach (string name in list) listUsers.Items.Add(name); lblCount.Text = list.Count.ToString(); } protected void btnRefresh_Click(object sender, EventArgs e) { ShowUsers(); } }

Page 61: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 151 All Rights Reserved

Multithreading Issues

• Multiple threads in an application can concurrently access data stored in application state.

− Hence you must take care to avoid race conditions and other synchronization problems.

− Thread synchronization is illustrated in the Login page of the StateDemo example.

• The HttpApplicationState class provides methods Lock and Unlock that allow only one thread at a time to access data stored in application state.

ArrayList list = (ArrayList) Application["UserList"]; Application.Lock(); list.Add(txtName.Text); Application.UnLock();

Page 62: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 152 All Rights Reserved

Bouncing the Web Server

• A Web application stays loaded for some time after all user activity has ceased.

− You can see this by “old” users still being logged in for the StateDemo application.

• You can force an application to unload by “bouncing” the Web server.

− Note that using Internet Information Services to stop the Web server does not suffice.

− Instead, use the Services snap-in (accessible from Administrative Tools in the Control Panel) to stop the World Wide Web Publishing service.

Page 63: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 153 All Rights Reserved

Lab 5A

Application and Session State

In this lab you will completely implement the StateDemo program discussed earlier in the chapter. You will gain practice working with both application state and session state.

Detailed instructions are contained in the Lab 5A write-up at the end of the chapter.

Suggested time: 60 minutes

Page 64: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 154 All Rights Reserved

Cookies

• A fundamental feature of the HTTP protocol is that it is stateless.

• We have seen that ASP.NET provides mechanisms for maintaining “session” information that persists across web pages.

− But we have not yet examined how session management is implemented.

• A standard mechanism used by web servers to save small amounts of information persistently is cookies.

− A cookie is used by the web server to save a small amount of information on the client machine.

− By default cookies expire as soon as the user exits the web application, but they may be set to persist until a specified expiration date.

− A cookie is identified by a character string name, and a cookie has a character string value.

− Cookies are passed as part of the HTTP header.

• The server requires client cooperation to set a cookie.

− Browsers can be set to limit or forbid use of cookies.

− Most users now accept cookies as harmless.

Page 65: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 155 All Rights Reserved

Cookies and ASP.NET

• A cookie is written to a client machine via the HTTP response header.

• ASP.NET provides a class HttpCookieCollection to maintain a type-safe collection of cookies.

− The collection is of type NamedValueCollection, like other HTTP collections described in Chapter 3.

− Standard properties and methods are available for manipulating the collection.

• The HttpResponse classes provide a property Cookies to expose the cookies collection.

• Cookies are sent back to the server via the HTTP request header.

• Cookies themselves are represented by the class HttpCookie.

− A cookie has a Name and a Value, which are both strings.

− Constructors take either a name or both a name and a value.

− A cookie can also have subkeys.

• Domain property limits transmission of the cookie to clients requesting a resource from that domain.

− The Path property can extend the Domain property to completely describe the specific URL to which the cookie applies.

Page 66: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 156 All Rights Reserved

HttpCookie Properties

• Additional useful properties of HttpCookie include:

− Expires is a DateTime (on the client) at which the cookie expires.

− HasKeys specifies whether a cookie has subkeys.

− Values is a collection of key/value pairs that can be contained within a single cookie.

− Items is a shortcut for Values, and in C# provides an indexer for the HttpCookie class.

userCookie["name"] = txtName.Text; userCookie["email"] = txtEmail.Text;

− Secure specifies whether to transmit the cookie securely, that is over HTTPS only.

Page 67: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 157 All Rights Reserved

Example – Exposing Cookies

• A demonstration program illustrates managing cookies with ASP.NET.

− See Cookies for all the files of the sample web application.

− The sample application allows you to add new cookies, delete existing cookies, and show all cookies.

Page 68: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 158 All Rights Reserved

Example – Exposing Cookies

1. Go to the page for adding a cookie, enter the name and value for the new cookie, and click the Add Cookie button. Do this two or three times.

2. Click the Home link to go back to the home page with the three buttons.

Page 69: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 159 All Rights Reserved

Example – Exposing Cookies

3. Go to the page for showing cookies. You will now see the cookies you just added among the list of cookies.

• Besides the cookie(s) you added yourself, there is another cookie used by the web server.

Page 70: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 160 All Rights Reserved

Example – Exposing Cookies

• Here is the relevant code from AddCookie.aspx: private void cmdAdd_Click(object sender, System.EventArgs e) { HttpCookieCollection cookies; cookies = Response.Cookies; HttpCookie cookie = new HttpCookie(txtName.Text); DateTime dt = DateTime.Now; TimeSpan ts = new TimeSpan(0, 0, 30, 0); // 30 minutes cookie.Expires = dt + ts; cookie.Value = txtValue.Text; cookies.Add(cookie); }

• ShowCookies.aspx uses data binding and the DataGrid control, topics which we will discuss later.

Page 71: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 161 All Rights Reserved

Example – Exposing Cookies

• Finally, DeleteCookie.aspx allows you to delete any cookie you don’t want anymore.

Page 72: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 162 All Rights Reserved

Example – Exposing Cookies

• To delete a cookie, you add a cookie with existing cookie’s name that expires immediately.

− From DeleteCookie.aspx:

private void cmdDelete_Click(object sender, System.EventArgs e) { string name = txtName.Text; HttpCookieCollection reqcookies = Request.Cookies; if (reqcookies[name] == null) lblMessage.Text = "Cookie " + name + " not found"; else { HttpCookieCollection cookies; cookies = Response.Cookies; HttpCookie cookie = new HttpCookie(txtName.Text); cookie.Expires = DateTime.Now; cookies.Add(cookie); lblMessage.Text = "Cookie " + name + " deleted"; } }

Page 73: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 163 All Rights Reserved

Acme Travel Agency Case Study

• The Acme Travel Agency provides a Web site with online hotel reservations.

− Acme in turn uses the services of a hotel broker.

− See CaseStudy\AcmeWeb\Step2.

• The home page of the Web site allows a user to book reservations.

Page 74: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 164 All Rights Reserved

Acme Travel Agency (Cont’d)

• A second page shows all the reservations for the user and lets him cancel a selected reservation.

• A Windows Forms program provides the code for the hotel broker and a GUI program that exercises most of its functionality.

− See CaseStudy\AcmeWin\Step2.

Page 75: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 165 All Rights Reserved

Lab 5B

Acme Travel Agency Case Study

In this lab you will continue the Acme Travel Agency case study begun in Lab 4. You will add a number of features:

• A login system to identify a user of the website, with the capability to remember a user through a cookie

• Capability to reserve a hotel room for a selected hotel in a selected city

• A reservations page that displays all reservations for the user and lets the user cancel a reservation.

Detailed instructions are contained in the Lab 5B write-up at the end of the chapter.

Suggested time: 90 minutes

Page 76: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 166 All Rights Reserved

Summary

• Session state is information that is associated with a single browser instance visiting a Web site.

• Application state enables sharing of global information across multiple sessions and requests within an ASP.NET application.

• The Page class has properties Session and Application which give you access to HttpSessionState and HttpApplicationState classes that you can use for managing these states.

• ASP.NET provides several classes to facilitate working with cookies, which are a standard mechanism used by Web servers to save small amounts of information persistently on clients.

Page 77: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 167 All Rights Reserved

Lab 5A

Application and Session State

Introduction In this lab you will completely implement the StateDemo program discussed earlier in the chapter. You will gain practice working with both application state and session state. Suggested Time: 60 minutes Root Directory: OIC\AspCs Directories: Labs\Lab5A (do your work here) Chap05\StateDemo (answer) Create an ASP.NET Web Application and Main Form 1. Use Visual Web Developer to create a new website StateDemo in the working

directory.

2. Enter the title “State Demo” for the page Default.aspx.

3. Bring up the Toolbox from the View menu, if not already showing.

4. From Tools | Options bring up CSS Positioning for HTML Designer. Make sure that for Positioning options you have Absolutely positioned.

5. Drag three Label controls, one textbox, one listbox, and one button onto the form, as shown in the screen capture.

6. For the three label controls, enter Text of “Shopper”, blank, and “New Item.” For the button, enter Text of “Add.”

Page 78: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 168 All Rights Reserved

7. Change the (ID) of the second label to lblShopper. Change the (ID) of the textbox to txtItem, of the listbox to listItems, and of the button to btnAdd.

8. If you need to make the layout of your controls neater, you can bring up the Layout toolbar by right-clicking an empty area of toolbar and selecting “Layout” from the context menu. You can then use the Align Left and Align top buttons to make your form neatly aligned.

Implement the List of Items for Each User

We are now ready to implement the list of items. Since there is a separate list for each user, we will store the list (an ArrayList) as session state.

1. Add a Global.asax file to your project.

2. In the Session_Start method of Global, initialize a session variable ItemList to a new ArrayList.

3. Add a using statement to bring in the System.Collections namespace.

4. Add a handler for the Add button.

5. In this handler do the following:

a. Obtain the Object from Session[“ItemList”] and cast it to an ArrayList and store in a temporary variable list.

b. Call the Add method of ArrayList to add the string in txtItem to the list.

c. Bind the listbox listItems to the ArrayList list by the following code:

listItems.DataSource = list; DataBind(); 6. Build and test. You should now be able to add items and see them displayed in the

listbox.

Implement the Login Page

1. In the Session_Start method of Global, initialize a session variable UserName to an empty string.

2. Add a new Web Form by right-clicking over the project and choosing Add New Item from the context menu. Choose Web Form as the template, and have the code placed in a separate file. Make the name of your new form Login.aspx.

3. Drag one label, one textbox, and one button on to the form and change the Text property of the label and button as shown:

Page 79: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 169 All Rights Reserved

4. Change the (ID) of the textbox to txtName, and the (ID) of the button to btnLogin.

5. Add a handler for the Login button. In the code do the following

a. Assign the session variable UserName to the string entered in the textbox control.

b. Redirect to Default.aspx.

6. Implement the Page_Load method of the Main class as follows:

a. Store the user name in a local variable name by casting the session variable to a string.

b. If this name is blank, redirect to Login.aspx.

c. Otherwise, if it is not a postback, set the lblShopper label to this name.

7. Build and test. You should now be at Step 1.

Implement the List of User

The last step is to implement a list of logged in users. This list will be stored in application state.

1. In the Application_Start method of Global, initialize an application variable UserList to a new ArrayList.

2. Add a new Web Form Users.aspx to the project.

3. Drag a listbox, a button, a hyperlink, and two labels onto the form, as shown in the screen capture.

4. Set the properties of the listbox, button and labels in the usual way. Make the Text of the hyperlink “Home”, and set the NavigateUrl property to Default.aspx.

Page 80: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 170 All Rights Reserved

5. This time, instead of binding the listbox to an ArrayList, we will populate the listbox by a different method. We want to be able to “Refresh” and see the result of some other users being added through a different browser client. To this end create the following helper method ShowUsers.

private void ShowUsers() { listUsers.Items.Clear(); ArrayList list = (ArrayList) Application["UserList"]; foreach (string name in list) listUsers.Items.Add(name); } 6. Add a handler for “Refresh”. Implement by calling ShowUsers.

7. Similarly, implement Page_Load by calling ShowUsers.

8. Modify the handler for “Login” in Login.aspx.cs to add the user just logged in to the list of user.

private void cmdLogin_Click(object sender, System.EventArgs e) { Session["UserName"] = txtName.Text; ArrayList list = (ArrayList) Application["UserList"]; list.Add(txtName.Text); Response.Redirect("Default.aspx"); } 9. Build and test. It’s not quite working right, because when you go back to Main.aspx

after visiting Users.aspx the list of items is lost. Fix this by adding appropriate code to Page_Load. You might find it useful to create a helper method ShowItems that can be called both by Page_Load and by the handler for the Add button.

10. You should now be able to run multiple browser clients and see the effects of several different users, each with its own list of items. (You may find it convenient to run under IIS to test this functionality. Be sure to configure the directory as an application in IIS.)

11. A final detail is to ensure thread safety when you manipulate application state. Add code to the Login handler to lock the list of users while adding a new user.

protected void btnLogin_Click(object sender, EventArgs e) { Session["UserName"] = txtName.Text; ArrayList list = (ArrayList)Application["UserList"]; Application.Lock(); list.Add(txtName.Text); Application.UnLock(); Response.Redirect("Default.aspx"); }

Page 81: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 171 All Rights Reserved

Lab 5B

Acme Travel Agency Case Study

Introduction In this lab you will continue the Acme Travel Agency case study begun in Lab 4. You will add a number of features:

• A login system to identify a user of the website, with the capability to remember a user through a cookie

• Capability to reserve a hotel room for a selected hotel in a selected city • A reservations page that displays all reservations for the user and lets the user

cancel a reservation. Suggested Time: 90 minutes Root Directory: OIC\AspCs Directories: Labs\Lab5B\AcmeWeb (do your work here) Labs\Lab4\AcmeWeb (previous lab work) CaseStudy\AcmeWeb\Step1 (backup of starter code) CaseStudy\AcmeWin\Step2 (source code for hotel broker) CaseStudy\AcmeWeb\Step2 (answer) Study the Hotel Broker Code 1. Build and run the Windows Forms program in CaseStudy\AcmeWin\Step2.

Experiment with making and canceling a few reservations.

2. Study the code in HotelBroker.cs. Note that we’ve added data structures and methods for manipulating reservations.

3. Briefly examine the Windows Forms exerciser program. It exercises some but not all the functionality of the hotel broker. This program has a single hard-coded user, Joe.

Web Page for Making Reservations 1. If you would like to use your code from Lab 4, delete the supplied starter files and

copy your Lab 4 files to the working directory.

2. Copy the file HotelBroker.cs from CaseStudy\AcmeWin\Step2 to the App_Code folder in the working directory, overwriting the old file of that name.

3. Open the website in the working directory in Visual Web Developer and run it, verifying that you can list the hotels in the various cities.

Page 82: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 172 All Rights Reserved

4. Select the four controls on Default.aspx and set the positioning to Absolute from the Layout | Position menu.

5. Drag the controls downward on the form somewhat to make room for two label controls at the top of the form showing the current customer.

6. Drag additional controls onto the form from the Toolbox as shown in the screen capture.

7. Assign properties to the new controls as shown in the table.

Control (ID) Text

Label Customer: Label lblCustomer Label Date TextBox txtDate Label Number Days TextBox txtNumDays TextBox txtMessage Hyperlink Manage My Reservations Button btnMake Make Reservation 8. Set the TextMode property of the txtMessage text box to MultiLine.

9. Set the NavigateUrl propery of the hyperlink to Reservations.aspx, which will be a new page.

10. Add code to the Page_Load() method to initialize lblCustomer.Text to “Joe.” (Later, we will change this code to be the name of a logged-in user.)

Page 83: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 173 All Rights Reserved

HotelBroker in Application State In Step 1 we never changed any data maintained by the hotel broker, so it sufficed to always obtain a new HotelBroker object. Now we will be making and canceling reservations, so it will be important to always work with the same HotelBroker object. We will store it in application state. 1. Add a Global Application Class Global.asax to your application.

2. Add code to Application_Start() to initialize an application variable “Broker” to a new HotelBroker object.

3. Replace the code in Page_Load() that instantiated a new HotelBroker object with code to obtain the HotelBroker object that is stored in application.

HotelBroker broker = (HotelBroker)Application["Broker"]; 4. Do the same thing in the handler for selecting a city from the dropdown.

5. Build and test your application. It should behave in the same manner as before, and you should see the new controls that you added.

Make Reservations 1. Add a handler for the Make Reservation button.

2. Next, we’re going to provide code to read and parse a date and an integer representing the number of days. If either is not correctly formatted, the exception error message should be displayed in the txtMessage text box. If the information is entered correctly, write out a debugging message using Debug.WriteLine(). You will need to bring in the System.Diagnostics namespace. The following code will accomplish the objective.

DateTime date; int numDays; txtMessage.Text = ""; try { date = DateTime.Parse(txtDate.Text); numDays = Convert.ToInt32(txtNumDays.Text); } catch (Exception ex) { txtMessage.Text = ex.Message; return; } Debug.WriteLine("date = " + date.ToShortDateString()); Debug.WriteLine("numDays = " + numDays); 3. Run under the debugger, and test with both valid and invalid formats for the date and

number of days.

Page 84: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 174 All Rights Reserved

4. Add code to initialize a HotelBroker object from application state and to obtain the city and hotel name from the dropdown boxes.

5. Now you can call the MakeReservation() method, obtaining back a ReservationResult.

6. If ReservationId is not -1, build up a multi-line message for txtMessage, using Environment.NewLine for the new line character, displaying the results of the reservation.

7. If ReservationId is -1, display the Comment field. The following code accomplishes the last several steps.

string city = listCities.Text; string hotelName = listHotels.Text; HotelBroker broker = (HotelBroker)Application["Broker"]; ReservationResult result = broker.MakeReservation( lblCustomer.Text, hotelName, city, date, numDays); string NL = Environment.NewLine; if (result.ReservationId != -1) { txtMessage.Text = "Reservation has been booked" + NL; txtMessage.Text += "ReservationId = " + result.ReservationId + ", "; txtMessage.Text += "ReservationRate = " + result.Rate + NL; txtMessage.Text += "ReservationCost = " + result.ReservationCost + NL; txtMessage.Text += result.Comment; } else { txtMessage.Text = "Reservation has not been booked" + NL; txtMessage.Text += result.Comment; } 8. Build and test, making several reservations.

Display and Cancel Reservations 1. Add a new Web Form Reservations.aspx to your project, with code in a separate file.

The new page should have title “Acme Travel.” Make the original Default.aspx page the start page for your project.

2. Add controls to your new page as shown in the screen capture on the following page. The small box at the top is a TextBox with (ID) of txtCustomer. The large box in the middle is a ListBox with (ID) of listRes. The hyperlink should point to Default.aspx.

Page 85: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 175 All Rights Reserved

3. Add code to Page_Load() to initialize txtCustomer.Text to “Joe.” (Later, we will change this to be the logged-in customer.)

4. Call a helper method ShowReservations(). This code will be implemented a little differently than in the Windows Forms version, where we could store arbitrary objects in the list box. In our Web Forms version we will store a string in the list box. We want to store the reservation ID, hotel name, city, arrival date and number of days, separated by commas. We obtain the list of reservations by calling the GetReservations() method of HotelBroker. The following code does the job.

private void ShowReservations() { HotelBroker broker = (HotelBroker)Application["Broker"]; ArrayList array = broker.GetReservations(txtCustomer.Text); if (array == null) { return; } ClearReservations(); foreach (Reservation item in array) { string rid = item.ReservationId.ToString(); string hotel = item.HotelName; string city = item.City; string arrive = item.ArrivalDate.ToString("d"); string number = item.NumberDays.ToString(); string str = rid + "," + hotel + "," + city + "," + arrive + "," + number; listRes.Items.Add(str); } } private void ClearReservations() { listRes.Items.Clear(); } 5. Build and test. You should now be able to make reservations for Joe, and see these

reservations.

6. Add a handler for the Cancel Selected Reservation button.

Page 86: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 176 All Rights Reserved

7. Provide code to break the string representing the reservation into fields separated by commas. From the first field determine the reservation ID, and use this in the call to the CancelReservation() method of HotelBroker. Show the reservations. The following code will do the job.

if (listRes.SelectedIndex != -1) { string selected = listRes.SelectedItem.ToString(); Debug.WriteLine(selected); char[] sep = new char[] {','}; string[] fields; fields = selected.Split(sep); int id = Int32.Parse(fields[0]); Debug.WriteLine(id.ToString()); HotelBroker broker = (HotelBroker)Application["Broker"]; broker.CancelReservation(id); ShowReservations(); } 8. Add a handler for the Refresh button. In this handler call ShowReservations().

9. Build and test. You should now be able to make and cancel reservations for Joe. Since the customer name is shown in a text box, you could try entering a name other than Joe and click Refresh. The list box of reservations should then be empty.

Login System Next, let’s provide the capability to log a user in, and use this name in place of the hardcoded “Joe.” The logged-in user will be saved in session state. 1. Add a new Web Form Login.aspx to your project. Code should be in a separate file.

Make the title of the page “Acme Travel.”

2. Add the controls shown in the screen capture. The (ID) of the text box should be txtName, and the (ID) of the checkbox chkCookie.

3. Add code to the Session_Start() method in Global.asax to initialize a session variable “Customer” to the empty string.

4. Add code to Page_Load() in Default.aspx.cs to retrieve the name of the customer from session state. If it is empty, redirect to Login.aspx, otherwise assign this name to lblCustomer.

Page 87: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 177 All Rights Reserved

5. In Login.aspx, provide a handler for the Login button. In this handler, initialize the “Customer” session variable to the name provided in the login form. Redirect to Default.aspx.

6. In Reservations.aspx, replace the code in Page_Load that initializes txtCustomer.Text with the hardcoded “Joe” with code that uses the “Customer” session variable.

7. Build and test. You should now be able to login in a customer and make/cancel reservations for that customer. Run again using the ASP.NET Web server (without closing your session of Visual Web Developer), and you can make/cancel reservations for a different customer. You can see the reservations for the previous customer by typing in the name and clicking Refresh.

Use a Cookie Finally, we’ll provide the capability to remember a user through a cookie. 1. Modify Page_Load() in Default.aspx to first look for the customer name in a cookie

named “Customer.” You could use the following code.

if (!IsPostBack) { // Look for customer name in either cookie or session state HttpCookie cookie = Request.Cookies["Customer"]; string name; if (cookie != null) { name = cookie.Value; Session["Customer"] = name; } else name = (string)Session["Customer"]; if (name == "") Response.Redirect("Login.aspx"); lblCustomer.Text = name; 2. Modify the handler for the Login button to initialize a cookie if requested by the user.

Session["Customer"] = txtName.Text; if (chkCookie.Checked) { HttpCookie cookie = new HttpCookie("Customer"); cookie.Value = txtName.Text; cookie.Expires = DateTime.Now.AddHours(1); Response.Cookies.Add(cookie); } Response.Redirect("Default.aspx"); 3. Build and test under the ASP.NET Development Server.

Page 88: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 5

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 178 All Rights Reserved

4. If you have time, do further testing using Internet Information Services. Note that if you have a cookie lying around that you’d like deleted, you can do so with the Cookies demonstration program!

Page 89: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 427 All Rights Reserved

Chapter 13

HTTP Pipeline

Page 90: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 428 All Rights Reserved

HTTP Pipeline

Objectives

After completing this unit you will be able to:

• Describe the general architecture of Web applications that generate dynamic content.

• Describe the architecture of the HTTP pipeline, which is used in Web Forms, Web services, and other ASP.NET applications.

• Outline the principal classes in ASP.NET that support the HTTP pipeline.

• Explain the role of context in ASP.NET applications.

• Customize the HTTP pipeline through the application class.

• Explain the use of HTTP handlers and modules.

• Implement custom HTTP handlers.

• Implement custom HTTP modules.

Page 91: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 429 All Rights Reserved

Web Applications

• Originally the Web served up static content in the form of HTML pages.

− Web servers then simply retrieved static pages from a file store.

• With the advent of dynamically generated content, the architecture of Web applications became more complex.

− The browser makes a request for a certain URL, but the request is satisfied through a program rather than a static page.

− The universal protocol for invoking a program was CGI (Common Gateway Interface). The drawback of CGI is the fact that each request spawns a process, and we have the overhead of inter-process communication.

− In Microsoft Windows, a much more efficient protocol is ISAPI (Internet Server Application Programming Interface). ISAPI applications run as a DLL in the same process as the Web server.

− The file extension of the requested page is used by the Web server to determine the protocol used for dispatching the request.

Page 92: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 430 All Rights Reserved

ASP.NET Request Processing

• ASP.NET running on Internet Information Services (IIS) processes requests in this general manner:

− IIS looks for an extension mapping for the requested page.

− If the extension is recognized by ASP.NET (.aspx, .asmx, and so on), IIS loads aspnet_isapi.dll and passes the request to it, using the ISAPI protocol.

− The ISAPI extension DLL locates the ASP.NET worker process aspnet_wp.exe and sets up named pipes for communication with it.

− The request is sent to the worker process to be handler.

− The worker process routes the request to the HTTP pipeline in an app domain that is associated with the virtual directory of the Web application.

− The HTTP pipeline processes the request, ultimately through a handler, which creates a response that is sent back through the same channels.

• This architecture, involving a worker process that is separate from the Web server, is used in IIS 5.0.

− See the figure on the following page.

Page 93: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 431 All Rights Reserved

ASP.NET Architecture with IIS 5.0

Browser

IIS

aspnet_isapi.dll

App Domain

HttpRuntime

Application

Handler

aspnet_wp.exe (worker process)

HTTPPipeline

OtherApp Domains

• Each ASP.NET application is housed in its own app domain, which provides isolation without the overhead of separate processes.

Page 94: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 432 All Rights Reserved

Pipeline Processing

• The HTTP pipeline processing of a request involves these steps:

1. An instance of the class HttpWorkerRequest is created, containing all the information about the request.

2. This request is passed to the ProcessRequest method of the HttpRuntime class.

3. An instance of the class HttpContext is created, keeping all the relevant information about the request together in one place, accessible throughout the pipeline.

4. Instances of HttpRequest and HttpResponse are created, stored as fields within HttpContext.

5. HttpRuntime obtains an application class (derived from HttpApplication) through HttpApplicationFactory. Either a new application instance is created, or one is pulled from a pool.

6. Modules associated with the application are created to do pre- and post-processing for the request.

7. HttpRuntime dispatches the request to the application class that has been created.

8. The application class locates a handler to service the request, either directly or by going through a handler factory.

9. The ProcessRequest method of the handler is invoked, passing in the current HttpContext.

10. The handler reads information from the HttpRequest field of the context and writes information to the HttpResponse field.

Page 95: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 433 All Rights Reserved

Pipeline Architecture

• This diagram illustrates the architecture of the HTTP pipeline:

Worker Process

HttpRuntime

Application Factory

HttpContext

Application

Handler Factory

Handler

Module

Page 96: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 434 All Rights Reserved

Customizing the HTTP Pipeline

• There are three major extensibility points for the HTTP pipeline:

− Through the application class, either using HttpApplication as is or deriving a new class from it.

− By creating a custom handler that implements the IHttpHandler interface.

− By creating custom modules to do pre- and post-processing of requests.

Page 97: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 435 All Rights Reserved

Customizing Applications

• The HttpApplication class is central to every ASP.NET application.

− It serves as the initial entry point for application requests.

− It provides a repository of resources that are globally accessible with the application, such as application state, session state, and the cache.

− It offers access to many events that occur during the lifetime of an application.

• Often you can simply make use of the base class HttpApplication itself.

− You can access a reference to the class through the ApplicationInstance property of either the HttpContext class or the Page class.

• You may obtain further customization by deriving a class from HttpApplication.

− Visual Studio does this for you automatically in the Global.asax file.

Page 98: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 436 All Rights Reserved

Customizing a Welcome Application

• As a simple illustration of customizing an application through the application class, let’s customize a “welcome” application.

− See the Welcome folder in the chapter directory.

− The core application simply displays a welcome message in bold.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Application Demo</title> </head> <body> <form id="form1" runat="server"> <div> <b>Welcome to ASP.NET</b> </div> </form> </body> </html>

Page 99: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 437 All Rights Reserved

Welcome Application (Cont’d)

• The code-behind file has no added code. public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } }

• If we run the application, we see additional output:

• If you use IIS, be sure to configure the Welcome directory as an application in IIS!

Page 100: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 438 All Rights Reserved

Welcome Application (Cont’d)

• The code for the additional output is provided by event handlers in the application class.

void Application_Start(Object sender, EventArgs e) { WriteLine("Application starting"); Context.Items["AppStart"] = DateTime.Now; log = new Logger( @"c:\OIC\Logs\AppDemoLog.txt"); Application["Log"] = log; log.Open(); log.Write("Application starting"); log.Write(DateTime.Now.ToLongTimeString()); } void Session_Start(Object sender, EventArgs e) { WriteLine("Session starting"); Context.Items["SessionStart"] = DateTime.Now; log = new Logger( @"c:\OIC\Logs\AppDemoLog.txt"); Application["Log"] = log; log.Open(); log.Write("Session starting"); log.Write(DateTime.Now.ToLongTimeString()); }

Page 101: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 439 All Rights Reserved

Welcome Application (Cont’d)

void Application_BeginRequest(Object sender, EventArgs e) { log = (Logger) Application["Log"]; WriteLine("Request starting"); Context.Items["RequestStart"] = DateTime.Now; log.Write("Request starting"); log.Write(DateTime.Now.ToLongTimeString()); } void Application_EndRequest(Object sender, EventArgs e) { log = (Logger) Application["Log"]; WriteLine("Request ending"); DateTime start = (DateTime) Context.Items["RequestStart"]; TimeSpan ts = DateTime.Now - start; WriteLine(ShowTime(ts)); log.Write("Request ending"); log.Write(DateTime.Now.ToLongTimeString()); log.Write(ShowTime(ts)); } ...

Page 102: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 440 All Rights Reserved

Welcome Application (Cont’d)

• Helper methods are provided to display elapsed time and to also provide logging to a file.

private Logger log; private void WriteLine(string text) { Context.Response.Write(text); Context.Response.Write("<br>"); } private string ShowTime(TimeSpan ts) { return string.Format( "{0} minutes, {1} seconds, {2} milliseconds", ts.Minutes, ts.Seconds, ts.Milliseconds); }

• Here is some sample log file output: ---------------------------- Application starting 9:19:42 AM Request starting 9:19:42 AM ---------------------------- Session starting 9:19:42 AM Request ending 9:19:43 AM 0 minutes, 0 seconds, 781 milliseconds

Page 103: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 441 All Rights Reserved

Logger Class

• The Logger class provides a simple logging mechanism.

using System.IO; public class Logger { private string m_path; private StreamWriter m_writer; public Logger(string path) { m_path = path; } public void Open() { FileStream fs; if (File.Exists(m_path)) { fs = new FileStream(m_path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); } else { fs = new FileStream(m_path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); } m_writer = new StreamWriter(fs); m_writer.WriteLine("----------------------"); } }

Page 104: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 442 All Rights Reserved

Logger Class (Cont’d)

public void Close() { m_writer.Close(); } public void Write(string text) { m_writer.WriteLine(text); m_writer.Flush(); } }

Page 105: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 443 All Rights Reserved

Custom Handlers

• Web Forms with a Page class rely on a handler provided by ASP.NET for files with a .aspx extension.

• A handler must implement the IHttpHandler interface.

public interface IHttpHandler { void ProcessRequest(HttpContext context); bool IsReusable {get;} }

• The Page class implements this interface.

− Its implementation of ProcessRequest() writes a response by rendering the controls within the page.

• You can create your own handler that is not tied into the rendering based on controls provided by the Page class.

− Create a class that implements the IHttpHandler interface.

− Hook your handler class to the application through the IIS extension mapping mechanism and the configuration file of your application.

Page 106: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 444 All Rights Reserved

IHttpHandler Interface

public interface IHttpHandler { void ProcessRequest(HttpContext context); bool IsReusable {get;} }

• The ProcessRequest() method takes the context of the request as input and performs the servicing of the request.

• The IsReusable property is used to indicate whether instances of a handler can be pooled.

− Usually, you would return false, indicating that your handler is not pooled.

− It might make sense to provide for handler pooling if there is significant overhead in setting up a handler.

Page 107: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 445 All Rights Reserved

Custom Handler Example

• As an example of a custom handler, examine the class library StringLib in the chapter directory, defining the class StringHandler.

namespace StringLib { public class StringHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { string s = ctx.Request["p"]; string op = ctx.Request["op"]; switch (op) { case "echo": ctx.Response.Write("Hello, " + s); break; case "upper": ctx.Response.Write(s.ToUpper()); break; default: ctx.Response.Write( "Illegal operation"); break; } } public bool IsReusable { get { return false; } } } }

Page 108: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 446 All Rights Reserved

Custom Handler Example (Cont’d)

• This handler supports two different operations on strings:

− “echo” will return a greeting “Hello, <p>”, echoing whatever is entered as the p parameter

− “upper” will convert the string in the p parameter to upper case.

• The operation itself is specified by the op parameter.

• The parameters are passed using ordinary parameter notation for GET requests.

• Here is a sample URL: http://localhost/AspCs/Chap13/StringPage/page.str? op=echo&p=Handler

• And here is the corresponding output:

Page 109: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 447 All Rights Reserved

Custom Handler Configuration

• The intricate part of working with custom handlers is not the code but doing the configuration required to make them work.

• Here is a summary of the steps:

1. Make the folder containing the target page an application in IIS.

2. Copy the DLL containing the handler into the bin subdirectory.

3. Add an entry to the Web.config file for our application within the httpHandlers section.

4. Configure IIS to map the desired file extension into aspnet_isapi.dll.

Page 110: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 448 All Rights Reserved

Custom Handler Demonstration

• Let’s illustrate this configuration by wiring up the StringHandler example to run within a folder in the Demos directory.

1. Create a folder StringPage in the Demos directory.

2. Inside this folder create a file page.str with arbitrary text in it.

3. Access this page using Internet Explorer and this URL:

http://localhost/AspCs/Demos/StringPage/page.str You should see the text of the file displayed.

4. Create a bin subfolder. Build the DLL in the StringLib project and copy StringLib.dll into it.

5. Make the StringPage folder an application in IIS.

Page 111: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 449 All Rights Reserved

Entry in Configuration File

6. Create a Web.config file with an appropriate entry for httpHandlers. (You could just copy the file from the StringPage folder in the chapter directory.)

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <httpHandlers> <add verb="GET" path="*.str" type="StringLib.StringHandler, StringLib" /> </httpHandlers> </system.web> </configuration>

− The verb list can be a comma-separated list of HTTP verbs or a wildcard *.

− The path attribute can be either a single URL path or else a path containing a wildcard.

− The type attribute is a comma-separated list class/assembly pair. The ASP.NET runtime searches for the assembly first in the application’s private bin folder and then in the general assembly cache.

Page 112: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 450 All Rights Reserved

Extension Mapping in IIS

7. The final step is to configure the extension in IIS. In Internet Services Manager right-click over Default Web Site and choose Properties. Select the Home Directory tab.

8. Click the Configuration button.

Page 113: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 451 All Rights Reserved

Extension Mapping in IIS (Cont’d)

9. The Application Configuration dialog comes up.

10. Click Add.

Page 114: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 452 All Rights Reserved

Extension Mapping in IIS (Cont’d)

11. The Add/Edit Application Extension Mapping Dialog comes up. Click Browse and find aspnet_isapi.dll in the WINDOWS\Microsoft.NET\Framework directory under a folder for the current version of .NET.

12. Type in the desired extension, in this case .str.

13. Click OK, OK, and OK. The new extension mapping should now be all set up.

14. Now again try to access page.str. Now the result will be different, with output generated by the custom handler.

Page 115: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 453 All Rights Reserved

Custom Handler Demo (Cont’d)

15. Experiment with different parameters, using GET parameter syntax in the URL. Here is “echo” for a person’s name.

16. And here is the “upper” operation.

17. Our small custom handler demonstration is now complete.

Page 116: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 454 All Rights Reserved

.ashx Files

• ASP.NET provides a special extension .ashx that can be used to implement a custom handler without the configuration steps required for a custom extension.

• Such a page requires two features:

− A WebHandler directive with a Class attribute.

− The class identified by the Class attribute must implement the IHttpHandler interface.

• For an example, see the file string.ashx at the top-level of the chapter directory.

− This example implements the same logic as our StringLib custom handler.

− The code is complete in one file, as shown on the following page.

Page 117: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 455 All Rights Reserved

string.ashx

<!-- string.ashx -> <%@ WebHandler Language="C#" Class="StringHandler" %> using System; using System.Web; public class StringHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { string s = ctx.Request["p"]; string op = ctx.Request["op"]; switch (op) { case "echo": ctx.Response.Write("Hello, " + s); break; case "upper": ctx.Response.Write(s.ToUpper()); break; default: ctx.Response.Write("Illegal operation"); break; } } public bool IsReusable { get { return false; } } }

Page 118: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 456 All Rights Reserved

Custom Modules

• The third major extensibility feature of the HTTP pipeline is the module.

− A module is created the first time the application itself is created and exists as long as the application exists.

− A module can hook into any of the HttpApplication events.

− A module is typically used to perform pre- and post-processing on requests (similar to ISAPI filters).

• There are two basic steps to using modules:

− Create a class that implements the IHttpModule interface and copy the DLL to the bin folder of the application using the module.

− Add a <httpModules> section to the configuration file of the application.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <httpModules> <add name="PrePostModule" type="DemoModule.PrePost, DemoModule" /> </httpModules> </system.web> </configuration>

Page 119: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 457 All Rights Reserved

Example: DemoModule

namespace DemoModule { public class PrePost : IHttpModule { public void Init(HttpApplication app) { app.BeginRequest += new EventHandler(app_BeginRequest); app.EndRequest += new EventHandler(app_EndRequest); } public void Dispose() { } private void app_BeginRequest(object sender, EventArgs e) { HttpApplication app = sender as HttpApplication; app.Context.Response.Write("Beginning..."); app.Context.Response.Write("<br>"); } private void app_EndRequest(object sender, EventArgs e) { HttpApplication app = sender as HttpApplication; app.Context.Response.Write("...Ending"); } } }

Page 120: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 458 All Rights Reserved

Using DemoModule

• This custom module can be used with any application simply by copying DemoModule.dll into the bin folder of the application and providing a <httpModules> section of Web.config.

• As a simple example, consider the Greeting application in the chapter directory.

<!-- Greeting.aspx --> <HTML> <BODY> Greetings from ASP.NET<br> </BODY> </HTML>

• The Web.config file is as shown earlier, and the folder Greeting must be configured in IIS as an application.

− It could also be run using the ASP.NET Development server.

• Here is the output.

Page 121: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 459 All Rights Reserved

Lab 13

Custom Handler and Module for Math Operations

In this lab you will create a custom handler for performing simple math operations. In this example, your handler will actually read the target page for input showing the math problems. The output will show the answers. You will also deploy a custom module that displays messages at the beginning of the request (pre-processing) and at the end of the request (post-processing).

Detailed instructions are contained in the Lab 13 write-up at the end of the chapter.

Suggested time: 60 minutes

Page 122: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 460 All Rights Reserved

Summary

• IIS 5.0 routes requests based on their file extensions.

• File extensions recognized by ASP.NET are routed to the ASP.NET worker process, and from there into the HTTP pipeline.

• The HttpContext class keeps all the relevant information about the request together in one place, accessible throughout the pipeline.

• The first customization point in the HTTP pipeline is the HttpApplication class.

• A handler provides the endpoint of a request and is responsible for creating the response that is sent back.

• A module can hook into any of the HttpApplication events and is typically used to perform pre- and post-processing on requests (similar to ISAPI filters).

• You can customize an ASP.NET application by implementing both custom handlers and custom modules.

Page 123: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 461 All Rights Reserved

Lab 13

Custom Handler and Module for Math Operations

Introduction In this lab you will create a custom handler for performing simple math operations. In this example, your handler will actually read the target page for input showing the math problems. The output will show the answers. You will also deploy a custom module that displays messages at the beginning of the request (pre-processing) and at the end of the request (post-processing).

Suggested Time: 60 minutes Root Directory: OIC\AspCs Directories: Labs\Lab13\MathLib (custom handler working directory) Labs\Lab13\MathPage (test pages) Chap13\Math Lib (answer for custom handler) Chap13\MathPage (backup of test pages) Chap13\DemoModule (custom module) Part 1. Create and Wire Skeleton Handler In this part you will create a skeleton handler whose response will be simply the file name of the target file returned in an HTML page. You will do the necessary configuration to wire your handler to the test pages that are supplied, using the .math extension 1. Create a new class library project called MathLib. Change the name of the starter

class to Math, leaving the namespace at MathLib.

2. Add using statements for System.Web and System.IO.

3. Add a reference to the DLL System.Web.dll.

4. Specify that your Math class implements the interface IHttpHandler and add skeletons for the methods of this interface.

5. Implement the IsReusable property by specifying that the handler is not pooled.

6. Implement the ProcessRequest() method to create an HTML page that displays the name of the requested file. You may obtain this file name from the PhysicalPath property of the Request object.

7. Create a bin subfolder of MathPage. This will hold the custom handler (and, later, the custom module).

Page 124: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 462 All Rights Reserved

8. Use IIS to make Lab13\MathPage an application.

9. You are going to be incrementally adding code to the MathLib project. To avoid having to repeatedly copy to the bin folder of MathPage, change the properties of the MathLib project to make the output path ..\MathPage\bin\. Build the project. Verify that a copy of MathLib.dll now resides in Lab13\MathPage\bin.

10. Create a Web.config file that that adds a handler pointing to the MathLib assembly. Allow for any verbs.

11. Use the Internet Services manager to add an extension mapping associating the executable aspnet_isapi.dll with the extension .math.

12. Use your browser to point to this URL:

http://localhost/AspCs/Labs/Lab13/MathPage/problems.math. You should see the physical path of the file problems.math displayed:

C:\OIC\AspCs\Labs\Lab13\MathPage\problems.math 13. Test again with the second file in the MathPage folder, bad.math.

Part 2. Read and Display the Target File In this part you will add code to the ProcessRequest() method to read the target .math file and echo it back in the response. 1. Obtain a StreamReader object by calling the OpenText() method of the File class,

passing in the file name that you have obtained.

2. Use the ReadLine method of StreamReader to read a line from the file.

3. Loop while the line is not null. Write the line to the Response object, followed by <br>, and then read the next line.

4. Build and test, using both problems.math and bad.math as target pages.

Part 3. Do the Math In this part you will add code to perform the actual calculations called for in the target file. For the purpose of this exercise, you may assume the following very simple format for the expressions to be calculated: infix operations with two integer operands and with only the operators +, -, * and /. Examples of good expressions are provided in the file problems.math, and some sample bad data is provided in bad.math. 1. Create a helper method calculate() that takes as input an array of strings and returns a

number or error message as a string.

Page 125: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 463 All Rights Reserved

2. Test that the input array has exactly three elements. If not, return the error string “BAD INPUT.”

3. Initialize an int variable result to 0.

4. Create a try block with a catch handler that will return the error string “BAD INPUT.”

5. Inside the try block convert the first and last strings in the array to integers.

6. Perform a switch on the middle element of the array. Provide a case statement for each of the four basic arithmetic operators. Assign result to the appropriate calculated value.

7. Provide a default for the switch statement that will throw an exception.

8. Return the result converted to a string.

9. In the ProcessRequest() method, provide code to break the input line to three tokens, represented by an array of strings. The following two lines of code will perform this step concisely:

char[] seps = {' '}; string[] tokens = line.Split(seps); 10. Call the calculate() method, passing in the array of three tokens, obtaining a string

value stored in the variable answer.

11. Write the answer to the Response object following the input line with an equal sign.

12. Build and test with both problems.math and bad.math.

Part 4. Hook in a Custom Module In this final part you will hook in a custom module that does simple pre- and post-processing of the input page. 1. If not already done, build the demonstration module project DemoModule.

2. Copy the file DemoModule.dll to the bin subfolder of your MathPage directory.

3. Add a <httpModules> section to your Web.config file to hook in this custom module.

4. Build and test. You should now get the same output as before, except for a “Beginning...” message at the top of the response page and an “...Ending” message at the bottom of the response page.

Page 126: ASP.NET Using C# - ITCourseware › docs › oi-aspcsharp-2.2 › evals › ... · Object Innovations Course 416 Student Guide Revision 2.2 ASP.NET Using C#

AspCs Chapter 13

Rev. 2.2 Copyright © 2006 Object Innovations Enterprises, LLC 464 All Rights Reserved