100
Object Innovations Course 4140 Student Guide Revision 4.0.1 ASP.NET Using C#

ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

  • Upload
    others

  • View
    18

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Object Innovations Course 4140

Student Guide Revision 4.0.1

ASP.NET Using C#

Page 2: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC ii All Rights Reserved

ASP.NET Using C# Rev. 4.0.1 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. Authors: Robert J. Oberg, Arun Ganesh, Srini Manickam Special Thanks: Mark Bueno, Peter Thorsteinson, Sharman Staples, Ernani Cecon Junior, Dave Solum, Daniel Berglund Copyright ©2010 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...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 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 ADO.NET and LINQ Chapter 12 Data Access in ASP.NET 4.0 Chapter 13 Personalization and Security Chapter 14 ASP.NET AJAX Chapter 15 ASP.NET MVC Appendix A Learning Resources Appendix B HTTP Pipeline

Page 4: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 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...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 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 Benefits of ASP.NET.......................................................................................................... 8 ASP.NET Example Program .............................................................................................. 9 An Echo Program.............................................................................................................. 10 ASP.NET Features............................................................................................................ 13 Compiled Code ................................................................................................................. 15 Server Controls ................................................................................................................. 16 Browser Independence...................................................................................................... 17 Separation of Code and Content ....................................................................................... 18 State Management............................................................................................................. 19 Lab 1 ................................................................................................................................. 20 Summary ........................................................................................................................... 21

Chapter 2 Web Forms Architecture ............................................................................... 25 Web Forms Architecture................................................................................................... 27 Code-Behind Version of Echo Example........................................................................... 28 HelloCodebehind.aspx...................................................................................................... 29 HelloCodebehind.aspx.cs.................................................................................................. 30 Page Class ......................................................................................................................... 31 Code-Behind Inheritance Model....................................................................................... 32 Web Forms Page Life Cycle ............................................................................................. 33 View State......................................................................................................................... 36 Enabling View State for Controls ..................................................................................... 37 Web Forms Event Model .................................................................................................. 38 Page Processing ................................................................................................................ 40 Page Events....................................................................................................................... 41 Page Properties ................................................................................................................. 42 Sample Program................................................................................................................ 43 Page Directive................................................................................................................... 47 Tracing .............................................................................................................................. 49 Lab 2 ................................................................................................................................. 51 Summary ........................................................................................................................... 52

Chapter 3 ASP.NET and HTTP ...................................................................................... 55 Classical Web Programming............................................................................................. 57 Active Server Pages Object Model ................................................................................... 58 Request and Response Objects ......................................................................................... 59 Request/Response in ASP.NET........................................................................................ 60 HttpRequest Class............................................................................................................. 61 Properties of HttpRequest ................................................................................................. 62 Using HttpRequest Class .................................................................................................. 63

Page 6: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC vi All Rights Reserved

HTTP Collections ............................................................................................................. 64 HttpResponse Class .......................................................................................................... 66 Redirect ............................................................................................................................. 67 HttpUtility ......................................................................................................................... 68 Echo Program Example .................................................................................................... 69 Echo.aspx .......................................................................................................................... 70 EchoBack.aspx.................................................................................................................. 71 GET and POST Compared................................................................................................ 72 QueryString and Form Collections ................................................................................... 73 Lab 3 ................................................................................................................................. 74 Summary ........................................................................................................................... 75

Chapter 4 Web Applications Using Visual Studio......................................................... 79 Using Visual Studio .......................................................................................................... 81 Visual Web Developer...................................................................................................... 82 Visual Web Developer Demo ........................................................................................... 83 Starter Web Site ................................................................................................................ 84 ASP.NET Empty Web Site ............................................................................................... 85 Adding a Web Form.......................................................................................................... 86 Using Components in ASP.NET....................................................................................... 90 Compilation Error ............................................................................................................. 91 Shadow Copying............................................................................................................... 95 Shadow Copy Demonstration ........................................................................................... 96 Temporary Copy of the Component ................................................................................. 98 ASP.NET Applications ................................................................................................... 100 Global.asax ..................................................................................................................... 101 Web Application Life Cycle ........................................................................................... 102 Application Life Cycle Example .................................................................................... 103 Sample Log File.............................................................................................................. 104 Code in Global.asax........................................................................................................ 105 Log Class ........................................................................................................................ 106 Adding Global.asax File ................................................................................................. 107 ListBox............................................................................................................................ 108 Data Binding ................................................................................................................... 109 Data Binding Code Example .......................................................................................... 110 Items Collection.............................................................................................................. 111 XHTML .......................................................................................................................... 112 XHTML in Visual Studio ............................................................................................... 113 Absolute Positioning....................................................................................................... 114 Lab 4 ............................................................................................................................... 115 Summary ......................................................................................................................... 116

Chapter 5 State Management and Web Applications ................................................. 123 Session and Application State......................................................................................... 126 Example Program............................................................................................................ 127 Session Object................................................................................................................. 128

Page 7: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC vii All Rights Reserved

Page_Load....................................................................................................................... 129 Session Variable Issues................................................................................................... 131 Session State and Cookies .............................................................................................. 132 Session State Timeout..................................................................................................... 133 Session State Store.......................................................................................................... 134 Application State............................................................................................................. 135 Implementing Application State ..................................................................................... 136 Global.asax ..................................................................................................................... 137 Users.aspx.cs................................................................................................................... 138 Multithreading Issues...................................................................................................... 139 Bouncing the Web Server ............................................................................................... 140 Lab 5A ............................................................................................................................ 141 Cookies ........................................................................................................................... 142 Cookies and ASP.NET.................................................................................................... 143 HttpCookie Properties..................................................................................................... 144 Example – Exposing Cookies ......................................................................................... 145 Acme Travel Agency Case Study ................................................................................... 151 State Management Techniques ....................................................................................... 153 Lab 5B............................................................................................................................. 154 Summary ......................................................................................................................... 155

Chapter 6 Server Controls ............................................................................................. 169 Server Controls in ASP.NET .......................................................................................... 171 HTML Server Controls ................................................................................................... 172 Using HTML Server Controls ........................................................................................ 173 HTML vs. Web Forms Server Controls.......................................................................... 174 Server Control Examples ................................................................................................ 175 HTML Controls Example ............................................................................................... 176 Code for Login................................................................................................................ 177 HTML Controls in Visual Studio ................................................................................... 178 Using HTML Controls.................................................................................................... 179 Web Controls .................................................................................................................. 180 Validation Controls......................................................................................................... 181 Required Field Validation............................................................................................... 183 Regular Expression Validation ....................................................................................... 184 Rich Controls .................................................................................................................. 185 Copying a Web Site ........................................................................................................ 186 Lab 6 ............................................................................................................................... 187 User Controls .................................................................................................................. 188 Using a User Control ...................................................................................................... 189 Copyright.ascx ................................................................................................................ 190 Copyright.ascx.cs............................................................................................................ 191 User Control Example..................................................................................................... 192 Summary ......................................................................................................................... 193

Chapter 7 Caching in ASP.NET.................................................................................... 197

Page 8: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC viii All Rights Reserved

