1 10264AD ENU TrainerHandbook Vol1

March 25, 2017 | Author: Ryan Fisher | Category: N/A
Share Embed Donate


Short Description

Download 1 10264AD ENU TrainerHandbook Vol1...

Description

O F F I C I A L

M I C R O S O F T

10264A

L E A R N I N G

P R O D U C T

Developing Web Applications with Microsoft® Visual Studio® 2010

Volume 1

ii

Developing Web Applications with Microsoft® Visual Studio® 2010

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein. © 2010 Microsoft Corporation. All rights reserved. Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are property of their respective owners.

Product Number: 10264A Part Number: X17-47398 Released: 11/2010

Programming in Visual Basic with Microsoft® Visual Studio® 2010

iii

iv

Programming in Visual Basic with Microsoft® Visual Studio® 2010

Programming in Visual Basic with Microsoft® Visual Studio® 2010

v

vi

Programming in Visual Basic with Microsoft® Visual Studio® 2010

Programming in Visual Basic with Microsoft® Visual Studio® 2010

vii

viii

Programming in Visual Basic with Microsoft® Visual Studio® 2010

Developing Web Applications with Microsoft® Visual Studio® 2010

ix

x

Developing Web Applications with Microsoft® Visual Studio® 2010

Acknowledgements Microsoft Learning would like to acknowledge and thank the following for their contribution towards developing this title. Their effort at various stages in the development has ensured that you have a good classroom experience.

Carsten Thomsen—Subject Matter Expert Carsten Thomsen is an independent consultant who has worked since 1990 as a software developer, analyst, architect, and author. He holds a number of Microsoft certifications, including MCTS and MCPD, in various tools and applications, including the Microsoft® .NET Framework, Microsoft Visual Basic®, Microsoft Visual C#®, and Microsoft Office SharePoint® Server 2007. He works with architecture, research, analysis, development, and troubleshooting, and spends countless hours with the Windows® operating system and many other Microsoft server products, including Hyper-V™ and SQL Server®.

Jeff Washburn—Subject Matter Expert Jeff Washburn is a Director of Microsoft Solutions for Sogeti USA. He specializes in architecting and building enterprise applications for some of the world’s largest international corporations. Jeff has been a Microsoft Certified Trainer and has developed and taught Microsoft curriculum for the last 12 years. In his free time, Jeff is an ice hockey referee and enjoys long distance motorcycling.

Toi Wright—Subject Matter Expert Toi is an independent consultant who has worked as a software developer for over 25 years. She has a Bachelor of Science degree in Computer Science and Engineering from the Massachusetts Institute of Technology, and a Master of Business Administration degree from Carnegie Mellon University. She has been a Microsoft MVP in ASP and ASP.NET since 2005. Toi is responsible for creating a national initiative for Microsoft, and its partners in starting We Are Microsoft, (www.wearemicrosoft.com), a community based partnership between IT professionals and local non-profits. She has been a leader and organizer of technical user groups in the Dallas, Texas area for over 10 years. She is currently the President of the Dallas ASP.Net User Group, www.dallasasp.net. She is the founder of Geeks in Pink, www.geeksinpink.org.

Tiberiu Covaci—ASP.NET: Developer and Trainer Tibi started his developer career in 1991, and since 1995 has worked with different Microsoft technologies and platforms. Since 2004, he has been working as an independent trainer, teaching Microsoft Official Curriculum classes, on all levels for .NET programming.

Developing Web Applications with Microsoft® Visual Studio® 2010

Contents Module 1: Overview of Web Application Architecture and Design Lesson 1: Overview of IIS 7.0

1-3

Lesson 2: Overview of ASP.NET 4.0

1-15

Lesson 3: Introduction to the MVC Framework

1-19

Lesson 4: Overview of the Request Life Cycle

1-23

Lab 1: Adventure Works Website Review

1-28

Module 2: Designing a Web Application Lesson 1: Web Applications: Case Studies

2-3

Lesson 2: Web Application Design Essentials

2-9

Lesson 3: Visual Studio 2010 Tools and Technologies for Web Application Design

2-19

Lab 2: Redesigning the Adventure Works Website

2-24

Module 3: Developing MVC Models Lesson 1: Exploring Ways to Create MVC Models

3-3

Lesson 2: Working with Data in MVC Models

3-10

Lesson 3: Creating a Data Repository

3-16

Lab 3: Creating MVC Models

3-30

Module 4: Developing MVC Controllers Lesson 1: Implementing MVC Controllers

4-3

Lesson 2: Creating Action Methods

4-13

Lab 4: Developing MVC Controllers

4-29

Module 5: Developing MVC Views Lesson 1: Implementing MVC Views

5-3

Lesson 2: Implementing Strongly-Typed MVC Views

5-14

Lesson 3: Implementing Partial MVC Views

5-28

Lab 5: Developing MVC Views

5-35

Module 6: Designing for Discoverability Lesson 1: Search Engine Optimization

6-3

Lesson 2: Discoverability Files

6-12

Lesson 3: Using ASP.NET Routing

6-22

Lab 6: Designing for Discoverability

6-43

Module 7: Writing Server-Side Code for Web Forms Lesson 1: Overview of the Structure of a Web Application Lesson 2: Controlling View State

7-3 7-10

xi

xii

Developing Web Applications with Microsoft® Visual Studio® 2010

Lesson 3: Localizing a Web Application

7-16

Lesson 4: Persisting Data on a Web Forms Page

7-27

Lesson 5: Validating User Input

7-33

Lab 7: Writing Server-Side Code for Web Forms

7-42

Module 8: Optimizing Data Management for Web Forms Lesson 1: Managing Data by Using LINQ to Entities

8-3

Lesson 2: Using Data Source Controls

8-18

Lesson 3: Using ASP.NET Dynamic Data

8-61

Lab 8A: Optimizing Data Management for Web Forms

8-37

Lab 8B: Optimizing Data Management for Web Forms

8-77

Module 9: Ensuring Quality by Debugging, Unit Testing, and Refactoring Lesson 1: Debugging and Refactoring Code Lesson 2: Unit Testing Code

9-3 9-22

Lesson 3: Processing Unhandled Exceptions

9-30

Lesson 4: Test-Driven Development

9-37

Lab 9: Debugging, Unit Testing and Refactoring

9-43

About This Course

xiii

About This Course This section provides you with a brief description of the course, audience, suggested prerequisites, and course objectives.

Course Description In this 5-day course, experienced web developers who know the basics of Web Forms development gain more advanced ASP.NET Web Forms and ASP.NET MVC design and development skills. Learning the MVC models and improving web application performance through server-side and client-side programming are the primary focus of this training.

Audience This audience includes professional web developers who use Microsoft® Visual Studio® in a team-based, medium to large-sized development environment. Members of the audience have a minimum of two to three years of experience developing web-based applications by using Microsoft Visual Studio and Microsoft ASP.NET. Members of the audience are experienced users of Microsoft Visual Studio 2008 SP1 and newer releases of the Visual Studio product. The audience understands how to use the new features of Visual Studio 2010. Members of the audience should have a minimum of 3 months of experience completing the following web development tasks: •

Identify the components of a simple ASP.NET 3.5 web application project



Create (start) a new ASP.NET web application project



Add a server control to a Web Form



Configure the basic properties of a server control



Build (compile) an ASP.NET Web Forms application



Deploy an ASP.NET Web Forms application



Add a new Web Form to an ASP.NET Web Forms application



Add and configure server controls in the new Web Form



Implement code-behind pages in a Web Forms application



Create event procedures for ASP.NET server controls



Handle Page events in a Web Forms application



Debug a web application to view run-time information



Debug a web application remotely



Enable and implement tracing a web application



Add validation controls to a Web Form and configure the validation controls



Add validation summary



Add appropriate error messages for the validation controls



Add and apply a new master page



Convert an existing Web Form to a content page



Connect to a Microsoft SQL Server® database by using the SqlDataSource control

xiv

About This Course



Bind a user control to the data source



Modify the source database and verify the changes



Load data from an XML file by using LINQ to XML



Save data to the database by using LINQ to SQL



Display data from the database by using LINQ to SQL



Register LINQ to SQL with Dynamic Data



Build a Dynamic Data web page



Test the Dynamic Data web page



Implement partial-page updates using ASP.NET Ajax



Display progress when updating a page with partial-rendering



Reuse existing functionality exposed by using XML Web Services



Create a web reference proxy for an XML web service



Call Web Service method from a Web Form by using the web reference proxy



Examine how ViewState helps to maintain server control state



Create an Application variable and use it maintain state



Configure an ASP.NET web application by using the Web.config file



Publish a Microsoft ASP.NET web application to a website



Implement Windows and Forms authentication



Implement File and URL authorization

Student Prerequisites In addition to their professional web development experience, students who attend this training should have the following technical knowledge: •

An understanding of the problem-solving techniques that apply to software development, including the following principles of software development: •

Modern software development models



Typical phases of a software development life cycle



Concepts of event-driven programming



Concepts of object-oriented programming



Creating use-case diagrams



Designing and building a user interface



Developing a structured application



A basic understanding of web, macro, and Windows® scripting techniques, and some hands-on experience writing scripts.



A general understanding of the purpose, function, and features of the following .NET Framework topics: •

Common Language Runtime (CLR)



.NET Framework class library

About This Course









Common Type System



Component interoperation



Cross-Language interoperability



Assemblies in the CLR



Application domains



Run-time hosts supported by the .NET Framework

xv

Experience using Visual Studio 2008 or Visual Studio 2010 in the following task areas: •

Declaring and initializing typed variables using the “CamelCase” naming convention



Using arithmetic, relational, and logical operators in code statements



Using branching statements to control code execution



Using looping statements to iterate through collections or repeat steps until a specified condition is met



Creating classes and methods to establish the basic structure of an application



Using methods and events to implement the programming logic of an application



Identifying syntax and logic errors



Accessing and managing data from a data source

Experience in object-oriented design and development as follows: •

Creating and accessing classes and class properties



Creating and accessing methods and overloaded methods



Implementing inheritance, base classes, and abstract classes



Declaring, raising, and handling events



Responding to and throwing exceptions



Implementing interfaces and polymorphism



Implementing shared and static members



Implementing generics



Creating components and class libraries

Experience in N-Tier application design and development as follows: •

Managing a software development process



Controlling input at the user interface level in Windows client and web applications



Debugging, tracing, and profiling .NET applications



Monitoring and logging .NET applications



Implementing basic testing best practices



Performing basic Data Access tasks with LINQ •

Basics of LINQ to XML



Basics of LINQ to Entities



Basics of LINQ to SQL

xvi

About This Course





Implementing basic security best practices in .NET applications • Basics of Code Access Security (CAS) •

Basics of Role-based security



Basics of Cryptography Services

Implementing basic service calls • Basics of creating and consuming XML Web Services •

Basics of creating and consuming WCF Services



Using .NET configuration files



Deploying .NET Framework applications using ClickOnce and the MS Installer

Course Objectives After completing this course, students will be able to: •

Describe the underlying architecture and design of a web application.



Apply best practices and make appropriate trade-offs based on business requirements when designing a web application.



Develop MVC models, controllers, and views.



Optimize the design of a web application for discoverability by search engines.



Write server-side code for Web Forms.



Optimize data management for Web Forms.



Ensure quality by debugging, unit testing, and refactoring.



Secure a web application.



Apply Master pages and CSS for a consistent application user interface (UI).



Develop client-side scripts and services for a responsive, rich, and interactive UI.



Implement advanced Ajax in a web application.



Deploy a web application.

Course Outline This section provides an outline of the course: Module 1, “Overview of Web Application Architecture and Design,” explains the underlying architecture and design of a web application. Module 2, “Designing a Web Application,” explains the best practices and trade-offs that you need to make when designing a web application. Module 3, “Developing MVC Models,” explains the MVC development model (Models, Controllers, and Views), and how to create the models that are used to access and modify the data in a data source. Module 4, “Developing MVC Controllers,” explains how to create the controllers that are used to respond to communications from the user, and to implement the application flow and logic. Module 5, “Developing MVC Views,” explains how to create the views that are used to expose the application UI. Students will also learn to manage pre-action and post-action behavior of controller action methods using the included action filters provided as part of MVC.

About This Course

xvii

Module 6, “Designing for Discoverability,” explains how to optimize the design of a website for discoverability by search engines. Module 7, “Writing Server-Side Code for Web Forms,” explains the advanced features of server side coding and technologies. Module 8, “Optimizing Data Management for Web Forms,” explains some of the ways to optimize and display data management tasks for a Web Forms-based application using Dynamic Data, Data Binding, Linq To Entities, server-side controls, and server-side code. Module 9, “Ensuring Quality by Debugging, Unit Testing, and Refactoring,” explains how to perform check-in testing for Web Forms and MVC applications, as well as how to use the built-in debugging capabilities of Visual Studio 2010. Module 10, “Securing a Web Application,” explains how to mitigate common security threats and implement the essentials of web security in both MVC and Web Forms applications. Module 11, “Applying Master Pages and CSS,” explains how to apply master pages and CSS for a consistent application UI. Module 12, “Developing Client-side Scripts and Services,” explains how to develop client-side scripts and services for a responsive, rich, and interactive application UI. Module 13, “Implementing Advanced Ajax in a Web Application,” explains how to add a rich user experience to web applications using the Microsoft Ajax Library and the jQuery JavaScript Library. Module 14, “ASP.NET Deployments,” explains how to plan, configure, and perform deployment tasks associated with a production website. Students will also learn about the website life cycle as it pertains to deployment. Module 15, “Developing a Web Application by Using Silverlight,” introduces students to Silverlight by having them integrate a Silverlight module into an existing ASP.NET application.

xviii

About This Course

Course Materials The following materials are included with your kit: •

Course Handbook A succinct classroom learning guide that provides all the critical technical information in a crisp, tightly-focused format, which is just right for an effective in-class learning experience. •

Lessons: Guide you through the learning objectives and provide the key points that are critical to the success of the in-class learning experience.



Labs: Provide a real-world, hands-on platform for you to apply the knowledge and skills learned in the module.



Module Reviews and Takeaways: Provide improved on-the-job reference material to boost knowledge and skills retention.



Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips when it’s needed.

Course Companion Content on the http://www.microsoft.com/learning/companionmoc/ Site: Searchable, easy-to-navigate digital content with integrated premium on-line resources designed to supplement the Course Handbook. •



Modules: Include companion content, such as questions and answers, detailed demo steps and additional reading links, for each lesson. Additionally, they include Lab Review questions and answers and Module Reviews and Takeaways sections, which contain the review questions and answers, best practices, common issues and troubleshooting tips with answers, and real-world issues and scenarios with answers. Resources: Include well-categorized additional resources that give you immediate access to the most up-to-date premium content on TechNet, MSDN®, Microsoft Press®

Student Course files on the http://www.microsoft.com/learning/companionmoc/ Site: Includes the Allfiles.exe, a self-extracting executable file that contains all the files required for the labs and demonstrations. •

Course evaluation At the end of the course, you will have the opportunity to complete an online evaluation to provide feedback on the course, training facility, and instructor. •

To provide additional comments or feedback on the course, send e-mail to [email protected]. To inquire about the Microsoft Certification Program, send e-mail to [email protected].

About This Course

xix

Virtual Machine Environment This section provides the information for setting up the classroom environment to support the business scenario of the course.

Virtual Machine Configuration In this course, you will use Microsoft Hyper-V™ to perform the labs. The following table shows the role of each virtual machine used in this course. Virtual machine

Role

10264A-GEN-DEV

Stand-alone machine

Software Configuration The following software is installed on each virtual machine: •

Visual Studio 2010 Ultimate (including .NET Framework 4.0)



Microsoft Silverlight 4



Microsoft Silverlight 4 Tools for Visual Studio 2010



Windows Internet Explorer® 8



Microsoft SQL Server 2008 R2 Express



Microsoft SQL Server 2008 R2 Management Studio Express



IIS Search Engine Optimization (SEO) Toolkit

Course Files There are files associated with the labs in this course. The lab files are located in the folder on the student computers.

Classroom Setup Each classroom computer will have the same virtual machine configured in the same way.

Course Hardware Level To ensure a satisfactory student experience, Microsoft Learning requires a minimum equipment configuration for trainer and student computers in all Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which Official Microsoft Learning Product courseware are taught.

xx

About This Course

Overview of Web Application Architecture and Design

Module 1 Overview of Web Application Architecture and Design Contents: Lesson 1: Overview of IIS 7.0

1-3

Lesson 2: Overview of ASP.NET 4.0

1-15

Lesson 3: Introduction to the MVC Framework

1-19

Lesson 4: Overview of the Request Life Cycle

1-23

Lab 1: Exploring the Adventure Works Website

1-28

1-1

1-2

Developing Web Applications with Microsoft® Visual Studio® 2010

Module Overview

An understanding of how the technology that runs your web application handles requests and returns content to your users is important when determining your web application’s architecture and design. Understanding how web applications function will also assist you in supporting your application once it is completed and released to your user community. This module will introduce you to the key concepts of building web applications in .NET Framework 4.0. After completing this module, you will become familiar with the life cycle of events that occur when a request is made in both Web Forms and MVC. You will also learn how you can work with the life cycle of events to manipulate the content that is displayed to your users.

Overview of Web Application Architecture and Design

1-3

Lesson 1

Overview of IIS 7.0

Internet Information Services (IIS) 7.0 is the engine that runs your ASP.NET Web Forms and MVC applications. Understanding how IIS 7.0 works will help you support and deliver your applications to your users when they are released.

Lesson Objectives: •

Describe the key features of IIS 7.0.



Describe the underlying architecture of IIS 7.0.



Administer a website by using IIS Manager.

1-4

Developing Web Applications with Microsoft® Visual Studio® 2010

Key Features of IIS 7.0

IIS 7.0 is a modern, flexible, and secure web server designed to meet any hosting need that you may have to deliver content to the web. IIS is built on a modular architecture that allows you to implement features and functionality that you need, and turn off what you do not need. Following are some key features of IIS 7.0.

Modular Architecture IIS 7.0 is built upon new architecture that is different from previous versions of IIS. Rather than including the core functionality in the server itself, IIS 7.0 is built upon a web server engine to which you can add or remove components, called modules, depending on your needs. Modules are individual features that the server uses to process requests. For example, IIS uses configuration modules to access application configuration files and cache modules to manage cache activity.

New Configuration Store IIS 7.0 uses a new configuration store that replaces the metabase model in IIS 6. The new configuration store will be familiar to developers used to the .NET XML-based .config format. IIS 7.0 uses a central configuration file named applicationHost.config located in %WINDIR%\System32\InetSrv\Config\. The file applicationHost.config contains global settings for each of the modules in IIS 7.0. Any property set in this file applies to all sites hosted by IIS. In addition to the central file, web.config files can appear at any level of a hosted site or web application’s hierarchy that can override the global settings in the central file for the applicable scope of the web.config file (site, application, and directory).

Management IIS Manager allows you to manage each site and web application that IIS is hosting on a local or remote machine. IIS Manager separates the management of your hosted sites and applications following the

Overview of Web Application Architecture and Design

1-5

modular nature of IIS 7.0. When you open IIS Manager, you will see your options separated by domain, such as ASP.NET, IIS, and Management. The management options are accessible by icons that represent the features that you can manage, such as Authentication, Logging, and Output Caching. The IIS Manager for IIS 7.0 follows the modular architecture by breaking up features into distinct modules that can be managed separately. Question: Which benefits are offered by the modular IIS architecture? Name at least one.

1-6

Developing Web Applications with Microsoft® Visual Studio® 2010

Architecture of ASP.NET on IIS 7.0

IIS 7.0 employs a new modular architecture that is very different from previous versions of IIS. The core modules are categorized according to the functionality for which they are responsible. The preceding illustration shows some of IIS’s core modules and their responsibilities, such as Security and Management. Gaining a deeper understanding of IIS’s core modules and its modular architecture will allow you to take advantage of built-in features that do not need to be created in your web application. Each module concerns itself with a specific piece of functionality. As an example, the Basic Authentication Module performs basic forms authentication. The categories by which these modules are grouped in the illustration make up the core functionality of IIS.

Security Includes all modules that are concerned with authentication, authorization, and securing resources.

Application Development Includes all modules that are concerned with processing custom-developed application logic, such as ASP.NET.

Health and Diagnostics Includes all modules that are concerned with monitoring the health and state of the server. Its applications are grouped as Health and Diagnostics.

FTP Publishing Includes all modules that are concerned with FTP transmission and publishing.

Performance Includes all modules that are concerned with increasing performance, such as compression.

Overview of Web Application Architecture and Design

1-7

Management Includes all modules that provide administration and management functionality.

Common HTTP Web Server Components Includes all modules that provide HTTP request and response processing.

Windows Process Activation Service (WAS) Includes all modules that provide Windows Process Activation Service (WAS) functionality. WAS allows IIS to serve non-HTTP or non-HTTPS requests.

1-8

Developing Web Applications with Microsoft® Visual Studio® 2010

ASP.NET Enhancements for IIS 7.0

In IIS 7.0, ASP.NET integration is significantly improved. IIS 7.0 enhances existing applications and allows new applications to take advantage of ASP.NET features in a variety of new ways.

All Content Types Supported In the past, ASP.NET functionality such as Forms authentication, roles, URL authorization, and output caching were only available to ASP.NET content types such as ASPX pages. Static files, classic ASP pages, and other content types could not benefit from these services. In IIS 7.0, all ASP.NET services are provided uniformly to all content. For example, you can protect all of your web content, including images and classic ASP pages, with your existing ASP.NET access control solution built on ASP.NET Forms authentication, membership, and login controls.

Fully Extend IIS with ASP.NET Previous versions of IIS frequently required server extensibility to be developed by using the native ISAPI filter or extension extensibility mode, due to the runtime limitations of ASP.NET. IIS 7.0 allows ASP.NET modules to plug in directly to the server pipeline, with the same runtime fidelity as modules developed with the native (C++) server API. ASP.NET modules can execute in all run-time stages of the request-processing pipeline, and can execute in any order with respect to native modules. The ASP.NET API is also expanded to allow more control over request processing than was previously possible.

Unified Server Runtime Tighter ASP.NET integration also unifies many of the features between IIS 7.0 and ASP.NET. IIS 7.0 provides a unified configuration for IIS and ASP.NET modules and handlers. Many other features, including custom errors and tracing, have been unified to allow better management and cohesive application design.

Overview of Web Application Architecture and Design

1-9

Demonstration: Administering IIS 7.0 by Using IIS Manager

This demonstration will illustrate the many features of IIS, and show how to administer its functions. These features include: •

Creating a new website



Authentication



Permissions



Connection strings



Application settings



Starting and stopping a site



Recycling the Application pool

Create a New Website 1.

On the Start menu, point to Administrative Tools, right-click Internet Information Services (IIS) Manager, and then click Run as administrator. •

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then click Yes.

2.

In Internet Information Services (IIS) Manager, expand 10264A-GEN-DEV (10264A-GENDEV\Admin), and then expand Sites.

3.

Right-click Sites, and then click Add Web Site.

1-10

Developing Web Applications with Microsoft® Visual Studio® 2010

4.

In the Add Web Site dialog box, specify the settings as shown in the following sample. You will need to create the demo subfolder in the C:\inetpub\ folder.

5.

Click OK.

Change Authentication 1.

In the Connections pane, click Demo.

2.

In the Demo Home pane, in the IIS section, double-click Authentication.

3.

In the Authentication pane, right-click Basic Authentication, and then click Enable.

Overview of Web Application Architecture and Design

1-11

Edit Permissions 1.

In the Connections pane, click Demo.

2.

In the Actions pane, click Edit Permissions.

3.

In the demo Properties dialog box, click Security.

4.

Click Edit.

5.

In the Permissions for demo dialog box, click Add.

6.

In the Select Users or Groups dialog box, in the Enter the object names to select box, type IIS_IUSRS, click Check Names, and then click OK.

7.

In the Permissions for demo dialog box, click OK.

8.

In the demo Properties dialog box, click OK.

Set Connection String 1.

In the Connections pane, click Default Web Site, and then click Demo.

2.

In the Demo Home pane, in the ASP.NET section, double-click Connection Strings.

3.

In the Actions pane, click Add.

4.

In the Add Connection String dialog box, specify the settings as shown in the following illustration.

1-12

Developing Web Applications with Microsoft® Visual Studio® 2010

5.

Click OK.

6.

In the Connection Strings pane, click Content View.

7.

In the Demo Content pane, click web.config.

Note: A web.config file is added to the website’s root directory. 8.

In the Connections pane, right-click Demo, and then click Explore.

9.

In Windows Explorer, double-click web.config.

Note: In Microsoft® Visual Studio® 2010, you can see the new connection string added to the web.config file. 10. Close Microsoft Visual Studio 2010. 11. Close Windows Explorer.

Specify Application Settings 1.

In the Connections pane, click Default Web Site, and then click Demo.

2.

In the Demo Content pane, click Features View.

3.

In the Demo Home pane, in the ASP.NET section, double-click Application Settings..

Overview of Web Application Architecture and Design

4.

In the Actions pane, click Add.

5.

In the Add Application Setting dialog box, specify the settings per the following.

6. 7.

Click OK. In Windows Explorer, double-click web.config.

1-13

Note: In Microsoft Visual Studio 2010, you can see the new application setting added to the web.config file. 8.

Close Microsoft Visual Studio 2010.

9.

Close Windows Explorer.

Restart the Website 1.

In the Connections pane, click Default Web Site, and then click Demo.

2.

In Actions pane, in the Manage Web Site section, click Restart.

Recycle an Application Pool 1.

In the Connections pane, click Application Pools.

1-14

Developing Web Applications with Microsoft® Visual Studio® 2010

2.

In the Application Pools pane, click DefaultAppPool, and then in the Actions pane, in the Application Pool Tasks section, click Recycle.

3.

Close Internet Information Services (IIS) Manager.

Overview of Web Application Architecture and Design

1-15

Lesson 2

Overview of ASP.NET 4.0

ASP.NET 4.0 is the latest .NET framework for building web applications. The features of ASP.NET 4.0 allow you to quickly create compelling web applications that perform and scale to meet the demands of your users.

1-16

Developing Web Applications with Microsoft® Visual Studio® 2010

ASP.NET 4.0 Architecture

ASP.NET is an engine for processing web requests from beginning to end, and is much more than just Web Forms, Web/WCF Services, and MVC. ASP.NET is a web request-processing engine. Incoming requests are processed and pass through an internal pipeline to an endpoint, where you, as the developer, can attach logic to process the request further.

ASP.NET Components Caching ASP.NET provides two different kinds of caching: output and application data caching. Output caching stores dynamic page and control content for quick responses without having to process the response dynamically. Application data caching allows you to programmatically store arbitrary objects such as data sets in server memory so that an application can access the object without having to hit the data store.

Pages Pages refer to Web Forms pages. This provides the functionality necessary to process Web Forms.

Profile ASP.NET Profiles give you the ability to provide profile functionality to your users. Profiles allow you to store user metadata in your application. Typical uses of Profiles would be to store the full name, address, and other pertinent information that can be attached to a user.

Intrinsic Objects Intrinsic objects are objects that are automatically created and attached to core objects used in processing requests to ASP.NET resources. An example of an Intrinsic Object is the Request object, which is defined as a property of the HttpContext object.

Overview of Web Application Architecture and Design

1-17

Modules ASP.NET Modules are components that implement and plug themselves into the ASP.NET requestprocessing pipeline by registering for certain events. When the event occurs, ASP.NET invokes the module so that it can further process the request.

Controls ASP.NET controls refers to Server Controls that are used in Web Forms projects. Controls are HTML form elements that abstract the markup and allow you to separate the processing from your page.

Roles ASP.NET Roles gives you built-in functionality to create roles for your users, and to restrict content according to the role of the user that is accessing the site.

Handlers HTTP Handlers are .NET components that can act as a target for incoming HTTP requests.

Globalization ASP.NET has built in components to develop applications that function for multiple cultures.

Master Pages ASP.NET Master Pages allow you to organize your design into templates, and to restrict content to locations that you assign.

Membership ASP.NET Membership provides built-in functionality to implement site members and provide login and user tracking features.

1-18

Developing Web Applications with Microsoft® Visual Studio® 2010

New Features in ASP.NET 4.0

ASP.NET 4.0 includes several new features such as extensible output caching, compressible serialized session state, and performance monitoring for individual applications. New features in ASP.NET include: •

Extensible ASP.NET 4.0 output caching ASP.NET 4.0 adds extensibility to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage medium to persist HTML content.



Compressible serialized session state ASP.NET 4.0 adds a new compression option for session-state providers. When the compressionEnabled configuration option is set to true, ASP.NET compresses serialized session state.



Performance monitoring for individual applications in a single worker process ASP.NET 4.0 adds resource-monitoring functionality in the CLR. When enabled, administrators have a more granular view of the resource consumption of individual applications.



Routing ASP.NET 4.0 adds built-in support for using routing with Web Forms. Routing allows you configure an application to accept request URLs that do not map to physical files.

Question: How is compression of serialized session state enabled?

Overview of Web Application Architecture and Design

1-19

Lesson 3

Introduction to the MVC Framework

MVC describes the design pattern Model-View-Controller, which was created to separate the concerns of data structures (M), presentation (V), and application logic (C). ASP.NET MVC is a framework for developing web applications built on top of ASP.NET. The ASP.NET MVC Framework allows you to build web applications using the latest advances in web application development. MVC separates the concerns of data handling, request/response processing, and view rendering to keep your design clean and easy to follow.

Lesson Objectives: •

Describe the MVC network.

1-20

Developing Web Applications with Microsoft® Visual Studio® 2010

What is the MVC Framework?

The MVC Framework was designed according to the MVC pattern, which is a framework for developing web applications built on top of ASP.NET. The MVC Framework, in accordance with the MVC pattern, attempts to separate the concerns of data structures (Model), presentation (View), and business logic (Controller) into distinct components, that together can complete the functionality in a web application. The components of an ASP.NET MVC solution are:

Model The Model portion of MVC includes all data structures. Your data structures may be dictated by an ORM (Object-Relational Mapping), such as LINQ to Entities, or you may be accessing data directly through requests to your data store. Your data structure objects and data access logic are included in the Model.

View The View portion of MVC includes all pages, master pages, and shared visual components, such as user controls.

Controller The Controller contains all the application logic necessary to form a response to a request, such as making requests against Model objects for specific data necessary to fulfill a request, and then feeding that data to the View to display it to the user. Question: What advantages are there in separating the concerns of data structures, presentation, and application logic?

Overview of Web Application Architecture and Design

1-21

Demonstration: Exploring an MVC Application

If you understand the architecture of one ASP.NET MVC application, all other MVC applications will be familiar to you. Due to the convention used in MVC applications, all model objects are contained in the Models folder, all views are contained in the Views folder, and all controllers are contained in the Controllers folder. In addition, all controller class or object names are suffixed with Controller; for example, HomeController for the controller Home.

Exploring the Adventure Works MVC Application 1.

Open Microsoft Visual Studio 2010. •

2.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Create a new MVC project. a.

In the Start Page – Microsoft Visual Studio window, on the File menu, click New Project, or press CTRL+SHIFT+N.

b.

In the New Project dialog box, in the left pane, in the Installed Templates section, expand Visual C# or Visual Basic, and then click Web.

c.

In the New Project dialog box, in the middle pane, click ASP.NET MVC 2 Web Application.

d.

In the New Project dialog box, in the middle pane, in the Name box, type DemoMvcApplication, in the Location box, type D:\Demofiles\Module 01\Demo 02, and then click OK.

3.

In the Create Unit Test dialog box, select the No, do not create a unit test project option, and then click OK.

4.

View the Controllers folder. •

In Solution Explorer, expand the Controllers folder.

1-22

Developing Web Applications with Microsoft® Visual Studio® 2010

Note: Observe that the code files all have the suffix Controller. 5.

View the Models folder •

6.

In Solution Explorer, expand the Models folder.

View all the code in the AccountModels code file. a.

In Solution Explorer, double-click the AccountModels.cs or AccountModels.vb code file.

b.

In the AccountModels.cs or AccountModels.vb window, press CTRL+M, CTRL+L.

c.

Scroll down and show the different regions of code.

Note: The model code file contains the data structures for this web application and classes that control logic for working with the data store. d. 7.

In the AccountModels.cs or AccountModels.vb window, click the Close button.

View the Views folder. •

In Solution Explorer, expand the Views folder.

Note: Several folders share their name with the names of the controllers in the Controllers folder. 8.

View the Views/Shared folder. •

In Solution Explorer, expand the Views/Shared folder.

Note: The Shared folder contains master pages, user controls, and pages shared across the MVC web application. 9.

Close Microsoft Visual Studio 2010. •

In the DemoMvcApplication - Microsoft Visual Studio 2010 window, click the Close Button.

Question: What other elements did you recognize in the MVC solution?

Overview of Web Application Architecture and Design

1-23

Lesson 4

Overview of the Request Life Cycle

The Request life cycle is composed of the series of events that transpire when processing a web request to your web application. Web Forms and MVC handle these requests differently. These differences will affect how you must implement code to handle these events.

Lesson Objectives: •

Describe the life cycle of a Web Forms request.



Describe the life cycle of a MVC request.



Describe the differences between the life cycle of a Web Forms and MVC request.

1-24

Developing Web Applications with Microsoft® Visual Studio® 2010

Life Cycle of a Web Forms Request

The Web Forms Page Event Life Cycle 1.

The Web Forms page event life cycle begins with a request to a Page resource.

2.

The HTTP handler processes the request and initializes the correct Page resource to handle the request.

3.

The page initializes, and all server controls in the page raise their initialization events as well.

4.

On postbacks (when a HTTP Post request is received), Postback Data (data that is available in the form) is loaded.

5.

The page loads and all server controls raise their Load event.

6.

On postbacks, the RaisePostBackEvent event is raised that can be accessed programmatically.

7.

The view state is saved and the event is raised.

8.

The page and all server controls are rendered into markup (HTML) and returned to the web server.

9.

The web server returns the rendered response.

Question: What is postback data?

Overview of Web Application Architecture and Design

1-25

Life Cycle of an MVC Request

The MVC Request Event Life Cycle 1.

The browser initiates a request.

2.

ASP.NET Routing routes the request to the appropriate resource, initiates the necessary controller, and invokes the action on the controller.

3.

The controller requests the necessary data from the model and does a lookup to determine the view that is required to render the response.

4.

The controller passes the viewdata built from the data structure given by the model to the view.

5.

The view takes the viewdata and renders the response.

6.

The rendered response is passed back to the browser.

Question: What is the first step of an MVC request?

1-26

Developing Web Applications with Microsoft® Visual Studio® 2010

Comparison of the Web Forms and MVC Request Life Cycles

The life cycle of Web Forms and MVC requests differs significantly. The Web Forms request life cycle is wrapped entirely around the concept of a Web Forms page. The ASP.NET runtime provides a mapped HTTP handler that passes requests to the appropriate Page resource. MVC uses routing based on the URL of the request to map its handler to the controller that will handle the request. In Web Forms, the page handles the entire process of requesting the necessary data structure needed to provide the content requested and the rendering of the response itself. MVC uses the controller to manage bringing together the resources needed to create a response. The controller requests the necessary data structure from the model, looks up the view necessary to form the response, and passes the viewdata created from the data structure provided by the model to the view, which renders the response. Question: In what other ways do the request life cycles differ between Web Forms and MVC?

Overview of Web Application Architecture and Design

1-27

Working with the Web Forms Page Life Cycle