Introduction..................................................................................................................... 199 What is Caching? ............................................................................................................ 200 Need for Caching (Why Cache?).................................................................................... 201 Data to be Cached – Time Frame ................................................................................... 202 ASP vs. ASP.NET Response Model............................................................................... 203 Caching in ASP.NET...................................................................................................... 204 Three Types of Caching in ASP.NET............................................................................. 205 Output Caching ............................................................................................................... 206 @ OutputCache Directive............................................................................................... 207 Simple Output Caching Example.................................................................................... 208 @ OutputCache – Attributes in Detail............................................................................ 211 VaryByParam in Detail................................................................................................... 212 HttpCachePolicy Class ................................................................................................... 214 HttpCachePolicy Class – Example ................................................................................. 215 Page Fragment Caching .................................................................................................. 217 Common Mistakes in Using Fragment Caching............................................................. 218 Fragment Caching Example............................................................................................ 219 Data Caching or Application Caching ............................................................................ 220 Add an Item to the Cache Object.................................................................................... 221 Insert and Add Methods.................................................................................................. 222 Application Caching – Example ..................................................................................... 223 Expiration........................................................................................................................ 225 Problems in Caching ....................................................................................................... 226 Lab 7 ............................................................................................................................... 227 Summary ......................................................................................................................... 228

Chapter 8 ASP.NET Configuration and Security Fundamentals .............................. 233 One-minute Introduction to XML! ................................................................................. 235 ASP.NET Configuration - Overview.............................................................................. 236 Multi-level Configuration ............................................................................................... 237 Configuration Hierarchy ................................................................................................. 238 Example of Configuration Hierarchy.............................................................................. 239 Web.Config File Structure .............................................................................................. 240 Web.Config Sections ...................................................................................................... 241 Application Settings........................................................................................................ 242 ASP.NET Security – Overview ...................................................................................... 243 Role-Based Security and CAS........................................................................................ 244 Types and Steps .............................................................................................................. 245 Steps in Enabling Role-Based Security .......................................................................... 246 Three Ways to Authenticate ........................................................................................... 247 Forms Authentication Example ...................................................................................... 248 Forms Authentication – Default.aspx ............................................................................. 250 Forms Authentication – Web.Config.............................................................................. 253 Features of Forms Authentication................................................................................... 254 Authentication Cookie .................................................................................................... 255 Forms Authentication Classes ........................................................................................ 256

Page 9: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC ix All Rights Reserved

Customizing Forms Authentication ................................................................................ 257 Authentication Source..................................................................................................... 258 Forms Authentication – Analysis ................................................................................... 259 Windows Authentication ................................................................................................ 260 Windows Authentication – Analysis .............................................................................. 261 Passport Authentication .................................................................................................. 262 Passport Authentication - Analysis................................................................................. 263 Authorization .................................................................................................................. 264 Lab 8 ............................................................................................................................... 265 Summary ......................................................................................................................... 266

Chapter 9 Debugging, Diagnostics and Error Handling............................................. 273 ASP.NET Diagnostics..................................................................................................... 275 Debugging Using Visual Studio ..................................................................................... 276 Calculator Example......................................................................................................... 277 Debugging Calculator ..................................................................................................... 278 Application-Level Tracing.............................................................................................. 280 Tracing Calculator .......................................................................................................... 281 Using the Page Cache ..................................................................................................... 284 Single Page Example ...................................................................................................... 285 Preparing to Debug ......................................................................................................... 286 Trace Messages............................................................................................................... 287 Tracing the Calculator Page............................................................................................ 288 Conditional Tracing ........................................................................................................ 289 Trace Category................................................................................................................ 290 Trace Warning ................................................................................................................ 291 Exceptions in Trace ........................................................................................................ 292 Errors in ASP.NET ......................................................................................................... 293 Uncaught Exception........................................................................................................ 294 Custom Error Pages ........................................................................................................ 295 Lab 9 ............................................................................................................................... 296 Summary ......................................................................................................................... 297

Chapter 10 More Server Controls................................................................................. 299 ASP.NET Control Improvements ................................................................................... 301 Newer Controls in ASP.NET.......................................................................................... 302 Master Pages ................................................................................................................... 303 Master Page Demonstration............................................................................................ 304 Creating Content Pages................................................................................................... 309 TreeView Control ........................................................................................................... 310 Master Page Application................................................................................................. 311 Lab 10 ............................................................................................................................. 312 Summary ......................................................................................................................... 313

Chapter 11 ADO.NET and LINQ.................................................................................. 319 ADO.NET ....................................................................................................................... 321 ADO.NET Architecture .................................................................................................. 322

Page 10: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC x All Rights Reserved

.NET Data Providers....................................................................................................... 324 ADO.NET Interfaces ...................................................................................................... 325 .NET Namespaces........................................................................................................... 326 Connected Data Access .................................................................................................. 327 AcmePub Database ......................................................................................................... 328 Creating a Connection .................................................................................................... 329 Using Server Explorer .................................................................................................... 330 Performing Queries......................................................................................................... 331 ADO.NET with ASP.NET.............................................................................................. 332 Web Client Isolation ....................................................................................................... 333 Web Client Database Code ............................................................................................. 334 Using Commands............................................................................................................ 336 Creating a Command Object........................................................................................... 337 Using a Data Reader ....................................................................................................... 338 Data Reader: Code Example........................................................................................... 339 Use of Session State........................................................................................................ 340 Generic Collections......................................................................................................... 341 Executing Commands ..................................................................................................... 342 Parameterized Queries .................................................................................................... 343 Parameterized Query Example ....................................................................................... 344 Lab 11A .......................................................................................................................... 345 DataSet............................................................................................................................ 346 DataSet Architecture....................................................................................................... 347 Why DataSet? ................................................................................................................. 348 DataSet Components....................................................................................................... 349 DataAdapter .................................................................................................................... 350 DataSet Example Program.............................................................................................. 351 Data Access Class ........................................................................................................... 352 Retrieving the Data ......................................................................................................... 353 Filling a DataSet ............................................................................................................. 354 Accessing a DataSet........................................................................................................ 355 Using a Standalone DataTable........................................................................................ 356 DataTable Update Example ............................................................................................ 357 Adding a New Row......................................................................................................... 359 Searching and Updating a Row ...................................................................................... 360 Deleting a Row ............................................................................................................... 361 Row Versions.................................................................................................................. 362 Row State ........................................................................................................................ 363 Iterating Through DataRows .......................................................................................... 364 Command Builders ......................................................................................................... 365 Updating a Database ....................................................................................................... 366 Language Integrated Query (LINQ) ............................................................................... 367 Bridging Objects and Data.............................................................................................. 368 LINQ Demo .................................................................................................................... 369 Object Relational Designer ............................................................................................. 370

Page 11: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC xi All Rights Reserved

IntelliSense...................................................................................................................... 372 Basic LINQ Query Operators ......................................................................................... 373 Obtaining a Data Source ................................................................................................. 374 LINQ Query Example..................................................................................................... 375 Filtering........................................................................................................................... 376 Ordering .......................................................................................................................... 377 Aggregation .................................................................................................................... 378 Obtaining Lists and Arrays ............................................................................................. 379 Deferred Execution ......................................................................................................... 380 Modifying a Data Source ................................................................................................ 381 Performing Inserts via LINQ to SQL.............................................................................. 382 Performing Deletes via LINQ to SQL ............................................................................ 383 Performing Updates via LINQ to SQL ........................................................................... 384 Lab 11B........................................................................................................................... 385 Summary ......................................................................................................................... 386

Chapter 12 Data Access in ASP.NET 4.0...................................................................... 397 Data Access in ASP.NET ............................................................................................... 399 Data Access Demonstration............................................................................................ 400 Data Entry Demonstration .............................................................................................. 405 SQL Generation Options ................................................................................................ 406 Enable Edit and Delete ................................................................................................... 407 Editing Records............................................................................................................... 408 GridView Control ........................................................................................................... 409 DetailsView Control ....................................................................................................... 410 Storing the Connection String......................................................................................... 411 Protecting the Configuration String................................................................................ 412 Lab 12A .......................................................................................................................... 413 FormView Control .......................................................................................................... 414 Master/Detail Web Pages................................................................................................ 415 Data Binding ................................................................................................................... 418 Template Editing............................................................................................................. 419 Using XML Data............................................................................................................. 421 Example Program............................................................................................................ 422 XML Data Source Demo ................................................................................................ 423 Multiple-Tier Data Access.............................................................................................. 426 Object Data Source ......................................................................................................... 428 Lab 12B........................................................................................................................... 431 Data Access in ASP.NET 4.0 ......................................................................................... 432 ListView Demonstration................................................................................................. 433 Using the Entity Data Model .......................................................................................... 434 EntityDataSource Control............................................................................................... 437 ListView Edit .................................................................................................................. 440 DataPager Control........................................................................................................... 441 LinqDataSource Control ................................................................................................. 442 Configuring LinqDataSource.......................................................................................... 443

Page 12: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC xii All Rights Reserved

QueryExtender Control................................................................................................... 446 QueryExtender Example................................................................................................. 447 Summary ......................................................................................................................... 448

Chapter 13 Personalization and Security ..................................................................... 457 Themes............................................................................................................................ 459 Control Skins .................................................................................................................. 460 Sample Skin File ............................................................................................................. 461 Applying Themes............................................................................................................ 462 Example of Themes ........................................................................................................ 463 Security in ASP.NET 4.0 ................................................................................................ 465 ASP.NET Membership ................................................................................................... 466 Login Controls ................................................................................................................ 467 Membership Demonstration............................................................................................ 468 Web Site Administration Tool ........................................................................................ 469 Access Rules ................................................................................................................... 471 Login Controls Demo ..................................................................................................... 473 Running the Membership Demo..................................................................................... 474 Lab 13A .......................................................................................................................... 476 Profile Properties ............................................................................................................ 477 Profile Demonstration..................................................................................................... 478 Using ASP.NET Profile Properties................................................................................. 479 Lab 13B........................................................................................................................... 481 Summary ......................................................................................................................... 482

Chapter 14 ASP.NET AJAX.......................................................................................... 493 Desktop Applications...................................................................................................... 495 Web Applications............................................................................................................ 496 Plug-Ins ........................................................................................................................... 497 Client-Side Scripting....................................................................................................... 498 JavaScript Example......................................................................................................... 499 Script Code ..................................................................................................................... 500 JavaScript in ASP.NET................................................................................................... 501 Dynamic Pages................................................................................................................ 502 Efficient Page Redraws................................................................................................... 503 AJAX .............................................................................................................................. 504 Google Maps................................................................................................................... 505 ASP.NET AJAX ............................................................................................................. 506 Partial Page Rendering.................................................................................................... 507 Partial Page Rendering Example .................................................................................... 508 UpdatePanel Control....................................................................................................... 509 AJAX Extensions Controls ............................................................................................. 510 UpdatePanel Demo ......................................................................................................... 511 AJAX Client Library ...................................................................................................... 513 Using the Client Library ................................................................................................. 514 ScriptManager Control ................................................................................................... 515

Page 13: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC xiii All Rights Reserved

Client Library Namespaces............................................................................................. 516 Sys.Debug Tracing.......................................................................................................... 517 Simple Client Library Example ...................................................................................... 518 Document Object Model................................................................................................. 519 JavaScript for Simple Calculator .................................................................................... 520 Using the Client Library ................................................................................................. 521 AJAX Control Toolkit .................................................................................................... 522 ACT Controls in Visual Studio....................................................................................... 523 ACT Sample Web Site.................................................................................................... 524 AjaxControlToolkit.dll ................................................................................................... 525 Registering AjaxControlToolkit.dll ................................................................................ 526 Extender Controls ........................................................................................................... 527 NumericUpDownExtender Control ................................................................................ 528 Lab 14 ............................................................................................................................. 529 Summary ......................................................................................................................... 530

Chapter 15 ASP.NET MVC........................................................................................... 537 Model-View-Controller (MVC) ..................................................................................... 539 What Is ASP.NET MVC? ............................................................................................... 540 Advantages of ASP.NET MVC ...................................................................................... 541 Advantages of Web Forms.............................................................................................. 542 Visual Studio ASP.NET MVC Project ........................................................................... 543 Starter Application.......................................................................................................... 544 Simple App with Controller Only................................................................................... 545 Action Methods and Routing.......................................................................................... 550 Action Method Return Type ........................................................................................... 551 Rendering a View ........................................................................................................... 552 Creating a View in Visual Studio ................................................................................... 553 The View Web Page ....................................................................................................... 554 Passing Data from Controller to View............................................................................ 555 Embedded Scripts ........................................................................................................... 556 Embedded Script Example.............................................................................................. 557 Using a Model................................................................................................................. 558 Controller Using the Model ............................................................................................ 559 View Using the Model .................................................................................................... 560 Strongly-Typed View ..................................................................................................... 561 Strongly-Typed View in Visual Studio .......................................................................... 562 Using Forms.................................................................................................................... 563 HTML Helper Functions ................................................................................................ 564 Displaying Sign In Form................................................................................................. 565 Handling Form Submission ............................................................................................ 566 Model Binding ................................................................................................................ 567 Greet View...................................................................................................................... 568 Input Validation .............................................................................................................. 569 Nullable Type ................................................................................................................. 570 Checking Model Validity................................................................................................ 571

Page 14: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC xiv All Rights Reserved

Validation Summary ....................................................................................................... 572 Lab 15 ............................................................................................................................. 573 Summary ......................................................................................................................... 574

Appendix A Learning Resources................................................................................... 581

Appendix B HTTP Pipeline............................................................................................ 585 Web Applications............................................................................................................ 587 Customizing the HTTP Pipeline ..................................................................................... 588 Customizing Applications............................................................................................... 589 Customizing a Welcome Application ............................................................................. 590 Logger Class ................................................................................................................... 595 Custom Handlers............................................................................................................. 597 IHttpHandler Interface.................................................................................................... 598 Custom Handler Example ............................................................................................... 599 .ashx Files ....................................................................................................................... 601 Custom Modules ............................................................................................................. 602 Example: DemoModule .................................................................................................. 603 Using DemoModule........................................................................................................ 604 Using IIS 7 ...................................................................................................................... 605 Summary ......................................................................................................................... 606

Page 15: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

Introduction to ASP.NET

Page 16: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 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.

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

• 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...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 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...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 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.

• One way to run the examples is to have Internet Information Services (IIS) installed on your system.

− You will have to explicitly install it with Windows 7 and Windows XP.

• 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.

• You may run also run the ASP.NET examples using the built-in ASP.NET Development Server.

− This built-in Web server is started automatically from within Visual Studio 2010 and is discussed in Chapter 4.

Page 19: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 5 All Rights Reserved

IIS Manager

• The figure shows the main window of the Internet Services Manager for IIS 7.5, which comes with Windows 7.

− We have selected the Content View tab at the bottom of the middle pane.

− You can Start and Stop the Web server and perform other

tasks from the Manage Web Site group.

− With Advanced Settings you can change the physical path of the Default Web Site, which by default is located at \inetpub\wwwroot on the drive where Windows is installed.

Page 20: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 6 All Rights Reserved

Virtual Directory

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

− Click Add Virtual Directory1.

− You can enter the desired alias, which will be the name of the virtual directory.

− Browse to the desired physical path and click OK.

• The figure shows creating an alias AspCs for the folder \OIC\AspCs.

− You should perform this operation now on your own system

so that you may follow along as the course examples are discussed.

1 You can also add a virtual directory from the context menu brought up by a right-click over the Default Web Site.

Page 21: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 7 All Rights Reserved

Home Page for ASP.NET Examples

• 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 the course.

Page 22: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 8 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.

• 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 23: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 9 All Rights Reserved

ASP.NET Example Program

• We examine an example, Hello.aspx, in detail.

− The example is complete in one file and contains embedded server code. ASP.NET pages have an .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> <title>Hello</title> <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> </form> </body> </html>

Page 24: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 10 All Rights Reserved

An Echo Program

• 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 25: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 11 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 26: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 12 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 modern browsers, such as Internet Explorer and Firefox.

• 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 27: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 13 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 for Web pages 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.

• ASP.NET MVC is a newer framework that provides an alternative to Web Forms for creating Web applications.

− It is based on the Model-View-Controller design pattern.

− ASP.NET MVC is introduced in the last chapter of this course.

Page 28: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 14 All Rights Reserved

ASP.NET Features (Cont’d)

• ASP.NET also supports Web Services, which 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.

− A newer technology, Windows Communication Foundation, is now preferred for implementing Web services.

• Web Forms, ASP.NET MVC, and ASP.NET Web services can all 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 29: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 15 All Rights Reserved

Compiled Code

• Web Forms can be written in any .NET language that that is compatible with the common language runtime, including C# and Visual Basic.

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

• Compilation normally occurs at HTTP request time, and subsequent accesses to the page do not require compilation.

− The ASP.NET compilation model is described in the next chapter.

• 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 30: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 16 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 31: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 17 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 32: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 18 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 33: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 19 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 34: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 20 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 35: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 21 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 for Web pages, Web Forms and ASP.NET MVC.

• 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 36: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 22 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 (console mortgage calculator) Files: Chap01\Mortgage.aspx (answer) 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.

Page 37: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 23 All Rights Reserved

2. Change the title to “Mortgage Calculator”.

3. 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.

4. 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.

5. 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); 6. 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); 7. Save your file and test it in the browser. Try out the test data obtained from running

the console version of the program.

Page 38: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 1

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 24 All Rights Reserved

Page 39: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 273 All Rights Reserved

Chapter 9

Debugging, Diagnostics and Error Handling

Page 40: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 274 All Rights Reserved

Debugging, Diagnostics and Error Handling

Objectives

After completing this unit you will be able to:

• Debug ASP.NET applications created using Visual Studio.

• Perform tracing at both the application and page level.

• Handle errors in your ASP.NET applications.

Page 41: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 275 All Rights Reserved

ASP.NET Diagnostics

• Debugging ASP applications has been notoriously difficult.

− A primary debugging tool is Response.Write().

• ASP.NET applications can be debugged the same way as other .NET applications and components.

− ASP.NET applications are compiled into executable assemblies, so the same techniques apply.

• Debugging ASP.NET applications using Visual Studio is easy, because any ASP.NET web site can be opened in Visual Studio.

• ASP.NET also provides convenient tracing facilities at both the page and application level.

• Later in the chapter we will also look at error handling in ASP.NET.

Page 42: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 276 All Rights Reserved

Debugging Using Visual Studio

• Applications created using Visual Studio are very easy to debug.

− Build in Debug mode (the default).

− You can then set breakpoints, single-step, use watch windows, and all the other features of the Visual Studio debugger.

Page 43: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 277 All Rights Reserved

Calculator Example

• We will illustrate diagnostics in this chapter with a simple Web calculator program VsCalculator.

− Work with the copy in the Demos folder. The original program is in the chapter folder.

− An initial Add works fine, but if you try Multiply or adding different numbers, the application behaves strangely.

− In the demo on the following page, your results may vary depending on how long it takes you to perform the various steps.

Page 44: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 278 All Rights Reserved

Debugging Calculator

1. Set breakpoints at the first instructions of the handlers for the Add and Multiply buttons.

2. Run under the debugger (Debug | Start or F5 or the toolbar button ). You will see a dialog box asking if you want to enable debugging. Click OK.

Page 45: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 279 All Rights Reserved

Debugging Calculator (Cont’d)

3. Examine the Web.Config file now.

<configuration> <appSettings/> <connectionStrings/> <system.web> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> <compilation debug="true" targetFramework="4.0"> </compilation> <trace enabled="false"/> ... 4. Enter some numbers to add, and click the Add button. You

should hit a breakpoint. Continue (F5 or toolbar button ).

5. Click the Multiply button. You don’t hit the breakpoint!

6. Try adding different numbers. You may see the original numbers brought back! And no breakpoint!

Page 46: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 280 All Rights Reserved

Application-Level Tracing

• In this case, debugging has not revealed the problem.

− We did not hit breakpoints, so we could not do things like inspect the value of the parameters that came in to the server from the client.

• Another diagnostic tool is tracing, which can be enabled at both the application level and page level.

• You enable tracing at the application level by setting trace enabled to true in the Web.config file.

<compilation debug="true" targetFramework="4.0"> </compilation> <trace enabled="true"/> ...

− The default setting will have the output shown directly on the page.

− With the pageOutput setting you can have the output shown directly on the page.

<trace enabled="true" pageOutput="true"/>

Page 47: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 281 All Rights Reserved

Tracing Calculator

1. In the CalculatorVs application enable tracing in the Web.config file as shown on the preceding page.

<trace enabled="true"/> 2. Run the application, not in the debugger.

3. Enter the numbers 5 and 77 and click the Add button.

4. Make the second number 777 and click Add again. You should see the results displayed of the first addition and not the second, and the second number has reverted to 77.

Page 48: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 282 All Rights Reserved

Tracing Calculator (Cont’d)

5. To see the trace, navigate in the browser to the trace.axd URL at the root of the application directory.

6. There is one GET, from the first view of the page, and two POST, one for each time you clicked the Add button.

Page 49: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 283 All Rights Reserved

Tracing Calculator (Cont’d)

7. View the details of the first POST. Look in the Form collection.

8. View the details of the second POST.

9. It is clear that the second number, 777, did reach the server.

Page 50: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 284 All Rights Reserved

Using the Page Cache

• By this time you may have realized what is likely the problem: we have cached this page!

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@OutputCache Duration="15" VaryByParam="none"%> <!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>Web Calculator</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtX" runat="server" Style="z-index: 100; left: 32px; position: absolute; top: 24px" Width="80px"> </asp:TextBox> <asp:TextBox ID="txtY" runat="server" Style="z-index: 101; left: 136px; position: absolute; top: 24px" Width="80px"> </asp:TextBox> ... </div> </form> </body> </html>

Page 51: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 285 All Rights Reserved

Single Page Example

• Let’s look some more at debugging and tracing.

• As an illustration, consider the Default.aspx page in the Calculator folder in this chapter, at the URL:

http://localhost/AspCs/Chap09/Calculator/Default.aspx

− The core logic is complete in one page, with no code-behind.

− This version of the program use flow layout instead of absolute positioning, and there is a Divide button.

Page 52: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 286 All Rights Reserved

Preparing to Debug

• You can enable debugging on a particular page by setting the Debug attribute of the Page directive to true.

<%@ Page Language="C#" Trace="false" Debug="true"%> <html> <head> <title>Calculator</title> <script runat="server"> void cmdAdd_Click(object source, EventArgs e) { Trace.Write("Add called"); int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int z = x + y; txtAnswer.Text = z.ToString(); } ...

• You can enable debugging for an entire application by setting debug to true in the compilation element of the Web.config file.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> ... <compilation defaultLanguage="c#" debug="true" targetFramework="4.0"/> ... </system.web> </configuration>

Page 53: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 287 All Rights Reserved

Trace Messages

• Besides the standard trace output, you may write custom trace messages using the Trace property of the Page class.

• As an example, see the Add handler in our Calculator/Default.aspx page.

... <script runat="server"> void cmdAdd_Click(object source, EventArgs e) { Trace.Write("Add called"); int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); int z = x + y; txtAnswer.Text = z.ToString(); } ...

• To enable tracing on a page, set the Trace attribute of the Page directive to true.

<%@ Page Language="C#" Trace="true" Debug="true" %> ...

Page 54: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 288 All Rights Reserved

Tracing the Calculator Page

• We can then see our custom trace message displayed when we click the Add button.

Page 55: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 289 All Rights Reserved

Conditional Tracing

• You can make the execution of your trace statements conditional on tracing being enabled by testing the IsEnabled property of Trace.

void cmdDivide_Click(object source, EventArgs e) { if (Trace.IsEnabled) Trace.Write("Custom", "Divide called"); ...

− You can verify by placing a breakpoint on the Trace.Write() statement, with debugging enabled and tracing disabled.

• What this means is that you can embed useful trace statements in a production application without concern about output or computation time in the normal case when tracing is disabled.

− When a problem arises, you can then enable tracing to obtain useful diagnostic information.

Page 56: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 290 All Rights Reserved

Trace Category

• An overloaded version of the Trace.Write() method allows you to specify an optional category for the trace message.

if (Trace.IsEnabled) Trace.Write("Custom", "Divide called"); ...

− This category will be displayed in the trace output.

Page 57: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 291 All Rights Reserved

Trace Warning

• The Warn method of Trace will cause the trace output to be displayed in red.

− In our example, we display a warning on an attempt to divide by zero.

try { int x = Convert.ToInt32(txtX.Text); int y = Convert.ToInt32(txtY.Text); if (y == 0) Trace.Warn("Custom", "Attempting divide by zero"); ...

Page 58: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 292 All Rights Reserved

Exceptions in Trace

• You may pass an Exception object as a third parameter in a call to Trace.Write().

catch (Exception ex) { Trace.Write("Custom", "Exception", ex); }

Page 59: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 293 All Rights Reserved

Errors in ASP.NET

• Another benefit to developing Web applications using ASP.NET is the robust exception handling provided in all .NET languages.

− This is in contrast to the weak support for exceptions offered by the scripting languages used with ASP.

• Our sample Calculator page has already illustrated handling exceptions.

• But what happens if an uncaught exception is encountered?

• To see the result, you can throw an exception in our catch handler.

catch (Exception ex) { Trace.Write("Custom", "Exception", ex); throw ex; }

Page 60: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 294 All Rights Reserved

Uncaught Exception

• ASP.NET displays a generic error page for errors, including exceptions that are not caught in application code.

− If we divide by zero in our modified Calculator page, we will see this error page:

Page 61: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 295 All Rights Reserved

Custom Error Pages

• Normally you would not want your users to see the generic error page displayed by ASP.NET.

• You can create custom error pages, which will be displayed as you direct.

− A particular error page can be designated on a page-by-page basis by using the ErrorPage attribute of the Page directive.

<%@ Page Language="C#" Trace="false" Debug="true" ErrorPage="PageError.html" %>

− A default error page can be provided for the entire application by using the customErrors element of the Web.config file.

<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.web> <customErrors defaultRedirect='GeneralError.html' mode='On'> </customErrors> ... </system.web> </configuration>

Page 62: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 296 All Rights Reserved

Lab 9

Error Pages for Calculator Application

In this lab you will create error pages for the Calculator example. The first error page is a general error page that applies to the entire application, and the second error page is specific to Calculator..

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

Suggested time: 30 minutes

Page 63: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 297 All Rights Reserved

Summary

• You can debug ASP.NET applications created using Visual Studio in the same manner as you would debug other .NET applications.

• To perform tracing at the application level, enable tracing in the Web.config file.

• You can enable tracing at the page level with the Trace attribute of the Page directive.

• .NET exceptions provide a robust exception handling mechanism for ASP.NET application.

• You can provide custom error pages to be displayed for uncaught exceptions.

Page 64: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 9

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 298 All Rights Reserved

Lab 9

Error Pages for Calculator Application

Introduction In this lab you will create error pages for the Calculator example. The first error page is a general error page that applies to the entire application, and the second error page is specific to Calculator.

Suggested Time: 30 minutes Root Directory: OIC\AspCs Directories: Labs\Lab9\Error (do your work here) Chap09\Calculator (contains backup of starter page) Chap09\Error (answer) Instructions: 1. Bring up the starter page using Visual Web Developer.

2. Verify that if you try to divide by zero, no exception is thrown (it is caught). If the answer textbox is blank, it will remain blank. Also, verify that you can perform additions and divisions if divisor is not zero.

3. In the catch block, add code to rethrow the Exception object. Display the page again in the browser and observe the generic error page. (Notice that if you do not have debugging turned on for the page, the error page will give a message explaining how you can enable debugging.)

4. Create an HTML page GeneralError.html that displays a simple message saying there was an error, try again. This could be invoked by accessing a bad file name.

5. In Web.config add a customErrors element that will redirect to the general error page you created in the previous step.

6. Test in the browser. Observe that this page will be displayed when you try to divide by zero (and also if you have illegal data in one of the input textboxes.)

7. Create an HTML page PageError.html that displays a different message.

8. Hook this new error page to Default.aspx by using the ErrorPage attribute of the Page directive.

9. Run again in the browser. When there is an input error, you should now see your new error page displayed in place of the original general error page you created

Page 65: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 457 All Rights Reserved

Chapter 13

Personalization and Security

Page 66: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 458 All Rights Reserved

Personalization and Security

Objectives

After completing this unit you will be able to:

• Use themes and skins to customize the look of pages and controls.

• Use the ASP.NET membership system to validate and store user credentials.

• Implement membership in your applications by using the ASP.NET Login control.

• Customize the behavior of your Web application for individual users through the use of profiles.

Page 67: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 459 All Rights Reserved

Themes

• A theme is a collection of property settings that enable you to specify the appearance of pages and controls.

− Using themes you can achieve consistency in look and feel across a Web application or a portion of a Web application.

• You can apply theme settings to:

− An entire Web site

− A page with all its controls

− Individual controls

• You define a theme for your application by a collection of skin files that reside in a subfolder of the App_Themes folder of your application.

− The skin files define settings for individual types of controls.

− The name of the folder containing the skin files is used as the name of the theme.

− An application can have multiple themes, which are used in different parts of the application.

Page 68: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 460 All Rights Reserved

Control Skins

• Control skins (or just skins) specify settings for individual controls such as Button, Label, and so on.

• Typically you will define a control skin for each type of control that you use in an application.

− You set the control properties in the skin so that the controls have a similar look.

• There are two types of control skins:

− A default skin applies to all controls of the same type.

− A named skin has a SkinId property. A named skin is applied to a specific control by the control specifying the SkinId of the skin.

• Skins are defined in files with the extension .skin.

− The name of the file has no significance to the application using the skin. The application only refers to named themes, and to specific SkinIds.

Page 69: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 461 All Rights Reserved

Sample Skin File

• See the Foo.skin file in the YellowTheme folder in the ThemeDemo example program for this chapter.

• This file defines two default skins and one named skin.

<asp:Label runat="server" ForeColor="red" Font-Size="14pt" Font-Names="Verdana" /> <asp:button runat="server" borderstyle="Solid" borderwidth="3px" bordercolor="Red" backcolor="yellow"/> <asp:button runat="server" SkinId="StandardButton"/>

• Note that the properties specified, such as ForeColor, Font-Size, and so on, all pertain to the visual appearance of a control.

• The specific properties that you can set via a theme are defined by the control itself.

− Such properties are called themable.

Page 70: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 462 All Rights Reserved

Applying Themes

• To apply a theme across an entire application, specify the theme in the Web.config file.

<configuration> <system.web> <pages theme="YellowTheme" /> </system.web> </configuration>

• You can also apply a theme to an individual page.

− In the @ Page directive set the Theme attribute to the name of the theme to be used on the page.

− This setting will override a theme that has been set for the whole application.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Theme="GreenTheme" %>

• Finally, you can apply a particular named skin from a theme to an individual control, overriding the page and application themes.

<asp:Button ID="Button3" runat="server" Text="Button" SkinID="StandardButton" />

Page 71: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 463 All Rights Reserved

Example of Themes

• The program ThemeDemo illustrates the use of themes.

• Two themes are defined.

− YellowTheme is applied to the whole application, which consists of three pages.

− GreenTheme is applied to the page Default.aspx.

Page 72: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 464 All Rights Reserved

Example of Themes (Cont’d)

• The application-wide theme YellowTheme applies to AnotherPage.aspx.

• YellowTheme also applies to the page ThirdPage.aspx.

− But on this page, the last control overrides the page theme by using the SkinId of a named skin.

Page 73: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 465 All Rights Reserved

Security in ASP.NET 4.0

• Security is a key consideration in modern Web applications.

• The foundation of security is authentication, which concerns determining the identity of the user or process requesting a service.

− Authentication answers the question: “Who are you?”

− It is achieved by comparing the configured user ID and password with the user provided ID and password.

• There are several authentication mechanisms supported by ASP.NET, but the most important is Forms Authentication.

− It redirects unauthenticated users to a specific URL, which challenges the user to provide credentials.

− If authenticated, the user is issued a token, which is then passed back in the header of every successive request.

• ASP.NET 4.0 greatly facilitates managing authentication through a Membership system.

• A powerful set of Login controls integrates with the Membership system to provide a robust solution for user membership and access control, requiring little or no code for a basic implementation.

Page 74: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 466 All Rights Reserved

ASP.NET Membership

• ASP.NET Membership provides a built-in way to store and validate user credentials.

− A SQL Server database is typically used to store user information.

− ASP.NET Membership integrates with the Login controls for a solution that is extremely easy to use.

• ASP.NET Membership includes facilities to:

− Create new users and passwords

− Store membership information in a SQL Server database or another data store

− Authenticate users who visit the Web site

− Manage passwords, include support for features such as maintaining a password reminder

• The Membership system can also integrate with other parts of ASP.NET, such as User Profile and Web Parts.

Page 75: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 467 All Rights Reserved

Login Controls

• The Membership system provides an API you can code against, but a very robust solution to many practical problems can be achieved with little or no code by employing the built-in Login Controls.

− The CreateUserWizard control collects user information and creates a corresponding account in the Membership system.

− The Login control is used at runtime to authenticate a user who presents a user name and password.

− The LoginStatus control presents a user interface offering the user a means to log in or log out, depending on the user’s status.

− The LoginName control displays the login name of a user who is logged in.

− The LoginView control displays different information depending on whether a user is logged in. Templates are provided for specifying what is to be displayed in each state.

− PasswordRecovery and ChangePassword controls support various features for user password management.

Page 76: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 468 All Rights Reserved

Membership Demonstration

• As with much else in ASP.NET, the best way to understand the capabilities of the Membership system is through a hands-on demo.

− Little or no coding is required, but you must go through a number of operations in Visual Web Developer.

• The MemberDemo program has three basic features:

− A home page Default.aspx that is accessible to anyone.

− A members page Members.aspx that is only accessible to logged in members.

− A login system that manages membership and lets user log in and log out.

1. Use Visual Web Developer to create a new ASP.NET Empty Web Site1 MemberDemo in the Demos directory.

2. Add a new Web Form Default.aspx. Provide a title. Switch to Design View. Enter heading “Home Page” using <H2> style.

3. In Solution Explorer, right-click over your Web site and add a regular folder named MembersOnly.

4. Add a page Members.aspx to this folder, with code in a separate file. Enter <H2> text “Members Page.” Also, provide a hyperlink to the home page.

5. Add a hyperlink on the home page that links to the members page.

1 An ASP.NET Web Site will provide login functionality automatically. In this demo we are adding the functionality ourselves for instructional purposes.

Page 77: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 469 All Rights Reserved

Web Site Administration Tool

6. Set Default.aspx as the Start Page.

7. From Website menu choose ASP.NET Configuration.

8. Click the Security tab.

9. Click on the link “Use the security Setup Wizard to configure security step by step.”

10. Proceed to Step 2 and select “From the Internet.” Click Next.

11. Proceed to Step 5, not changing anything in Steps 3 and 4.

Page 78: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 470 All Rights Reserved

Web Site Admin Tool (Cont’d)

12. Enter “John Doe” for the user and “John&Doe” for the password. (The use of the ampersand and mixed upper and lower case will ensure a “strong” password. It will also be easy to remember for testing purposes!) Enter any data you wish for email address, security question and security answer.2

13. Click Create User, Continue, and then Next.

2 If you have trouble creating a user from within the wizard, you can use the Create User link from the main page of the Security tab.

Page 79: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 471 All Rights Reserved

Access Rules

14. In Step 6, expand the MemberDemo folder and select the MembersOnly folder we created.

15. For “Rule applies to” select Anonymous Users. For “Permssion” select Deny. This rule will prevent users who are not logged in from accessing any pages in the MembersOnly folder.

16. Click Add This Rule and then Finish.

Page 80: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 472 All Rights Reserved

Membership Demonstration (Cont’d)

17. Try running the application at this point. You can bring up the home page OK, but if you click on the link to the members page, you will get an error, because you are not logged in. Note that the error message is not too specific: no gratuitous aid to hackers!

Page 81: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 473 All Rights Reserved

Login Controls Demo

• We will now use several of the Login controls to implement a basic Login mechanism.

1. From the Login group of the Toolbox, drag a LoginStatus control onto your home page. Note that this has two views, one for a Logged Out state and another for a Logged In state.

2. For the Logged Out state a link is provided to a page named Login.aspx. Add such a page to your Web site.

3. Open this new page in Design View, and drag a Login control onto the page.

4. From the Validation group of controls, drag a ValidationSummary control onto the page.

5. Set the ValidationGroup property of this control to Login1, the ID of the Login control.

Page 82: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 474 All Rights Reserved

Running the Membership Demo

1. Now run your application again. The home page is displayed.

2. Click on the Members Page link.

3. You are challenged by the Login page. Enter the valid “John Doe” / “John&Doe” user name and password and click the Log In button.

Page 83: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 475 All Rights Reserved

Membership Demo (Cont’d)

4. Now you will be brought to the Members page.

5. Click the link to the home page. The LoginStatus control now gives you an opportunity to log out.

6. Experiment some more. Try logging out, and then logging in from the home page. Also, try some invalid logins, and see the error messages that are displayed. You are now at Step 1.

Page 84: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 476 All Rights Reserved

Lab 13A

An Enhanced Membership Demo

In this lab you will enhance the Membership Demo program to support some additional features:

• Display additional information for logged in or logged out users.

• Provide a registration page for adding new users.

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

Suggested time: 30 minutes

Page 85: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 477 All Rights Reserved

Profile Properties

• A common requirement for a Web application is to store and utilize information that is unique to a particular user.

− When this user visits the site, she can be presented with a personalized version of the Web site.

• This kind of application personalization requires a number of elements:

− Store the information using a unique user identifier

− Recognize users when they visit again

− Fetch the personalized user information

• The ASP.NET Profile system provides a persistent storage facility and API to support this kind of personalization.

− By default, a SQL Server 2008 database is used. You do not need your own database.

− The system supports storing any data type, both simple and complex.

− Both anonymous and logged-in users can be supported.

Page 86: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 478 All Rights Reserved

Profile Demonstration

• The example program ProfileDemo illustrates the ASP.NET Profile system.

− You can store the user’s country as a string.

− You can store a list of favorite fruits as an ArrayList.

Page 87: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 479 All Rights Reserved

Using ASP.NET Profile Properties

• You specify profile properties in the application’s configuration file.

− Note that you must be using Forms authentication.

− If you want to store properties for anonymous users, you must so indicate in the configuration file.

<system.web> <authentication mode="Forms" /> <anonymousIdentification enabled="true" /> <profile> <properties> <add name="Country" type="System.String" allowAnonymous="true" /> <add name="Fruits" type="System.Collections.ArrayList" allowAnonymous="true" /> </properties> </profile> </system.web>

• You can access the profile properties in a strongly typed manner as properties of the Profile object.

protected void Page_Load(object sender, EventArgs e) { lblCountry.Text = Profile.Country; ShowFavoriteFruits(); }

Page 88: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 480 All Rights Reserved

Using Profile Properties (Cont’d)

• You may also set profile properties by simple assignment.

protected void btnRemember_Click(object sender, EventArgs e) { Profile.Country = Server.HtmlEncode(txtCountry.Text); lblCountry.Text = Profile.Country; }

• You may also work with complex data types, such as collections, as profile properties.

protected void btnAddFruit_Click(object sender, EventArgs e) { String fruit = Server.HtmlEncode(txtFruit.Text); if (Profile.Fruits == null) { Profile.Fruits = new ArrayList(); } Profile.Fruits.Add(fruit); ShowFavoriteFruits(); } private void ShowFavoriteFruits() { ddFruit.DataSource = Profile.Fruits; ddFruit.DataBind(); }

Page 89: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 481 All Rights Reserved

Lab 13B

Concluding Acme Publishing Case Study

In this lab you will conclude the Acme Publishing case study by adding a number of additional features to your application:

• A My Account page for Acme customers

• A membership system so that only registered customers can access the My Account page

• A login system allowing customers to login to the site

• A registration page for adding new customers

• Display of personalized information on the My Account page showing the book categories of interest to the customer.

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

Suggested time: 75 minutes

Page 90: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 482 All Rights Reserved

Summary

• You can use themes and skins to customize the look of pages and controls.

• With the ASP.NET membership system you can validate and store user credentials.

• ASP.NET provides a suite of Login controls that you can use to implement membership in your applications.

• You can customize the behavior of your Web application for individual users through the use of profiles.

Page 91: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 483 All Rights Reserved

Lab 13A

An Enhanced Membership Demo

Introduction In this lab you will enhance the Membership Demo program to support some additional features:

• Display additional information for logged in or logged out users. • Provide a registration page for adding new users.

. Suggested Time: 30 minutes Root Directory: OIC\AspCs Directories: Demos\MemberDemo (continue your work here)

Labs\Lab13A\MemberDemo (alternate work area) Chap13\MemberDemo\Step1 (backup of starter code)

Chap13\MemberDemo\Step2 (answer) Additional Information for Logged In or Logged Out Users 1. If you did not complete the demo, do so now. Alternatively, you may work with the

starter code that is provided. Run your starting application to make sure that the basic member functionality is working.

2. Use Server Explorer to take a peek at the SQL Server database created for you.

Page 92: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 484 All Rights Reserved

3. Open Default.aspx in Design View, and drag a LoginView control onto the page.

4. The Anonymous Template is open. This template lets you provide content that users will see when they are not logged in. Provide the following text: “Please click the Login link to log in. If you don’t have an account, click the Register link.”

5. Now select the LoggedIn Template. Provide this text: “You are logged in.”

6. In Members.aspx provide the static text “Welcome” followed by a LoginName control.

7. Run your application. You should see appropriate messages displayed on the home page, depending on whether you are logged in or not. If you are logged in, you will also see a welcome message in the members page.

Page 93: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 485 All Rights Reserved

Registration Page 1. Add a new page Register.aspx to your project.

2. Provide <H2> style text “Please Register.”

3. Drag a CreateUserWizard control onto your page.

4. In the Properties window, set ContinueDestinationPageUrl to Default.aspx.

5. Drag a ValidationSummary control onto the page, and set the ValidationGroup property to CreateUserWizard1.

6. Add a hyperlink to the home page.

7. On the home page provide a hyperlink to the registration page.

8. Test your enhanced demonstration program. You should now be able to register additional users. You can also use the ASP.NET Website Administration Tool to manage the users you created dynamically.

Page 94: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 486 All Rights Reserved

Lab 13B

Concluding Acme Publishing Case Study

Introduction In this lab you will conclude the Acme Publishing case study by adding a number of additional features to your application:

• A My Account page for Acme customers • A membership system so that only registered customers can access the My

Account page • A login system allowing customers to login to the site • A registration page for adding new customers • Display of personalized information on the My Account page showing the book

categories of interest to the customer . Suggested Time: 75 minutes Root Directory: OIC\AspCs Directories: Labs\Lab13B\AcmePub (work area) Labs\Lab12B\AcmePub (your previous version) CaseStudy\AcmePub\Step3 (backup of starting code) CaseStudy\AcmePub\Step4 (answer) Part 1: My Account Page for Acme Customers In Part 1 you will add a new page, My Account, intended to be used exclusively by Acme customers. A link to this page will be provided in the top menu of the master page. In the preliminary implementation, the new page will be accessible by anyone. 1. If you prefer to work with your own code from Lab 12B, delete the provided starter

code and copy your work from Lab 12B. Otherwise, just use the supplied starter code.

2. Run the application in the work area and verify that the three pages of the application are functioning properly.

3. In Solution Explorer, right-click over your Web site and add a regular folder named Customers.

4. Add a page MyAccount.aspx to this folder, with <H2> text “Welcome” followed by a space. The new page should have code in a separate file and use the master page Site.master.

5. Edit the source of Site.master to provide a new menu item that links to the MyAccount.aspx page.

Page 95: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 487 All Rights Reserved

<asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home"/> <asp:MenuItem NavigateUrl="~/Authors.aspx" Text="Authors"/> <asp:MenuItem NavigateUrl="~/Titles.aspx" Text="Titles"/> <asp:MenuItem NavigateUrl="~/Customers/MyAccount.aspx" Text="My Account"/> 6. Run the application, and observe that now there are four pages that work smoothly

together.

Part 2: A Membership System In Part 2 you will add a membership system to the site, including a login feature. Only logged in customers will be able to access the My Account page. Logged in members will be welcomed by their user name. 1. From the Website menu choose ASP.NET Configuration. Click the Security tab.

2. Click on the link “Select authentication type.” Choose “From the internet” and go back to the previous page.

3. Click on the link “Create user”. Enter “John Doe” for the user and “John&Doe” for the password. Enter any data you wish for email address.

4. Click on the Home tab and then on Security. Click on the link “Create access rules”.

5. Expand the AcmePub folder if necessary and select the Customers folder we created.

6. For “Rule applies to” select Anonymous Users. For “Permission” select Deny. This rule will prevent users who are not logged in from accessing any pages in the Customers folder. Click OK. Close the browser.

7. Try running the application at this point. You can bring up the home page OK, but if you click on the link to the My Account page, you will get an error, because you are not logged in.

Part 3: A Login System In Part 3 you will use several of the Login controls to implement a basic Login mechanism. 1. From the Login group of the Toolbox, drag a LoginStatus control onto your home

page. Note that this has two views, one for a Logged Out state and another for a Logged In state.

2. For the Logged Out state a link is provided to a page named Login.aspx. Add such a page to your Web site. Don’t worry about this new page using a master page.

3. Open this new page, and drag a Login control onto the page.

Page 96: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 488 All Rights Reserved

4. From the Validation group of controls, drag a ValidationSummary control onto the page.

5. Set the ValidationGroup property of this control to Login1, the ID of the Login control.

6. On the MyAccount page, provide a LoginName control to personalize the greeting.

7. Try running the application. Look at the error message when you try to access the MyAccount page. The Login page is expected to be in an Account folder, which had been provided when the Web site was originally created in Visual Studio. We had deleted this folder. Now create an ordinary folder Account and move Login.aspx down into it.

8. Build and run. The basic login mechanism should now be working. Experiment with various legal and illegal user names. (Right now, the only valid user name is “John Doe.”)

Part 4: Registering New Customers In Part 4 you will enhance your program to support some additional features:

• Display additional information for logged in or logged out customers. • Provide a registration page for adding new customers.

1. Open Default., and drag a LoginView control onto the content area of the page.

2. The Anonymous Template is open. This template lets you provide content that users will see when they are not logged in. Provide the following text: “Please click the Login link to log in. If you don’t have an account, click the Register link.”

3. Now select the LoggedIn Template. Provide this text: “You are logged in.”

4. Run your application. You should see appropriate messages displayed on the home page, depending on whether you are logged in or not. If you are logged in, you will also see a personalized welcome message in the My Account page.

5. Add a new page Register.aspx to your project. This should not be based on the master page.

6. Provide <H2> style text “Please Register.”

7. Drag a CreateUserWizard control onto your page.

8. In the Properties window, set ContinueDestinationPageUrl to Default.aspx.

9. Drag a ValidationSummary control onto the page, and set the ValidationGroup property to CreateUserWizard1.

Page 97: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 489 All Rights Reserved

9. On the home page provide a hyperlink to the registration page.

10. Test your enhanced demonstration program. You should now be able to register additional users. You can also use the ASP.NET Website Administration Tool to manage the users you created dynamically.

Part 5: Display Personalized Information In Part 5 you will add a user interface to the My Account page to show the categories of books that the customer is interested in. The customer can update this list, which will be persisted. NOTE: If you have added any categories to the AcmePub database beyond .NET, Java, XML, and Databases, please delete them at this time. You may use the UpdateAcme application from Chapter 11. 1. Add the static text “My areas of interest:” underneath the welcome message of

MyAccount.aspx.

2. Drag a CheckBoxList control onto the page.

3. Configure the Data Source for this control to use AcmePubConnectionString. Configure the Select statement to retrieve data from the Category table, obtaining both the CategoryId and Description columns. Select Description as the data field to be displayed in the CheckBoxList. Select CategoryId as the data field for the value of the CheckBoxList. Set the ID of the CheckBookList control to cbCat.

4. You may run the application at this point. If you log in as John Doe, you should see the following displayed in the content area of the My Account page.

5. Now let’s add code to allow the user to save his interests in a profile object. We don’t care about anonymous users, only logged in users. Provide the following information to the application’s configuration file.

<profile> <properties> <add name="Categories"

Page 98: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 490 All Rights Reserved

type="System.Collections.ArrayList" allowAnonymous="false" /> </properties> </profile> 6. Add a button Update Interests to the My Account page. Make the ID of this button

btnUpdateInterests.

7. Add a label control below the button, with blank text and ID of lblMessage.

8. Add a handler for the Update Interests button. As an initial test implementation, provide code to create an ArrayList that will be populated by the bool Checked values of the items in the CheckBoxList. Show the contents of the ArrayList in the lblMessage control. You will need to import the System.Collections namespace.

protected void btnUpdateInterests_Click(object sender, EventArgs e) { ArrayList cats = new ArrayList(); for (int i = 0; i < cbCat.Items.Count; i++) { cats.Add(cbCat.Items[i].Selected); } string msg = ""; foreach (bool cat in cats) msg += cat.ToString() + " "; lblMessage.Text = msg; } 9. Try running the application. Check some of the categories, and click the button. You

should see output similar to this:

10. Now let’s store the ArrayList in the Profile. Comment out the temporary code to show debugging information in the label control.

protected void btnUpdateInterests_Click(object sender, EventArgs e) { ... //lblMessage.Text = msg; Profile.Categories = cats;

Page 99: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 491 All Rights Reserved

11. Create a helper method to display the categories from the Profile in the

CheckBoxList. See the code for ShowCategories() below.

12. Add code to Page_Load() to bind the data controls (the CheckBoxList) and to show the categories as stored in the Profile. See the code below.

13. Run your application. Perform experiments with various users expressing their interests.

private void ShowCategories() { if (Profile.Categories == null || Profile.Categories.Count == 0) return; for (int i = 0; i < cbCat.Items.Count; i++) { cbCat.Items[i].Selected = (bool) Profile.Categories[i]; } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataBind(); ShowCategories(); } }

Page 100: ASP.NET Using C# - ITCourseware...2010/07/14  · ASP.NET Using C# - ITCourseware ... This

AspCs Chapter 13

Rev. 4.0.1 Copyright © 2010 Object Innovations Enterprises, LLC 492 All Rights Reserved