The events that occur during the Web Forms page life cycle can be manipulated to process the request according to your needs during the Web Forms page life cycle. Often you need to handle and inject new functionality into the page life cycle to handle different scenarios. For example, you may want to handle a postback request that requires action to be taken on form data differently than you would if the request is a new request for the page. Often this processing is handled during the page’s Load event as shown in the following example. [Visual C#] protected void Page_Load(object sender, EventArgs e) { }

[Visual Basic] Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub

Question: What other scenarios can you imagine where you would need to use events in the page’s life cycle to process the page correctly?

1-28

Developing Web Applications with Microsoft® Visual Studio® 2010

Lab 1: Exploring the Adventure Works Website

Objectives: •

Describe the Adventure Works website.



Explain code differences between Web Forms and MVC.



Describe the request life cycle for both Web Forms and MVC.

Introduction In this lab, you will review the existing Adventure Works website and become familiar with its design. Furthermore, you will compare how application development by using Web Forms differs from application development by using the MVC framework. Finally, you will explore how to create controls dynamically by adding an advertisement on the page.

Overview of Web Application Architecture and Design

1-29

Lab Scenario

As a web developer at Adventure Works, you have worked extensively with ASP.NET 2.0. However, you have limited experience with ASP.NET 4.0. You need to further explore the features of ASP.NET 4.0 to accomplish the goals set by management for the new Adventure Works website. As a first step toward this end, you want to examine the MVC framework and understand how it compares with the Web Forms programming model.

1-30

Developing Web Applications with Microsoft® Visual Studio® 2010

Exercise 1: Exploring the Adventure Works Website The main tasks for this exercise are as follows: 1.

Open the AdventureWorks solution in Visual Studio 2010.

2.

Start the web application.

3.

Browse the products list.

4.

Add products to the shopping cart.

5.

Place an order.

6.

Explore the life cycle of a Web Forms page.

7.

Open the AdventureWorksMvc solution in Visual Studio 2010.

8.

Explore the life cycle of an MVC request.

 Task 1: Open the AdventureWorks solution in Visual Studio 2010 1.

Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.

2.

Open Microsoft Visual Studio 2010.

3.

Open the AdventureWorks solution at the following location. Programming Language

Location

Microsoft Visual C#®

D:\Lab Files\CS\Lab 01\Starter\WebForms

Microsoft Visual Basic®

D:\Lab Files\VB\Lab 01\Starter\WebForms

 Task 2: Start the web application •

Run the AdventureWorks solution in Debug mode.

 Task 3: Browse the products list •

In the Product Categories list, select Bib-Shorts, and then click the Submit button. Note: Observe the products available in the Bib-Shorts product category.

 Task 4: Add products to the shopping cart 1.

Add one pair of Men’s Bib-Shorts, size M, to the shopping cart.

2.

Continue shopping.

 Task 5: Place an order 1.

Open the shopping cart.

2.

Place the order.

 Task 6: Explore the life cycle of a Web Forms page 1.

Switch to Visual Studio 2010 with the AdventureWorks solution open.

2.

Open the Default.aspx Web Form in Code view.

3.

Place a breakpoint at the beginning of the Page_Load method.

Overview of Web Application Architecture and Design

4.

Switch to Windows® Internet Explorer®.

5.

Open the Home page.

1-31

Note: The debugger reaches your breakpoint in the Page_Load method. 6.

Step through the web application startup until you reach the end of Page_Load method.

7.

Continue the web application.

Note: The URL displayed in the address bar of Internet Explorer includes the name of the Web Form or page (Default.aspx) displayed. 8.

Close Windows Internet Explorer.

 Task 7: Open the AdventureWorksMvc solution in Visual Studio 2010 1.

Open a second instance of Microsoft Visual Studio 2010.

2.

Open the AdventureWorksMvc solution at the following location. Programming Language

Location

Visual C#

D:\Lab Files\CS\Lab 01\Starter\MVC

Visual Basic

D:\Lab Files\VB\Lab 01\Starter\MVC

 Task 8: Explore the life cycle of an MVC request 1.

In the Controllers folder, open the HomeController.cs or HomeController.vb file.

2.

Notice the methods that are available and the way they relate to the actions that are available to the user.

3.

Close the HomeController.cs or HomeController.vb file.

4.

Open the Global.asax file.

5.

Place a breakpoint at the beginning of the Application_Start method.

6.

Run the AdventureWorksMvc solution in Debug mode.

Note: The debugger reaches the breakpoint in the Application_Start method. 7.

Examine the static/Shared RegisterRoutes method.

8.

Step through the web application startup until you reach the last line of code in the Index action method of the Home controller.

9.

Continue the web application.

Note: The URL displayed in the address bar of Internet Explorer does not include the name of the page (Index.aspx) displayed. 10. Close Windows Internet Explorer.

1-32

Developing Web Applications with Microsoft® Visual Studio® 2010

Results: After completing this exercise, you should have reviewed the Adventure Works website by adding products to your shopping cart and checking out. You should also have reviewed the Page and MVC request life cycles by placing breakpoints in methods that execute during the life cycle.

Overview of Web Application Architecture and Design

1-33

Exercise 2: Comparing Web Forms and MVC The main tasks for this exercise are as follows: 1.

View the AdventureWorks solution in Visual Studio 2010.

2.

Examine the markup and code found in the Default.aspx Web Forms page.

3.

View AdventureWorksMvc solution in Visual Studio 2010. 1.

Examine the markup and code used for rendering the default MVC page.

2.

Discuss as a group the differences in the way Web Forms and MVC responds and delivers content to a request.

 Task 1: View the AdventureWorks solution in Visual Studio 2010 Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.

 Task 2: Examine the markup and code found in the Default.aspx Web Forms page 1.

Examine the code in the Default.aspx.cs or Default.aspx.vb code file.

2.

Examine the markup in the Default.aspx Web Form.

 Task 3: View AdventureWorksMvc solution Microsoft Visual Studio 2010 •

Switch to the Visual Studio 2010 instance with the AdventureWorksMvc solution open.

 Task 4: Examine the markup and code used for rendering the default MVC page 1.

Open the Adventure Works MVC project at the following location: Language

Location

C#

D:\Lab Files\CS\Lab 01\Starter\MVC

Visual Basic

D:\Lab Files\VB\Lab 01\Starter\MVC

2.

Examine the code in the HomeController.cs or HomeController.vb code file.

3.

Examine the markup in the Index.aspx page.

 Task 5: Discuss as a group the differences in the way Web Forms and MVC responds and delivers content to a request •

In the classroom, discuss the differences between the page life cycles of the two different web application models, Web Forms and MVC, including the page-centric Web Forms request vs. the MVC routing, the use of server controls in Web Forms vs. HTML controls, and MVC helper methods.

Results: After completing this exercise, you should have reviewed the code in a Web Forms and MVC page, and discussed the differences as a class.

1-34

Developing Web Applications with Microsoft® Visual Studio® 2010

Exercise 3: Working with the Request Life Cycle The main tasks for this exercise are as follows: 1.

Exploring the life cycle of a Web Forms page.

2.

Exploring the life cycle of a MVC request.

 Task 1: Explore the life cycle of a Web Forms page 1.

Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.

2.

View the Default.aspx Web Form.

3.

Locate the Content control with the ContentPlaceHolderID property set to MainContent.

4.

Add the following Label control markup before any other content in the Content control.

5.

View the code-behind file for the Default Web Form.

6.

In the Page_Load method, add the following code at the beginning of the method. [Visual C#] lblAdvertisement.Text = "My advertisement here";

[Visual Basic] lblAdvertisement.Text = "My advertisement here"

7.

Run the web application and view the rendered Default.aspx page.

Note: During the page’s Load event, the text is added to the lblAdvertisement Label control. 8.

Close Windows Internet Explorer.

9.

Close Visual Studio 2010.

 Task 2: Explore the life cycle of a MVC request 1.

Switch to the Visual Studio 2010 instance with the AdventureWorks solution open.

2.

Open the Views\Home\Index.aspx view.

3.

Locate the Content control with the ContentPlaceHolderID property value of MainContent.

4.

Add the following code before any content in the Content control. [Visual C#]

[Visual Basic]

5.

Open the file Controllers\HomeController.cs or Controllers\HomeController.vb. •

In Solution Explorer, expand Controllers, and then double-click HomeController.cs or HomeController.vb.

6.

Locate the Index method in the file.

7.

Add the following code at the beginning of the Index method. [Visual C#]

Overview of Web Application Architecture and Design

1-35

ViewData["Advertisement"] = "My advertisement here";

[Visual Basic] ViewData("Advertisement") = "My advertisement here"

8.

Run the web application and view the rendered Index.aspx view.

Note: During the controller’s Index action method, the text is added to Index view by using the ViewData. 9.

Close Windows Internet Explorer.

10. Close Visual Studio 2010.

 Task 3: Turn off the virtual machine and revert the changes 1.

In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off.

2.

In the Turn Off Machine dialog box, click Turn Off.

3.

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

4.

In the Revert Virtual Machine dialog box, click Revert.

Results: After completing this exercise, you should have explored the life cycle of both a Web Form and an MVC page, by adding code to write to the page during the page request.

1-36

Developing Web Applications with Microsoft® Visual Studio® 2010

Module Review and Takeaways

Review Questions 1.

What are some of the key features of IIS 7.0?

2.

What is the purpose of the Adventure Works website?

3.

What does it mean when we say that the architecture of IIS 7.0 is modular?

4.

What is the MVC framework?

5.

How do the Web Forms and MVC request life cycles differ?

Real-world Issues and Scenarios •

You have been asked to provide system status messages and error messages to users in your web application. How can you dynamically provide these messages to your users?

Designing a Web Application

Module 2 Designing a Web Application Contents: Lesson 1: Web Applications: Case Studies

2-3

Lesson 2: Web Application Design Essentials

2-9

Lesson 3: Visual Studio 2010 Tools and Technologies for Web Application Design

2-19

Lab 2: Redesigning the Adventure Works Website

2-24

2-1

2-2

Developing Web Applications with Microsoft® Visual Studio® 2010

Module Overview

The design of a web application plays a key role in its adoption and continued use by its users. Beyond the consideration of having people use your application is the ability to support it quickly and easily, and add new features, when required. Whether providing a consistent design for users or creating an easily supportable product, design should be at the center of consideration when starting a web application project. This module will introduce business scenarios, best practices, and options that are available for the design of web applications. Topics that will be covered include the needs of e-commerce sites vs. other business and information sites, essentials of designing web applications with ASP.NET, such as deciding between Web Forms and Model-View-Controller (MVC), and some of the tools and technologies available using Microsoft® Visual Studio® 2010 for creating web applications.

Designing a Web Application

2-3

Lesson 1

Web Applications: Case Studies

Web applications come in many varieties and fulfill many needs that may or may not apply directly to achieving the objective. This lesson will discuss the strategies used in different business scenarios, what the unique characteristics of web applications are, and define the process of designing a web application.

Lesson Objectives: After completing this lesson, you will be able to: •

Identify major types of web applications.



Describe the process of designing a web application.



Identify web application design considerations.



Describe differences in the design of various types of web applications.



Apply guidelines for documenting the design of a web application.

2-4

Developing Web Applications with Microsoft® Visual Studio® 2010

Discussion: Overview of Web Applications and Their Characteristics

Recognizing similarities between types of web applications will help you quickly understand the audience for whom you are designing a website, and also help you to learn from the lessons of others who have developed web applications over the years. This lesson will cover four different common web application types (e-commerce, blog, news/information, and business/non e-commerce) that you will encounter frequently, and be asked to design. This knowledge will assist you in fitting a web application that you are asked to design into a common mold so that you can quickly recognize the challenges you will face.

E-Commerce Site (Shopping Cart) All e-commerce sites have key features in common with one another, they are: •

Ability to search for products



Ability to view product details



A shopping cart that allows you to store items for purchase and continue shopping



Some sort of checkout functionality that allows you to purchase your selected items

Without these key features, an e-commerce site would not be successful. Keep these features in mind when you are asked to design e-commerce sites, and be sure to notice similarities and differences between e-commerce sites when you are shopping on the web. Key considerations for e-commerce sites include: •

Security: When taking payments and storing sensitive customer information, such as addresses, security is a primary concern. You want your customers to feel secure and trust that you have their best interests at heart when they shop at your site. You can do this by providing secure logon and checkout functionality based on best practices, such as only using security certifications through reputable companies.



Ease of managing and introducing new products: Any e-commerce site will have products being introduced, updated, and removed from the site on a regular basis. This functionality needs to be very simple for an administrator to accomplish. Working directly with the people who will administrate the

Designing a Web Application

2-5

site, and learning what their workflow is will help you deliver features that will keep the site running smoothly. •

Simple workflow from search to checkout, for keeping your customers from leaving for another competitor’s site: Any distraction from finding and purchasing the products your ecommerce site has to offer is enough to cause a user to leave the site and look elsewhere. Concentrate on making the workflow from selection to purchase as simple and pain-free as possible.

Blog Site All blog sites have key features in common with one another, they are: •

Ability to add, edit, manage, and publish posts (articles)



Ability to categorize posts for easy searching



Ability for readers to comment on published posts



Ability for authors to administrate content and comments

A blog would hardly be a blog without these key features. At times, you may be asked to design a web application where a blog is just one feature in a larger picture. Many business and information sites also include blogs as a way to communicate to their readers and customers. A blog web application is very simple at its core. It is a question of the extent to which it is expanded that sets its complexity. Features such as spam protection, tagging, and custom widgets can quickly expand the scope of the project. Key considerations for blog sites include: •

Rich content editing features for authors and administrators: The easier it is for authors to publish content for a blog site, the more quickly the site will gain readership and become successful. As important as it is to make the site easy for readers, it is more important to make it a good experience for the authors that will be working with the web application the most often.



Simple search functionality for readers: It should be simple for readers to find content that interests them. This can be done by categorizing posts (so that readers can quickly find common themes), and by adding tagging (so that readers can quickly find posts on a particular topic).



Controls on comments and contributing to keep spam to a minimum: Blog sites invite abuse from spammers if there are not protections set from the beginning. Design the blog to allow for moderation of comments if the administrator sets the option and be sure to give the administrator control to close commenting and delete offending comments if necessary.

News/Information Site All news/information sites have key features in common with one another, they are: •

Very dense presentation of content



Content provided in column layout



Categorization of content so that it is easy to find what you are looking for

A news/information site would not be recognized if it did not have that typical newspaper layout, and provide very dense presentation of content (meaning there is quite a bit more content on the screen than on a typical site). Content is also categorized so that the user can find the information that interests him or her as quickly as possible, such as weather or sports. Key considerations for news/information sites include: •

Advertising: Typically, news/information sites sell advertising for revenue. Keeping this in mind while designing will allow you to add advertising to the web application without having it look like an afterthought.

2-6

Developing Web Applications with Microsoft® Visual Studio® 2010



Ability to adapt design to trends quickly: The designs and layouts used in news/information sites change more often than in other sites. The ability to change a design and layout quickly will give you an edge.



Rich content editing features for authors and administrators: Just as with blogs sites, content is everything with news/information sites. Authors and administrators need to be able to quickly add, edit, delete, and publish their articles.

Business Site (Non E-commerce) All business sites have key features in common with one another, they are: •

Strongly branded designs



Designs and content that try to send a message about the business



Access to information on the business, and contact information for further questions

Business sites are typically very straightforward and change less often than the other three common web application types. The content is carefully crafted to send the message the organization would like their customers/clients to see. Business sites are typically strongly branded, with emphasis on logos and colors that correlate to the business and the message being broadcast. Key considerations for business sites include: •

Emphasis on design: From the beginning, emphasis will be on design. Typically, you will work with a marketing group or key executives to form the image of the site being presented. Take the time to understand the business goals and design to meet them.



Simple navigation: Typically, business sites are not very dense with information. There are very few pages and links required. As such, keep the navigation as simple as possible.



Easy to find contact information: Concentrate on making the information available very easy to find. Make the contact information for the business obvious and not hidden.

Question: What are some further variations on websites that were not covered? Question: While not being an exact fit, do these four types of websites relate to the previous question’s answers in some ways?

Designing a Web Application

2-7

Overview of the Web Application Design Process

The design of a web application should address the goals outlined for it, and apply the requirements given to meet those goals. By following a design process, even loosely, you will be much closer to hitting the goals of the web application than if you dive right into building your solution from the start. The design process typically fits within the vision and planning steps of the development process. There isn’t necessarily a wrong way to conduct your design process during these two steps, as long as it is before you start building your product. How you conduct the design process during one project may be different in another. Do what feels right, and be sure to do it before you begin building the product. The design process workflow: •

Identify business goals



Determine requirements



Create a design specification to support your findings

Identify Business Goals The first step in a successful design is to solidify the goal you are working towards achieving. This requires you to work with business leaders to determine what it is that the web application should achieve for the organization. Without this knowledge, it is hard to design an application successfully that will meet the needs of the organization.

Determine Requirements After the goals for the project have been identified, the project team needs to define the requirements that are necessary to meet those goals. The requirements developed during this phase will shape the architecture of the product to a large degree.

2-8

Developing Web Applications with Microsoft® Visual Studio® 2010

Example: If one of the goals determined for the project is that it must be delivered in a very short timeframe, that would likely lead to architecture and platform decisions that will impact the development of the product.

Create Design Specification Now that you understand the goal that you are trying to achieve and what is required to achieve it, you are in a position to write a design specification. A design specification should contain all of the information that you have gathered during the design process, and describe it in language that anyone from either the technical or the business teams can understand. Design specifications themselves can be a complex topic, with many opinions on the correct format and language. The correct way to document your design is what works best for your project team and organization. Question: Have you participated in a project that did not fully specify the design of your project as described in this topic? If so, what were the ramifications? What could have been done differently? Question: In your experience, in which activities of the design process did you participate? Do you feel it was beneficial towards your understanding of the goals and requirements of the solution?

Designing a Web Application

2-9

Lesson 2

Web Application Design Essentials

Each web application has a focus that leans towards one of the common types covered in Lesson 1. The common types each have design considerations that should be well covered during the first two steps of the design process (understanding business goals and determining requirements). Understanding the considerations that are common to each type will assist you in speeding up the design process itself, while not missing requirements that may be key for a type of web application. Understanding each of the considerations for these web application types will also assist you in deciding on which ASP.NET framework to build your web application. Web Forms and MVC both have strengths and weaknesses that may fit well with a given business scenario and web application type. Making the right decision between these frameworks for a particular web application type can save you time during your development process.

Lesson Objectives: After completing this lesson, you will be able to: •

Identify common design considerations for each of the website types covered in Lesson 1.



Identify the key differences between Web Forms and MVC.



Apply guidelines for determining when to use Web Forms and MVC.



Identify factors to be considered when using Web Forms with MVC.

2-10

Developing Web Applications with Microsoft® Visual Studio® 2010

Common Design Considerations

During the design process of your web application, the following considerations are likely to play a role in the design decisions that you make. The type of web application that you are designing determines the importance of each consideration. The five considerations are: •

Security



Scalability and reliability (availability)



Search Engine Optimization (SEO)



Localization



Accessibility

Security Security is the level of importance and effort you are willing to put toward securing data and the administration features of your application. Every web application will require some level of security. Some web application types require much more focus on this consideration, such as e-commerce sites, where sensitive information may be stored. Importance of consideration by web application type (highest importance listed first): •

E-commerce



News/Information



Business/Non E-commerce



Blog

Designing a Web Application

2-11

Scalability and Reliability (Availability) Scalability is concerned with the ability of your web application to scale when demand requires more resources. Reliability is concerned with the ability of your web application to survive resource outages, such as a single server failure. Often scalability and reliability are closely linked, as the ability to recover from the loss of resources requires the ability of your web application to spread its processing across more than one single point of failure. Importance of consideration by web application type: •

News/Information



E-Commerce



Blog



Business/Non E-Commerce

More information on the subject of scalability and reliability as it relates to web applications can be found in the documentation for IIS (Internet Information Server) and Microsoft SQL Server®. Both of these platforms provide built-in scalability and reliability services.

Search Engine Optimization (SEO) SEO is concerned with the ease with which automated search engine crawlers can traverse your site. Automated search engine crawlers follow links that are available in your site and save key information about the content of your site on each page. This information is stored and is searchable by users who are interested in the topics that your site may cover. Automated search engine crawlers can be very picky about the layout of your site, and the way that you place content. If you do not follow the standards and norms of web application design, you may find that search engines are not indexing your site as efficiently as they might, leading to fewer visitors through keyword searches. Importance of consideration by web application type: •

News/Information



E-Commerce



Blog



Business/Non E-Commerce

Each search engine provides documentation on the standards and practices that lead to optimal indexing for that search engine.

Localization Localization is concerned with providing your content to your users in multiple languages. Providing your content in several languages can expand your potential user base dramatically. Importance of consideration by web application type: •

E-Commerce



Business/Non E-Commerce

2-12

Developing Web Applications with Microsoft® Visual Studio® 2010



News/Information



Blog

For more information on localization options in ASP.NET solutions, see the ASP.NET Globalization and Localization page on MSDN at http://go.microsoft.com/fwlink/?LinkID=203984&clcid=0x409.

Accessibility Accessibility is concerned with providing interfaces that allow disabled individuals the opportunity to use your web application. Accessibility is typically much easier to include in your solution if it is added as a requirement from the inception of the project, rather than attempting to add it later. As the web becomes a more pervasive and important medium to all people, accessibility becomes more important so that everyone has an opportunity to participate on the web. Importance of consideration by web application type: •

E-Commerce



Business/Non E-Commerce



News/Information



Blog

For more information on considering accessibility in your design, see the Evaluating Web Sites for Accessibility page from the WC3, at http://go.microsoft.com/fwlink/?LinkID=203953&clcid=0x409. Question: How does security play a role in every type of web application? Question: How do scalability and reliability relate to one another?

Designing a Web Application

2-13

Discussion: Web Forms and MVC

Successful web applications can be built on both Web Forms and MVC. Web Forms and MVC have different approaches on the design and development of your web application. Web Forms and MVC share similarities, given that they are both built on top of ASP.NET. Their differences are in how they approach separating concerns and delivering content when requested. Web Forms attempts to model the life cycle of desktop applications by maintaining state across web pages and user activity. MVC stays with the stateless model of web applications and separates concerns through the model-view-controller pattern.

Web Forms •

Built on top of ASP.NET



Supports rapid application development (RAD)



Supports Drag-and-drop development



HTML generated by the controls



Event driven



Only one form element



Supports client side settings storage (viewstate)



Hard to test

Web Forms are designed for rapid application development (RAD), using controls. These controls define code that runs on the server and generates HTML that the client’s browser can render. The key benefits offered by Web Forms are the separation of HTML interface design from application logic, a large suite of server-side controls, and rich data binding.

2-14

Developing Web Applications with Microsoft® Visual Studio® 2010

Web Forms will be immediately familiar to anyone who has developed Windows Forms applications. It is designed to be event-driven and to maintain the state of the session through the stateless medium of the web. Some of the key features in Web Forms are seen as both an asset and a deficit. The concept of viewstate provided by Web Forms allows you to maintain a client’s state throughout the client’s entire session with the application. This feature can be very powerful, but also can be very taxing on resources, and goes against the grain of the typical paradigm of web development as a stateless platform. Combining the concept of viewstate with server-side controls and postback behavior leads to a framework that is very hard to test. Those who are interested in TDD (Test-Driven Development) will not find Web Forms to be TDD friendly.

MVC •

Built on top of ASP.NET



Complete control over the generated HTML



Separation of concerns (Model-View-Controller)



Easy to test



No postback or viewstate

MVC takes a different approach to web development than Web Forms. The acronym MVC stands for model-view-controller. MVC is a pattern that can be extended to more than just web application development. It is a solid pattern for any application architecture that seeks to separate the concerns involved in presentation, logic, and data manipulation. With MVC, there is no concept of viewstate and postback. You also have complete control over your presentation, which can be both a blessing and a curse for some developers. Along with the concept of separation of concern that is built into the MVC pattern, ASP.NET MVC is also very testable right out of the box. For a team that is interested in practicing TDD, they will find MVC to be very friendly. Question: What features, common or different, do you see in both the Web Forms and MVC frameworks that would benefit your development efforts?

Designing a Web Application

2-15

Guidelines for Determining When to Use Web Forms and When to Use MVC

There are several considerations that you need to keep in mind when deciding between Web Forms and MVC for your project, such as product domain, business requirements, and personal preference. Different scenarios may lead you towards one choice over the other. Ultimately, very successful applications have been written on both platforms. You cannot go wrong, but you might find that one suits you and your situation better than the other does.

Guidelines You can use the following considerations as guidelines for choosing between Web Forms and MVC: •

Internet vs. intranet: If you are working on a web application that will be available strictly over the intranet, many of the considerations that lend themselves towards MVC will not be as important. Considerations such as search engine optimization (SEO), localization, and accessibility will be less important with a typical intranet web application. In this scenario, the strengths of Web Forms, such as rapid application development (RAD) and the large library of available server controls, may be the deciding factor.



Control over markup: MVC gives you strict control over your markup. Depending on how important SEO is as a consideration for your web application, MVC may be the best option for you if strict control over markup is a priority. Web Forms abstracts much of the markup that will be generated with server controls that create the markup for you, so that you do not have to.



Familiarity with patterns: MVC strictly utilizes the model-view-controller pattern. Web Forms allows you to use many patterns to separate concerns, such as MVP, model-view-presenter. You have many more options using Web Forms in deciding the patterns you will use to separate business logic, data access, and presentation from one another. Depending on your level of comfort with the MVC pattern, you may choose MVC or Web Forms based on your familiarity.



RAD: Web Forms was written with RAD (rapid application development) in mind. If you are facing very tight schedules, it may be the framework of choice given your scenario. While those that are comfortable with the MVC pattern will quickly develop quality solutions, it is hard to compete with

2-16

Developing Web Applications with Microsoft® Visual Studio® 2010

the vast library of available server-side controls available for Web Forms where the rendered HTML is done for you. •

Personal preference: For developers who are familiar with Windows Forms development, Web Forms will be much easier to use. Web Forms were developed with the Windows Forms developer in mind. Web Forms allows them to transition easily to the web, working in the same paradigm. Other developers that are new to ASP.NET may be more familiar with the concepts of the MVC pattern. Familiarity with the pattern you are working with can be a strong incentive in deciding between Web Forms and MVC. A successful design can be created using Web Forms or MVC; your level of comfort with the pattern implemented is a strong factor when deciding which framework to use.

Question: What solutions in your experience may have benefited from implementation using MVC? Question: What key features of Web Forms that you use frequently might you miss when developing with MVC?

Designing a Web Application

2-17

Considerations for Using Web Forms with MVC

Although there are some specific features of Web Forms that are not compatible with MVC, some features are of ASP.NET are fully compatible with both Web Forms and MVC. This topic will review some of the key features of ASP.NET that are compatible with both Web Forms and MVC and the common features of Web Forms that are incompatible with MVC. Understanding these differences will help you determine the correct course of action when converting Web Form functionality to MVC.

Compatible Features Many features are shared among both Web Forms and MVC. The following highlights the more common compatible features. •

Membership: ASP.NET Membership allows you to configure security quickly for your web application.



Authentication: ASP.NET Forms Authentication allows you to configure user logon/logoff quickly.



Roles: ASP.NET Roles allows you to couple the membership and authentication features with the ability to add authorization functionality to your application.



Configuration: ASP.NET configuration features, such as Application Settings and Connection Strings allow you to store static information that your application uses in an XML configuration that is easily accessible throughout your application.

Incompatible Features Some features are handled differently between Web Forms and MVC. The following sections highlight the more common features, and explain how those features differ from one another. •

Server-side controls (GridView, Repeater, DataList, and so on): Server side controls, such as GridView, are not compatible with MVC. The functionality that these controls rely on is not available in MVC, such as postback and viewstate.



Viewstate: Viewstate as a concept is not present in MVC. MVC provides a stateless model of interaction between the client and server.

2-18

Developing Web Applications with Microsoft® Visual Studio® 2010



Page Event life cycle: Without the concept of viewstate, MVC also does not implement the Page Event life cycle as it exists in Web Forms. No Page_Load events can be used to process and manipulate the page or data involved. This functionality is handled in the controller in the MVC paradigm.

Designing a Web Application

Lesson 3

Visual Studio 2010 Tools and Technologies for Web Application Design

Microsoft provides several tools and technologies that assist taking the design specification that you create and implementing it in your web application. These tools include design tools built into Visual Studio 2010 and the IIS SEO Toolkit. The Enterprise Library is a collection of reusable software components called application blocks. Each block is designed to assist you with common development challenges.

Lesson Objectives: After completing this lesson, you will be able to: •

Describe the design tools available in Visual Studio 2010.



Describe what the Enterprise Library is.



Describe the key blocks of the Enterprise Library.



Describe what the IIS SEO Toolkit is.

2-19

2-20

Developing Web Applications with Microsoft® Visual Studio® 2010

Overview of the Design View in Visual Studio 2010

Visual Studio 2010 provides a Design view of the pages of your web application that shows you what your page will look like as you implement your design. The design view shows you any master pages and nested master pages that are implemented in your page, so that you see exactly what you would see when you view the page in a browser. In the Design view, each control has a button attached that allows you to configure that control further. The image on the slide shows you this functionality for a ListBox control. The Toolbox window allows you to drag and drop controls into your design. Simply select the control that you want to place in your page and drag it to where you want the control to be placed in the page. Except for very simple pages, you will use a combination of the Source and Design views to implement your design specification for a page. The Source view gives you direct access to the markup for the page (HTML, CSS, JavaScript), and the Design view gives you a rendered view of your page as you create it. You can select the view to display from the menu on the bottom of the screen, as shown in the following image.

Question: What value does the Design view bring to your development process?

Designing a Web Application

2-21

Enterprise Library

The Enterprise Library is a collection of reusable components (application blocks), which provide developers with solutions for commonly needed functionality in an application. Functionality such as encryption, logging, exception handling, and data access is addressed in the Enterprise Library. The implementation of each application block in the library is built on Microsoft’s proven best practices for .NET application development. The blocks are available to use as is, or to extend for custom implementations to meet your specific needs.

Key Blocks of the Enterprise Library •

Cryptography application block: The Cryptography application block includes features that simplify the implementation of typical cryptographic functions in your applications. Functions such as encryption, hashing, and comparing hash values for validation are all included in the library.



Data Access application block: The Data Access application block provides features that simplify accessing and manipulating data. Tasks such as connection management and caching parameters are built into the library, as well as reading data from a data source and passing data through an application layer. You can execute stored procedures using built-in functionality, as well as write inline SQL to query your data source directly.



Exception Handling application block:The Exception Handling application block assists with the always-present chore of handling exceptions through a uniform strategy for processing exceptions throughout all layers of your architecture. Using this application block, you can create exceptionhandling policies that are defined and maintained at an administrative level, so that support and changing of these policies can be accomplished without changing application block code.



Logging application block: The Logging application block provides common logging functions. Using this application block, you can write to a number of locations, including an email message, the event log, a database, a message queue, a text file, and custom locations that you define. You can specify consistent logging throughout your application, to many destinations, using a common interface. Configuration of the logging application block can be accomplished using a custom

2-22

Developing Web Applications with Microsoft® Visual Studio® 2010

configuration interface available in Visual Studio that makes it very easy to customize logging for your needs. Question: What benefits can you see to using the Enterprise Library as a consistent interface for common tasks that your applications require?

Designing a Web Application

2-23

IIS SEO Toolkit

Search Engine Optimization (SEO) is the act of optimizing your web application’s markup (HTML) so that search engines can index it easily and properly. A significant portion of your site’s traffic can be driven through searches, and implementing proper SEO allows the information that you want available to your audience to be properly indexed for searching through a search engine. When your site is indexed properly, every available result that should be shown for your site for a given keyword is available.

Robots.txt and Sitemap.xml Files The IIS SEO Toolkit provides features for creating and configuring robots.txt and sitemap.xml files for your site. Robots.txt is a file that sits in your site’s root folder that every search engine uses to direct their indexing. The robots.txt file tells a search engine what it can and cannot crawl when indexing your site. Properly configuring your robots.txt file will ensure that the information that you want to be indexed will be indexed by search engines. The Sitemap.xml file provides a map of your site for a search engine crawler. This allows the crawler to access areas of your site that it might not have without the sitemap. Properly configuring a sitemap.xml file ensures that the search engine’s crawler will index your entire site.

Site Analysis The Site Analysis feature crawls your site as if it were a search engine crawler, and then reports on issues that it found in the files and markup contained in your site. By running the Site Analysis tool, you will find and correct potential issues that will stop a search engine crawler from properly attributing relevance to your content and possibly halting the indexing of your site altogether. Question: What value do the robots.txt and sitemap.xml files provide? Question: How does the Site Analysis tool help you understand how a search engine crawler will react to the content of your site?

2-24

Developing Web Applications with Microsoft® Visual Studio® 2010

Lab 2: Redesigning the Adventure Works Website

Note: Tasks in this lab will be the same regardless of the programming language your solution is using.

Objectives: After completing this lab, you will be able to: •

Draw diagrams showing the overall architecture and page flow of the Adventure Works website.



Identify which pages of the website will use Web Forms, and which pages will use MVC, based on business requirements.



Add MVC capabilities to the existing website.

Introduction In this lab, you will first capture your understanding of the current Adventure Works website by diagramming its overall architecture and page flow. You will then review the business requirements set by management, and recommend which pages of the website will use Web Forms, and which pages will use MVC. You will also do the groundwork necessary for adding MVC capabilities to the existing website so that you can get started as soon as Management approval comes through.

Designing a Web Application

2-25

Lab Scenario

Now that you have a better understanding of Web Forms and MVC, you can see the benefits of using MVC to develop some pages of the Adventure Works website. Your next task is to create a proposal detailing recommendations for redesigning the website. Your proposal needs to describe the structure of the current website and recommend an appropriate programming model for developing the pages of the redesigned website. Keep in mind that you are operating on a tight budget, so you need to consider the costs and benefits of your decisions before making recommendations. The proposal should also enumerate the rationale underlying your recommendations to help management assess them.

2-26

Developing Web Applications with Microsoft® Visual Studio® 2010

Exercise 1: Reviewing the Adventure Works Website Structure The main tasks for this exercise are as follows: •

Open the AdventureWorks solution in Visual Studio 2010.



Examine the code and markup location and purpose.



Draw a diagram showing the overall architecture.



Draw a diagram showing the page flow.



Discuss your findings with the class.

 Task 1: Open the AdventureWorks solution in Visual Studio 2010 1.

Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.

2.

Open Microsoft Visual Studio 2010.

3.

Open the AdventureWorks solution at the following location. Programming Language

Location

Visual C#®

D:\Lab Files\CS\Lab 02\Solution\Exercise 01

Visual Basic®

D:\Lab Files\VB\Lab 02\Solution\Exercise 01

 Task 2: Examine the code and markup location and purpose •

Analyze the solution and determine its intent and structure.

 Task 3: Draw a diagram showing the overall architecture •

On a sheet of paper, draw a diagram describing the overall Adventure Works website architecture, based on your analysis.

 Task 4: Draw a diagram showing the page flow •

On a sheet of paper, draw a diagram showing the page flow of the AdventureWorks web application, based on your analysis.

 Task 5: Discuss your findings with the class •

Discuss the diagrams created amongst the class.

Results: After completing this exercise, you should have created two diagrams describing the existing architecture and page flow of the AdventureWorks web application.

Designing a Web Application

2-27

Exercise 2: Redesigning the Adventure Works Website The main tasks for this exercise are as follows: •

Read the requirements document.



Determine which pages will use Web Forms and which will use MVC. •

Discuss your recommendations and their rationale with the class.

 Task 1: Read the requirements document •

The redesigned AdventureWorks web application must meet the requirements as set by management and listed in the following sections.

Business Requirements and Considerations •

Build a responsive, rich, and interactive UI



Enhance the performance of existing pages and resolve errors



Use URLs that are search engine friendly and facilitate indexing of products by search engines



Include a section for blogs



Include an administration section to enable the Sales team to manage information stored in the database



Secure the blog management pages and the administration section

Functional Requirements: Shopping Cart •

List product categories



Click a category to display products



Display products in a detailed view



Add products to the shopping cart



Remove products from the shopping cart



Submit the shopping cart

Functional Requirements: Blogs •

Log on to the website



Add a new blog entry



Edit and delete blog entries



Add anonymous comments



Approve comments

Functional Requirements: Administration Section •

Log on to the website



Manage products



Manage product categories



Manage sales order headers



Manage customers



User Interface Requirements

2-28

Developing Web Applications with Microsoft® Visual Studio® 2010



Display a welcome message on the home page in English or French (Canada)



Minimize page refreshes



Provide support for easily changing the overall look of the application



Reflect the corporate branding and propose two styles based on the corporate colors



Display a marketing message on the Product Detail page



Display a product advertisement on the blog pages



Display a ticker showing biking-related news headlines on the blog pages

 Task 2: Determine which pages will use Web Forms and which will use MVC •

Based on the requirements given, determine and document which pages will remain Web Forms pages and which will be implemented in MVC.

 Task 3: Discuss your recommendations and their rationale with the class •

Discuss the recommendations created with the class.

Results: After completing this exercise, you should have reviewed the requirements document for the Adventure Works website, determined which pages will remain Web Forms pages and which will use MVC, and discussed your recommendations and their rationale with the class.

Designing a Web Application

2-29

Exercise 3: Adding MVC Capabilities to the Adventure Works Website The main tasks for this exercise are as follows: •

Open the AdventureWorks solution in Visual Studio 2010.



Add required assemblies to the project.



Add the MVC Assembly references and namespaces to the Web.config file.



Map the default MVC request routes.



Change project to reflect an MVC Project.

 Task 1: Open the AdventureWorks solution in Visual Studio 2010 1.

Open Microsoft Visual Studio 2010.

2.

Open the AdventureWorks solution at the following location. Programming Language

Location

Visual C#

D:\Lab Files\CS\Lab 02\Starter\Exercise 03

Visual Basic

D:\Lab Files\VB\Lab 02\Starter\Exercise 03

 Task 2: Add required assemblies to the project 1.

Add references to the System.Web.Abstractions assembly to the project.

2.

Add references to the System.Web.MVC and System.Web.Routing assemblies to the project.

 Task 3: Add the MVC Assembly references and namespaces to the Web.config file 1.

Open the Web.config file in the root AdventureWorks folder.

2.

Add the following text to your Web.config file in their proper sections as shown, this adds the appropriate assemblies to your project and configures special MVC handlers: ... ... ...

2-30

Developing Web Applications with Microsoft® Visual Studio® 2010



3.

Save the Web.config file.

The final Web.config file should appear as follows [Visual C#]

Designing a Web Application

2-31

[Visual Basic]

Designing a Web Application

2-33



 Task 4: Map the default MVC request routes 1.

Import the System.Web.Mvc and System.Web.Routing namespaces in Global.asax to support MVC request routing. [Visual C#] using System.Web.Mvc; using System.Web.Routing; [Visual Basic] Imports System.Web.Mvc Imports System.Web.Routing

2.

Create a method named RegisterRoutes to register the MVC routes and exclude routes for existing Web Form pages, handlers, and WCF services. [Visual C#] public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.aspx/{*pathInfo}"); routes.IgnoreRoute("{resource}.svc/{*pathInfo}");

}

routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } );

// Parameter defaults

[Visual Basic] Shared Sub RegisterRoutes(ByVal routes As RouteCollection) routes.IgnoreRoute("{resource}.axd/{*pathInfo}") routes.IgnoreRoute("{resource}.aspx/{*pathInfo}") routes.IgnoreRoute("{resource}.svc/{*pathInfo}") routes.MapRoute( "Default", "{controller}/{action}/{id}", New With {.controller = "Home", .action = "Index", .id = ""} ) End Sub

3.

Call the RegisterRoutes in the Application_Start method. [Visual C#] protected void Application_Start(object sender, EventArgs e) {

2-34

Developing Web Applications with Microsoft® Visual Studio® 2010

}

RegisterRoutes(RouteTable.Routes);

[Visual Basic] Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) RegisterRoutes(RouteTable.Routes) End Sub

4.

Save the Global.asax file.

 Task 5: Change project to reflect an MVC Project 1.

Open the project, AdventureWorks.csproj or AdventureWorks.vbproj file in Notepad for direct editing.

2.

Locate the ProjectTypeGuids element. [Visual C#] {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b00c04f79efbc} [Visual Basic] p.ProductID == 680));

It is definitely shorter and simpler, although the use of Lambdas can make your code harder to read. Keep in mind that even if the syntax is shorter, you still need to submit your changes to the database. Question: Which method is used to submit local changes to the database? Answer: The SaveChanges method is used to submit local changes to the database.

8-18

Developing Web Applications with Microsoft® Visual Studio® 2010

Lesson 2

Using Data Source Controls

The ASP.NET framework comes with a number of web server controls, where many of them are databound and others are data source controls. The former are used to display data in a data source, such as an XML file or a database, whereas the latter are used to connect to and retrieve data from a data source and make it available for other controls to bind to, without requiring code. They can also support modifying data. This lesson explains how to use both types of controls, and describes some of the controls in detail.

Lesson Objectives After completing this lesson, you will be able to: •

Describe data bound and data source controls.



Describe the capabilities of data source controls.



Use the LinqDataSource and EntityDataSource controls.



Use the GridView, ListView, DetailsView, and Microsoft Chart controls.

Optimizing Data Management for Web Forms

8-19

Types of Data Source Controls

Key Points Data source controls have a long history within the ASP.NET framework—since version 2.0, to be exact— and they have been increasingly popular with many developers. The different data source controls in the ASP.NET framework are: AccessDataSource, EntityDataSource, LinqDataSource, ObjectDataSource, SiteMapDataSource, SqlDataSource, and XmlDataSource. The following table describes these data source controls in detail. Data Source control

Description

AccessDataSource

Enables you to work with a Microsoft Access® database. Supports sorting, filtering, and paging when data is returned as a DataSet object. This control should only be used with an Access database.

EntityDataSource

Enables you to bind to data that is based on the Entity Data Model (EDM). Supports automatic generation of update, insert, delete, and select commands. The control also supports sorting, filtering and paging.

LinqDataSource

Enables you to use Language-Integrated Query (LINQ) in an ASP.NET web page through declarative markup to retrieve and modify data from a data object. Supports automatic generation of select, update, insert, and delete commands. The control also supports sorting, filtering, and paging. The LinqDataSource control can be used with a database or an in-memory data collection such as an array.

ObjectDataSource

Enables you to work with a business object or other class and create web applications that rely on middle-tier objects to manage data. Basically, the ObjectDataSource control supports three-tier architecture by providing a way for you to bind data controls on the page to a middle-tier business object. Supports advanced sorting and paging scenarios unavailable with the other data source controls.

8-20

Developing Web Applications with Microsoft® Visual Studio® 2010

Data Source control

Description

SiteMapDataSource

Used with ASP.NET site navigation for databinding controls.

SqlDataSource

Enables you to work with Microsoft SQL Server, OLE DB, ODBC, or Oracle databases. When used with SQL Server, supports advanced caching capabilities. The control also supports sorting, filtering, and paging when data is returned as a DataSet object.

XmlDataSource

Enables you to work with an XML file, especially for hierarchical ASP.NET server controls such as the TreeView or Menu control. Supports filtering capabilities using XPath expressions and enables you to apply an XSLT transformation to the data. The XmlDataSource allows you to update data by saving the entire XML document with changes.

The programming surface and design-time experience of the EntityDataSource, LinqDataSource, ObjectDataSource, SqlDataSource and XmlDataSource controls are very similar. Common to all of the data source controls, is that they can be configured declaratively, either manually (directly in the markup), or by specifying the properties in the Properties window. Alternatively, you can use the designers, which are available from Design view of the Web Form on which the data source control is placed.

EntityDataSource Control The EntityDataSource control supports data binding scenarios in web applications that use the ADO.NET Entity Framework, and thus the EDM. The EntityDataSource control manages create, read, update, and delete operations against a data source on behalf of data-bound controls on the same web page. The EntityDataSource control works with editable grids, forms with user-controlled sorting and filtering, twoway bound drop-down list controls, and master-detail pages. You can supply parameter values to queries from page controls, cookies, query parameters appended to the page URI, and other ASP.NET parameter objects. The EntityDataSource designer makes it easier to configure an EntityDataSource control at design time.

LinqDataSource Control The LinqDataSource control exposes LINQ to web developers through the ASP.NET data source control architecture. By using declarative markup, you can create a LinqDataSource control that connects to data from either a database or an in-memory data collection such as an array. In the declarative text, you can write all the conditions that are required to retrieve, filter, order, and group the data. When you retrieve data from a SQL database table, you can also configure a LinqDataSource control to handle updating, inserting, and deleting data. The control does this without requiring you to write the SQL commands to perform these tasks. The LinqDataSource class also provides an event model that enables you to handle customized scenarios.

Additional Reading For more information about the AccessDataSource control, see AccessDataSource Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203958&clcid=0x409. For more information about the ObjectDataSource control, see ObjectDataSource Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203959&clcid=0x409.

Optimizing Data Management for Web Forms

For more information about the SiteMapDataSource control, see SiteMapDataSource Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203960&clcid=0x409. For more information about the SqlDataSource control, see SqlDataSource Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203961&clcid=0x409. For more information about the XmlDataSource control, see XmlDataSource Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203962&clcid=0x409. Question: Which data source control should you use for managing site navigation? Answer: You should you use the SiteMapDataSource control for managing site navigation.

8-21

8-22

Developing Web Applications with Microsoft® Visual Studio® 2010

Capabilities of Data Source Controls

Key Points Data source controls have different capabilities, including binding, sorting, filtering, and modifying data.

Binding The binding capability of the data source controls is what make them special; they expand the capabilities of databound controls such as the GridView, FormView, and DetailsView controls. Without this capability, there would be no need for data source controls. In fact, by working together, the data source controls and the databound controls let you retrieve, modify, page, sort, and filter data from different data sources with little or no code at all. You can work with data in a databound control by binding the databound control to a data source control such as the EntityDataSource or LinqDataSource control. The data source control is responsible for connecting to a data source, such as a database or an entity class, and then retrieving or updating the data. The databound control can then use this data. To perform the binding, you set the databound control's DataSourceID property to point to a data source control, by specifying the ID of the data source control. The databound control can automatically take advantage of the data services provided by the data source control, once databound. Here is an example of the LinqDataSource declared in markup bound to the NorthwindObjectContext, and a GridView control bound to the LinqDataSource control. ...

For the more complex databound controls, such as the GridView and FormView controls, there can be more to setting up the control, such as specifying where the individual columns from the data source are displayed. Here is an example of a FormView control, bound to the previously shown LinqDataSource control.

Optimizing Data Management for Web Forms

8-23

Product ID: Product Name: ... ...

The important thing to notice is the Eval statements in the inline code blocks that reference the columns returned by the LinqDataSource and made available by the FormView control, to which all of the Label controls belong.

Sorting The sorting capability of the data source controls is a handy feature that you can use to sort the data at runtime without requiring any code at all. Keep in mind, though, that sorting can be customized with code. To enable sorting of data at runtime, you can use the AccessDataSource, LinqDataSource, ObjectDataSource, or SqlDataSource control as your data source control. To display the data that can be sorted, you can use a GridView or a ListView control, because both controls provide a default sorting UI. The LinqDataSource control supports sorting when the AutoSort property is set to true (the default value). AllowSorting="true"

The same is true for the AccessDataSource and SqlDataSource controls, but only when the DataSourceMode property is set to DataSet (the default value). The ObjectDataSource control supports sorting only if the object returned by the SelectMethod is a DataSet, DataTable, or DataView object.

Filtering Data source controls provide filtering data based on the search criteria you specify. Filtering is especially convenient when working with cached data, because this means that you can provide search capabilities without having to re-run your queries. To filter data, you need to configure your data source control. The AccessDataSource or SqlDataSource controls, must have the DataSourceMode property set to DataSet.

8-24

Developing Web Applications with Microsoft® Visual Studio® 2010

DataSourceMode="DataSet"

When using the ObjectDataSource control, you must ensure that the underlying source object returns a DataSet or DataTable object. When using the XmlDataSource control, you can filter data using XPath queries. The LinqDataSource control supports sorting when the AutoSort property is set to true (the default value). AllowSorting="true"

The same is true for the AccessDataSource and SqlDataSource controls, but only when the DataSourceMode property is set to DataSet (the default value). The ObjectDataSource control supports sorting only if the object returned by the SelectMethod is a DataSet, DataTable, or DataView object. You can set the FilterExpression property to specify the filter to be applied to the data returned, when using an AccessDataSource, ObjectDataSource, or SqlDataSource control. The syntax for the filter expression is based on the syntax of the Expression property of the DataColumn class. For the data source controls mentioned, you can provide a parameterized filter expression. This enables you to provide filter values at runtime without writing any code. You can specify the filter expression parameters by using the FilterParameters collection. The parameters can retrieve data from controls, the QueryString object, session state, form field values, cookie values, and user profile properties. In the filter expression, you create placeholders that correspond to items in the data source control's FilterParameters collection by specifying the number of the item on the zero-based collection. You specify a placeholder in the filter expression by placing the number of the filter parameter in '{' and '}' characters. FirstName = '{0}' AND LastName LIKE '{1}'

Modifying The one capability that makes the data source controls very useful is the ability to make databound controls such as the DetailsView, FormView, GridView, and ListView controls able to modify data in the data source without any additional code. The data source control performs the data modification, so that the databound controls can support updates. The AccessDataSource, ObjectDataSource, and SqlDataSource controls can be configured with data commands to insert, update, and delete data. When you use the LinqDataSource control for data modification, you do not have to provide commands to insert, update, and delete data. Those commands are automatically generated for you, as shown.

The AccessDataSource and SqlDataSource controls enable you to supply SQL commands for modifying the data. The InsertCommand, UpdateCommand, and DeleteCommand properties are used for this purpose.

Optimizing Data Management for Web Forms

8-25

The ObjectDataSource control enables you to specify a data object method for performing a specific type of update, by setting the InsertMethod, UpdateMethod, or DeleteMethod property. You can make the data-update scenarios more flexible and secure by using parameters to pass values to be inserted, updated, or deleted in a data store. Parameter values can include the values of controls on the page, ASP.NET application variables, session values, and so on. Parameter values typically come from databound controls when those controls invoke an update, insert, or delete operation. Additionally, you can create explicit parameter objects for the data source control for a given operation, which allows you to customize the parameters.

Additional Reading For more information about binding by using data source controls, see Binding to Data Using a Data Source Control at http://go.microsoft.com/fwlink/?LinkID=203963&clcid=0x409. For more information about sorting by using data source controls, see Sorting Data with Data Source Controls at http://go.microsoft.com/fwlink/?LinkID=203964&clcid=0x409. For more information about filtering by using data source controls, see Filtering Data Using Data Source Controls at http://go.microsoft.com/fwlink/?LinkID=203965&clcid=0x409. For more information about filtering by using the XmlDataSource control, see Filtering Data Using the XmlDataSource Control at http://go.microsoft.com/fwlink/?LinkID=203966&clcid=0x409. For information on the types of parameters that can be used in the FilterParameters collection, see Using Parameters with Data Source Controls at http://go.microsoft.com/fwlink/?LinkID=2039674&clcid=0x409. Question: Which property of the LinqDataSource control should you set to enable sorting? Answer: You should set the AllowSorting property to a value of true to enable sorting.

8-26

Developing Web Applications with Microsoft® Visual Studio® 2010

Advanced GridView Control Techniques

Key Points The GridView control has been around for a number of years, and it has been a favorite control for many developers over the years. Basically, it is used to display tabular data, and you can display, edit, and delete data from many different kinds of data sources, including databases, XML files, and business objects that expose data. Besides the more obvious uses, including automatically binding to and displaying data from a data source control, as well as the ability to select, sort, page through, edit, and delete data from a data source control, the GridView control also has some more advanced features. This includes utilizing templates to create custom user interface (UI) elements, as well as customized paging.

Templates As is the case with most web server controls, the GridView control has a default look and layout, which can be customized by setting properties or by using styles. However, only some web server controls, including the GridView control, also allow you to customize their look by using templates. A template is a set of HTML elements and controls that make up the layout for a particular portion of a control. You can customize the GridView control's look by defining different templates for individual columns, as well as the pager. Templates can be created in the web form markup (.aspx) file, as XML declarations. The following example shows how you can customize the columns for a GridView at design-time.

Optimizing Data Management for Web Forms

8-27

...

Notice how the AutoGenerateColumns property has been set to False, to prevent overriding of the customization at runtime. In addition, the columns are now specified in the Columns element, which holds two different types of columns. The last one is a typical BoundField control, which does not offer customization. However, the first one is the customized TemplateField column with a HeaderText property value of ID, and it does allow for customization. The TemplateField consists of two templates: the EditItemTemplate and the ItemTemplate. The EditItemTemplate holds the markup and controls to be used when then grid is in edit mode, and the ItemTemplate holds the markup and controls to be used when then grid is in display mode. Besides customizing the columns by using the TemplateField column, it is also possible to customize the display for an empty grid, that is, with no data to display. This is done by using the EmptyDataTemplate element. There are no data to display.

Custom Paging The GridView control supports paging over the items in its data source. You set the AllowPaging property to true to enable paging. When the GridView control is bound to a data source control capable of returning a single page of data, the GridView control takes advantage of that capability. The GridView control can use custom paging in different ways. You can set the number of items to display at once by using the PageSize property.

You can also set the current page of the GridView control by setting the PageIndex property. [Visual Basic] ' Display page 3

ProductsGridView.PageIndex = 3 [Visual C#] // Display page 3 ProductsGridView.PageIndex = 3;

You can specify custom behavior by setting the PagerSettings property, which allows you to customize the appearance of the paging UI that is automatically generated by the GridView control. The GridView control can display direction controls that allow forward and backward navigation, as well as numeric controls that allow a user to move to a specific page. The PagerSettings property of the GridView control is set to a PagerSettings class, which exposes the following properties for UI customization.

8-28

Developing Web Applications with Microsoft® Visual Studio® 2010

Property Name

Description

FirstPageImageUrl

Sets the URL to an image to display for the first-page button.

FirstPageText

Sets the text to display for the first-page button.

LastPageImageUrl

Sets the URL to an image to display for the last-page button.

LastPageText

Sets the text to display for the last-page button.

Mode

Sets the mode in which to display the pager controls in a control that supports pagination. These are the valid values for this property: NextPrevious, NextPreviousFirstLast, Numeric, and NumericFirstLast.

NextPageImageUrl

Sets the URL to an image to display for the next-page button.

NextPageText

Sets the text to display for the next-page button.

PageButtonCount

Sets the number of page buttons to display in the pager when the Mode property is set to the Numeric or NumericFirstLast value.

Position

Sets a value that specifies the location where the pager is displayed in the GridView control. The valid values are: Bottom, Top, TopAndBottom.

PreviousPageImageUrl

Sets the URL to an image to display for the previous-page button.

PreviousPageText

Sets the text to display for the previous-page button.

You can also specify custom behavior by supplying a pager template. This is done by setting the PagerTemplate property. This property gets or sets custom content for the pager row in the GridView control. To specify which paging operation to perform, include a Button control with the CommandName property set to Page and a CommandArgument set to one of the following values: First, Last, Prev, Next, or a page number. ASP.NET Dynamic Data automatically adds a custom control named GridViewPager.ascx as the custom pager for the GridView control with the List.aspx and ListDetails.aspx page templates. Parts of the ListDetails.aspx web form are shown below. ... ... ...

Additional Reading For more information about the PagerSettings class, see PagerSettings Class at http://go.microsoft.com/fwlink/?LinkID=203968&clcid=0x409. Question: Which XML element is used for customizing the display of an empty data source in the GridView control?

Optimizing Data Management for Web Forms

8-29

Answer: You use the EmptyDataTemplate element to customize the display of an empty data source in the GridView control.

8-30

Developing Web Applications with Microsoft® Visual Studio® 2010

Walkthrough: Creating a GridView TemplateField

Key Points While it is possible to create templated fields, or TemplateField objects in your markup manually, it is easier and quicker to use the GridView Tasks dialog box. This dialog box is accessible, when you open your master page, web form, or user control, in Design view. As described in the previous topic, TemplateField objects can be used when the AutoGenerateColumns property of the GridView control is set to False. This means you must manually add the columns to be displayed to the user, and these must be added to the Columns item, in your markup. 1.

When in Design view, you first select the GridView control for which you want to create the TemplateField object(s).

2.

With the GridView control selected, click the Smart Tag button, and then in the GridView Tasks dialog box, click Edit Columns.

3.

With the Fields dialog box open, in the Selected fields list, click the existing field/column that you want to convert to a TemplateField object, and then click Convert this field into a TemplateField.

4.

If you want to create a new TemplateField object, with the Fields dialog box open, click TemplateField in the Available fields list, and then click Add.

Question: Which dialog box can be used to create a TemplateField object for the GridView control? Answer: You use the Fields dialog box to create a TemplateField object for the GridView control.

Optimizing Data Management for Web Forms

8-31

How to Use the ListView and DetailsView Controls

Key Points Both the ListView and DetailsView controls are used to display data from a data source, but they are different in how the data is presented. The ListView control is similar to the GridView control, in that it displays the data in a tabular manner, whereas the DetailsView only displays the values for a single row from the data source at a time.

ListView While the ListView is similar to the GridView control, in functionality and default appearance, it displays the values of a data source by using user-defined templates. This means that unlike the GridView control, you can customize the individual items amongst other customization options. In order for the ListView control to display content, you must create templates for different parts of the control. The ItemTemplate is required; all other templates are optional. The LayoutTemplate property is not required. The ListView control is useful for data in any repeating structure, similar to the DataList and Repeater controls. However, unlike those controls, by default, and without any coding, the ListView control enables the user to edit, insert, and delete data, and to sort and page data. The following example shows how the ListView control can be customized by using templates.

8-32

Developing Web Applications with Microsoft® Visual Studio® 2010

... ... ID ... ...

The LayoutTemplate element is used for specifying if and how the content should be contained. In the example, the content is contained in an HTML table element, which is also evident from the HTML tr and td elements in the content templates. The SelectedItemTemplate is used to specify the appearance for the currently selected item, if any. The ItemTemplate is used to specify the appearance for all items not covered by the other templates, such as the SelectedItemTemplate, EditItemTemplate, and InsertItemTemplate templates. The EditItemTemplate is used to specify the appearance for the item

Optimizing Data Management for Web Forms

8-33

currently being modified, if any. The InsertItemTemplate is used to specify the appearance for the item currently being modified for inserting, if any.

DetailsView The DetailsView control displays the values of a single row from a data source in a table, and by default, each column/field from the data row is displayed on its own line/table row. Each data row in the DetailsView control is created by declaring a field control. Different row field types determine the behavior of the rows in the control. Field controls derive from DataControlField, and these are field types that can be used: BoundField, ButtonField, CheckBoxField, CommandField, HyperLinkField, ImageField, and TemplateField. The HyperLinkField is often used to display e-mail addresses and URLs, and the CheckBoxField is often used to display Boolean values. The DetailsView control can be used in combination with a GridView control for master-detail scenarios, as it is done in ASP.NET Dynamic Data, in the ListDetails.aspx page template.

Additional Reading For more information about the ListView control, see ListView Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203969&clcid=0x409. For more information about the DetailsView control, see DetailsView Web Server Control Overview at http://go.microsoft.com/fwlink/?LinkID=203970&clcid=0x409. Question: Which ListView control template element do you use to specify the appearance for an item that is currently being edited? Answer: The EditItemTemplate is used to specify the appearance for the item currently being modified in a ListView control.

8-34

Developing Web Applications with Microsoft® Visual Studio® 2010

Using the Microsoft Chart Control

Key Points The Microsoft Chart control provides rich data visualization for developers. It enables you to create ASP.NET pages with simple, intuitive, and visually compelling charts for complex statistical or financial analysis. The Chart control enables you to add robust charting abilities to your applications with little effort. In line with the other controls in this lesson, the Microsoft Chart control is used to present data in a number of different ways, by using the many distinct chart types, most of which support 3D. The Chart control can be found in the Toolbox, on the Data tab.

By binding the Chart control to a data source controls, as shown previously, you can show the data retrieved from the data source with little or no code, simply by settings the properties in your markup. The following markup shows how little configuration you can use, in many cases, to display the data in the data source control.

Optimizing Data Management for Web Forms

8-35



The easiest and simplest way to configure the Chart control is to add it to your web form in Design view, specify the data source control, and then select the chart type.

Once you have selected the chart type, you can preview not only the data from the data source, but also set the member for the X and axis for the first data series. The member is a column/field from the data returned by the data source control.

Configuring a Basic Chart These are the basic steps to setting up your Chart control, once you have placed it on your web form. 1

Right-click the Chart control in the design area, and then click Properties.

2

In the Properties window, click the Categorized button. In the Chart category of the Properties window, click the ChartAreas collection property, and then click the ellipsis button (…). The ChartAreas Collection Editor opens. Note: The ChartAreas collection (a ChartAreaCollection object) contains all chart areas in the Chart control. Notice that the collection already contains a chart area named "ChartArea1". a.

Click Add, and then click OK. A new ChartArea object is added to the collection with the default name "ChartArea2".

Note: The chart in the design area shrinks to half the original size. This is because the newly created chart area is placed at the bottom, but does not contain a data series yet. b.

In the Properties window, click the Series collection, and then click the ellipsis button. The Series Collection Editor opens.

8-36

Developing Web Applications with Microsoft® Visual Studio® 2010

Note: The Series collection (a SeriesCollection object) contains all data series in the Chart control. Notice that the collection already contains a series named "Series1". c.

In the Series Collection editor, click Add, and then set the following properties with the newly created Series object:

Property

Value

ChartArea

ChartArea2

ChartType

Bar

Name

BarChart

d.

Click OK, and then click OK again.

Now that there are chart areas, each chart area contains one data series. However, you will not see anything when you run your application because the series do not have any data yet.

Adding Legends to the Chart 1.

In the Chart category of the Properties window, click the Legends collection property, and then click the … button at the right. The Legend Collection Editor opens. Note: The Legends collection (a LegendCollection object) contains all legends in the Chart control.

2.

If there is not already a legend in the Legend Collection editor, click Add. a. Set the following properties with the Legend object: Property

Value

DockedToChartArea

ChartArea1

Docking

Right

IsDockedInsideChartArea

False

b.

Click Add again, and then set the following properties with the newly created Legend object:

Property

Value

DockedToChartArea

ChartArea2

Docking

Right

c.

Click OK.

Note: In the design area, the second legend is shown to be empty. By default, both series are assigned to the first legend. You can assign each series to a different legend. d.

Open the Series Collection editor again.

e.

In the Members area, select BarChart.

Optimizing Data Management for Web Forms

f.

8-37

In the Legend category of the BarChart properties area, in the Legend property's drop-down list, select Legend2, and then click OK.

Adding a Title to the Chart •

In the Chart category of the Properties window, click the Titles collection property, and then click the ellipsis button. The Title Collection editor opens. Note: The Titles collection (a TitleCollection object) contains all titles in the Chart control. a.

In the Legend Collection editor, click Add.

b.

In the Appearance category of the Title1 properties area, type a chart title in the Text property, and then click OK.

Additional Reading For some samples of how to use the Microsoft Chart controls, see Samples Environment for Microsoft Chart Controls at http://go.microsoft.com/fwlink/?LinkID=203971&clcid=0x409. Question: Where in Visual Studio 2010 can you find the Chat control? Answer: The Chart control can be found on the Data tab of the Toolbox in Visual Studio 2010.

8-38

Developing Web Applications with Microsoft® Visual Studio® 2010

Lab 8A: Optimizing Data Management for Web Forms

Note: You can perform tasks in this lab either by using Visual Basic or Visual C# programming language. If you are using Visual Basic as your programming language, refer to the steps provided in the Section 1 of the lab document. If you are using Visual C# as your programming language, refer to the steps provided in Section 2 of the lab document.

Objectives After completing this lab, you will be able to: •

Manage data by using the LinqDataSource control.



Display data using the grid control.



Display parent and child data in the list and detail controls.



Display dashboard information using the chart control.

Introduction In this lab, you will develop the administration section of the website by using various ASP.NET data source controls.

Optimizing Data Management for Web Forms

8-39

Lab Scenario

The AdventureWorks Sales team has requested the addition of an administration section to the website so that they can manage information, as well as provide a dashboard to senior management. As a first step toward this end, you need to create a set of web form pages that will enable the Sales team to do the following: •

View, add, edit, and delete products



View sales orders



View and edit customer details



Display sales information in a graphical format (dashboard)

In this lab, you will develop the administration section of the website by using various ASP.NET data source controls.

8-40

Developing Web Applications with Microsoft® Visual Studio® 2010

Section 1: Visual Basic Exercise 1: Managing Data by Using LINQ to Entities The main tasks in this exercise are as follows: •

Create a new Entity Framework data model.

 Task 1: Open an existing ASP.NET web application 1.

Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd.

2.

Open Microsoft Visual Studio 2010.

3.

Open the AdventureWorks solution from the D:\Lab Files\VB\Lab 08\Starter\Exercise 01 folder.

 Task 2: Create a new Entity Framework data model 1.

Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx. The data model should be generated from a database, by using the AdventureWorksLT2008 connection string from the Web.config file. All tables from the database, with the exception of the BuildVersion table, should be added to the data model.

2.

Save and close the ADO.NET Entity Data Model item.

3.

Build the project and fix any errors.

4.

Close Visual Studio 2010.

Optimizing Data Management for Web Forms

8-41

Exercise 2: Customizing the GridView The main tasks in this exercise are as follows: 1.

Create a Shopping Cart Quantity user control.

2.

Modify the ShoppingCart entity class.

3.

Convert a BoundField column to TemplateField.

4.

Add Computed column to the GridView control.

5.

Make GridView updatable.

6.

Add user control to TemplateField

7.

Implement GridView paging.

8.

Test the GridView control.

 Task 1: Open an existing ASP.NET web application 1.

Open Microsoft Visual Studio 2010.

2.

Open the AdventureWorks solution from the the D:\Lab Files\VB\Lab 08\Starter\Exercise 02 folder.

 Task 2: Create a Shopping Cart Quantity user control 1.

Create a new user control named Quantity.ascx.

2.

Add a TextBox control named QuantityTextBox to the user control.

3.

Add a RequiredFieldValidator control named QuantityRequiredFieldValidator to the user control. The RequiredFieldValidator control must validate the QuantityTextBox control, and display the text “You must fill in the Quantity.” as the error message, if the user leaves the text box empty. The display mode must be dynamic.

4.

Add a public property named Text to the user control. The property must be of type String, and get and set the Text property of the QuantityTextBox control. Public Property Text As String Get Return QuantityTextBox.Text End Get Set(ByVal value As String) QuantityTextBox.Text = value End Set End Property

5.

Save and close the user control.

6.

Build the project and fix any errors.

8-42

Developing Web Applications with Microsoft® Visual Studio® 2010

Note: Observe the “Build succeeded” message in the Build pane of the Output window.

 Task 3: Modify the ShoppingCart entity class 1.

Open the ShoppingCart.vb class file.

2.

Add a private member variable named productQuantity of type Integer to the ShoppingCart class. Private productQuantity As Integer

3.

Modify the auto-implemented Quantity property, to get and set the productQuantity member variable. Public Property Quantity As Integer Get Return productQuantity End Get Set productQuantity = value End Set End Property

4.

Add an auto-implemented TotalPrice property, of type Decimal. Public Property TotalPrice As Decimal

5.

Update the TotalPrice property, when the Quantity property is set. TotalPrice = productQuantity * ListPrice

6.

Save and close the ShoppingCart entity class.

7.

Build the project and fix any errors.

 Task 4: Convert a BoundField column to TemplateField 1.

Open the ShoppingCart.aspx content page in Design view.

2.

Select the gvCart GridView control.

3.

Open the Fields dialog box for the GridView control, by using the Smart Tag.

4.

Convert the Quantity field to a template field.

 Task 5: Add Computed column to GridView control 1.

Append a new template field with a HeaderText property value of Total Price and close the Fields dialog box.

2.

Open the ShoppingCart.aspx content page in Source view. Note: Observe how the Quantity field/column has been converted into a TemplateField, and the newly added Total Price TemplateField.

 Task 6: Make GridView updatable •

Open the ShoppingCart.aspx content page in Design view. a.

Select the gvCart GridView control.

Optimizing Data Management for Web Forms

b.

Set the AutoGenerateEditButton property to a value of True.

c.

Add an event handler for the RowCancelingEdit event.

d.

Add an event handler for the RowEditing event.

e.

Add an event handler for the RowUpdating event.

f.

Make the existing code in the Page_Load event handler execute only on first request by wrapping the existing code in the Page_Load event handler in an If statement.

8-43

If Not IsPostBack Then End If

g.

Add a new Sub/void method named BindData to the ShoppingCart1 class.

Private Sub BindData() Dim cart As List(Of ShoppingCart) = CType(Session("_cart"), List(Of ShoppingCart)) gvCart.DataSource = cart gvCart.DataBind() End Sub

h.

Add code to the gvCart_RowEditing method, for setting the edit index and bind the data by using the BindData method.

Protected Sub gvCart_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvCart.RowEditing ' Set edit index gvCart.EditIndex = e.NewEditIndex ' Bind data BindData() End Sub

i.

Add code to the gvCart_RowCancelingEdit method, for resetting the edit index and bind the data by using the BindData method. Protected Sub gvCart_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gvCart.RowCancelingEdit ' Reset edit index gvCart.EditIndex = -1 ' Bind data BindData() End Sub

j.

Add code to the gvCart_RowUpdating method, for retrieving the existing cart from Session. ' Retrieve existing cart from session Dim cart As List(Of ShoppingCart) = CType(Session("_cart"), List(Of ShoppingCart))

k.

Append code to the gvCart_RowUpdating method, for retrieving the current row from the GridView control.

' Get current row Dim row As GridViewRow = gvCart.Rows(e.RowIndex)

l.

Append code to the gvCart_RowUpdating method, for finding the matching row in the stored cart, stored in a new variable named cartToEdit of type ShoppingCart. Use the generic List Find method with an anonymous Lambda expression. ' Find matching row in stored cart Dim cartToEdit As ShoppingCart = cart.Find(Function(cartToFind) cartToFind.ProductId = Integer.Parse(row.Cells(1).Text))

m. Append code to the gvCart_RowUpdating method, for updating the quantity value of the cartToEdit shopping cart with the value of the Text property of the Quantity user control, located in the current row of the GridView control.

8-44

Developing Web Applications with Microsoft® Visual Studio® 2010

Dim qty As Quantity = CType(gvCart.Rows(e.RowIndex).FindControl("Quantity1"), Quantity) cartToEdit.Quantity = Integer.Parse(qty.Text)

n.

Append code to the gvCart_RowUpdating method, to save the updated cart to Session state.

' Save updated cart to session Session("_cart") = cart

o.

Append code to the gvCart_RowUpdating method, for resetting the edit index and bind the data by using the BindData method.

' Reset edit index gvCart.EditIndex = -1 ' Bind data BindData()

p.

Save and close the ShoppingCart code-behind file.

q.

Build the project and fix any errors.

 Task 7: Add user control to TemplateField •

Add the user control to the Shopping Cart Web Form.

Note: Observe how the Quantity user control has been registered using the Register directive, and the user control has been added to the Web Form. a.

Move the markup for the Quantity user control to the top of the EditItemTemplate element.

b.

Copy the Text attribute and value from the TextBox1 control to the Quantity1 control.

c.

Delete the TextBox1 control.

d.

Make the ProductId BoundField control read-only.

e.

Format the display of the ListPrice BoundField control using the DataFormatString attribute and a value of {0:c}.

f.

Modify the format of the TemplateField control with a HeaderText attribute value of Total Price, to appear as follows.

 Task 8: Implement GridView paging •

Set the AllowPaging property to true for GridView control. a.

Set the PageSize property to 1 for GridView control.

b.

Add an event handler for the PageIndexChanging event.

Optimizing Data Management for Web Forms

c.

8-45

Add code to prevent page index to change, when in edit mode, and display an appropriate error message in the lblMessage Label control, by using the following code.

' Cancel paging operation if user attempts to navigate ' to another page while in edit mode If CType(sender, GridView).EditIndex -1 Then ' Cancel paging operation e.Cancel = True ' Display error message Dim newPageIndex As Integer = e.NewPageIndex + 1 lblMessage.Text = "Update the item before moving to page " & newPageIndex.ToString() Else ' Clear message text lblMessage.Text = "" ' Set page index CType(sender, GridView).PageIndex = e.NewPageIndex BindData() End If

d.

Save and close the ShoppingCart files.

e.

Build the project and fix any errors.

 Task 9: Test the GridView control •

Run the application. a.

On the Home page, in the Product Categories list, click Bike Stands, and then click Submit.

b.

On the Products page, in the Bike Stands list, click All-Purpose Bike Stand.

c.

On the Product Detail page, click Order.

d.

On the Shopping Cart page, click Edit.

e.

In the Quantity box, type 5, and then click Update.

Note: Observe how the Quantity and Total Price columns are updated. f.

On the Shopping Cart page, click Continue Shopping.

g.

On the Home page, in the Product Categories list, click Cranksets, and then click Submit.

h.

On the Products page, in the Cranksets list, click HL Crankset.

i.

On the Product Detail page, click Order.

Note: Observe that the customized pager has been added to the GridView, now that more items than the specified page size have been added to the GridView. j.

On the Shopping Cart page, in the GridView pager, click 2.

k.

Close Windows® Internet Explorer®.

l.

Close Visual Studio 2010.

Note: The page index is changed and the content updated appropriately.

8-46

Developing Web Applications with Microsoft® Visual Studio® 2010

Exercise 3: Using ListView, DetailsView and Charts The main tasks in this exercise are as follows: 1.

Create the Sales Orders Master Details view.

2.

Test the Master Details view.

3.

Create the Sales Order Items History dashboard.

4.

Test the Master Details view.

 Task 1: Open an existing ASP.NET web application •

Open Microsoft Visual Studio 2010. a.

Open the AdventureWorks solution from the D:\Lab Files\VB\Lab 08\Starter\Exercise 03 folder.

 Task 2: Create the Sales Orders Master Details view •

Build the project. a.

Open the SalesOrders.aspx content page in Design view.

b.

Place the cursor in the HTML p element at the bottom of the MainContent Content control.

c.

Add a ListView control named SalesOrdersListView to the p element.

d.

Add a new LinqDataSource control, by using the SalesOrdersListView Smart Tag.

e.

Use LINQ as the data source, and name the LinqDataSource control SalesOrdersLinqDataSource, by using the Data Source Configuration Wizard.

f.

Select the AdventureWorks.AdventureWorks2008LTEntities object context using the existing Entity Data Model as the object context for the LinqDataSource control.

g.

Select the SalesOrderHeaders table and include the SalesOrderID, OrderDate, DueDate, ShipDate and CustomerID fields for the LinqDataSource control.

h.

Select only sales orders that have already shipped, by specifying a where clause, and compare ShipDate with the DateTime.Now method.

i.

Order the sales orders by CustomerID and ShipDate, by specifying an Order By clause.

j.

Finish the Data Source Configuration Wizard.

k.

Set the SalesOrderID field as the DataKeyNames property value.

l.

Open the SalesOrders.aspx web form in Source view.

m. Remove the WhereParameters element from the LinqDataSource control.

n.

Modify the Where property to appear as follows.

Where="ShipDate <= DateTime.Now"

o.

Open the SalesOrders.aspx web form in Design view.

p.

Configure the SalesOrdersListView control, by using the SalesOrdersListView Smart Tag. Refresh the schema before configuring the control.

q.

Select the Grid layout and the Professional style for the SalesOrdersListView control.

Optimizing Data Management for Web Forms

r.

Enable paging for the SalesOrdersListView control.

s.

Disable editing and inserting a SalesOrderHeader item in the SalesOrdersListView control, by deleting the corresponding templates in Source view.

t.

Add a Select button to the AlternatingItemTemplate and ItemTemplate elements. Use the Button server control and place it at the top of the HTML tr element.

8-47



u.

Add an empty HTML th element to the LayoutTemplate element. Make the th element a server control and place it at the top of the HTML tr element.



v.

Add an empty HTML td element to the SelectedItemTemplate element. Place it at the top of the HTML tr element.



w. Add an empty HTML p element below the existing p element.

x.

Add a new LinqDataSource control with the following markup, within the empty HTML p element.



y.

Add a DetailsView control with the following markup, at the top of the new HTML p element.



8-48

Developing Web Applications with Microsoft® Visual Studio® 2010



 Task 3: Test the Master Details view •

Run the application. a.

On the Sales Orders page, click Select for any item in the ListView control.

b.

The DetailsView containing the Sales Order Details is displayed below the ListView control.

c.

Close Windows® Internet Explorer®.

 Task 4: Create the Sales Order Items History dashboard •

Open the SalesOrderItemsHistory.aspx content page in Source view. a.

Add an EntityDataSource control named SalesOrderItemsEntityDataSource to the MainContent Content control.



b.

Open the SalesOrderItemsHistory.aspx content page in Design view.

c.

Add a Chart control named SalesOrderItemsHistoryChart.

d.

Set the Chart type to Bar by using the Smart Tag.

e.

Use the SalesOrderItemsEntityDataSource control as the data source, by using the DataSourceID property, the X values should come from the SalesOrderItems field, the Y values should come from the OrderDate field. Refresh the schema, after selecting the data source control.

f.

Modify the default chart area, by setting the X and Y axis titles to # Sales Order Items and Order Date. Use the ChartArea Collection Editor, accessible from the Properties window.

 Task 5: Test the Master Details view •

Run the application. Note: Observe how the Chart shows how the number of items per order are shown by order date. a.

Close Internet Explorer.

b.

Close Visual Studio 2010.

 Task 6: Turn off the virtual machine and revert the changes •

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off. a.

In the Turn Off Machine dialog box, click Turn Off.

b.

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

Optimizing Data Management for Web Forms

c.

In the Revert Virtual Machine dialog box, click Revert.

Note: The answers to the exercises are on the Course Companion CD.

8-49

8-50

Developing Web Applications with Microsoft® Visual Studio® 2010

Section 2: Visual C# Exercise 1: Managing Data by Using LINQ to Entities The main tasks in this exercise are as follows: •

Create a new Entity Framework Data Model.

 Task 1: Open an existing ASP.NET web application •

Open Microsoft Visual Studio 2010. •

Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 08\Starter\Exercise 01 folder.

 Task 2: Create a new Entity Framework Data model •

Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx. The data model should be generated from a database, by using the AdventureWorksLT2008 connection string from the Web.config file. All tables from the database, with the exception of the BuildVersion table, should be added to the data model. a.

Close the ADO.NET Entity Data Model item.

b.

Build the project and fix any errors.

c.

Close Visual Studio 2010.

Optimizing Data Management for Web Forms

8-51

Exercise 2: Customizing the GridView The main tasks in this exercise are as follows: 1.

Create a Shopping Cart Quantity user control.

2.

Modify the ShoppingCart entity class.

3.

Convert a BoundField column to TemplateField.

4.

Add Computed Column to the GridView control.

5.

Make GridView updatable.

6.

Add user control to TemplateField.

7.

Implement GridView paging.

8.

Test the GridView control.

 Task 1: Open an existing ASP.NET web application •

Open Microsoft Visual Studio 2010. •

Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 08\Starter\Exercise 02 folder.

 Task 2: Create a Shopping Cart Quantity user control •

Create a new user control named Quantity.ascx. a.

Add a TextBox control named QuantityTextBox to the user control.



b.

Add a RequiredFieldValidator control named QuantityRequiredFieldValidator to the user control. The RequiredFieldValidator control must validate the QuantityTextBox control, and display the text “You must fill in the Quantity.” as the error message, if the user leaves the text box empty. The display mode must be dynamic.



c.

Add a public property named Text to the user control. The property must be of type string, and get and set the Text property of the QuantityTextBox control.

public string Text { get { return QuantityTextBox.Text; } set { QuantityTextBox.Text = value; } }

d.

Save and close the user control.

e.

Build the project and fix any errors.

Note: Observe the Build succeeded message in the Build pane of the Output window.

8-52

Developing Web Applications with Microsoft® Visual Studio® 2010

 Task 3: Modify ShoppingCart Entity class •

Open the ShoppingCart.cs class file. a.

Add a private member variable named productQuantity of type int to the ShoppingCart class.

private int productQuantity;

b.

Modify the auto-implemented Quantity property, to get and set the productQuantity member variable.

public int Quantity { get { return productQuantity; } set { productQuantity = value; } }

c.

Add an auto-implemented TotalPrice property, of type decimal.

public decimal TotalPrice { get; set; }

d.

Update the TotalPrice property, when the Quantity property is set.

TotalPrice = productQuantity * ListPrice;

e.

Save and close the ShoppingCart entity class.

f.

Build the project and fix any errors.

 Task 4: Convert a BoundField column to TemplateField •

Open the ShoppingCart.aspx content page in Design view. a.

Select the gvCart GridView control.

b.

Open the Fields dialog box for the GridView control, by using the Smart Tag.

c.

Convert the Quantity field to a template field.

 Task 5: Add Computed column to GridView control 1

Append a new template field with a HeaderText property value of Total Price and close the Fields dialog box.

2

Open the ShoppingCart.aspx content page in Source view. Note: Observe how the Quantity field/column has been converted into a TemplateField, and the newly added Total Price TemplateField.

 Task 6: Make GridView updatable •

Open the ShoppingCart.aspx content page in Design view. a.

Select the gvCart GridView control.

b.

Set the AutoGenerateEditButton property to a value of True.

c.

Add an event handler for the RowCancelingEdit event.

d.

Add an event handler for the RowEditing event.

Optimizing Data Management for Web Forms

e.

Add an event handler for the RowUpdating event.

f.

Make the existing code in the Page_Load event handler execute only on first request by wrapping the existing code in the Page_Load event handler in an if statement.

8-53

if (!IsPostBack) { }

g.

Add a new void method named BindData to the ShoppingCart class.

private void BindData() { List cart = (List) Session["_cart"]; gvCart.DataSource = cart; gvCart.DataBind(); }

h.

Add code to the gvCart_RowEditing method, for setting the edit index and bind the data by using the BindData method.

protected void gvCart_RowEditing(object sender, GridViewEditEventArgs e) { // Set edit index gvCart.EditIndex = e.NewEditIndex; // Bind data BindData(); }

i.

Add code to the gvCart_RowCancelingEdit method, for resetting the edit index and bind the data by using the BindData method. protected void gvCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { // Reset edit index gvCart.EditIndex = -1; // Bind data BindData(); }

j.

Add code to the gvCart_RowUpdating method, for retrieving the existing cart from Session. // Retrieve existing cart from session List cart = (List) Session["_cart"];

k.

Append code to the gvCart_RowUpdating method, for retrieving the current row from the GridView control.

// Get current row GridViewRow row = gvCart.Rows[e.RowIndex];

l.

Append code to the gvCart_RowUpdating method, for finding the matching row in the stored cart, stored in a new variable named cartToEdit of type ShoppingCart. Use the generic List Find method with an anonymous Lambda expression. // Find matching row in stored cart ShoppingCart cartToEdit = cart.Find((cartToFind) => cartToFind.ProductId == int.Parse(row.Cells[1].Text));

m. Append code to the gvCart_RowUpdating method, for updating the quantity value of the cartToEdit shopping cart with the value of the Text property of the Quantity user control, located in the current row of the GridView control. // Update values Quantity qty = gvCart.Rows[e.RowIndex].FindControl("Quantity1") as Quantity; cartToEdit.Quantity = int.Parse(qty.Text);

n.

Append code to the gvCart_RowUpdating method, for saving the updated cart to Session state.

8-54

Developing Web Applications with Microsoft® Visual Studio® 2010

// Save updated cart to session Session["_cart"] = cart;

o.

Append code to the gvCart_RowUpdating method, for resetting the edit index and bind the data by using the BindData method.

// Reset edit index gvCart.EditIndex = -1; // Bind data BindData();

p.

Save and close the ShoppingCart code-behind file.

q.

Build the project and fix any errors.

 Task 7: Add User control to TemplateField •

Add the user control to the Shopping Cart web form. a.

Open the ShoppingCart.aspx content page in Source view.

Note: Observe how the Quantity user control has been registered using the Register directive, and the user control has been added to the web form. b.

Move the markup for the Quantity user control to the top of the EditItemTemplate element.



c.

Copy the Text attribute and value from the TextBox1 control to the Quantity1 control.



d.

Delete the TextBox1 control.



e.

Make the ProductId BoundField control read-only.

ReadOnly="true"

f.

Format the display of the ListPrice BoundField control using the DataFormatString attribute and a value of {0:c}. DataFormatString="{0:c}"

g.

Modify the format of the TemplateField control with a HeaderText attribute value of Total Price, to appear as follows.



 Task 8: Implement GridView paging •

Set the AllowPaging property to true for GridView control. a.

Set the PageSize property to 1 for GridView control.

Optimizing Data Management for Web Forms

b.

Add an event handler for the PageIndexChanging event.

c.

Add code to prevent page index to change, when in edit mode, and display an appropriate error message in the lblMessage Label control, by using the following code.

// Cancel paging operation if user attempts to navigate // to another page while in edit mode if (((GridView) sender).EditIndex != -1) { // Cancel paging operation e.Cancel = true; // Display error message int newPageIndex = e.NewPageIndex + 1; lblMessage.Text = "Update the item before moving to page " + newPageIndex.ToString();

} else { // Clear message text lblMessage.Text = ""; // Set page index ((GridView) sender).PageIndex = e.NewPageIndex; BindData(); }

d.

Save and close the ShoppingCart files.

e.

Build the project and fix any errors.

 Task 9: Test GridView control •

8-55

Run the application. a.

On the Home page, in the Product Categories list, click Bike Stands, and then click Submit.

b.

On the Products page, in the Bike Stands list, click All-Purpose Bike Stand.

c.

On the Product Detail page, click Order.

d.

On the Shopping Cart page, click Edit.

e.

In the Quantity box, type 5, and then click Update.

Note: Observe how the Quantity and Total Price columns are updated. f.

On the Shopping Cart page, click Continue Shopping.

g.

On the Home page, in the Product Categories list, click Cranksets, and then click Submit.

h.

On the Products page, in the Cranksets list, click HL Crankset.

i.

On the Product Detail page, click Order.

Note: Observe that the customized pager has been added to the GridView, now that more items than the specified page size has been added to the GridView. j.

On the Shopping Cart page, in the GridView pager, click 2.

Note: Observe that the page index is changed and the content updated appropriately.

8-56

Developing Web Applications with Microsoft® Visual Studio® 2010

k.

Close Windows® Internet Explorer®.

l.

Close Visual Studio 2010.

Optimizing Data Management for Web Forms

8-57

Exercise 3: Using ListView, DetailsView and Charts The main tasks in this exercise are as follows: 1.

Create the Sales Orders Master Details view.

2.

Test the Master Details view.

3.

Create the Sales Order Items History dashboard.

4.

Test the Master Details view.

 Task 1: Open an existing ASP.NET web application •

Open Microsoft Visual Studio 2010. •

Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 08\Starter\Exercise 03 folder.

 Task 2: Create the Sales Orders Master Details view •

Build the project. a.

Open the SalesOrders.aspx content page in Design view.

b.

Select the HTML p element at the bottom of the MainContent Content control.

c.

Add a ListView control named SalesOrdersListView to the p element.

d.

Add a new LinqDataSource control, by using the SalesOrdersListView Smart Tag.

e.

Use LINQ as the data source, and name the LinqDataSource control SalesOrdersLinqDataSource, by using the Data Source Configuration Wizard.

f.

Select the AdventureWorks.AdventureWorksLT2008Entities object context from the existing Entity Data Model as the object context for the LinqDataSource control.

g.

Select the SalesOrderHeaders table and include the SalesOrderID, OrderDate, DueDate, ShipDate and CustomerID fields for the LinqDataSource control.

h.

Select only sales orders that have already shipped, by specifying a where clause, and compare ShipDate with the DateTime.Now method.

i.

Order the sales orders by CustomerID and ShipDate, by specifying an Order By clause.

j.

Finish the Data Source Configuration Wizard.

k.

Set the SalesOrderID field as the DataKeyNames property value.

l.

Open the SalesOrders.aspx web form in Source view.

m. Remove the WhereParameters element from the LinqDataSource control.

n.

Modify the Where property to appear as follows.

Where="ShipDate <= DateTime.Now"

o.

Open the SalesOrders.aspx web form in Design view.

p.

Configure the SalesOrdersListView control, by using the SalesOrdersListView Smart Tag. Refresh the schema before configuring the control.

q.

Select the Grid layout and the Professional style for the SalesOrdersListView control.

8-58

Developing Web Applications with Microsoft® Visual Studio® 2010

r.

Enable paging for the SalesOrdersListView control.

s.

Disable editing and inserting a SalesOrderHeader item in the SalesOrdersListView control, by deleting the corresponding templates.

t.

Add a Select button to the AlternatingItemTemplate and ItemTemplate elements. Use the Button server control and place it at the top of the HTML tr element.

u.

Add an empty HTML th element to the LayoutTemplate element. Make the th element a server control and place it at the top of the HTML tr element.



v.

Add an empty HTML td element to the SelectedItemTemplate element. Place it at the top of the HTML tr element.



w. Add an empty HTML p element below the existing p element.

x.

Add a new LinqDataSource control with the following markup, within the empty HTML p element.



y.

Add a DetailsView control with the following markup, at the top of the new HTML p element.



Optimizing Data Management for Web Forms

8-59



 Task 3: Test the Master Details view •

Run the application. a.

On the Shopping Cart page, click Select, for any item in the ListView control.

b.

The DetailsView containing the Sales Order Details is displayed below the ListView control.

c.

Close Windows® Internet Explorer®.

 Task 4: Create the Sales Order Items History dashboard •

Open the SalesOrderItemsHistory.aspx content page in Source view. a.

Add an EntityDataSource control named SalesOrderItemsEntityDataSource to the MainContent Content control.



b.

Open the SalesOrderItemsHistory.aspx content page in Design view.

c.

Add a Chart control named SalesOrderItemsHistoryChart.

d.

Set the Chart type to Bar by using the Smart Tag.

e.

Use the SalesOrderItemsEntityDataSource control as the data source, by using the DataSourceID property, the X values should come from the SalesOrderItems field, the Y values should come from the OrderDate field. Refresh the schema, after selecting the data source control.

f.

Modify the default chart area, by setting the X and Y axis titles to # Sales Order Items and Order Date. Use the ChartArea Collection Editor, accessible from the Properties window.

 Task 5: Test the Master Details view •

Run the application. Note: Observe how the Chart shows how the number of items per order are shown by order date. a.

Close Internet Explorer.

b.

Close Visual Studio 2010.

 Task 6: Turn off the virtual machine and revert the changes •

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off. a.

In the Turn Off Machine dialog box, click Turn Off.

b.

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

8-60

Developing Web Applications with Microsoft® Visual Studio® 2010

c.

In the Revert Virtual Machine dialog box, click Revert.

Note: The answers to the exercises are on the Course Companion CD.

Optimizing Data Management for Web Forms

8-61

Lab Review

Review Questions and Answers Question: Why did you create a templated column in the GridView control? Answer: You created the templated column in the GridView control to add a custom user control, which is used to display the shopping cart quantity. Question: For which purpose did you use the DetailsView control? Answer: You used the DetailsView control to display the details of a selected order.

8-62

Developing Web Applications with Microsoft® Visual Studio® 2010

Lesson 3

Using ASP.NET Dynamic Data

Because of the amount of markup and code that must be created when you enable data in your data source to be viewed and possibly managed from a web interface, it can be advantageous to use page templates for this purpose and thus save valuable development time. Using ASP.NET Dynamic Data, you can set up your data source, a data model to manage the data, a scaffolding to determine which tables and columns get displayed, the routing to specify the way the user can request to view the various tables, and the page and field templates that determine the behavior of the tables and fields when displayed. ASP.NET Dynamic Data is a framework that enables you to build a functional, data-driven application quickly, based on an Entity Framework or LINQ to SQL data model. ASP.NET Dynamic Data is specifically used to create data-driven applications. Data-driven applications use, manipulate, and analyze data to perform tasks. ASP.NET Dynamic Data can also be used for creating websites that display and manage data that is automatically read and written to the data source, with little or no coding. This lesson explains what ASP.NET Dynamic Data is, and in which scenarios it can be used. It also discusses the scaffolding and routing features of ASP.NET Dynamic Data. In addition, you will learn how to create an ASP.NET Dynamic Data web application.

Lesson Objectives After completing this lesson, you will be able to: •

Describe ASP.NET Dynamic Data and its features.



Identify the scenarios in which ASP.NET Dynamic Data is used.



Describe the scaffolding feature of ASP.NET Dynamic Data.



Describe the routing feature of ASP.NET Dynamic Data.

Optimizing Data Management for Web Forms



Create an ASP.NET Dynamic Data web application.

8-63

8-64

Developing Web Applications with Microsoft® Visual Studio® 2010

What Is ASP.NET Dynamic Data?

Key Points The ASP.NET Dynamic Data framework is used to create data-driven ASP.NET web applications. Some of the features of ASP.NET Dynamic Data is that the ASP.NET Dynamic Data framework can automatically discover the metadata of the data model at runtime, and then use this metadata to derive the UI behavior. A scaffolding framework provides a functional website to manage the data provided by the model. The scaffolding framework exposes a default behavior that you can override.

Scaffolding Scaffolding is used to enhance the existing ASP.NET web forms page framework by dynamically displaying pages based on the data and the metadata exposed by the data model. Scaffolding provides the following capabilities: •

Allows you to create a data-driven web application with little or no code.



Provides built-in data validation based on the database schema, as exposed by the data model.



Automatically creates filters for each foreign key or Boolean field, which are derived from the database schema, as exposed by the data model. You can customize the existing filters or create your own filters.

Data Model The data model is used to represent the information in a database and depicts how the various database objects are related. ASP.NET Dynamic Data currently supports both the ADO.NET Entity Framework data model and the LINQ to SQL data model. If you register a data model with ASP.NET Dynamic Data, the data model can perform automatic validation of the various data fields. You can also control the appearance and behavior of data at the data layer level, by annotating or applying attributes to the data model. For example, you can annotate whether a table should be part of the web application and whether a field should be shown when the data in the containing table is displayed. You can also add a display name attribute for a field that it is

Optimizing Data Management for Web Forms

8-65

different from the actual field name, a field description attribute that is used by Dynamic Data to add a tooltip when you mouse over the control that is used to display the field and value, custom formatting for different values (such as dates and times), change the order in which the fields are arranged, and specify the resources used for localizing the field names. You can include multiple data models in an ASP.NET Dynamic Data web application or an ASP.NET Dynamic Data website, but the models that are used for the scaffolding must be of the same type. ASP.NET Dynamic Data is model oriented, because the ASP.NET Dynamic Data infrastructure is entirely based on the data model. You can use the ASP.NET Dynamic Data infrastructure to control the request routing, control the look and feel of the user interface, and manage the data in the data source.

Templates ASP.NET Dynamic Data uses a number of generic templates to display various data. This includes page templates and field templates. The templates are disk-based files, such as ASP.NET Web Form and User Control templates. These templates are used at runtime by ASP.NET Dynamic Data for generating the rendered pages and controlling the pages that contain data from the data source. •

Page Templates. You can use page templates to provide a default view of data entities. These templates are ASP.NET web forms configured to display data from any entity in the data model. ASP.NET Dynamic Data provides page templates for different views of data: •

Details view: Displays the details for a single row.



Edit view: Allows the user to edit rows.



Insert view: Allows the user to insert a row.



List Details: Displays parent and child entities as a master and details view.



List view: Displays the table rows. This is the default view.

You can modify the routing for your web application to use any page template as the default template, or to use different page templates for different purposes. You can customize the existing page templates or create custom page templates for a specific entity in your data model. •

Field Templates. ASP.NET Dynamic Data uses field templates to render the UI for managing the data in the individual data fields. ASP.NET Dynamic Data determines the appropriate field template from the data field types in the data model schema. ASP.NET Dynamic Data includes separate field templates to display and edit data fields. For example, for a DateTime data field, Dynamic Data uses the following templates: •

Text.ascx. This template displays fields of type String, Decimal, Double, and integer types as literal text.



Text_Edit.ascx. This template renders a TextBox control and is used for editing text values, if the TextMode property is set to SingleLine. •



You can customize the built-in field templates or create new ones to specify how individual data fields are rendered. You can override the use of the default field templates by creating your own custom field templates and then annotate the data model with the UIHint attribute to use those field templates.

Entity Templates. The ASP.NET Dynamic Data entity templates are user controls that let you customize the layout for a whole data row in a table. They give you better control over table layout than page templates. When you create an ASP.NET Dynamic Data web application, Visual Studio 2010 adds a DynamicData\EntityTemplates folder to the project, which contains the default entity templates, which display data in two columns, using a label for the field name and an appropriate control for the field value.

8-66

Developing Web Applications with Microsoft® Visual Studio® 2010



There are entity templates for display, edit, and insert operations. Entity templates are included in the Details.aspx, Insert.aspx, and Update.aspx page templates, and you can use them in custom page templates. Entity templates use field templates to render the actual data. The entity templates are displayed on a page by using the DynamicEntity control. At run time, Dynamic Data replaces this control with the contents of the applicable entity template.

Data Controls ASP.NET Dynamic Data enhances existing data controls to include dynamic behavior. ASP.NET 4.0 provides several template-based databound controls, including the GridView, DetailsView, ListView, and FormView web server controls. ASP.NET Dynamic Data enhances these existing data controls to include dynamic behavior. •

The GridView and DetailsView controls display data dynamically by using predefined ASP.NET Dynamic Data templates. You can customize these templates and use specific controls for rendering the UI for managing the data fields. This enables you to make changes in one location and affect the appearance and behavior of the data controls across the web application. The DynamicField class is used by the GridView and DetailsView controls to display a field value.



The ListView and FormView controls implement the behavior by using a DynamicControl control in their templates. You must manually specify the data entity field that the ListView and FormView controls need to manage. ASP.NET Dynamic Data automatically builds the UI for these controls, based on the specified templates. DynamicControl controls do not automatically render the UI for any field; you must bind the controls to a specific data field. Note: See Lesson 2 for more information on databound controls, including the GridView, DetailsView, ListView, and FormView web server controls.

At run-time, ASP.NET Dynamic Data examines the data model metadata and provides automatic validation based on that metadata. For example, if a column in the database is marked as not nullable, a RequiredFieldValidator control is automatically rendered for that column. You can also apply custom metadata to customize further how data fields are rendered and validated, such as how a data is formatted for display, and how many characters a text column allows on input.

Additional Reading For more information about how the data model represents the information in a database and how the objects in the database are related to each other, see ASP.NET Dynamic Data Model Overview at http://go.microsoft.com/fwlink/?LinkID=181296&clcid=0x409. For more information about the DynamicControl control, see DynamicControl Class at http://go.microsoft.com/fwlink/?LinkID=181291&clcid=0x409. For more information about the DynamicField control, see the DynamicField Class at http://go.microsoft.com/fwlink/?LinkID=181305&clcid=0x409. Question: What does scaffolding do in the context of ASP.NET Dynamic Data?

Optimizing Data Management for Web Forms

8-67

Answer: Scaffolding is used to enhance the existing ASP.NET web forms page framework by dynamically displaying pages based on the data and the metadata exposed by the data model.

8-68

Developing Web Applications with Microsoft® Visual Studio® 2010

ASP.NET Dynamic Data Usage Scenarios

Key Points ASP.NET Dynamic Data is a fantastic tool that can save you a lot of time when creating data-driven web applications. However, it is more appropriate to use in some scenarios than others. In which scenarios is it most appropriate to use ASP.NET Dynamic Data? Consider the following scenarios and any other scenarios you can think of, and discuss all of these scenarios in the classroom. •

Rapid Application Development (RAD)



Administration Pages



Prototypes

Optimizing Data Management for Web Forms

8-69

Scaffolding Feature of ASP.NET Dynamic Data

Key Points Scaffolding is the feature of ASP.NET Dynamic Data that makes it possible to create pages dynamically at runtime, based on the data model, by extending the existing ASP.NET web forms page framework. These autogenerated web form pages provide create, read, update, and delete (CRUD) operations for each entity. Scaffolding must be enabled for all entities or for one or more specific entities, and data validation is built in, based on the database schema. Note: If you enable scaffolding for all entities, any user, malicious or not, may be able to work out the schema of the database. If you are creating a simple data management application, or an administration section for an application, it might be the best choice to enable scaffolding for all entities, allowing you to save development time. Scaffolding is enabled on the registration of the data context or object context in the global application file. This registration is made by using the RegisterContext method, which takes a System.Web.DynamicData.ContextConfiguration object parameter. You are required to register the data context that will use the ASP.NET Dynamic Data features, even if you are not going to use the scaffolding mechanism. This registration is made in the Global.asax.vb or Global.asax.cs file by using the RegisterContext method. The RegisterContext method accepts a ContextConfiguration object as a parameter. To enable the scaffolding mechanism while registering the data or object context, set the ScaffoldAllTables property of the ContextConfiguration object to true, to enable the scaffolding mechanism for the entire data model. [Visual Basic] DefaultModel.RegisterContext(GetType(MyObjectContext),

8-70

Developing Web Applications with Microsoft® Visual Studio® 2010

New ContextConfiguration() With {.ScaffoldAllTables = True})

[Visual C#] DefaultModel.RegisterContext(typeof(MyObjectContext), new ContextConfiguration() { ScaffoldAllTables = true });

If you choose to use this approach, you can specifically hide entities from the scaffolding mechanism by using the ScaffoldTableAttribute attribute. You can use the ScaffoldTableAttribute attribute to set the ScaffoldAllTables property to False/false when registering with the data model. You can also use the ScaffoldTableAttribute attribute to enable or disable the scaffolding mechanism for a given entity, by applying the attribute to a partial class with the same name as the entity in the data model. In the following code examples, the partial class is manually created, with the scaffolding enabled for the Customers entity. [Visual Basic] Imports System.ComponentModel.DataAnnotations Partial Public Class Customer ... End Class

[Visual C#] using System.ComponentModel.DataAnnotations; [ScaffoldTable(true)] public partial class Customer { ... }

Notice that the class is named, “Customer”, in singular, and not “Customers” in plural when you use the ADO.NET Entity Data Model or LINQ to SQL to name the classes. Because the Customer class is a partial class, you must use the same name that is used in the data model. You can also control the data fields that are being exposed, by applying the ScaffoldColumnAttribute attribute to enable or disable scaffolding for a particular data field. You must apply the attribute to a data field in a metadata class associated with the partial entity class. You must create the metadata class manually. You must also associate the metadata class with the partial entity class by applying the System.ComponentModel.DataAnnotations.MetadataTypeAttribute attribute to the partial class. The following example shows how a partial class for the Customers database entity is part of the scaffolding. However, by creating the CustomerMetadata class for the Customer class, the CreatedDate field will be hidden. [Visual Basic] Public Class CustomerMetadata Public CreatedDate As Object End Class Partial Public Class Customer ... End Class

[Visual C#] public class CustomerMetadata

Optimizing Data Management for Web Forms

{ }

8-71

[ScaffoldColumn(false)] public object CreatedDate;

[ScaffoldTable(true)] [MetadataType(typeof(CustomerMetadata))] public partial class Customer { ... }

The public properties in the metadata class are of type Object/object, and they override or hide a public property of the corresponding entity class in the meta model.

Template Customization You can modify how ASP.NET Dynamic Data performs tasks that do not rely on a specific database schema. You can create these modifications one time and use them for any number of projects. This type of customization lets you define a consistent behavior for any schema without having to redefine the customization every time that you add or modify a data entity.

Page Templates You can customize the layout for all tables, by changing the page templates that are in the DynamicData\PageTemplates folder. You can use this approach to change the appearance and behavior of all the tables in a website independently from the database. You can also customize the layout for an individual table, by creating a folder under the DynamicData\CustomPages whose name matches the name of the table in the data model. In the new folder, you add a page whose name matches the name of the default page template that you want to customize. You can use this approach to change the appearance and behavior of an individual table for a specific database.

Entity Templates You can customize the layout for all tables, by customizing the default entity templates. You can perform this customization by changing the entity templates that are in the DynamicData\EntityTemplates folder, which gives you a more control than that provided by data field customization, and is useful if you want to apply a custom UI to default or custom page templates. You can also customize the layout for an individual table, by creating custom entity templates for the table whose layout you want to customize. If you were using the Entity Framework data model, entity templates for an Address table would be named Address.ascx, Address_Edit.ascx, and Address_Insert.ascx. If you were using the LINQ to SQL data model, entity templates for an Address table would be named Addresses.ascx, Addresses_Edit.ascx, and Addresses_Insert.ascx.

Field Templates You can customize the UI for a specific data type, by changing the default field templates in the DynamicData\FieldTemplates folder. You can customize the UI for an individual data field in the database, by creating a custom field template and then map a data field declaratively to the template in a data-bound control.

Filter Templates You can customize the filter for a specific data type, by modifying the controls in the DynamicData\FilterTemplates folder.

8-72

Developing Web Applications with Microsoft® Visual Studio® 2010

You can also create a custom filter, by creating an ASP.NET user control that derives from the QueryableFilterUserControl class. You can use this approach to override a default filter or to create a data type filter if a default one does not exist.

Additional Reading For more information about how the MetaModel.RegisterContext method registers the data context with the meta model, see MetaModel.RegisterContext Method at http://go.microsoft.com/fwlink/?LinkID=181297&clcid=0x409. For more information about how the ContextConfiguration class provides information for a datacontext instance to allow customization, see ContextConfiguration Class at http://go.microsoft.com/fwlink/?LinkID=181298&clcid=0x409. For more information about how the MetadataTypeAttribute class specifies the metadata class to associate with a data model class, see MetadataTypeAttribute Class at http://go.microsoft.com/fwlink/?LinkID=181298&clcid=0x409. For more information about page template customization, see How to: Customize the Layout of an Individual Table By Using a Custom Page Template at http://go.microsoft.com/fwlink/?LinkID=192698&clcid=0x409. For more information about entity template customization, see Walkthrough: Customizing Table Layout Using Entity Templates at http://go.microsoft.com/fwlink/?LinkID=203972&clcid=0x409. For more information about field template customization, see How to: Customize ASP.NET Dynamic Data Default Field Templates at http://go.microsoft.com/fwlink/?LinkID=203974&clcid=0x409. For more information about filter template customization, see Walkthrough: Filtering Rows in Tables That Have a Parent-Child Relationship at http://go.microsoft.com/fwlink/?LinkID=203975&clcid=0x409. Question: What is the ScaffoldColumn attribute used for? Answer: It is used to show or hide a column/field in the UI.

Optimizing Data Management for Web Forms

8-73

Routing Feature of ASP.NET Dynamic Data

Key Points ASP.NET Dynamic Data uses ASP.NET routing to match and handle URL requests. The routes are defined in the global application file. Scaffolding infers the view and the entity that a user wants to view from the URL requested. The benefit of using the routing mechanism is that the URL requested does not have to match the physical path in the application, but it can allow both physical files and dynamically-generated pages. By default, ASP.NET Dynamic Data uses a different page template for each request (list, select, edit, and insert), but you can modify the URL routing to use any page template as the default page for a specific operation, or to use different page templates for different purposes. You can customize the routes to specify different page templates. You can also customize them to display different URLs, remove the file extension (aspx), or pass parameters by using routes, instead of query string values. The following code, which is part of the default Global.asax.vb or Global.asax.cs file, specifies the default route to use, where a template is specified for each action on any table in the data model. [Visual Basic] routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With { .Constraints = New RouteValueDictionary(New With {.Action = "List|Details|Edit|Insert"}), .Model = DefaultModel})

[Visual C#] routes.Add(new DynamicDataRoute("{table}/{action}.aspx") { Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }), Model = DefaultModel });

8-74

Developing Web Applications with Microsoft® Visual Studio® 2010

The following code examples, which are part of the default Global.asax.vb or Global.asax.cs file that is commented out by default, specifies the routes to use only one page template for all operations. [Visual Basic] routes.Add(New DynamicDataRoute("{table}/ListDetails.aspx") With { .Action = PageAction.List, .ViewName = "ListDetails", .Model = DefaultModel}) routes.Add(New DynamicDataRoute("{table}/ListDetails.aspx") With { .Action = PageAction.Details, .ViewName = "ListDetails", .Model = DefaultModel})

[Visual C#] routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") { Action = PageAction.List, ViewName = "ListDetails", Model = DefaultModel }); routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") { Action = PageAction.Details, ViewName = "ListDetails", Model = DefaultModel });

The first route enables all actions in the page for a given table, by using the ListDetails page template. The second route enables a page to navigate to the details of a record, such as navigating to a relationship table when you have a foreign key field. The routes are analyzed in the order they appear in the code. You need to first define the specific routes and then the generic ones, just as you declare the exception type order, when you wrap code in a Try/try statement. You can specify specific routes for specific tables, by specifying a different page template than the one used by the rest of the tables. The following examples show how to specify a different page template for the Customers entity, and then define a generic page template for the other tables of the data model. [Visual Basic] routes.Add(New DynamicDataRoute("Customers/{action}.aspx") With { .ViewName = "ListDetails", .Table = "Customers", .Model = model}) routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With { .Constraints = New RouteValueDictionary( New With {.Action = "List|Details|Edit|Insert"}), .Model = model})

[Visual C#] routes.Add(new DynamicDataRoute("Customers/{action}.aspx") { ViewName = "ListDetails", Table = "Customers", Model = model }); routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {

Optimizing Data Management for Web Forms

});

Constraints = new RouteValueDictionary( new { action = "List|Details|Edit|Insert" }), Model = model

Additional Reading For more information about ASP.NET Routing, see ASP.NET Routing at http://go.microsoft.com/fwlink/?LinkID=181301&clcid=0x409. Question: In which file is ASP.NET Dynamic Data routing defined? Answer: ASP.NET Dynamic Data routing is defined in the global application file.

8-75

8-76

Developing Web Applications with Microsoft® Visual Studio® 2010

Demonstration: Creating an ASP.NET Dynamic Data Web Application

Key Points In this demonstration, you will learn how to create an ASP.NET Dynamic Data web application, and how to customize it. Perform the following step to create and customize the ASP.NET Dynamic Data web application. 1.

Open Visual Studio 2010. •

2.

3.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Create a web application by using the New Project dialog box. a.

On the File menu, click New Project.

b.

In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.

c.

In the middle pane, click ASP.NET Dynamic Data Entities Web Application.

d.

In the Name box, type DDWebApp, in the Location box, type D:\Demofiles\VB or D:\Demofiles\CS, and then click OK.

Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx. a.

In Solution Explorer, right-click DDWebApp, point to Add, and then click New Item.

b.

In the Add New Item - DDWebApp dialog box, in the left pane, click Data, and then in the middle pane, click ADO.NET Entity data Model.

c.

In the Name box, type AdventureWorks.edmx, and then click Add.

4.

In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from database, and then click Next.

5.

On the Choose Your Data Connection page, click New Connection.

Optimizing Data Management for Web Forms

8-77

6.

In the Connection Properties dialog box, in the Server name box, type 10264A-GENDEV\SQLEXPRESS, in the Select or enter a database name box, type AdventureWorksLT2008R2, and then click OK.

7.

In the Entity Data Model Wizard, on the Choose Your Data Connection page, click Next.

8.

On the Choose Your Database Objects page, in the Which database objects do you want to include in your model? list, expand Tables, select the Tables check box, clear the BuildVersion (dbo)check box, and then click Finish.

9.

Save and close the AdventureWorks.edmx file. a.

On the File menu of Visual Studio 2010, click Save AdventureWorks.edmx.

b.

In the AdventureWorks.edmx window, click the Close button.

10. In the Global.asax.vb or Global.asax.cs file, add context registration to the RegisterRoutes procedure. [Visual Basic] DefaultModel.RegisterContext(GetType(AdventureWorksLT2008R2Entities), New ContextConfiguration() With {.ScaffoldAllTables = True})

[Visual C#] DefaultModel.RegisterContext(typeof(AdventureWorksLT2008R2Entities), new ContextConfiguration() { ScaffoldAllTables = true });



In the Global.asax.vb or Global.asax.cs window, add the following code at the top of to the RegisterRoutes procedure.

[Visual Basic] DefaultModel.RegisterContext(GetType(AdventureWorksLT2008R2Entities), New ContextConfiguration() With {.ScaffoldAllTables = True})

[Visual C#] DefaultModel.RegisterContext(typeof(AdventureWorksLT2008R2Entities), new ContextConfiguration() { ScaffoldAllTables = true });

Note: Point out that this will register the Entity Data model object context for use by using the Dynamic Data field, and enable the automatic scaffolding of the data model. 11. Save and close the Global.asax.vb or Global.asax.cs file. a.

On the File menu of Visual Studio 2010, click Save Global.asax.vb or Save Global.asax.cs.

b.

In the Global.asax.vb or Global.asax.cs window, click the Close button.

12. Build and run the web application. •

On the Debug menu of Visual Studio 2010, click Start Without Debugging. The page displayed in the browser displays a list of the tables you added to the data model.

13. Test the web application for the Dynamic Data functionality and view some of the dynamically generated pages.

8-78

Developing Web Applications with Microsoft® Visual Studio® 2010

a.

In the Dynamic Data Site – Windows Internet Explorer window, click Addresses. The page displays the List view that contains the data from the Addresses table.

b.

In the Addresses - Windows Internet Explorer window, click Details, to the left of an address. The page displays the Details view that contains the data for the selected row from the Addresses table.

c.

In the Addresses - Windows Internet Explorer window, click Show all items, and then click PostalCode. The page displays the List view that contains the data of addresses, sorted by postal code.

d.

In the Addresses - Windows Internet Explorer window, in the first row, under CustomerAddresses, click View CustomerAddresses. The page displays the List view that contains the data of customer addresses.

e.

In the Address list, click All.

f.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click Insert new item to create a new customer address.

g.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click Insert, and view the smart validation that has been added to the required fields, and then click Cancel. The page displays the List view that contains the data from the CustomerAddresses table. This is the default view and the one you are returned to, after cancelling.

h.

In the CustomerAddresses - Windows Internet Explorer window, to the left of a customer address, click Edit to modify a customer address. The page displays the Edit view that contains the data for the selected row from the CustomerAddresses table.

i.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click Cancel to cancel the edit operation.

14. Close Windows Internet Explorer. •

In the CustomerAddresses – Windows Internet Explorer window, click the Close button.

15. Close Visual Studio 2010. •

In the DDWebApp – Microsoft Visual Studio window, click the Close button.

Additional Reading For more information about how to create a data-driven website with minimal or no additional code, see the Walkthrough: Creating a New ASP.NET Dynamic Data Web Site Using Scaffolding at http://go.microsoft.com/fwlink/?LinkID=181302&clcid=0x409. Question: What is the RegisterContext method used for? Answer: The RegisterContext method is used for registering the data or object context.

Optimizing Data Management for Web Forms

8-79

Lab 8B: Optimizing Data Management for Web Forms

Note: You can perform tasks in this lab either by using Visual Basic or Visual C# programming language. If you are using Visual Basic as your programming language, refer to the steps provided in the Section 1 of the lab document. If you are using Visual C# as your programming language, refer to the steps provided in Section 2 of the lab document.

Objectives After completing this lab, you will be able to: •

Manage data by using ASP.NET Dynamic Data.

Introduction In this lab, you will develop the administration section of the website by using various ASP.NET data source controls and by using the ASP.NET Dynamic Data framework.

8-80

Developing Web Applications with Microsoft® Visual Studio® 2010

Lab Scenario

The AdventureWorks Sales team has requested the addition of an administration section to the website so that they can manage information, as well as provide a dashboard to senior management. As a first step toward this end, you need to create a set of web form pages that will enable the Sales team to do the following: •

View, add, edit, and delete products



View sales orders



View and edit customer details

In this lab, you will develop the administration section of the website by using the ASP.NET Dynamic Data framework.

Optimizing Data Management for Web Forms

8-81

Section 1: Visual Basic Exercise 4: Managing Data by Using ASP.NET Dynamic Data The main tasks in this exercise are as follows: 1.

Create a new ASP.NET Dynamic Data web application.

2.

Add a new ADO.NET Entity Data Model.

3.

Register the object context.

4.

Run the application.

 Task 1: Create a new ASP.NET Dynamic Data web application •

Open Microsoft Visual Studio 2010. •

Create an ASP.NET Dynamic Data web application named AWDynamicData by using the New Project dialog box, and the ASP.NET Dynamic Data Entities Web Application project template. Place the project in the D:\Lab Files\VB\Lab 08\Starter\Exercise 04 folder.

 Task 2: Add a new ADO.NET Entity Data Model •

Add an ADO.NET Entity Data Model project item named AWEDM.edmx. a.

Generate the model from the AdventureWorksLT2008R2 database, on the .\SQLEXPRESS server, and select only the Customer (SalesLT), SalesOrderDetail (SalesLT), and SalesOrderHeader (SalesLT) tables.

b.

Save and close the AWEDM.edmx file.

 Task 3: Register the object context •

In the Global.asax.vb file, add context registration to the RegisterRoutes procedure, registering all tables for the AWDynamicData.AdventureWorksLT2008R2Entities object context. DefaultModel.RegisterContext(GetType(AWDynamicData.AdventureWorksLT2008R2Entities), New ContextConfiguration() With {.ScaffoldAllTables = True})



Save and close the Global.asax.vb file.

 Task 4: Run the application •

Build and run the web application. a.

The page displayed in the browser displays a list of the tables you added to the data model.

b.

View the Customers page, showing all customers.

c.

The page displays the List view that contains the data from the Customers table.

d.

View the Details view, for a customer.

e.

The page displays the Details view that contains the data for the selected row from the Customers table.

f.

View the Customers page, showing all customers, by clicking Show all items.

g.

Sort the customers by the LastName column.

h.

The page displays the List view that contains the data of customers, sorted by last name.

i.

View the sales order headers associated with the second customer displayed from the top.

8-82

Developing Web Applications with Microsoft® Visual Studio® 2010

j.

The page displays the List view that contains the data of customer sales order headers.

k.

Filter the sales order headers by entries that have the OnlineOrderFlag column set to True.

l.

The page now displays no sales order headers, because none of the sales order headers have the OnlineOrderFlag set to true.

m. View the customers page. n.

Create a new customer, by clicking Insert new item.

o.

Save the new customer, with empty fields, and then cancel the new customer.

p.

The page displays the List view that contains the data from the Customers table. This is the default view and the one you are returned to, after cancelling.

q.

Edit the last customer displayed.

r.

The page displays the Edit view that contains the data for the selected row from the Customers table.

s.

Cancel the edit and close Windows Internet Explorer.

t.

Close Microsoft Visual Studio 2010.

 Task 5: Turn off the virtual machine and revert the changes •

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off. a.

In the Turn Off Machine dialog box, click Turn Off.

b.

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

c.

In the Revert Virtual Machine dialog box, click Revert.

Optimizing Data Management for Web Forms

8-83

Section 2: Visual C# Exercise 4: Managing Data by Using ASP.NET Dynamic Data The main tasks in this exercise are as follows: 1.

Create a new ASP.NET Dynamic Data web application.

2.

Add a new ADO.NET Entity Data Model.

3.

Register the object context.

4.

Run the application.

 Task 1: Create a new ASP.NET Dynamic Data web application •

Log on to the 10264A-GEN-DEV virtual machine as Student, with the password, Pa$$w0rd. a.

Open Microsoft Visual Studio 2010.

b.

Create an ASP.NET Dynamic Data web application named AWDynamicData by using the New Project dialog box, and the ASP.NET Dynamic Data Entities Web Application project template. Place the project in the D:\Lab Files\CS\Lab 08\Starter\Exercise 04 folder.

 Task 2: Add a new ADO.NET Entity Data Model •

Add an ADO.NET Entity Data Model project item named AWEDM.edmx. a.

Generate the model from the AdventureWorksLT2008R2 database, on the .\SQLEXPRESS server, and select only the Customer (SalesLT), SalesOrderDetail (SalesLT), and SalesOrderHeader (SalesLT) tables.

b.

Save and close the AWEDM.edmx file.

 Task 3: Register the object context •

In the Global.asax.cs file, add context registration to the RegisterRoutes procedure, registering all tables for the AWDynamicData.AdventureWorksLT2008R2Entities object context. DefaultModel.RegisterContext(typeof(AWDynamicData.AdventureWorksLT2008R2Entities), new ContextConfiguration() { ScaffoldAllTables = true });



Save and close the Global.asax.cs file.

 Task 4: Run the application •

Build and run the web application. a.

The page displayed in the browser displays a list of the tables you added to the data model.

b.

View the Customers page, showing all customers.

c.

The page displays the List view that contains the data from the Customers table.

d.

View the Details view, for a customer.

e.

The page displays the Details view that contains the data for the selected row from the Customers table.

f.

View the Customers page, showing all customers, by clicking Show all items.

8-84

Developing Web Applications with Microsoft® Visual Studio® 2010

g.

Sort the customers by the LastName column.

h.

The page displays the List view that contains the data of customers, sorted by last name.

i.

View the sales order headers associated with the second customer displayed from the top.

j.

The page displays the List view that contains the data of customer sales order headers.

k.

Filter the sales order headers by entries that have the OnlineOrderFlag column set to True.

l.

The page now displays no sales order headers, because none of the sales order headers have the OnlineOrderFlag set to true.

m. View the customers page. n.

Create a new customer, by clicking Insert new item.

o.

Save the new customer, with empty fields, and then cancel the new customer.

p.

The page displays the List view that contains the data from the Customers table. This is the default view and the one you are returned to, after cancelling.

q.

Edit the last customer displayed.

r.

The page displays the Edit view that contains the data for the selected row from the Customers table.

s.

Cancel the edit and close Windows Internet Explorer.

t.

Close Microsoft Visual Studio 2010.

 Task 5: Turn off the virtual machine and revert the changes •

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off. a.

In the Turn Off Machine dialog box, click Turn Off.

b.

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

c.

In the Revert Virtual Machine dialog box, click Revert.

Note: The answers to the exercises are on the Course Companion CD.

Optimizing Data Management for Web Forms

Lab Review

Review Questions and Answers Question: What is the use of the ScaffoldAllTables property? Answer: The ScaffoldAllTables property specifies that all entities in the data model should be made available for managing in the UI.

8-85

8-86

Developing Web Applications with Microsoft® Visual Studio® 2010

Module Review and Takeaways

Review Questions and Answers Question: Which component of the ADO.NET Entity Framework enables you to query, insert, update, and delete data, all expressed as strongly-typed CLR objects? Answer: Object Services is the component of the ADO.NET Entity Framework that enables you to query, insert, update, and delete data, all expressed as strongly-typed CLR objects. Question: Name at least three data source controls. Answer: EntityDataSource, LinqDataSource, ObjectDataSource, SiteMapDataSource, SqlDataSource, and XmlDataSource. Question: What is a templated control? Answer: A templated control is an ASP.NET server control that can be customized with one or more templates used for specifying behavior and appearance. Question: What are the features of Dynamic Data? Answer: Dynamic Data offers the following features: •

Web scaffolding that can run a web application that is based on reading the underlying database schema. Scaffolding is a mechanism that enhances an existing ASP.NET web form page framework by dynamically displaying pages based on the data model, without a physical page behind the scenes. Dynamic Data scaffolding can generate a standard UI from the data model.



Full data access operations such as create, update, remove, and display operations, relational operations, and data validation.

Optimizing Data Management for Web Forms

8-87



Automatic support for foreign-key relationships. Dynamic Data detects relationships between tables and creates UI that makes it easy for users to view data from related tables.



The ability to customize the UI that is rendered to display and edit specific data fields, and to display and edit data fields for a specific table.



The ability to customize data field validation. This lets you keep the business logic in the data layer separate from the presentation layer.

Real-World Issues and Scenarios 1.

2.

You need to display data in a tabular format by using a single server control, but you need to control the overall layout, the layout of the individual items, the selected item, the item being edited, and the item being inserted. What is the easiest way to do this? Use the ListView server control. You need to create a specific view for a single entity in your data model when using an ASP.NET Dynamic Data web application. How do you do this? Create a subfolder in the DynamicData\CustomPages folder, and name the subfolder the same as the entity in your data context, but use a plural ending. Then, create a new content page and add it to the subfolder.

Best Practices Mention some best practices in the context of your own business situations. •

Do not modify the generated DataContext or ObjectContext classes. Instead, create partial classes and place the custom code in partial classes. When the DataContext or ObjectContext classes are regenerated, any changes are overridden.

8-88

Developing Web Applications with Microsoft® Visual Studio® 2010

Ensuring Quality by Debugging, Unit Testing, and Refactoring

Module 9 Ensuring Quality by Debugging, Unit Testing, and Refactoring Contents: Lesson 1: Debugging and Refactoring Code

9-3

Lesson 2: Unit Testing Code

9-22

Lesson 3: Processing Unhandled Exceptions

9-30

Lesson 4: Test-Driven Development

9-37

Lab 9: Debugging, Unit Testing and Refactoring

9-43

9-1

9-2

Developing Web Applications with Microsoft® Visual Studio® 2010

Module Overview

Developers will spend more time debugging and refactoring code than they will initially writing it. To avoid additional debugging and refactoring cycles, unit tests can be implemented to isolate and ensure that code is working properly. If an error should make it to production, there are mechanisms to handle these issues. Whether it is debugging, refactoring, unit testing, or managing unhandled exceptions, Visual Studio® 2010 makes it easier than ever to perform these tasks. The goal of this module is to teach the basics of debugging and refactoring code by using Visual Studio 2010.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-3

Lesson 1

Debugging and Refactoring Code

You have created your application and resolved the build errors. You must now correct those logic errors that keep your application from running correctly. You can do this using the integrated debugging functions in the Visual Studio 2010 debugger. These functions allow you to stop at procedure locations, inspect memory and register values, change variables, observe message traffic, and get a closer look at what your code does.

Lesson Objectives After completing this lesson, you will be able to: •

Understand the basics of debugging.



Debug a web application.



Understand the basics of refactoring.



Refactor code by using Visual Studio 2010.

9-4

Developing Web Applications with Microsoft® Visual Studio® 2010

Overview of Debugging

Debugging is the process of observing the run-time behavior of your application, and then locating and fixing logic errors. A modern debugger lets you break, or suspend, the execution of your application, and subsequently lets you examine the code, evaluate and edit variables in your application, view registers, see the instructions created from your source code, and view the memory space used by your application. By using breakpoints, you can instruct the debugger to pause execution whenever a breakpoint in your code is hit.

Enable Debugging for an ASP.NET web application To debug your web application, you need to enable debugging in the Project Designer and in the Web.config file. These are the steps to perform for enabling debugging, with your web application open in Visual Studio 2010. 1.

In Solution Explorer, right-click the name of your web application, and then click Property Pages.

2.

In the Project Designer, click Web.

3.

In the Project Designer, on the Web page, in the Debuggers area, select the ASP.NET check box.

4.

In Solution Explorer, double-click Web.config.

5.

Locate the opening compilation tag. •

In the compilation tag, add the debug attribute or modify the value of the debug attribute, if it already exists, to true.

Note: If you do not set the debug attribute to true and try to start a debugging session, a dialog box will appear, offering to create a Web.config file with the attribute set.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-5

. . .

A website can contain multiple virtual directories and subdirectories, and Web.config files may exist in each one. ASP.NET applications inherit settings from Web.config files at higher levels in the URL path. Hierarchical configuration files allow you to change settings for several ASP.NET applications at the same time, such as for all applications below it in the hierarchy. However, if debug is set in a file lower in the hierarchy, it will override the higher value. Note: Enabling debug mode will greatly affect the performance of your ASP.NET application. Remember to disable debug mode before you deploy a release application or conduct performance measurements.

Debugging Permissions For remote debugging, local and remote computers must be on a domain setup or a workgroup setup. To debug the ASP.NET worker process you must have permission to debug that process. By default, ASP.NET applications run as the ASPNET user. If the worker process is running as ASPNET, or as NETWORK SERVICE, you must have Administrator privileges to debug it.

9-6

Developing Web Applications with Microsoft® Visual Studio® 2010

Overview of Debugging Using Visual Studio 2010 Debugging Tools

The Visual Studio debugger is a powerful tool that allows you to observe the run-time behavior of your program, and locate logic errors. The debugger works with all Visual Studio programming languages and their associated libraries. With Edit and Continue, you can make changes to your code while debugging, and then continue execution. The Visual Studio 2010 debugger has been enhanced by the addition of the following features: •

Breakpoint enhancements, which include the ability to search in the Breakpoints window, the ability to label breakpoints, the ability to import and export breakpoints, and string comparison for breakpoint conditions in native debugging.



A newly redesigned Threads window provides filtering, call-stack searching and expansion, and grouping. New columns display affinity masks, process names, and managed IDs. You can customize which columns appear and in what order.



Use the Parallel Stacks and Parallel Tasks debugger tool windows to visualize and debug parallel code that is written in C++, C#, or Visual Basic®.



Enhanced DataTips can float on top of other windows or be pinned. DataTips now have a comment field. Floating DataTips that are open persist between debug sessions.



For dump debugging, a new summary page displays basic information about the contents of the dump file before you begin to debug. This page offers quick links to the most common next steps, such as setting your symbol paths and starting to debug. The debugger now fully supports debugging of managed dumps for applications that are using common language-run-time (CLR) version 4.0.



The Watch window and DataTips provide an icon to warn you when evaluating an expression that requires other threads to run, which can change the program state and cause debug events such as breakpoints to be ignored. If you click the icon, the threads run.



Enhancements to symbol loading. See How to: Specify Symbol Locations and Loading Behavior at http://go.microsoft.com/fwlink/?LinkID=204072&clcid=0x409.

Ensuring Quality by Debugging, Unit Testing, and Refactoring



Debug mixed-mode native and managed code on 64-bit operating systems.

Question: What percentage of your time development do you spend debugging? Question: Without a debugger what is another way to debug an application?

9-7

9-8

Developing Web Applications with Microsoft® Visual Studio® 2010

Demonstration: Enabling Debugging of a Web Application

In this demonstration, you will see how to enable debugging of a web application. 1.

Open Microsoft® Visual Studio. •

2.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Create a new ASP.NET web application by using the New Project dialog box. a.

On the File menu, click New Project.

b.

In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.

c.

In the middle pane, click ASP.NET Web Application.

d.

In the Name box, type DebugWebApp, in the Location box, type D:\Demofiles\VB or D:\Demofiles\CS, and then click OK.

3.

Build the project. • In the DebugWebApp – Microsoft Visual Studio window, on the Build menu, click Build DebugWebApp.

4.

Open the Web.config file. •

In Solution Explorer, double-click Web.config.

5.

Navigate to the self-closing system.web element and notice the attributes and values in the compilation tag.

6.

In Solution Explorer, right-click DebugWebApp, and then click Properties.

7.

Open the Web page. •

In the Properties Designer, click Web.

8.

Examine the various options on the Web page.

9.

In the Debuggers section, ensure the ASP.NET check box is selected.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

10. Close the Properties Designer. •

In the DebugWebApp window, click the Close button.

11. Close Microsoft Visual Studio 2010. •

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

9-9

9-10

Developing Web Applications with Microsoft® Visual Studio® 2010

What is Refactoring?

Refactoring is the process of improving your code, after it has been written, by changing the internal structure and format of the code, without changing the external behavior of the code. Visual Studio 2010 provides the following refactoring commands on the Refactor menu, when you have a Visual C#® project open: •

Rename



Extract Method



Encapsulate Field



Extract Interface



Remove Parameters



Reorder Parameters

These commands invoke functionality that does exactly what the name says, and each is covered later in this topic and Lesson.

Multi-Project Refactoring Visual Studio 2010 supports multi-project refactoring for projects that are in the same solution. All of the refactoring functionality that corrects references across files corrects those references across all projects of the same programming language. This works for any project-to-project references. For example, if you have a console application that references a class library, when you rename the name of a class library type by using the Rename refactoring functionality, the references to the class library type in the console application are also updated.

Changes Review Much of the refactoring functionality provides an opportunity for you to review all the reference changes that a refactoring operation would perform on your code, before committing to those changes. For this

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-11

refactoring functionality, a Preview reference changes option will appear in the Refactoring dialog box. After selecting that option and accepting the refactoring operation, the Preview Changes dialog box opens. Notice that the Preview Changes dialog box has two views. The bottom view displays your code with all the reference updates due to the refactoring operation. If you click Cancel in the Preview Changes dialog box stops the refactoring operation, and no changes are made to your code.

Refactoring Warnings If the compiler does not have a complete understanding of your program, and the refactoring engine might not update all of the appropriate references, the Refactoring Warning dialog box is displayed. This warning dialog box also provides an opportunity for you to preview your code in the Preview Changes dialog box before you commit changes. If a method contains a syntax error, which the IDE indicates with a red wavy line under the code in error, then the refactoring engine will not update any references to an element within that method. By default, if you execute a refactoring operation without previewing reference changes and a compilation error is detected in your program, then the development environment displays this warning dialog box. If you execute a refactoring operation that has Preview reference changes enabled, and a compilation error is detected in your program, then the development environment will display the following warning message at the bottom of the Preview Changes dialog box, in lieu of displaying the Refactoring Warning dialog box: Your project or one of its dependencies does not currently build. References may not be updated. This refactoring warning is only available for refactoring operations that provide the Preview reference changes option.

Error-Tolerant Refactoring and Verification Results Key Points Refactoring is error tolerant. In other words, you can perform a refactoring in a project that cannot build. However, in these cases the refactoring process might not update ambiguous references correctly. The Verification Results dialog box can notify you if the refactoring engine detects compile errors or discovers that a refactoring operation inadvertently causes a code reference to bind to something different from what it was originally bound to (rebinding issue). To turn on the verification results feature, on the Tools menu, click Options. In the Options dialog box, expand Text Editor, and then expand C#. Click Advanced and select the Verify results of refactoring check box. The Verification Results dialog box distinguishes the difference between two kinds of rebinding issues. •

References whose definition will no longer be the renamed symbol: This kind of rebinding issue occurs when a reference no longer refers to a renamed symbol. For example, consider the following code: [Visual C#] class Example { private int a;

}

public Example(int b) { a = b; }

9-12

Developing Web Applications with Microsoft® Visual Studio® 2010

[Visual Basic] Class Example Private a As Integer Sub New(ByVal b As Integer) a = b End Sub End Class

If you use refactoring to rename a to b, the Verification Results dialog box appears. The reference to the renamed variable a now binds to the parameter that is passed to the constructor instead of binding to the field. •

References whose definition will now become the renamed symbol: This kind of rebinding issue occurs when a reference that previously did not refer to the renamed symbol now does refer to it. For example, consider the following code: [Visual C#] class Example { private static void Method(object a) { } private static void OtherMethod(int a) { }

}

static void Main(string[] args) { Method(5); }

[Visual Basic] Class Example Private Shared Sub Method(ByVal a As Object) End Sub Private Shared Sub OtherMethod(ByVal a As Integer) End Sub Shared Sub Main(ByVal args As String()) Method(5) End Sub End Class

If you use refactoring to rename OtherMethod to Method, the Verification Results dialog box appears. The reference in Main now refers to the overloaded method that accepts an int parameter instead of the overloaded method that accepts an object parameter. Question: What problems have you encountered by refactoring code without the use of a tool? Question: What percentage of your development time do you spend refactoring code? Question: What third-party tools have you used to accomplish refactoring?

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-13

Extract Method Refactoring

Extract Method is a refactoring operation that provides an easy way to create a new method from a code fragment in an existing member. Using Extract Method, you can create a new method by extracting a selection of code from inside the code block of an existing member. The new, extracted method contains the selected code, and the selected code in the existing member is replaced with a call to the new method. Turning a fragment of code into its own method lets you quickly and accurately reorganize code for better reuse and readability. Extract Method has the following benefits: •

Encourages best coding practices by emphasizing discrete, reusable methods.



Encourages self-documenting code through good organization.



When descriptive names are used, high-level methods can read more like a series of comments.



Encourages the creation of finer-grained methods to simplify overriding.



Reduces code duplication.

When you use the Extract Method command, the new method is inserted following the source member in the same class.

9-14

Developing Web Applications with Microsoft® Visual Studio® 2010

Demonstration: Extract Method Refactoring

In this demonstration, you will learn how to extract a method from existing code. The solution from the Enable Debugging of a Web Application demonstration is being used. 1.

Open Microsoft Visual Studio. •

2.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Open the DebugWebApp solution from the D:\Demofiles\CS\DebugWebApp folder. a.

In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project.

b.

In the Open Project dialog box, in the File name box, type D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.

3.

Open Default.aspx in Code view. • In Solution Explorer, right-click Default.aspx and then click View Code.

4.

In the Page_Load method, type in the following code: [Visual C#] protected void Page_Load(object sender, EventArgs e) { var i = 1; var j = 2; var answer = i + j; }

5.

Select the three lines of code you just added.

6.

Right-click the selection, point to Refactor, and then click Extract Method.

7.

In the Extract Method dialog box, in the New method name box, type Add, and then click OK. Note: The code has been extracted into a new method, and the function has been called in its place.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

8. Build the project. • In the DebugWebApp – Microsoft Visual Studio window, on the Build menu, click Build DebugWebApp. 9. Close Microsoft Visual Studio 2010. • In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

9-15

9-16

Developing Web Applications with Microsoft® Visual Studio® 2010

Encapsulate Field Refactoring

The Encapsulate Field refactoring operation enables you to quickly create a property from an existing field, and then seamlessly update your code with references to the new property. When a field is public, other objects have direct access to that field and can modify it, undetected by the object that owns that field. By using properties to encapsulate that field, you can disallow direct access to fields. To create the new property, the Encapsulate Field operation changes the access modifier for the field that you want to encapsulate to private, and then generates get and set accessors for that field. In some cases, only a get accessor is generated, such as when the field is declared read-only. The refactoring engine updates your code with references to the new property in the areas specified in the Update References section of the Encapsulate Field dialog box.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-17

Demonstration: Encapsulate Field Refactoring

In this demonstration, you will see how to encapsulate a field. The solution from the Enable Debugging of a Web Application demonstration is being used. 1.

Open Microsoft Visual Studio. •

2.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Open the DebugWebApp solution from the D:\Demofiles\CS\DebugWebApp folder. a.

In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project.

b.

In the Open Project dialog box, in the File name box, type D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.

3.

In Solution Explorer, right-click DebugWebApp, point to Add, and then click Class.

4.

In the Add New Item – DebugWebApp dialog box, in the Name box, type Person, and then click Add.

5.

Create a single private variable named name, by adding the following code [Visual C#] public class Person { private string name; }

6.

In the Person.cs window, right-click name, point to Refactor, and then click Encapsulate Field.

7.

In the Encapsulate Field dialog box, click OK.

8.

In the Preview Reference Changes - Encapsulate Field dialog box, click Apply. Note: The new property with accessors has been created.

9-18

Developing Web Applications with Microsoft® Visual Studio® 2010

9.

Build the project. •

In the DebugWebApp – Microsoft Visual Studio window, on the Build menu, click Build DebugWebApp.

10. Close Microsoft Visual Studio 2010. •

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-19

Extract Interface Refactoring

Extract Interface is a refactoring operation that provides an easy way to create a new interface with members that originate from an existing class, structure, or interface. When several clients use the same subset of members from a class, structure, or interface, or when multiple classes, structures, or interfaces have a subset of members in common, it can be useful to embody the subset of members in an interface. Extract Interface generates an interface in a new file, and positions the cursor at the beginning of the new file. You can specify which members to extract into the new interface, the name of the new interface, and the name of the generated file using the Extract Interface dialog box.

9-20

Developing Web Applications with Microsoft® Visual Studio® 2010

Demonstration: Extract Interface Refactoring

In this demonstration, you will see how to extract an interface from an existing class. The solution from the Enable Debugging of a Web Application demonstration is being used. 1.

Open Microsoft Visual Studio. •

2.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Open the DebugWebApp solution from the D:\Demofiles\CS\DebugWebApp folder. a.

In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project.

b.

In the Open Project dialog box, in the File name box, type D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.

3.

Open the Person.cs file. • In Solution Explorer, double-click Person.cs.

4.

Add the age member variable, Age property, and Hire method to the Person class. [Visual C#] public class Person { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; }

Ensuring Quality by Debugging, Unit Testing, and Refactoring

} public void Hire() { // implementation Code }

}



In the Person.cs window, in the Person class, append the following code. [Visual C#] private int age; public int Age { get { return age; } set { age = value; } } public void Hire() { // implementation Code }

5.

Right-click Person, point to Refactor, and then click Extract Interface.

6.

In the Extract Interface dialog box, select the Age, Hire(), and Name check boxes, and then click OK. Note: The new interface is now created in a new file.

7.

Display the Person.cs file, and notice how the class now implements the new interface. •

8.

Build the project. •

9.

In the DebugWebApp – Microsoft Visual Studio window, click Person.cs.

In the DebugWebApp – Microsoft Visual Studio window, on the Build menu, click Build DebugWebApp.

Close Microsoft Visual Studio 2010. •

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

9-21

9-22

Developing Web Applications with Microsoft® Visual Studio® 2010

Lesson 2

Unit Testing Code

The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect. Each unit is tested separately before integrating it into modules to test the interfaces between modules. Unit testing has proven its value in that a large percentage of defects are identified during its use.

Lesson Objectives After completing this lesson, you will be able to: •

Understand the basics of unit testing.



Create and run unit tests.



Understand the steps of unit testing.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-23

What is Unit Testing?

The most common approach to unit testing requires drivers and stubs to be written. The driver simulates a calling unit, and the stub simulates a called unit. The investment of developer time in this activity sometimes results in demoting unit testing to a lower level of priority and that is almost always a mistake. Even though the drivers and stubs cost time and money, unit testing provides some undeniable advantages. It allows for automation of the testing process, reduces difficulties of discovering errors contained in more complex pieces of the application, and test coverage is often enhanced because attention is given to each unit. For example, if you have two units and decide it would be more cost effective to glue them together and initially test them as an integrated unit, an error could occur in a variety of places: •

Is the error due to a defect in unit 1?



Is the error due to a defect in unit 2?



Is the error due to defects in both units?



Is the error due to a defect in the interface between the units?



Is the error due to a defect in the test?

Finding the error (or errors) in the integrated module is much more complicated than first isolating the units, testing each, and then integrating them and testing the whole. Drivers and stubs can be reused so that the constant changes that occur during the development cycle can be retested frequently without writing large amounts of additional test code. In effect, this reduces the cost of writing the drivers and stubs on a per-use basis, and the cost of retesting is better controlled. Unit testing takes the smallest piece of testable software in an application and isolates it from the rest of the project. This allows the developer to test that piece of code, isolating it so that external influences don’t affect the testing. This method of testing helps find the majority of defects in a system. There are two parts to a unit test.

9-24

Developing Web Applications with Microsoft® Visual Studio® 2010

Driver: The driver is the calling mechanism that isolates the testable software and looks for a particular result. Stub: The stub represents the code that is being tested. There are two phases to creating a unit test. The first phase is generating a unit test file that contains a skeleton version of a test method for each method in the code that you are testing. Each skeleton test method is generated with empty variables and a placeholder Assert statement. The second phase is initializing the variables and replacing the placeholder Assert statement with an appropriate one. You use the Create Unit Tests dialog box to generate unit tests for any or all of the methods in the code that you are testing. Question: Have you ever isolated an error in an integrated module, and then applied a fix? Question: What percentage of your development time is spent writing tests?

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-25

Steps to Creating a Unit Test

There are several steps to creating a unit test. Create the code that is to be tested. Any code that has been written can be tested. Typically, the code is in properties or in methods. Event procedures can be tested, but it is better practice to put all code in separate methods. Use the Create Unit Test feature in Visual Studio. Once there is code to be tested, use the Create Unit Tests dialog box to specify what is to be tested. This can be accessed through the Test menu, or by rightclicking the code. Once the dialog box has been opened, you can specify which items you want to test.

9-26

Developing Web Applications with Microsoft® Visual Studio® 2010

Selecting an item will create the unit tests for it. Create a Unit Test. There are two phases to creating a unit test. Phase 1 is generating a unit test file. This file contains a skeleton version of a test method for each method you are testing. It is created with empty variables and a placeholder Assert statement. Phase 2 is initializing the variables and replacing them with relevant values that you are testing. Add validation. Before you can run a test, you must replace the variables with meaningful data so you that know that the method performs properly. As well, the placeholder Assert statement should be replaced for one that is appropriate for that method. Typically the Assert.AreEqual method is used.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-27

Demonstration: Creating and Running a Unit Test

In this demonstration, you will see how to create and run a unit test. 1.

Open Microsoft Visual Studio. •

2.

3.

On the Start menu of 10264A-GEN-DEV, point to All Programs, click Microsoft Visual Studio 2010, and then click Microsoft Visual Studio 2010.

Open the UnitTest solution from the D:\Demofiles\CS or D:\Demofiles\VB folder. a.

In the Start Page – Microsoft Visual Studio window, on the File menu, click Open Project.

b.

In the Open Project dialog box, in the File name box, type D:\Demofiles\CS\UnitTest.sln or D:\Demofiles\VB\UnitTest.sln, and then click Open.

Open the Person.cs or Person.vb file. •

4.

In Solution Explorer, double-click Person.cs or Person.vb.

Modify the Age property as follows: [Visual C#] public int Age { get { return personAge; } set { if (value < 21) throw new Exception("Age must be greater than 21");

}

}

personAge = value;

[Visual Basic] Public Property Age As Integer Get Return personAge

9-28

Developing Web Applications with Microsoft® Visual Studio® 2010

End Get Set(ByVal value As Integer) If value < 21 Then Throw New Exception("Age must be greater than 21") End If personAge = value End Set End Property

5.

Right-click anywhere in the code for the Age property, and then click Create Unit Tests.

6.

In the Create Unit Tests dialog box, ensure the Age check box is selected, and then click OK.

7.

In the New Test Project dialog box, click Create. Note: Notice the new project created for unit testing.

8.

In the open PersonTest.cs or PersonTest.vb file, review the AgeTest test method.

9.

Change the declaration code for the expected local variable as follows. [Visual C#] int expected = 25; [Visual Basic] Dim expected As Integer = 25

10. Delete the following code. [Visual C#] Assert.Inconclusive("Verify the correctness of this test method."); [Visual Basic] Assert.Inconclusive("Verify the correctness of this test method.")

11. Right-click the AgeTest method declaration, and then click Run Tests. Note: In the Test Results window, notice the AgeTest test passed. 12. Change the declaration code for the expected local variable as follows. [Visual C#] int expected = 2; [Visual Basic] Dim expected As Integer = 2

13. Right-click the AgeTest method declaration, and then click Run Tests. Note: In the Test Results window, notice the AgeTest test failed. 14. Close Microsoft Visual Studio 2010. •

In the UnitTest - Microsoft Visual Studio window, click the Close button.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-29

Optional Unit Test Steps

There are several optional unit-test steps that will make your testing more effective. Create a Test Category. You can manage multiple tests into testing categories. This makes selecting which tests to run during a testing cycle easier. You add test categories as attributes to your test methods. You can use logical operators with test categories, to run tests from multiple categories together, or to limit the tests that you run to tests that belong to multiple categories. Create a Test List. Test lists are similar to test categories. However, you can run tests from multiple unit test files, across a build, or you can use them as a list to enforce a check-in policy. Check-in policies are used with source control applications such as the Microsoft Team Foundation Server (TFS) 2010. View Code Coverage. If you collect code coverage information, you can use the Code Coverage window to see what percentage of methods in the code are covered by your unit tests. Question: How can unit test help you document code? Question: Which third-party tools have you used to write unit tests?

9-30

Developing Web Applications with Microsoft® Visual Studio® 2010

Lesson 3

Processing Unhandled Exceptions

When a run-time error occurs on a web application in production, it is important to notify a developer and to log the error so that it can be diagnosed at a later time. It is also important to provide the end user relevant support information to allow him or her to continue using the web application. This lesson provides an overview of how ASP.NET processes runtime errors, and looks at one way to have custom code execute whenever an unhandled exception bubbles up to the ASP.NET runtime. This lesson also explains how to implement a custom error page that provides the end user with relevant support information, and matches your site’s look and feel.

Lesson Objectives After completing this lesson, you will be able to: •

Display a custom error page.



Process unhandled exceptions.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-31

Displaying a Custom Error Page

Unfortunately, runtime errors are unavoidable. Even the best developers are guilty of creating code with issues. The classes in the .NET Framework signal an error by throwing an exception. Exceptions can be handled using try/catch/finally blocks. If code within a try block throws an exception, control is transferred to the appropriate catch block, where the developer can attempt to recover from the error. If there is no matching catch block, or if the code that threw the exception is not in a try block, the exception percolates up the call stack in search of try/catch/finally blocks. If the exception rises all the way up to the ASP.NET runtime without being handled, the HttpApplication class' Error event is raised, and the configured error page is displayed. By default, ASP.NET displays an error page that is commonly referred to as the Yellow Screen of Death (YSOD). There are two versions of the YSOD: one shows the exception details, a stack trace, and other information helpful to developers debugging the application; the other simply states that there was a run-time error. None of these pages is useful to the end user, and can ultimately affect their perception of the application. This can be avoided by directing end users to an error page that maintains the site's look and feel with more user-friendly prose describing the situation.

Configuring Error Pages The customErrors section in a Web.config file has two attributes that affect which error page is shown: defaultRedirect and mode. The defaultRedirect attribute is optional. If provided, it specifies the URL of the custom error page, and indicates that the custom error page should be shown instead of the Runtime Error YSOD. The mode attribute is required, and accepts one of three values: On, Off, or RemoteOnly. •

On: Indicates that the custom error page or the Runtime Error YSOD is shown to all visitors, regardless of whether they are local or remote.



Off: Specifies that the Exception Details YSOD be displayed to all visitors, regardless of whether they are local or remote.



RemoteOnly: Indicates that the custom error page or the Runtime Error YSOD is shown to remote visitors, while the Exception Details YSOD is shown to local visitors only.

9-32

Developing Web Applications with Microsoft® Visual Studio® 2010

Unless you specify otherwise, ASP.NET acts as if you have set the mode attribute to RemoteOnly and have not specified a defaultRedirect attribute value. In other words, the default behavior is that the Exception Details YSOD is displayed to local visitors, while the Runtime Error YSOD is shown to remote visitors. You can override this default behavior by adding a customErrors section to your web application's Web.config file. Every web application should have a custom error page. It provides a more professional-looking alternative to the Runtime Error YSOD, it is easy to create, and configuring the application to use the custom error page takes only a few moments. The first step is adding an informative and themed custom error page to your solution. Specify the URL of the error page in the customErrors elements defaultRedirect attribute. Add the following markup to your application's Web.config file: ... ... ...

This will configure the application to show the Exception Details YSOD to users visiting locally, while using the custom error page CustomErrorPage.aspx for those users visiting remotely.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-33

Processing Unhandled Exceptions

Errors that occur in development environments are observed by developers who can examine the exception details, and the steps required to reproduce the error. Errors that occur in a production environment are observed by end users. Unless end users take the time to report the details of an error, developers are not notified of the error and the error details. Only errors that are encountered in the development environment will be remedied. For these reasons, it is important that any error in the production environment is logged to some persistent store, and that the developers are alerted to this error. Events provide an object a mechanism for signaling that something interesting has occurred, and for another object to execute code in response. As an ASP.NET developer you are accustomed to thinking in terms of events. If you want to run some code when the visitor clicks a particular button, you create an event handler for that button's Click event and put your code there. Given that the ASP.NET runtime raises its Error event whenever an unhandled exception occurs, it follows that the code for logging the error's details would go in an event handler. But how do you create an event handler for the Error event? The Error event is one of many events in the HttpApplication class that is raised at certain stages in the HTTP pipeline during the lifetime of a request. For example, the HttpApplication class' BeginRequest event is raised at the start of every request; the AuthenticateRequest event is raised when a security module has identified the requestor. These HttpApplication events give the page developer a means to execute custom logic at the various points in the lifetime of a request. Event handlers for the HttpApplication events can be placed in a special file named Global.asax. To create this file in your web application, add a new item to the root of your website using the Global Application Class project item template. [Visual C#] using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security;

9-34

Developing Web Applications with Microsoft® Visual Studio® 2010

using System.Web.SessionState; namespace xxx { public class Global : System.Web.HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } }

}

[Visual Basic] Imports System.Web.SessionState Public Class Global_asax Inherits System.Web.HttpApplication Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the application is started End Sub Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the session is started End Sub Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) ' Fires at the beginning of each request End Sub Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) ' Fires upon attempting to authenticate the use

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-35

End Sub Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Fires when an error occurs End Sub Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the session ends End Sub Sub Application_End(ByVal sender As Object, ByVal e As EventArgs) ' Fires when the application ends End Sub End Class

When the Application_Error event handler executes, you should notify a developer of the error, and log its details. To accomplish this, you first need to determine the details of the exception that was raised. For this purpose, you can use the Server object's GetLastError method. [Visual C#] protected void Application_Error(object sender, EventArgs e) { // Get the error details HttpException lastErrorWrapper = Server.GetLastError() as HttpException; } [Visual Basic] Protected Sub Application_Error(sender As Object, e As EventArgs) ' Get the error details Dim lastErrorWrapper As HttpException = TryCast(Server.GetLastError(), HttpException) End Sub

The GetLastError method returns an object of type Exception, which is the base type for all exceptions in the .NET Framework. However, in the code shown, the Exception object returned by GetLastError is cast to an HttpException object. If the Error event is being fired because an exception was thrown during the processing of an ASP.NET resource, then the exception that was thrown is wrapped within an HttpException. To get the actual exception that precipitated the Error event, you can access the InnerException property. If the Error event was raised because of an HTTP-based exception, such as a request for a non-existent page, an actual HttpException is thrown, but it does not have an inner exception. The following code uses the GetLastErrormessage to retrieve information about the exception that triggered the Error event, storing the HttpException in a variable named lastErrorWrapper. It then stores the type, message, and stack trace of the originating exception in three string variables, checking to see if the lastErrorWrapper is the actual exception that triggered the Error event (in the case of HTTPbased exceptions), or if it's merely a wrapper for an exception that was thrown while processing the request. [Visual C#] protected void Application_Error(object sender, EventArgs e) { // Get the error details HttpException lastErrorWrapper = Server.GetLastError() as HttpException; Exception lastError = lastErrorWrapper; if (lastErrorWrapper.InnerException != null) lastError = lastErrorWrapper.InnerException; string lastErrorTypeName = lastError.GetType().ToString(); string lastErrorMessage = lastError.Message;

9-36

Developing Web Applications with Microsoft® Visual Studio® 2010

}

string lastErrorStackTrace = lastError.StackTrace;

[Visual Basic] Protected Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Get the error details Dim lastErrorWrapper As HttpException = TryCast(Server.GetLastError(), HttpException) Dim lastError As Exception = lastErrorWrapper If Not lastErrorWrapper.InnerException Is Nothing Then lastError = lastErrorWrapper.InnerException End If Dim lastErrorTypeName As String = lastError.[GetType]().ToString() Dim lastErrorMessage As String = lastError.Message Dim lastErrorStackTrace As String = lastError.StackTrace End Sub

At this point, you have all the information you need to write code that will log the exception's details to a database table. You can create a database table with columns for each of the error details of interest (the type, the message, the stack trace, and so on) along with other useful pieces of information (such as the URL of the requested page and the name of the user currently logged on). In the Application_Error event handler you can then connect to the database and insert a record into the table. Likewise, you can add code to alert a developer of the error via email. The error logging libraries examined in the coming modules provide such functionality out of the box, so there's no need to build this error logging and notification yourself. Question: Have you ever experienced a default error page on a production site? How did your perception of the site change? Question: Have you ever experienced a custom error page on a production site? Did the custom error page provide you relevant information that improved your experience?

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-37

Lesson 4

Test-Driven Development

Test-driven development (TDD) is one of the core practices of Extreme Programming (XP). The practice extends the feedback approach, and requires that you develop test cases before you develop code. Using TDD, developers develop functionality to pass the existing test cases. Next, the test team adds new test cases to test the existing functionality, and runs the entire test suite to ensure that the code fails (either because the existing functionality needs to be modified or because required functionality is not yet included). The developers then modify the functionality or create new functionality so that the code can withstand the failed test cases. This cycle continues until the test code passes all of the test cases that the team can create. The developers then refactor the functional code to remove any duplicate or dead code and make it more maintainable and extensible.

Objectives •

Learn the difference between test-driven and traditional development.



Learn how to execute test-driven development.

9-38

Developing Web Applications with Microsoft® Visual Studio® 2010

Advantages of Test-Driven over Traditional Development

Test-driven development (TDD) reverses the traditional development process. Instead of writing functional code first and then testing it, the team writes the test code before the functional code. The team does this in very small steps—one test and a small amount of corresponding functional code at a time. The developers do not write code for new functionality until a test fails because some functionality is not present. Only when a test is in place do developers do the work required to ensure that the test cases in the test suite pass. In subsequent iterations, when the team has the updated code and another set of test cases, the code may break several existing tests as well as the new tests. The developers continue to develop or modify the functionality to pass all of the test cases. TDD allows you to start with an unclear set of requirements, and relies on the feedback loop between the developers and the customers for input on the requirements. The customer, or a customer representative, is the part of the core team, and immediately provides feedback about the functionality. This practice ensures that the requirements evolve over the course of the project cycle. Testing before writing functional code ensures that the functional code addresses all of the requirements, without including unnecessary functionality. With TDD, you do not need to have a well-defined architectural design before beginning the development phase, as you do with traditional development life cycle methodologies. TDD allows you to tackle smaller problems first, and then evolve the system as the requirements become more clear later in the project cycle. Other advantages of TDD are as follows: •

Promotes loosely coupled and highly cohesive code, because the functionality is evolved in small steps. Each piece of the functionality needs to be self-sufficient in terms of the helper classes and the data that it acts on so that it can be successfully tested in isolation.



The test suite acts as documentation for the functional specification of the final system.



The system uses automated tests, which significantly reduce the time taken to retest the existing functionality for each new build of the system.

Ensuring Quality by Debugging, Unit Testing, and Refactoring



9-39

When a test fails, you have a clear idea of the tasks that you must perform to resolve the problem. You also have a clear measure of success when the test no longer fails. This increases your confidence that the system actually meets the customer requirements.

TDD helps ensure that your source code is thoroughly unit tested. However, you must still consider traditional testing techniques, such as functional testing, user acceptance testing, and system integration testing. Much of this testing can also be done early in your project. In fact, in XP, the acceptance tests for a user story are specified by the project stakeholder(s), either before, or in parallel to the code being written, giving stakeholders confidence that the system meets their requirements. Question: What obstacles do you envision when transitioning from traditional development to testdriven development? Question: For what percentage of your code do you write unit tests?

9-40

Developing Web Applications with Microsoft® Visual Studio® 2010

The Test-Driven Development Process

To execute TDD, follow these steps. 1.

Create the test code. Use an automated test framework to create the test code. The test code drives the development of functionality.

2.

Write/modify the functional code. Write the functional code for the application block so that it can pass all test cases from the test code. The first iteration involves developing new functionality; subsequent iterations involve modifying the functionality based on the failed test cases.

3.

Create additional tests. Develop additional tests to test the functional code.

4.

Test the functional code. Test the functional code based on the test cases developed in steps 3 and 1. Repeat steps 2 through 4 until the code passes all of the test cases.

5.

Refactor the code. Modify the code so that there is no dead code or duplication. The code should adhere to best practices for maintainability, performance, and security.

Step 1: Create the Test Code You create the test code before any code is written for the functionality of the application block. The general guidelines for writing the test code are as follows: •

Your goal is to write test code that tests basic functionality.



Write a test case for each code requirement. The developers will write the functional code based on the tests, so that the test case passes.



Avoid writing code for multiple test cases at any one time. Write code for a single test case, and proceed through the remaining cycle of coding and refactoring.



Write code that tests only small pieces of functionality. If the test code is complex, divide it into smaller tests so that each one tests only a small piece of functionality.

You will not be able to compile the test code until the developer writes the functional code. The developer then writes the code so that the test compiles and passes.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-41

Step 2: Write or Modify the Functional Code In step 2, your goal is to develop functionality that passes the test cases that were created in step 1. If you are in the first iteration, in all probability the test code will not compile and you can assume that it failed. You must modify the functionality being tested so that the test code compiles and can be executed. After the functionality passes all of the test cases created in step 1, the developer stops developing the module. The outcome of step 2 is code that implements basic functionality. However, in the later iterations, when additional test cases are created to test the functionality, the code in the previous example will fail. The developers must make further changes in subsequent iterations so that all of the functionality can pass the additional test cases. The developers continue to improve the functionality until all of the existing test cases pass.

Step 3: Create Additional Tests After step 2, the code has the basic functionality to pass all of the test cases that were created in step 1. The tester must now test this functionality for various types of input. You should ensure that the amount of time spent developing additional test cases is proportionate to the criticality of the feature. For example, if various code paths in an API need to be tested by providing different input, you can write multiple test stubs, with each stub catering to one possible code path. The general guidelines for creating these additional tests are as follows: •

Create additional tests that could possibly break the code. Continue to create these additional tests until you have no more test cases.



Write test cases that focus on the goal of the code (what the user needs the code to do), rather than the implementation. For example, if the goal of a function is to return values from a database that is based on some identifier, test the function by passing both valid and invalid identifier values, rather than testing only those values that the current implementation supports (which can be only a valid set of values).



If all of the test cases created in step 1 have passed but the functionality still does not work as intended, you have probably missed an important test scenario, and must develop additional test cases that reproduce the failure of the functionality. These test cases are in addition to the existing test cases that pass invalid input to the API to force an exception.



Avoid writing separate test cases for each unique combination of input. The number of test cases you write should be based on the risk assessment of the feature, and on ensuring that all critical scenarios and the majority of test input have been accounted for.

Step 4: Test the Functional Code The next step is to test the functionality by using the additional test cases. To do so, execute all of the test cases from step 1 and step 3, and note any test cases that fail the test. The developers must then make changes to the functional code so that it passes all of the existing test cases. Repeat steps 2, 3, and 4 until the testers can no longer create additional test cases that break the functionality of the code. Each time a test fails, the developers fix the functionality based on the test cases and submit the improved code to the testers for a new round of testing.

Step 5: Refactor the Code After the completion of the previous steps, the code can be run and is capable of handling all of the test cases. In this step, the developers refactor the code to make it maintainable and extensible, so that changes in one part of the module can be worked on in isolation without changing the actual interfaces exposed to the end user.

9-42

Developing Web Applications with Microsoft® Visual Studio® 2010

In addition to making code easier to maintain, refactoring removes duplicate code and can reduce code complexity. This helps to ensure that the basic principles of loosely coupled and highly cohesive design are followed without breaking the functionality in any way. Question: Have you ever authored tests as part of requirements gathering? Question: How does authoring tests before development change your mindset? Question: What design considerations will you need to make to accomplish test-driven development?

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-43

Lab 9: Debugging, Unit Testing, and Refactoring

Objectives After completing this lab, you will be able to: •

Configure error handling.



Debug code.



Configure logging.



Create unit tests.



Implement the test-first/test-driven development methodology.

Introduction In this lab you will configure error handling in a web application, debug code to identify errors, log errors to the event log, and create and run unit tests.

9-44

Developing Web Applications with Microsoft® Visual Studio® 2010

Lab Scenario

Adventure Works has requested that you look into how you can improve the quality of the coding. As a first step toward this end, your team has determined you should look into the following functionality and features of Visual Studio 2010 and the .NET Framework: •

Configure error handling



Debug code



Log errors



Implement a code-first development methodology



Implement a test-first/test-driven development methodology

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-45

Exercise 1: Configuring Error Handling The main tasks for this exercise are as follows: •

Create a generic error page for unhandled errors.



Modify Global.asax and Web.config to redirect to the generic error page when an unhandled error occurs.

 Task 1: Open an existing ASP.NET web application 1.

Open Microsoft Visual Studio 2010.

2.

Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 01 or D:\Lab Files\VB\Lab 09\Starter\Exercise 01 folder.

 Task 2: Create a generic error page for unhandled errors 1.

Add a new Web Form named CustomErrorPage.

2.

Add the text CUSTOM ERROR PAGE to the CustomErrorPage Web Form.

3.

Save the AdventureWorks project.

4.

Close the CustomErrorPage Web Form.

 Task 3: Modify Web.config to redirect to the generic error page when an unhandled error occurs 1.

Open the Web.config file.

2.

Add the following markup to the system.web element.

3.

Save and close the Web.config file.

4.

Run the application.

5.

Click the Submit button. Note: The custom error page is displayed.

6.

Close Windows® Internet Explorer®.

7.

Close Visual Studio 2010. Results: After this exercise, you should have created a custom error page for unhandled exceptions.

9-46

Developing Web Applications with Microsoft® Visual Studio® 2010

Exercise 2: Debugging Code The main tasks for this exercise are as follows: •

Run the application.



Debug Default.aspx.



Debug a java script error using breakpoints and single-stepping.



Debug Default.aspx.js.

 Task 1: Open an existing ASP.NET web application 1.

Open Microsoft Visual Studio 2010.

2.

Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 02 or D:\Lab Files\VB\Lab 09\Starter\Exercise 02 folder.

 Task 2: Run the application 1.

Set Default.aspx as the project start page.

2.

Run the application in Debug mode.

 Task 3: Debug Default.aspx 1.

Click the Submit button.

Note: In Visual Studio, in the FormatException was unhandled by user code pane, the error text Input string was not in a correct format is displayed. 2.

Press F5 to continue.

Note: The custom error page is displayed. Do not close Internet Explorer. 3.

In Visual Studio, place a breakpoint in Default.aspx.cs or Default.aspx.vb on the following line of code. [Visual C#] string category = lbCategories.SelectedValue;

[Visual Basic] Dim category As String = lbCategories.SelectedValue

4.

Click the Back button on your browser.

Note: The Home page is displayed. 5.

Click the Submit button.

Note: Visual Studio is now shown, with the breakpoint highlighted. 6.

Press F10 to step over the line of code that sets the local variable category to the selected value of the list.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-47

7.

Hover the mouse over category and notice it is an empty string, which cannot be parsed by the code in the Products page.

8.

Press SHIFT+F5 to end debugging.

9.

In Visual Studio, modify the line of code that sets the local variable category to the selected value of the list, as follows. [Visual C#] string category = lbCategories.SelectedValue == string.Empty ? "5" : lbCategories.SelectedValue; [Visual Basic] Dim category As String = IIf(lbCategories.SelectedValue = String.Empty, "5", lbCategories.SelectedValue)

Note: If the breakpoint disappears after modifying the line of code, place the cursor on the line of code, and then press F9. 10. Run the application in Debug mode. 11. Click the Submit button. Note: Visual Studio is now shown, with the breakpoint highlighted. 12. Press F10 to step over the line of code that sets the local variable category to the selected value of the list. 13. Hover the mouse over category and notice it is a string with the value of 5. 14. Press F5 to continue. Note: The Products page is displayed, showing a list of Mountain Bikes. 15. Close Windows Internet Explorer. 16. Remove all breakpoints by pressing CTRL+SHIFT+F9.

 Task 4: Debug a java script error using breakpoints and single stepping •

Run the application in Debug mode. Note: The Home page is displayed.

 Task 5: Debug Default.aspx.js 1.

Click the Select First button. Note: A dialog box with an alert message is now shown.

2.

In the Message from webpage message box, click OK three times.

3.

In Visual Studio, place a breakpoint in Default.aspx.js on the following line of code.

9-48

Developing Web Applications with Microsoft® Visual Studio® 2010

for (i = 0; i < 3;

4.

i++) {

Click the Back button in your browser. Note: The Home page is displayed.

5.

Click the Select First button. Note: Visual Studio is now shown, with the breakpoint highlighted.

6.

Press F10 to step over the statements of code, until a message box is displayed.

7.

In the Message from webpage message box, click OK.

8.

Repeat the previous two steps twice.

9.

Press F5. Note: The Products page is displayed.

10. Close Windows Internet Explorer. 11. Close Visual Studio 2010. Results: After this exercise, you should have experience debugging Visual C# or Visual Basic, and java script code.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-49

Exercise 3: Logging The main tasks for this exercise are as follows: •

Configure logging to an Error Log.



Set the logging level in the Web.config file to allow for future debugging.



Create a generic error handler.

 Task 1: Open an existing ASP.NET web application 1.

Open Microsoft Visual Studio 2010.

2.

Open the AdventureWorks solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 03 or D:\Lab Files\VB\Lab 09\Starter\Exercise 03 folder.

 Task 2: Configure logging to an Error Log 1.

Open Products.aspx in Code view.

2.

Import the System.Diagnostics namespace. [Visual C#] using System.Diagnostics; [Visual Basic] Imports System.Diagnostics

3.

Modify the Page_Load method with the following code. [Visual C#] protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string categoryName = string.Empty; string categoryId = string.Empty; if (Request["id"] != null) { categoryId = Request["id"]; } try {

categoryName = DataAccessLayer.Products.GetCategoryName(int.Parse(categoryId)); } catch (Exception ex) { EventLog Log = new EventLog(); Log.Source = "Application"; Log.WriteEntry(ex.Message, EventLogEntryType.Error); } lblCategory.Text = categoryName; var data = DataAccessLayer.Products.GetProductsByCategory(int.Parse(categoryId));

}

}

gvProducts.DataSource = data; gvProducts.DataBind();

[Visual Basic]

9-50

Developing Web Applications with Microsoft® Visual Studio® 2010

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim categoryName As String = String.Empty Dim categoryID As String = String.Empty If Not Request("id") Is Nothing Then categoryID = Request("id") End If Try

categoryName = AdventureWorks.DataAccessLayer.Products.GetCategoryName(Integer.Parse(categoryID)) Catch ex As Exception Dim Log As New EventLog() Log.Source = "Application" Log.WriteEntry(ex.Message, EventLogEntryType.[Error]) End Try lblCategory.Text = categoryName Dim data = AdventureWorks.DataAccessLayer.Products.GetProductsByCategory(Integer.Parse(categoryID )) gvProducts.DataSource = data gvProducts.DataBind() End If End Sub

4.

Run the application. Note: The custom error page is displayed.

5.

Open the Event Viewer and show the Application log entry. If necessary, sort the Application log entries by date and time.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

6.

Close the Event Viewer.

7.

Close Windows Internet Explorer.

 Task 3: Set the logging level in the Web.config file to allow for future debugging 1.

Open the Web.config file.

2.

In the opening compilation tag, ensure that the value of the debug attribute is set to true.

3.

Close the Web.config file.

 Task 4: Create a generic error handler 1.

Open the Global.asax file. •

2.

In Solution Explorer, double-click Global.asax.

Import the System.Diagnostics namespace. [Visual C#] using System.Diagnostics; [Visual Basic] Imports System.Diagnostics

3.

Modify the Application_Error method with the following code. [Visual C#] void Application_Error(object sender, EventArgs e) { string message = "Url: " + Request.Path + " Error: " + Server.GetLastError().ToString(); EventLog log = new EventLog();

9-51

9-52

Developing Web Applications with Microsoft® Visual Studio® 2010

}

log.Source = "Application"; log.WriteEntry(message, EventLogEntryType.Error);

[Visual Basic] Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) Dim message As String = "Url: " & Request.Path & " Error: " & Server.GetLastError().ToString() Dim log As New EventLog() log.Source = "Application" log.WriteEntry(message, EventLogEntryType.Error) End Sub

4.

Build the project and fix any errors. •

In the AdventureWorks – Microsoft Visual Studio window, on the Build menu, click Build AdventureWorks.

5.

Close Visual Studio 2010. •

In the AdventureWorks – Microsoft Visual Studio window, click the Close button

Results: After this exercise, you should have experience installing a generic error handler for logging that can be called by a single method and all modules.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-53

Exercise 4: Creating Unit Tests The main tasks for this exercise are as follows: •

Create a method to add two numbers.



Add a test project.



Edit the test method to pass.



Run the test.



Edit the test method to fail.



Run the tests.

 Task 1: Open an existing ASP.NET web application 1.

Open Microsoft Visual Studio 2010.

2.

Open the MyClassLibrary solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 04 or D:\Lab Files\VB\Lab 09\Starter\Exercise 04 folder.

 Task 2: Create a method to add two numbers 1.

Open the Calculator.cs or Calculator.vb file.

2.

Add the following code to Calculator class. [Visual C#] public int Add(int p1, int p2) { return p1 + p2; } [Visual Basic] Public Function Add(ByVal p1 As Integer, ByVal p2 As Integer) As Integer Return p1 + p2 End Function

3.

Save Calculator.cs or Calculator.vb.

4.

Build the project and fix any errors.

 Task 3: Add a test project •

Add a test project named CalculatorTestProject for the Add method.

 Task 4: Edit the test method to pass 1.

In the AddTest method, modify the value assigned to local variable p1 to 2. [Visual C#] int p1 = 2; [Visual Basic] Dim p1 As Integer = 2

2.

In the AddTest method, modify the value assigned to local variable p2 to 3. [Visual C#] int p2 = 3; [Visual Basic] Dim p2 As Integer = 3

9-54

Developing Web Applications with Microsoft® Visual Studio® 2010

3.

In the AddTest method, modify the value assigned to local variable expected to 5. [Visual C#] int expected = 5; [Visual Basic] Dim expected As Integer = 5

4.

Remove the following code. [Visual C#] Assert.Inconclusive("Verify the correctness of this test method."); [Visual Basic] Assert.Inconclusive("Verify the correctness of this test method.")

5.

Ensure the AddTest method appears as follows. [Visual C#] [TestMethod()] public void AddTest() { Calculator target = new Calculator(); int p1 = 2; // TODO: Initialize to an int p2 = 3; // TODO: Initialize to an int expected = 5; // TODO: Initialize int actual; actual = target.Add(p1, p2); Assert.AreEqual(expected, actual); }

// TODO: Initialize to an appropriate value appropriate value appropriate value to an appropriate value

[Visual Basic] _ Public Sub AddTest() Dim target As Calculator = New Calculator() ' TODO: Initialize to an appropriate value Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate value Dim expected As Integer = 5 ' TODO: Initialize to an appropriate value Dim actual As Integer actual = target.Add(p1, p2) Assert.AreEqual(expected, actual) End Sub

 Task 5: Run the test •

Start the test. Note: In the Test Result window, you can see that the AddTest test passed.

 Task 6: Edit the test method to fail 1.

In the AddTest method, modify the value assigned to local variable expected to 6. [Visual C#] int expected = 6; [Visual Basic] Dim expected As Integer = 6

2.

Ensure the AddTest method appears as follows. [Visual C#]

Ensuring Quality by Debugging, Unit Testing, and Refactoring

[TestMethod()] public void AddTest() { Calculator target = new Calculator(); int p1 = 2; // TODO: Initialize to an int p2 = 3; // TODO: Initialize to an int expected = 6; // TODO: Initialize int actual; actual = target.Add(p1, p2); Assert.AreEqual(expected, actual); }

9-55

// TODO: Initialize to an appropriate value appropriate value appropriate value to an appropriate value

[Visual Basic] _ Public Sub AddTest() Dim target As Calculator = New Calculator() ' TODO: Initialize to an appropriate value Dim p1 As Integer = 2 ' TODO: Initialize to an appropriate value Dim p2 As Integer = 3 ' TODO: Initialize to an appropriate value Dim expected As Integer = 6 ' TODO: Initialize to an appropriate value Dim actual As Integer actual = target.Add(p1, p2) Assert.AreEqual(expected, actual) End Sub

 Task 7: Run the tests 1.

Start the test.

Note: In the Test Result window, you can see that the AddTest test failed. 2.

Close Visual Studio 2010.

Results: After this exercise, you should have experience creating unit tests for existing methods.

9-56

Developing Web Applications with Microsoft® Visual Studio® 2010

Exercise 5: Implementing the Test-First/Test-Driven Development Methodology The main tasks for this exercise are as follows: •

Create tests.



Create method stub.



Run the tests.



Add logic to stub methods.



Run the tests.

 Task 1: Open an existing ASP.NET web application 1.

Open Microsoft Visual Studio 2010.

2.

Open the MyClassLibrary solution from the D:\Lab Files\CS\Lab 09\Starter\Exercise 05 or D:\Lab Files\VB\Lab 09\Starter\Exercise 05 folder.

 Task 2: Create tests 1.

Open CalculatorTest.cs or CalculatorTest.vb file in the CalculatorTestProject project.

2.

Add the following code to CalculatorTest class. [Visual C#] [TestMethod()] public void ClassMultiplyMethodTest() { Calculator target = new Calculator(); Assert.IsNotNull(target); int expected = 6; int unexpected = 5; int actual = target.Multiply(3, 2);

}

Assert.AreEqual(expected, actual); Assert.AreNotEqual(unexpected, actual);

[TestMethod()] public void ClassSubtractMethodTest() { Calculator target = new Calculator(); Assert.IsNotNull(target); int expected = 1; int unexpected = 6; int actual = target.Subtract(3, 2);

}

Assert.AreEqual(expected, actual); Assert.AreNotEqual(unexpected, actual);

[Visual Basic] Public Sub ClassMultiplyMethodTest() Dim target As New Calculator() Assert.IsNotNull(target)

Ensuring Quality by Debugging, Unit Testing, and Refactoring

Dim expected As Integer = 6 Dim unexpected As Integer = 5 Dim actual As Integer = target.Multiply(3, 2) Assert.AreEqual(expected, actual) Assert.AreNotEqual(unexpected, actual) End Sub Public Sub ClassSubtractMethodTest() Dim target As New Calculator() Assert.IsNotNull(target) Dim expected As Integer = 1 Dim unexpected As Integer = 6 Dim actual As Integer = target.Subtract(3, 2) Assert.AreEqual(expected, actual) Assert.AreNotEqual(unexpected, actual) End Sub

3.

Save the CalculatorTest.cs or CalculatorTest.vb file.

 Task 3: Create method stub 1.

Open the Calculator.cs or Calculator.vb file in the ClassLibrary project.

2.

Add the following code to the Calculator class. [Visual C#] public int Multiply(int p1, int p2) { throw new NotImplementedException(); } public int Subtract(int p1, int p2) { throw new NotImplementedException(); } [Visual Basic] Public Function Multiply(ByVal p1 As Integer, ByVal p2 As Integer) As Integer Throw New NotImplementedException() End Function Public Function Subtract(ByVal p1 As Integer, ByVal p2 As Integer) As Integer Throw New NotImplementedException() End Function

3.

Build the solution and fix any errors.

 Task 4: Run the tests 1.

Open the CalculatorTest.cs or CalculatorTest.vb file.

2.

Start the ClassMultiplyMethodTest test. Note: In the Test Result window, you can see that the ClassMultiplyMethodTest test failed.

3.

Start the ClassSubtractMethodTest test.

9-57

9-58

Developing Web Applications with Microsoft® Visual Studio® 2010

Note: In the Test Result window, you can see that the ClassSubtractMethodTest test failed. 4.

Close the CalculatorTest.cs or CalculatorTest.vb file.

 Task 5: Add logic to the stub methods 1.

Replace the Multiply method in the Calculator class with following code. [Visual C#] public int Multiply(int p1, int p2) { return p1 * p2; } [Visual Basic] Public Function Multiply (ByVal p1 As Integer, ByVal p2 As Integer) As Integer Return p1 * p2 End Function

2.

Replace the Subtract method in the Calculator class with following code. [Visual C#] public int Subtract(int p1, int p2) { return p1 - p2; } [Visual Basic] Public Function Subtract(ByVal p1 As Integer, ByVal p2 As Integer) As Integer Return p1 - p2 End Function

3.

Build the solution and fix any errors.

 Task 6: Run the tests 1.

Open CalculatorTest.cs or CalculatorTest.vb file in the CalculatorTestProject project.

2.

Start the ClassMultiplyMethodTest test. Note: In the Test Result window, you can see that the ClassMultiplyMethodTest test passed.

3.

Start the ClassSubtractMethodTest test. Note: In the Test Result window, you can see that the ClassSubtractMethodTest test passed.

4.

Close the CalculatorTest.cs or CalculatorTest.vb file.

5.

Close Visual Studio 2010.

 Task 7: Turn off the virtual machine and revert the changes 1.

In Hyper-V™ Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Turn Off.

2.

In the Turn Off Machine dialog box, click Turn Off.

3.

In Hyper-V Manager, in the Virtual Machines pane, right-click 10264A-GEN-DEV, and then click Revert.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

4.

In the Revert Virtual Machine dialog box, click Revert. Results: After this exercise, you should have experience creating tests first, and then implementing methods.

9-59

9-60

Developing Web Applications with Microsoft® Visual Studio® 2010

Lab Review

Question: Why was the generic error handler implemented in the Global.asax file? Question: Where was a custom error page configured? Question: What are the advantages and disadvantages of using the Event Log for logging errors?

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-61

Module Review and Takeaways

Review Questions 1.

Do you believe unit testing will decrease the time you spend debugging?

2.

Have you ever broken code because of refactoring?

3.

Do you dedicate cycles to refactoring code?

4.

After applying a fix to an integrated module have you ever broken other modules?

5.

How have existing tests provided you with the intent of the original developer?

6.

What is the most helpful custom error page you’ve ever encountered? What features did it include?

Common Issues and Troubleshooting Tips Related to ASP.NET 4.0 Issue

Troubleshooting tip

Security when writing to Error Log

Depending on operating systems, writing to the error log requires elevated security.

Real-world Issues and Scenarios •

Unit test coverage requires additional effort, time, and money. These issues must be factored into estimates when starting a project. If you do not account for these, your project will be late and over budget.



Your code is only as good as your tests. Writing a simple test that does not fully exercise your code does you no good. Tests that fully exercise the code give you meaningful results.



Unit testing is not a replacement for Quality Assurance. Unit tests are authored through the eyes of a developer. Additional testing from an end user perspective should always be executed.

9-62

Developing Web Applications with Microsoft® Visual Studio® 2010



Mocking external components can be very complicated. Depending on the framework you use, mocking external systems or code without an interface can be extremely complicated to mock. Without mocks, it is very hard to isolate code and fully test it.

Best Practices Supplement or modify the following best practices for your own work situations: •

Don’t make unnecessary assertions.



Test only one code unit at a time.



Mock out all external services and state.



Avoid unnecessary preconditions.



Don’t unit-test configuration settings.



Name your unit tests clearly and consistently.

Tools Tool

Use for

Where to find it

NUnit

NUnit is an open source unittesting framework for all .NET languages.

http://go.microsoft.com/fwlink/ ?LinkID=204073&clcid=0x409

NMock

NMock is a dynamic mock object library for .NET. Mock objects make it easier to test single components—often single classes—without relying on real implementations of all of the other components.

http://go.microsoft.com/fwlink/ ?LinkID=204074&clcid=0x409

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF