MOC 2373 - Programming With Microsoft Visual Basic .NET - Delivery Guide
MOC 2373 - Programming With Microsoft Visual Basic .NET - Delivery Guide
NET
Delivery Guide
Course Number: 2373B
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Contents
Introduction
Course Materials .................................................................................................. 2 Prerequisites......................................................................................................... 3 Course Outline ..................................................................................................... 4 Microsoft Certified Professional Program ........................................................... 6 Facilities............................................................................................................... 8
iv
vii
Description
This five day instructor-led course provides students with the knowledge and skills needed to develop Microsoft .NETbased applications by using Microsoft Visual Basic .NET. The course focuses on the new features and enhancements to Visual Basic.
Audience
This course is intended for experienced Visual Basic developers who want to upgrade to Visual Basic .NET.
Student Prerequisites
This course requires that students meet the following prerequisites: Experience developing applications using Microsoft Visual Basic 4.0 or later Successful completion of Course 1013A, Mastering Microsoft Visual Basic 6 Development, or equivalent knowledge Or Successful completion of Course 1016A, Mastering Enterprise Development Using Microsoft Visual Basic 6, or equivalent knowledge Familiarity with basic concepts of object-oriented programming Familiarity with the Extensible Markup Language (XML) Familiarity with Microsofts .NET strategy as described on Microsofts .NET Web site at http://www.microsoft.com/net/ Familiarity with the .NET Framework as described on the following Web sites: http://msdn.microsoft.com/msdnmag/issues/0900/Framework/ Framework.asp and http://msdn.microsoft.com/msdnmag/issues/1000/Framework2/ Framework2.asp
viii
Course Objectives
After completing this course, the student will be able to: List the major elements of the .NET Framework and describe some of the major enhancements to the new version of Visual Basic. Describe the basic structure of a Visual Basic .NET project and use the main features of the integrated development environment (IDE). Use the new language features and syntax in Visual Basic .NET. Explain the basic concepts and terminology of object-oriented design specifically for Visual Basic .NET. Explain and use the basic concepts and terminology of object-oriented programming in Visual Basic .NET. Create applications by using Microsoft Windows Forms. Create Internet applications that use Web Forms and Web Services. Create applications that use ADO.NET. Create components in Visual Basic .NET. Set up and deploy various types of Visual Basic .NETbased applications. Prepare existing Visual Basicbased applications for upgrade to Visual Basic .NET.
ix
Course Timing
The following schedule is an estimate of the course timing. Your timing may vary.
Day 1
Start 9:00 9:30 10:30 10:45 11:45 12:45 1:30 2:30 2:45 3:30 4:00 End 9:30 10:30 10:45 11:45 12:45 1:30 2:30 2:45 3:30 4:00 4:30 Module Introduction Module 1: Overview of the Microsoft .NET Platform Break Module 2: Development Environment Features Lunch Lab 2.1: Exploring the Development Environment Module 3: Language and Syntax Enhancements Break Lab 3.1: Working with Variables and Procedures Module 3: Language and Syntax Enhancements (continued) Lab 3.2: Implementing Structured Exception Handling
Day 2
Start 9:00 9:30 10:45 11:00 11:45 12:45 1:30 2:15 2:30 3:15 End 9:30 10:45 11:00 11:45 12:45 1:30 2:15 2:30 3:15 4:15 Module Day 1 review Module 4: Object-Oriented Design for Visual Basic .NET Break Lab 4.1: Creating Class Diagrams from Use Cases Lunch Module 5: Object-Oriented Programming in Visual Basic .NET Lab 5.1: Creating the Customer Class Break Module 5: Object-Oriented Programming in Visual Basic .NET (continued) Lab 5.2: Inheriting the Package Class
Day 3
Start 9:00 9:30 10:30 10:45 11:45 12:30 1:30 2:30 3:30 3:45 4:45 End 9:30 10:30 10:45 11:45 12:30 1:30 2:30 3:30 3:45 4:45 5:30 Module Day 2 review Module 6: Using Windows Forms Break Module 6: Using Windows Forms (continued) Lab 6.1: Creating the Customer Form Lunch Module 7: Building Web Applications Lab 7.1: Creating the Customer Logon Web Forms Break Module 7: Building Web Applications (continued) Lab 7.2: Creating and Using the CustomerService Web Service
Day 4
Start 9:00 9:30 10:30 10:45 11:45 12:45 1:45 2:30 3:30 3:45 4:15 4:45 End 9:30 10:30 10:45 11:45 12:45 1:45 2:30 3:30 3:45 4:15 4:45 5:00 Module Day 3 review Module 8: Using ADO.NET Break Module 8: Using ADO.NET (continued) Lunch Lab 8.1: Creating Applications That Use ADO.NET Module 9: Developing Components in Visual Basic .NET Lab 9.1: Creating a Serviced Component Break Module 9: Developing Components in Visual Basic .NET (continued) Lab 9.2: Creating a Web Forms User Control Module 9: Developing Components in Visual Basic .NET (continued)
Day 5
Start 9:00 9:30 10:15 10:30 10:45 11:15 11:45 12:45 1:45 End 9:30 10:15 10:30 10:45 11:15 11:45 12:45 1:45 2:45 Module Day 4 review Module 10: Deploying Applications Lab 10.1: Packaging a Component Assembly Break Module 10: Deploying Applications (continued) Lab 10.2: Deploying a Windows-Based Application Lunch Module 11: Upgrading to Visual Basic .NET Course Wrap-up
xi
xii
xiii
Sampcode. This folder contains sample code that is accessible through the Web pages on the Student Materials compact disc. If there is no sample code, this folder does not appear. Sampsite. This folder contains files that create the sample site associated with this course. If there is no sample site, this folder does not appear. Webfiles. This folder contains the files that are required to view the course Web page. To open the Web page, open Windows Explorer, and in the root directory of the compact disc, double-click Default.htm or Autorun.exe. Wordview. This folder contains the Word Viewer that is used to view any Word document (.doc) files that are included on the compact disc.
xiv
Document Conventions
The following conventions are used in course materials to distinguish elements of the text.
Convention Use Indicates an introductory page. This symbol appears next to a topic heading when additional information on the topic is covered on the page or pages that follow it. bold Represents commands, command options, and syntax that must be typed exactly as shown. It also indicates commands on menus and buttons, dialog box titles and options, and icon and menu names. In syntax statements or descriptive text, indicates argument names or placeholders for variable information. Italic is also used for introducing new terms, for book titles, and for emphasis in the text. Indicate domain names, user names, computer names, directory names, and folder and file names, except when specifically referring to case-sensitive names. Unless otherwise indicated, you can use lowercase letters when you type a directory name or file name in a dialog box or at a command prompt. Indicate the names of keys, key sequences, and key combinations for example, ALT+SPACEBAR. Represents code samples or examples of screen text. In syntax statements, enclose optional items. For example, [filename] in command syntax indicates that you can choose to type a file name with the command. Type only the information within the brackets, not the brackets themselves. In syntax statements, enclose required items. Type only the information within the braces, not the braces themselves. In syntax statements, separates an either/or choice. Indicates a procedure with sequential steps. ... . . . In syntax statements, specifies that the preceding item may be repeated. Represents an omitted portion of a code sample.
italic
Title Capitals
[]
{} |
Introduction
Contents Introduction Course Materials Prerequisites Course Outline Microsoft Certified Professional Program Facilities 1 2 3 4 6 8
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
Introduction
iii
Instructor Notes
Presentation: 30 Minutes The Introduction module provides students with an overview of the course content, materials, and logistics for Course 2373B, Programming with Microsoft Visual Basic .NET.
Preparation Tasks
To prepare for this course, you must: Complete the Course Preparation Checklist that is included with the trainer course materials.
iv
Introduction
Module Strategy
Use the following strategy to present this module: Course 2373B: Programming with Microsoft Visual Basic .NET Show the slide that displays the course number and course title. Introduction Welcome students to the course and introduce yourself. Provide a brief overview of your background to establish credibility. Have students introduce themselves and provide their background, product experience, and expectations of the course. Record student expectations on a whiteboard or flip chart that you can reference later in class. Course Materials Explain the purpose of all materials used in this course. Prerequisites Provide the students with the list of prerequisites that they should have met before taking this course. This is an opportunity for you to identify students who may not have the appropriate background or experience to attend this course. Course Outline Provide an overview of each module and what students will learn. Explain how this course will meet students expectations by relating the information covered in individual modules to their expectations. Setup Provide the students with any necessary setup information for the course. Note By default, the lab and demo files are installed in the folders located at C:\Program Files\Msdntrain\2373\Labs and C:\Program Files\ Msdntrain\2373\DemoCode. Microsoft Certified Professional Program Inform students about the Microsoft Certified Professional (MCP) program and the various certification options. Facilities Explain the facility information for the training site.
Introduction
Introduction
To introduce yourself, establish credibility, meet students, and set student expectations for the course.
Topic Objective
Name Company Affiliation Title/Function Job Responsibility Visual Basic Programming Experience Expectations for the Course
Lead-in
Good morning. Welcome to Programming with Microsoft Visual Basic .NET. My name is...
Delivery Tip
As students introduce themselves, use a whiteboard or flip chart to record their expectations of the course.
Introduction
Course Materials
Topic Objective
To identify and describe the course materials.
Lead-in
Name Card Student Workbook Student Materials Compact Disc Course Evaluation
We have provided everything you need for this course. You will find the following materials at your desk.
The following materials are included with your kit: Name card. Write your name on both sides of the name card. Student workbook. The student workbook contains the material covered in class, in addition to the hands-on lab exercises. Student Materials compact disc. The Student Materials compact disc contains the Web page that provides you with links to resources pertaining to this course, including additional readings, review and lab answers, lab files, multimedia presentations, and course-related Web sites. Note To open the Web page, insert the Student Materials compact disc into the CD-ROM drive, and then in the root directory of the compact disc, double-click Autorun.exe or Default.htm. Course evaluation. To provide feedback on the course, training facility, and instructor, you will have the opportunity to complete an online evaluation near the end of the course. To provide additional comments or inquire about the Microsoft Certified Professional program, send e-mail to [email protected].
Delivery Tip
Demonstrate how to open the Web page provided on the Student Materials compact disc. On the Trainer Materials compact disc, double-click Autorun.exe or Default.htm in the StudentCD folder.
Introduction
Prerequisites
Topic Objective
To present and describe the prerequisites for this course.
Lead-in
Experience developing applications in Visual Basic 4.0 or later Familiarity with the Microsoft .NET strategy Familiarity with the Microsoft .NET Framework
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This course requires that you meet the following prerequisites: Experience developing applications in Microsoft Visual Basic 4.0 or later Successful completion of Course 1013A, Mastering Microsoft Visual Basic 6 Development, or equivalent knowledge Or Successful completion of course 1016A, Mastering Enterprise Development Using Microsoft Visual Basic 6, or equivalent knowledge Familiarity with basic object-oriented concepts Familiarity with Extensible Markup Language (XML) Familiarity with Microsofts .NET strategy as described on Microsofts .NET Web site (http://www.microsoft.com/net/) Familiarity with the .NET Framework as described on the following Web sites: http://msdn.microsoft.com/msdnmag/issues/0900/Framework/ Framework.asp and http://msdn.microsoft.com/msdnmag/issues/1000/Framework2/ Framework2.asp
Introduction
Course Outline
To provide an overview of each module and what students will learn.
Topic Objective
Module 1: Overview of the Microsoft .NET Platform Module 2: Development Environment Features Module 3: Language and Syntax Enhancements Module 4: Object-Oriented Design for Visual Basic .NET Module 5: Object-Oriented Programming in Visual Basic .NET
Lead-in
Module 1, Overview of the Microsoft .NET Platform, describes the rationale and features that provide the foundation for the .NET platform, including the .NET components. The purpose of this module is to build an understanding of the .NET platform for which you will be developing Visual Basic .NET version 7.0 code. After completing this module, you will be able to describe the components of the .NET platform. Module 2, Development Environment Features, describes the major benefits of the new integrated development environment (IDE) and the basic structure of a Visual Basic .NETbased application. You will learn how to create projects in Visual Basic .NET, and will try some of the tools that make the IDE powerful for application development. Finally, you will learn how to debug your projects and how to compile them. Module 3, Language and Syntax Enhancements, describes the many language and syntax enhancements available in Visual Basic .NET. You will learn how these enhancements help make it an excellent development tool for the .NET platform. Module 4, Object-Oriented Design for Visual Basic .NET, describes how to begin the class design process by using use cases. You will then learn about some common object-oriented programming concepts, including inheritance, interfaces, and polymorphism. Finally, you will see how to document your system design. Module 5, Object-Oriented Programming in Visual Basic .NET, provides information on how to implement object-oriented programming in Visual Basic .NETbased applications. You will learn how to define classes, their properties, and their methods. You will learn about the life cycle of an object, from creation to destruction. You will also learn how to work with classes by using inheritance, interfaces, polymorphism, shared members, events, and delegates.
Introduction
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Module 6, Using Windows Forms, describes how to use the new features available in Microsoft Windows Forms and how to make changes to forms and controls, and to their properties, methods, and events. You will also learn how to create some of the standard Windows dialog boxes. Finally, you will learn about visual inheritance, which allows you to use object-oriented techniques within your forms. Module 7, Building Web Applications, explains how to create dynamic, powerful Web applications by using the ASP.NET framework. You will learn how to use Web Services from a browser or from another client application. Module 8, Using ADO.NET, explains how to use ADO.NET. You will learn about the Microsoft .NET providers included in the .NET Framework and about how to use the DataSet object. You will also learn how to use the Microsoft Visual Studio .NET data designers and how to bind data to Microsoft Windows Forms and Web Forms. Finally, you will learn about the integration of Extensible Markup Language (XML) with ADO.NET. Module 9, Developing Components in Visual Basic .NET, describes the different types of components that can be created in Visual Basic .NET, including component classes and serviced components. This module also explains how to enhance your applications by using threading. Module 10, Deploying Applications, explains how to deploy assemblies for use by client applications, how to decide what type of distribution strategy to implement, and how to deploy Windows-based and Web-based applications. Module 11, Upgrading to Visual Basic .NET, explains the factors you must consider when deciding whether to upgrade an existing application, the options you have for upgrading, and how to use the Upgrade Wizard.
Introduction
Lead-in
http://www.microsoft.com/trainingandservices/
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The Microsoft Certified Professional program is a leading certification program that validates your experience and skills to keep you competitive in todays changing business environment. The following table describes each certification in more detail.
Certification MCSA on Microsoft Windows 2000 Description The Microsoft Certified Systems Administrator (MCSA) certification is designed for professionals who implement, manage, and troubleshoot existing network and system environments based on Microsoft Windows 2000 platforms, including the Windows .NET Server family. Implementation responsibilities include installing and configuring parts of the systems. Management responsibilities include administering and supporting the systems. The Microsoft Certified Systems Engineer (MCSE) credential is the premier certification for professionals who analyze the business requirements and design and implement the infrastructure for business solutions based on the Microsoft Windows 2000 platform and Microsoft server software, including the Windows .NET Server family. Implementation responsibilities include installing, configuring, and troubleshooting network systems. The Microsoft Certified Solution Developer (MCSD) credential is the premier certification for professionals who design and develop leading-edge business solutions with Microsoft development tools, technologies, platforms, and the Microsoft Windows DNA architecture. The types of applications that MCSDs can develop include desktop applications and multi-user, Web-based, N-tier, and transaction-based applications. The credential covers job tasks ranging from analyzing business requirements to maintaining solutions.
MCSD
Introduction (continued) Certification MCDBA on Microsoft SQL Server 2000 Description The Microsoft Certified Database Administrator (MCDBA) credential is the premier certification for professionals who implement and administer Microsoft SQL Server databases. The certification is appropriate for individuals who derive physical database designs, develop logical data models, create physical databases, create data services by using Transact-SQL, manage and maintain databases, configure and manage security, monitor and optimize databases, and install and configure SQL Server. The Microsoft Certified Professional (MCP) credential is for individuals who have the skills to successfully implement a Microsoft product or technology as part of a business solution in an organization. Hands-on experience with the product is necessary to successfully achieve certification. Microsoft Certified Trainers (MCTs) demonstrate the instructional and technical skills that qualify them to deliver Microsoft Official Curriculum through Microsoft Certified Technical Education Centers (Microsoft CTECs).
MCP
MCT
Certification Requirements
The certification requirements differ for each certification category and are specific to the products and job functions addressed by the certification. To become a Microsoft Certified Professional, you must pass rigorous certification exams that provide a valid and reliable measure of technical proficiency and expertise. For More Information See the Microsoft Training and Certification Web site at http://www.microsoft.com/traincert/. You can also send e-mail to [email protected] if you have specific certification questions.
Introduction
Facilities
To inform students of class logistics and rules for the training site.
Topic Objective
Class Hours
Lead-in
Building Hours
Phones
Rest Rooms
Smoking
Meals
Recycling
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 60 Minutes Lab: 00 Minutes This module provides students with an overview of the Microsoft .NET Platform. It defines some of the terminology specific to the .NET Platform and describes its key features and benefits. The module starts with an overview of the .NET Platform, and then introduces the .NET Framework and services. It describes the design goals of the .NET Framework and provides other information about the major components. Finally, students will learn about the programming languages that can be used with the .NET Framework and about the major enhancements to Microsoft Visual Basic .NET version 7.0. This module contains no labs. After completing this module, students will be able to: List the main elements of the .NET Platform. Describe the .NET Framework and its components. List the major enhancements to Visual Basic .NET.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_01.ppt Module 1, Overview of the Microsoft .NET Platform
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module.
iv
Module Strategy
This first module must set the tone for the rest of the course. Visual Basic developers may initially be hesitant to upgrade their skills to Visual Basic .NET because of the substantial changes to the product. While it may take students a bit longer to adapt to this version of Visual Basic, the advantages are significant, and these advantages must be made clear to students from the very beginning. Use the following strategy to present this module: What Is the Microsoft .NET Platform? Discuss the core services and technologies provided by the .NET Platform. Briefly talk about the .NET Framework. It is covered in more detail in the next lesson. What Is the .NET Framework? Ensure that students understand the function that the Common Language Specification plays in language development for the .NET Platform. Stress the fact that the existing model provides no consistency in the availability of application programming interfaces (APIs). The choice of programming model also becomes the choice of language. So if you are a Visual Basic developer, you are limited by the set of functionality that it provides for the platform. Or, if you are a C++ developer, your existing skills do not transfer to Active Server Pages (ASP) development. However, because this course focuses on Visual Basic development, point out that most students will already be familiar with many .NET concepts, such as ASP development and Web Services, Microsoft Visual Basic Scripting Edition, and Simple Object Access Protocol (SOAP)/ Visual Basic 6.0. Mention that Visual Basic has been upgraded significantly to support the .NET Platform. Explain that C# is a new language specifically created for the .NET Framework and that C++ has been enhanced to support the .NET Platform. Point out that several third-party languages are also .NET enabled, and that more will follow over time.
What Are the .NET Framework Components? Briefly describe each of the .NET Framework components. Point out to the students each area where Visual Basic developers can benefit from the .NET Framework components, such as garbage collection, type checking, and exception handling. ADO.NET is also an important new tool for Visual Basic .NET developers, and they should not find this tool difficult if they are familiar with previous versions of ActiveX Data Objects (ADO). Web Forms and Web Services are of course some of the major new features of the .NET Platform. Students should be aware that they no longer need to learn a scripting language in order to create Web applications; they can now use Visual Basic .NET, using their existing Visual Basic skills. Microsoft Windows-based applications are not to be forgotten in Visual Basic .NET. Students need to realize that there are many new and exciting aspects of the new Microsoft Windows Forms development. What Are the Visual Basic .NET Enhancements? Point out that the course focuses on Microsoft Visual Studio .NET from the perspective of a Visual Basic developer. Describe the main areas of enhancement, but make it clear that they are covered in detail in the remainder of the course.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
What Is the Microsoft .NET Platform? What Is the .NET Framework? What Are the .NET Framework Components? What Are the Visual Basic .NET Enhancements?
Lead-in
In this module, you will be introduced to the .NET Platform. You will then learn about the .NET Framework and the language support that the .NET Framework provides for the platform.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Microsoft Visual Basic .NET version 7.0 is a major enhancement to the Visual Basic product line. As a Visual Basic developer, you will find it useful to understand the rationale and features that provide the foundation for the Microsoft .NET Platform before you look at Visual Basic .NET in detail. After completing this module, you will be able to: List the main elements of the .NET Platform. Describe the .NET Framework and its components. List the major enhancements to Visual Basic .NET.
This module provides an overview of the .NET systems for Visual Basic developers. Make sure to point out the advantages of .NET over previous versions of Windows development architectures and Visual Basic whenever possible.
Topic Objective
Lead-in
Visual Studio .NET Orchestration .NET Framework Internet COM+ .NET Enterprise Servers
Internet
The .NET Platform consists of several core services and features, as shown on this slide. One goal of this new platform is to simplify Web development. This topic will provide a brief look at the architecture of the .NET Platform.
Windows
Available Today With .NET Enhancements New Capabilities
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This topic describes the components of the .NET Platform, including the .NET Framework, the .NET Building Block Services, .NET Enterprise Servers, and Microsoft Visual Studio .NET. The .NET Platform is important to you because the goal of the .NET Platform is to simplify Web development by providing all of the tools and technologies that you need to build distributed Web applications. The .NET Platform provides: A language-independent, consistent programming model across all tiers of an application. Seamless interoperability between technologies. Easy migration from existing technologies. Full support for the Internets platform-neutral, standards-based technologies, including Hypertext Transfer Protocol (HTTP), Extensible Markup Language (XML), and Simple Object Access Protocol (SOAP).
The .NET Framework is based on a new common language runtime. This runtime provides a common set of services for projects built in Visual Studio .NET, regardless of the language. These services provide key building blocks for applications of any type, across all application tiers. Microsoft Visual Basic, Microsoft Visual C++, and other Microsoft programming languages have been enhanced to take advantage of these services. Third-party languages that are written for the .NET Platform also have access to the same services. Note Because of the common language runtime, all .NET languages will use the same run-time files. This means that there is no need to distribute Visual Basicspecific run-time libraries because .NET run-time files will be installed automatically in future versions of Microsoft Windows. .NET Building Block Services The .NET Building Block Services are distributed programmable services that are available both online and offline. A service can be invoked on a stand-alone computer not connected to the Internet, provided by a local server running inside a company, or accessed by means of the Internet. The .NET Building Block Services can be used from any platform that supports SOAP. Services include identity, notification and messaging, personalization, schematized storage, calendar, directory, search, and software delivery. Visual Studio .NET Visual Studio .NET provides a high-level development environment for building applications on the .NET Framework. It provides key enabling technologies to simplify the creation, deployment, and ongoing evolution of secure, scalable, highly available Web applications and Web Services. It also enables a new generation of Windows-based applications with many new features available through the .NET Framework.
.NET Enterprise Servers The .NET Enterprise Servers provide scalability, reliability, management, and integration within and across organizations, and many other features as described in the following table.
Server Microsoft SQL Server 2000 Description Includes rich XML functionality, support for Worldwide Web Consortium (W3C) standards, the ability to manipulate XML data by using Transact SQL (T-SQL), flexible and powerful Web-based analysis, and secure access to your data over the Web by using HTTP. Provides enterprise application integration (EAI), business-to-business integration, and the advanced BizTalk Orchestration technology to build dynamic business processes that span applications, platforms, and organizations over the Internet. Provides the best way to embrace Internet, intranet, and client/server technologies while preserving investments in existing systems. Microsoft Host Integration Server 2000 is the replacement for SNA Server. Builds on the powerful Exchange messaging and collaboration technology by introducing several important new features and further increasing the reliability, scalability, and performance of its core architecture. Other features enhance the integration of Exchange 2000 with Microsoft Windows 2000, Microsoft Office 2000, and the Internet. Provides a deployment and management tool for highavailability Web applications. Provides secure, fast, and manageable Internet connectivity. Internet Security and Acceleration Server integrates an extensible, multilayer enterprise firewall and a scalable, high-performance Web cache. It builds on Windows 2000 security and directory for policybased security, acceleration, and management of internetworking. Provides an application framework, sophisticated feedback mechanisms, and analytical capabilities.
Microsoft Application Center 2000 Microsoft Internet Security and Acceleration Server 2000
Topic Objective
Overview of the .NET Framework Benefits of the .NET Framework Languages in the .NET Framework
Lead-in
The .NET Framework provides all the common services you need to enable your applications to run.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn how the .NET Framework provides all common services required for your applications to run. You will learn how services are available in any .NET-compatible language through the common language specification (CLS). You will also learn what languages are supported in the .NET Framework.
Topic Objective
Lead-in
The .NET Framework provides all common services required to run your Visual Basic .NET applications. These services are available in any .NETcompatible language through the Common Language Specification.
Visual Basic
C++
C#
J#
.NET Framework
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The .NET Framework provides all the common services required to run your Visual Basic .NET applications.
Based on Web standards and practices Extensible Easy for developers to use Designed using unified application models
.NET Framework
Lead-in
Before you learn about the various .NET Framework components, it is helpful to understand the design goals of the .NET Framework. This will help you to see how the .NET Framework simplifies software development.
MFC/ATL
ASP
Windows API
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this topic, you will learn about some of the benefits of the .NET Framework.
Visual Basic .NET New version of Visual Basic with substantial language innovations C# designed for .NET New component-oriented language Managed Extensions to Visual C++ Provides more power and control J# .NET Takes full advantage of the .NET Framework Third-party languages
Lead-in
In this topic, you will learn about the languages that Microsoft is providing for the .NET Framework with Visual Studio .NET. Youll also learn about some of the languages for .NET that are being created by third-party developers.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The .NET Platform is language neutralall common services needed to enable programs to run are provided by the .NET Framework. The .NET Framework provides support for numerous programming languages, including Microsoft and third-party languages.
Language Microsoft Visual Basic .NET Description Visual Basic .NET provides substantial language innovations over previous versions of Visual Basic. Visual Basic .NET supports inheritance, constructors, polymorphism, overloading, structured exceptions, stricter type checking, free threading, and many other features. With this release, Visual Basic Scripting Edition provides full Visual Basic functionality. C# was designed for the .NET Platform and is the first modern component-oriented language in the C and C++ family. It can be embedded in ASP.NET pages. Some of the key features of this language include classes, interfaces, delegates, boxing and unboxing, namespaces, properties, indexers, events, operator overloading, versioning, attributes, unsafe code, and XML documentation generation. No header or Interface Definition Language (IDL) files are needed. The Visual C++ upgrade is a managed, minimal extension to the C++ language. This extension provides access to the .NET Framework that includes garbage collection, single-implementation inheritance, and multiple-interface inheritance. This upgrade also eliminates the need to write plumbing code for components. It offers low-level access where useful. J# .NET is a language for Java-language developers who want to build applications and services for the .NET Framework. J# .NET is fully integrated with the Visual Studio .NET IDE, and is designed to take full advantage of the .NET Framework. Various third-party languages are supporting the .NET Platform. These languages include APL, COBOL, Pascal, Eiffel, Haskell, ML, Oberon, Perl, Python, Scheme, and SmallTalk.
Microsoft Visual C#
Topic Objective
The .NET Framework Components Common Language Runtime .NET Framework Class Library ADO .NET: Data and XML ASP .NET: Web Forms and Services User Interface
Lead-in
In this lesson, you will learn about the different components that make up the .NET Framework.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn about the Microsoft .NET Framework components. The .NET Framework is a set of technologies that are an integral part of the .NET Platform. The .NET Framework provides the basic building blocks to develop Web applications and Web Services by using ASP.NET.
10
Lead-in
Visual Basic .NET uses these components that are provided by the .NET Framework.
User Interface
ADO .NET: Data & XML .NET Framework Class Library Common Language Runtime
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The components of the .NET Framework are as follows: Common language runtime .NET Framework Class Library ADO.NET: data and XML ASP.NET: Web Forms and Services User interface
11
Topic Objective
Base Class Library Support Thread Support Type Checker Security Engine MSIL to Native Compilers Code Manager Class Loader COM Marshaler Exception Manager Debug Engine Garbage Collection
Lead-in
This topic will give you an overview of the various components of the common language runtime. Each component will be briefly described. As a Visual Basic developer, you will never physically see these pieces. But discussing them gives you a better understanding of the richness of the runtime.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The Common Language Runtime simplifies application development, provides a robust and secure execution environment, supports multiple languages, simplifies application deployment and management, and provides a managed environment.
Many of these issues are directly beneficial to Visual Basic .NET developers and will be highlighted throughout the course.
12
Manages code execution. Provides automatic lifetime management of all of your objects. This is a multiprocessor, scalable garbage collector. Provides evidence-based security based on the origin of the code as well as the user. Allows you to debug your application and trace the execution of code. Will not allow unsafe casts or uninitialized variables. IL can be verified to guarantee type safety. Provides structured exception handling, which is integrated with Windows Structured Exception Handling (SEH). Error reporting has been improved. Provides classes and interfaces that enable multithreaded programming. Provides marshaling to and from COM. Integrates code with the runtime that supports the .NET Framework Class Library. The .NET Framework Class Library is covered in the following lesson.
13
Lead-in
In this topic, you will learn how the .NET Framework Class Library exposes features of the runtime and provides other high-level services.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The .NET Framework Class Library exposes features of the runtime and provides other high-level services that every programmer needs through an object hierarchy. This object hierarchy is known as a namespace.
The .NET Framework Class Library provides many powerful new features for Visual Basic .NET developers. For example, the Collections namespace adds many new possibilities, such as sorting, queues, stacks, and auto-sizing arrays. The Threading system class also creates new possibilities to Visual Basic .NET developers for creating true multithreaded applications. A simple overview of namespaces at this point may be useful.
System Namespaces
The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications. The System.Collections namespace provides sorted lists, hash tables, and other ways to group data. The System.IO namespace provides file I/O, streams, and so on. The System.NET namespace provides Transmission Control Protocol/Internet Protocol (TCP/IP) and sockets support. For more information about namespaces, search for namespaces in the .NET Framework SDK documentation. Namespaces will also be covered in Module 2, Development Environment Features, in Course 2373B, Programming with Microsoft Visual Basic .NET.
14
Lead-in
The .NET Framework provides a new set of ADO.NET classes to handle data.
System.Data
System.Xml System.Xml.Schema
DataSet DataTable
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip ADO.NET is the next generation of ActiveX Data Object (ADO) technology. ADO.NET provides improved support for the disconnected programming model. It also provides rich XML support.
ADO.NET has been created especially for Internet usage, as it uses XML as its core technology. This means that developers no longer need to pass Recordset objects around the system, potentially limiting which clients they can service. It also improves the disconnected programming model seen in previous versions of ADO. Point out that Visual Basic developers knowledge of ADO will greatly assist them in moving to ADO.NET. Check students understanding of basic XML concepts.
System.Data Namespace
The System.Data namespace consists of classes that constitute the ADO.NET object model. At a high level, the ADO.NET object model is divided into two layers: the connected layer and the disconnected layer. The System.Data namespace includes the DataSet class, which represents multiple tables and their relations. These data sets are completely self-contained data structures that can be populated from a variety of data sources. One data source could be XML, another could be OLE DB, and a third data source could be the direct adapter for SQL Server.
System.Xml Namespace
The System.Xml namespace provides support for XML. It includes an XML parser and a writer, which are both W3C compliant. Transformations are provided by the System.Xml.Xsl namespace and the implementation of XPath that allows data graph navigation in XML. The System.XML.Serialization namespace provides the entire core infrastructure for Web Services, including features such as moving back and forth between objects and an XML representation.
15
Topic Objective
Lead-in
ASP .NET
System.Web
Services Description Discovery Protocols Caching Configuration Security SessionState UI HtmlControls WebControls
The Internet is quickly evolving from todays Web sites that just deliver UI pages to browsers, to a next generation of programmable Web sites that link organizations, applications, services, and devices directly together. These programmable Web sites are more than passively accessed sites; they are reusable, intelligent Web Services.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** ASP.NET is a programming framework that is built on the common language runtime and that can be used on a server to build powerful Web applications. ASP.NET Web Forms provide an easy and powerful way to build dynamic Web user interfaces (UIs). ASP.NET Web Services provide the building blocks for constructing distributed Web-based applications. Web Services are based on open Internet standards, such as HTTP and XML. You can think of a Web Service as a reusable component that is accessible across the Internet, rather than being limited to Windows clients on a local area network. Delivery Tip The common language runtime provides built-in support for creating and exposing Web Services by using a programming abstraction that is consistent and familiar to both Active Server Pages (ASP) and Visual Basic developers. The resulting model is both scalable and extensible. This model is based on open Internet standards (HTTP, XML, SOAP, and SDL) so that it can be accessed and interpreted from any client or Internet-enabled device. Some of the more common ASP.NET classes are described in the following paragraphs.
Web development becomes almost as simple as Windows-based application development with Visual Basic .NET. Creating Web applications can be accomplished in the one IDE, whether they are Web page applications or Web Services.
System.Web Namespace
In the System.Web namespace, there are services such as caching, security, configuration, and others that are shared between Web Services and Web user interface (UI).
System.Web.Services Namespace
The System.Web.Services namespace handles Web Service requirements such as transportation protocols and service discovery.
System.Web.UI Namespace
The System.Web.UI namespace provides two classes of controls: HTML controls and Web controls. The HTMLControls provide direct mapping of HTML tags, such as <INPUT>. There are also WebControls that are richer and allow you to structure controls with templates (for example, a grid control).
16
User Interface
Topic Objective
To explain how the .NET Framework handles the user interface for traditional Windows applications.
Lead-in
In this lesson, you will learn how .NET handles the user interface. The System.Windows.Forms class provides the clientside UI, and System.Drawing provides the next generation of GDI services.
System.Windows.Forms System.Drawing
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Windows applications can provide more powerful user interfaces than ever by using the .NET Frameworks System.Windows.Forms and System.Drawing namespaces. The new .NET Windows Forms will look very familiar to Visual Basic developers.
System.Windows.Forms Namespace
You can use the System.Windows.Forms namespace classes to build the client UI. This class lets you implement the standard Windows UI in your .NET applications. Many functions that were previously only accessible by means of application programming interface (API) calls are now available as part of the forms themselves, making development much easier and more powerful.
System.Drawing Namespace
The System.Drawing namespace provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces.
17
Lead-in
Visual Basic .NET provides major language enhancements, full access to the .NET Framework, and enhanced Web development.
Discuss each point on the slide and the advantages each one gives developers.
18
19
Review
To reinforce module objectives by reviewing key points.
Topic Objective
What Is the Microsoft .NET Platform? What Is the .NET Framework? What Are the .NET Framework Components? What Are the Visual Basic .NET Enhancements?
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. What is the .NET Platform? The .NET Platform is a set of technologies designed to transform the Internet into a full-scale distributed computing platform. It provides new ways to build applications from collections of Web Services. The .NET Platform fully supports the existing Internet infrastructure (HTTP, XML, SOAP).
2. What are the core technologies in the .NET Platform? .NET Framework, .NET Enterprise Servers, .NET Building Block services, Visual Studio .NET, and Windows.
3. List the components of the .NET Framework. Common language runtime, .NET Framework Class Library, data and XML, Web Services and Forms, and Windows Forms.
4. What is the purpose of common language runtime? It provides an environment in which you can execute code.
20
5. What is the purpose of common language specification? It defines a set of features that all .NET-compatible languages should support.
6. What is a Web Service? A Web Service is a programmable Web component that can be shared between applications on the Internet or an intranet.
7. What is a managed environment? A managed environment is one in which the environment provides services, such as garbage collection, security, and other similar features.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 60 Minutes Lab: 45 Minutes This module teaches students some of the overall benefits of using the new Microsoft Visual Studio .NET version 7.0 integrated development environment (IDE) and how to create Visual Basic .NET projects. Students will try some of the tools that make the IDE so powerful for application development. They will learn how to debug and compile projects. After completing this module, students will be able to: Describe the overall benefits of the new IDE. Describe the different types of Visual Basic .NET projects and their structures, including their file structures. Reference external applications from a project. View and set the properties of a project. Use the various windows in the IDE, including the Server Explorer, Object Browser, and Task List. Debug a simple application. Build and compile a simple application.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_02.ppt Module 2, Development Environment Features
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the labs.
iv
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
5. Expand the new data connection. Point out the functional similarity to the Data View window found in previous versions of Microsoft Visual Basic. To use the Server Explorer to examine the local server 1. In Server Explorer, expand Servers. 2. Expand the instructor machine. 3. Expand and examine the server items, such as Event Logs, SQL Servers, Performance Counters, and Services. 4. To start the SQLServerAgent service, expand the Services item, right-click SQLSERVERAGENT, and then click Start. Point out how to stop the service if required. 5. Click Auto Hide to hide Server Explorer.
vi
To edit an Extensible Markup Language (XML) file 1. Using Windows Explorer, navigate to the install folder\DemoCode\Mod02 folder. 2. Drag the Customers.xml file from Windows Explorer to the SimpleProject node of the tree view in Solution Explorer. If you drop it anywhere else, it may not be added to the project successfully. 3. Point out that this copy of the document is stored with the project files. 4. Double-click Customers.xml in the Solution Explorer to edit the document. 5. Examine the document in XML view and then Data view. 6. Change the first name of one of the customers by using the editable grid, and then press ENTER. Confirm the change has taken place by checking the data in XML view. 7. Save your project and close Visual Studio .NET.
Debugging a Project
To prepare for the demonstration Open Visual Studio .NET, and then open the install folder\DemoCode\ Mod02\Debugging\Starter\Debugging.sln solution. To set a conditional breakpoint 1. Open the code window for the form. 2. Explain the purpose of the code. 3. Set a breakpoint on the Button1_Click procedure definition. 4. Right-click the breakpoint itself and click Breakpoint Properties. In the Breakpoint Properties dialog box, click Condition. Set the following condition:
iCounter = 4
5. Close the Breakpoint Properties dialog box. To step through the code 1. Run the project. 2. When the form appears, click the Begin button on the form. Verify that the Output window displays the debugging information as a result of the Debug.WriteLine statement. 3. To demonstrate that the condition is not initially met, click Begin three times until execution halts at the conditional breakpoint. 4. Point out the various debugging windows, including the Locals and Breakpoints windows, and the value of the iCounter variable. 5. Step through the entire code by using either the Debug menu or toolbar before closing the form and stopping the debugging process.
vii
To use the Command window 1. Ensure that the Command window is activated and that the command prompt (>) is displayed. If it is not, type >cmd and press ENTER. 2. Use the Debug.Start command to start the debugger. 3. Click Begin three times to enter debugging mode, and then click the Command window tab to make it the active window. 4. Use the immed command to change to Immediate mode. 5. Type ?iCounter to check the value of the iCounter variable. 6. Use the >cmd command to change back to Command mode. 7. Use the Debug.StopDebugging command to end the debugging session. 8. Use the Exit command to close Visual Studio .NET.
viii
Module Strategy
Use the following strategy to present this module: Describing the Integrated Development Environment This lesson is an introduction to the general benefits of using the Visual Studio .NET IDE. The most important aspect of this lesson is that there is only one IDE that is required to create all types of projects. Students no longer must develop their components in the Visual Basic IDE and their Web pages in Microsoft Visual InterDev or another Web development tool. Creating Visual Basic .NET Projects This lesson introduces some of the basic concepts required to create a Visual Basic .NET project. Many aspects of this lesson are similar to concepts covered in previous Visual Basic courses, such as project templates, structures, properties, and references. This lesson also introduces assemblies and namespaces, both of which are fundamental aspects of .NET-compatible development. Explain assemblies enough to give the students an overall understanding of their purpose, without going into too much depth. Concepts such as versioning and security will be covered in Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET. The namespaces lesson has a small amount of simple code that you will need to explain to students. This code defines classes and creates objects based on those classes. This type of code will be easily understood by all Visual Basic developers, but advise them that this code will be explained in Module 5 Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. Using Development Environment Features This lesson introduces the various features of the IDE such as the Solution Explorer, Server Explorer, Object Browser, Task List, Dynamic Help, XML editing, and macros. Some of these items are similar to those found in previous versions of Visual Basic, such as the Solution Explorer and Object Browser, so you will not have to explain them in detail. Students should have a basic amount of XML knowledge, but check that they understand the structure of the XML document, Customers.xml, shown in the demonstration.
ix
Debugging Applications This lesson begins by discussing breakpoints and how to set them. This will not be new to most students. However, explain how to set conditional breakpoints in detail, because this is handled differently in Visual Basic .NET than in previous versions of Visual Basic. This lesson discusses the various debugging techniques and debugging windows that are available. Again, because several of these features are based on previous versions of Visual Basic, point out the enhancements rather than explaining each feature in much detail. The Command window is also discussed, and the slide shows an example of the windows use. Step through the example and point out the various effects each statement has on the environment. Compiling in Visual Basic .NET This lesson begins by looking at how the Task List window assists you in tracking syntax errors during an attempted compilation. The last slide discusses the various compilation options available to the developer, including the possible configuration settings Debug and Release. Be sure students understand the difference between the two settings. This will affect the assembly that is generated.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Describing the Integrated Development Environment Creating Visual Basic .NET Projects Using Development Environment Features Debugging Applications Compiling in Visual Basic .NET
Lead-in
In this module, you will learn about the Visual Studio .NET development environment and the many powerful features it provides for Visual Basic .NET developers.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The Microsoft Visual Studio .NET version 7.0 integrated development environment (IDE) provides you with enhancements to many tools found in previous versions of Microsoft Visual Basic, combined with features found in other environments, such as Microsoft Visual C++. In this module, you will learn the overall benefits of using this new IDE. You will learn how to create Visual Basic .NET projects, and will try some tools of the new IDE. Finally, you will learn how to debug your projects and how to compile them. After completing this module, you will be able to: Describe the overall benefits of the new IDE. Describe the different types of Visual Basic .NET projects and their structures, including their file structures. Reference external applications from your project. View and set the properties of a project. Use the various windows in the IDE, including Server Explorer, the Object Browser, and the Task List. Debug a simple application. Build and compile a simple application.
Lead-in
There is one IDE for all .NET projects Solutions can contain multiple programming languages Example: Visual Basic .NET and C# in the same solution The IDE is customizable through My Profile The IDE has a built-in Internet browser
The Visual Basic .NET IDE provides some significant benefits over previous Visual Basic IDEs.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The Visual Studio .NET IDE provides some significant enhancements to previous IDEs for Visual Basic. There is one IDE for all Microsoft .NET projects The Visual Studio .NET IDE provides a single environment where you can develop all types of .NET applications, from simple applications based on Microsoft Windows, to complex n-tier component systems and complete Internet applications. For example, you no longer need to create your components in a separate environment from your Internet pages and scripts. Solutions can contain multiple programming languages You can incorporate multiple programming languages within one solution and edit all your code within the same IDE. This can aid team development of a system where parts of the solution are written in Visual Basic .NET, and other parts are written in C# or other .NET-compatible languages. The IDE is customizable through My Profile The IDE is fully customizable through the My Profile configuration section on the Visual Studio .NET Start Page. You can select a preexisting profile such as the Visual Basic Developer, or you can modify each section manually. You can specify how you want your IDE screen to look and how the keyboard behaves. This is particularly useful if you are used to Visual Basic version 6.0 keyboard shortcuts for various actions. You can choose to filter help files based on your preferences. The IDE has a built-in Internet browser You can browse the Internet within the IDE, enabling you to look up online resources without moving between multiple application windows. This built-in browser can also display the Visual Studio .NET Help files for easy access to the relevant documentation.
Lead-in
Choosing a Project Template Analyzing Project Structures What Are Assemblies? Setting Project References What Are Namespaces? Creating Namespaces Importing Namespaces Setting Project Properties
Many concepts in Visual Basic .NET project creation will be familiar to you.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Many aspects of project development in Visual Basic .NET are similar to those in previous versions of Visual Basic. You still have a range of project templates to choose from, you still need to reference other projects and applications, and you still need to set project properties. Visual Basic .NET provides enhancements to these and other aspects of project development. In this lesson, you will become familiar with the project templates provided by Visual Basic .NET. After completing this lesson, you will be able to: Choose the correct template for your project. Explain how various Visual Basic .NET projects are structured. Explain what assemblies are and how to create them. Reference other code from your project. Create and use namespaces in your projects. Use the Imports statement to access objects. Set various project properties that affect how your application behaves.
Windows Application Class Library Windows Control Library ASP .NET Web Application / Service / Control Library Console Application Windows Service Others
Lead-in
As in previous versions of Visual Basic, you can choose from a variety of project templates to assist you in the creation of a new project.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic developers are used to having multiple project templates to choose from when starting a new project. Visual Basic .NET provides many familiar templates along with a range of new ones. Delivery Tip
Template Windows Application Class Library Use this template to create: Standard Windows-based applications. Class libraries that provide similar functionality to Microsoft ActiveX dynamic-link libraries (DLLs) by creating classes accessible to other applications. User-defined Windows control projects, which are similar to ActiveX Control projects in previous versions of Visual Basic. Web applications that will run from an Internet Information Services (IIS) server and can include Web pages and XML Web services. Web applications that provide XML Web Services to client applications. User-defined Web controls that can be reused on Web pages in the same way that Windows controls can be reused in Windows applications. Console applications that will run from a command line. Windows services that will run continuously regardless of whether a user is logged on or not. Previous versions of Visual Basic require you to use third-party products or low-level application programming interface (API) calls to create these types of applications. Other templates exist for creating enterprise applications, deployment projects, and database projects.
Point out that students will use many of these project templates during the remainder of the course.
Other
Lead-in
Solution files (.sln, .suo) Project files (.vbproj) Local project items Classes, forms, modules, etc. (.vb) Web project items XML Web services (.asmx) Web forms (.aspx) Global application classes (.asax)
Visual Basic .NET projects contain various types of files that you use depending on the type of project you are creating.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Each project contains a variety of files unique to the type of project. To simplify management, the project files are usually stored within the same project directory. Solution files (.sln, .suo) The .sln extension is used for solution files that link one or more projects together, and are also used for storing certain global information. These files are similar to Visual Basic groups (.vbg files) in previous versions of Visual Basic. Solution files are automatically created within your Visual Basic .NET projects, even if you are only using one project in the solution. The .suo file extension is used for Solution User Options files that accompany any solution records and any customizations you make to your solution. This file saves your settings, such as breakpoints and task items, so that they are retrieved each time you open the solution. Project files (.vbproj) The project file is an Extensible Markup Language (XML) document that contains references to all project items, such as forms and classes, in addition to project references and compilation options. Visual Basic .NET project files use a .vbproj extension, which allows you to differentiate between files written in other .NET-compatible languages (Microsoft Visual C# uses .csproj). This makes it easy to include multiple projects that are based on different languages within the same solution.
Delivery Tip
Local project items (.vb) Previous versions of Visual Basic use different file extensions to distinguish between classes (.cls), forms (.frm), modules (.bas), and user controls (.ctl). Visual Basic .NET enables you to mix multiple types within a single .vb file. For example, you can create more than one item in the same file. You can have a class and some modules, a form and a class, or multiple classes all within the same file. This allows you to keep any strongly related items together in the same file; for example, the Customer and Address classes. Any files that are not based on a programming language have their own extension; for example, a Crystal Report file (.rpt) or text file (.txt). Web project items (.aspx., .asmx, .asax) Web projects store their items in a Web server virtual directory and in an offline cache. Like local project items, Web project items also use the .vb file extension for classes and modules. However, Web project items include Web-specific files, such as .aspx for Web Forms, .asmx for XML Web Services, and .asax for global application classes. Note For more information about Web projects, see Module 7, Building Web Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Explain that you can store more than one item in the same file, such as two classes in a single .vb file. This allows you to keep related classes together for easy maintenance.
Lead-in
Assemblies are a key concept in the .NET Framework. They are the building block of all .NETcompatible applications.
An assembly is an .exe or .dll file with other supporting files that make up a Visual Studio .NET application The .NET Framework provides predefined assemblies Assemblies are created automatically when you compile source files Click Build on the Build menu Use the command-line command vbc.exe
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip An assembly is one or more files that make up a Visual Studio .NET application. These files include an .exe or .dll, and resource files such as manifest files or graphics files. Assemblies are a key concept in .NET development; they serve as a building block for all .NET applications. The .NET Framework provides many predefined assemblies for you to reference within your projects. These assemblies provide the classes and functionality of the common language runtime that enables your applications to work. Assemblies are created automatically when you compile Visual Studio .NET source files. To create an assembly, compile your application by clicking Build <projectname> on the Build menu. You can also use the command-line command vbc.exe to compile an assembly. Your assembly can then be referenced by other applications, in much the same way that ActiveX components can be referenced in previous versions of Visual Basic. Note For more information about assemblies, see Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Point out that assemblies will be discussed in more detail later in the course but make sure students understand the basic concepts at this stage.
Topic Objective
Lead-in
Most projects reference other applications or code libraries to use the functionality that they provide. Use the Add Reference dialog box to set project references.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can set project references to other applications or code libraries in order to use the functionality these applications provide. You can set project references to other .NET assemblies, existing COM components, or other .NET projects within the same .NET solution. To add a reference 1. Select the current project in Solution Explorer. On the Project menu, click Add Reference. 2. In the Add Reference dialog box, select the appropriate type of reference by clicking the .NET, COM, or Projects tab. Only projects within the same solution are displayed in the Projects tab. 3. Locate the required component in the list, or if item is not displayed in the list use the Browse button to locate the file. Click the item in the list, and then click Select. 4. Repeat step 3 for all the components you require, and then click OK. After you set a reference, you can use it in the same way that you use COM components in previous versions of Visual Basic. You can view information about the reference in the Object Browser and create code that uses the functionality of the reference.
Topic Objective
Namespaces organize objects defined in an assembly Group logically related objects together Namespaces create fully qualified names for objects Prevent ambiguity Prevent naming conflicts in classes
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Namespaces are used in .NET Framework assemblies to organize the objects of an assembly (classes, interfaces, and modules) into a structure that is easy to understand. Namespaces group logically related objects together so that you can easily access them in your Visual Basic .NET code. For example, the SQLClient namespace defined within the System.Data assembly provides the relevant objects required to use a Microsoft SQL Server database. When you prefix an object with the namespace it belongs to, the object is considered to be fully qualified. Using unique, fully qualified names for objects in your code prevents ambiguity. You can declare two classes with the same name in different namespaces without conflict.
10
Creating Namespaces
Topic Objective
To explain how to create namespaces.
Lead-in
Use Namespace End Namespace syntax Use the root namespace defined in Assembly Properties
Namespace Namespace Top Top Public Public Class Class Inside Inside ... ... End End Class Class 'Fully 'Fully qualified qualified as as MyAssembly.Top MyAssembly.Top 'Fully qualified as 'Fully qualified as MyAssembly.Top.Inside MyAssembly.Top.Inside
You can create your own namespaces or use the namespaces that are defined in the assembly properties.
Namespace 'Fully Namespace InsideTop InsideTop 'Fully qualified qualified as as MyAssembly.Top.InsideTop MyAssembly.Top.InsideTop Public Public Class Class Inside Inside 'Fully 'Fully qualified qualified as as MyAssembly.Top.InsideTop.Inside MyAssembly.Top.InsideTop.Inside ... ... End End Class Class End End Namespace Namespace End End Namespace Namespace
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can create your own namespaces in an assembly by creating a block of code that uses the NamespaceEnd Namespace syntax. The following example shows how to create a namespace named Customers:
Namespace Customers 'Create classes, modules, and interfaces 'Related to Customer information End Namespace
This is an animated slide. It begins by showing the bullet points only. Click the slide to reveal the following sections: 1. Top namespace 2. Inside class 3. InsideTop namespace
The assembly usually defines a root namespace for the project that is set in the Project Properties dialog box. You can modify or delete this root namespace if you choose. The following example shows code in an assembly that has a root namespace named MyAssembly:
Namespace Top 'Fully qualified as MyAssembly.Top Public Class Inside 'Fully qualified as MyAssembly.Top.Inside ... End Class Namespace InsideTop 'Fully qualified as MyAssembly.Top.InsideTop Public Class Inside 'Fully qualified as MyAssembly.Top.InsideTop.Inside ... End Class End Namespace End Namespace
11
The following example shows how code from the same assembly, when outside of the Top namespace, calls classes. Notice that the MyAssembly namespace is not required as part of the fully qualified name, because this code also resides in the MyAssembly namespace.
Public Sub Perform( ) Dim x As New Top.Inside( ) Dim y As New Top.InsideTop.Inside( ) ... End Sub
Note You can also create nested namespaces without nesting the definitions, by using the fully qualified name. For example, you can declare the InsideTop namespace anywhere by using the following code:
Namespace MyAssembly.Top.InsideTop
12
Importing Namespaces
Topic Objective
To explain how imports and aliases can simplify code.
Lead-in
Referencing the full namespace makes code difficult to read. You can avoid this by using the Imports statement and aliases.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can access any object in an assembly by using a fully qualified name. The problem with this approach is that it makes your code difficult to read, because variable declarations must include the entire namespace hierarchy for you to access the desired class or interface.
13
Import Aliases
You can use the Imports statement to create import aliases for parts of namespaces. Import aliases provide a convenient way to access items in a namespace. They prevent naming conflicts but still make code easy to write and understand. The following example creates an import alias called IT for the MyAssembly.Top.InsideTop namespace. You can reference any item belonging to the namespace by using the IT import alias.
Imports IT = MyAssembly.Top.InsideTop Module ModMain Sub Perform( ) Dim x As New IT.Inside( ) ... End Sub End Module
'Alias used
14
Common Property Settings Defining assembly name Root namespace Project output type Startup object Importing project-level namespaces Configuration Property Settings Debugging settings Build options
Lead-in
Visual Basic .NET provides many project properties that can affect how your project behaves.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can specify many project properties in the project Property Pages dialog box. These properties affect how the project behaves both in the IDE and after it is compiled. The following screen shot shows the project Property Pages dialog box for an application named SimpleApp:
The project property pages are shown during the next demonstration, Creating a Visual Basic .NET Project.
15
Startup object
Some of the frequently used Configuration Property settings are listed below.
Property Debugging settings Purpose These properties allow you to set debugging options, like for previous versions of Visual Basic. You can choose how your application starts up when debugging by starting the project, starting an external program that calls your code, or displaying a Web page from a URL that calls your code. You can also specify any command-line arguments your application needs for testing purposes. You can specify an output directory for your compiled code (\bin is the default). You can also enable or disable the generation of debugging information contained in the .pdb file.
Build options
16
Topic Objective
Lead-in
This demonstration will show you how to create a Visual Basic .NET project by using the project templates.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a Visual Basic .NET project based on the project templates. You will also learn about the files that comprise the project structure and how to create a reference to another assembly.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
17
Lead-in
Using Solution Explorer Using Server Explorer Using the Object Browser Using the Task List Using Dynamic Help Using XML Features Recording and Using Macros
The development environment contains many enhanced features that make developing Visual Basic .NET projects faster and more efficient.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The Visual Studio .NET IDE contains several features that enable more efficient development of projects. Some of these features are enhancements of existing Visual Basic features. Others are amalgamated from other sources, such as Microsoft Visual InterDev. After completing this lesson, you will be able to: Use IDE tools such as Solution Explorer, Server Explorer, Object Browser, and Task List. Use Dynamic Help while developing your Visual Basic .NET applications. Edit XML documents in the IDE. Record and use macros for repetitive tasks in your projects.
Several of the IDE windows will be familiar to Visual Basic developers, so detailed discussion should not be required.
18
Lead-in
Displays project hierarchy Project references Forms, classes, modules Folders with subitems Show All Files mode Manipulating projects Drag-and-drop editing Context menus
Solution Explorer enhances the Project Explorer found in previous versions of Visual Basic.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Solution Explorer displays your project hierarchy, including all project references; project items such as forms, classes, modules, and so on; and any subfolders that contain project items. If your solution contains more than one project, you will see the same sort of hierarchy used in previous versions of Visual Basic when a project group exists.
Manipulating Projects
The following features allow you to manipulate your projects with Solution Explorer: Drag-and-drop editing You can use drag-and-drop editing to move existing project items between folders. Context menus Most items provide context menus that allow you to perform standard actions, such as adding items to the project, deleting items from the project, and excluding items from the project, which removes the file from the project but does not delete the file. If you use Microsoft Visual SourceSafe, you can add items to Visual SourceSafe from Solution Explorer.
19
Topic Objective
Lead-in
Managing Data Connections Viewing and Managing Servers Using Drag-and-Drop Techniques
Server Explorer allows you to establish data connections similar to the Data View window in Visual Basic 6.0. However, Server Explorer also has the ability to manage and use specific aspects of a server.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In previous versions of Visual Basic, you can manipulate databases by using the Data View window. Server Explorer provides the same functionality and additional functionality for managing and using server components.
20
Message Queues
21
Lead-in
Visual Basic .NET enhances the Object Browser found in previous versions of Visual Basic.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET enhances the Object Browser found in previous versions of Visual Basic. Previous versions of the Object Browser show only a high-level view of objects and their methods. Using the Visual Basic .NET Object Browser, you can: Examine objects and their members within a library, exploring the object hierarchy to find details about a particular method or item. Access lower-level items, such as interfaces and object inheritance details. Examine how the .NET Framework class libraries use inheritance in their object hierarchies.
22
The following screen shot shows the Microsoft Visual Basic .NET Runtime library and its various namespaces. This screen shot highlights the Microsoft.VisualBasic namespace and shows the classes it contains, including the DateAndTime class, which inherits characteristics from the System.Object class.
23
Similar to the Tasks feature in Microsoft Outlook Stored with the solution in the .suo file Adding to the Task List You can add tasks manually by typing in appropriate field Visual Basic .NET adds build errors, upgrade comments, etc.
You can use token strings to add comments in code
Lead-in
The IDE provides a Task List to track tasks that are awaiting completion and that are related to a particular solution.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** If you use Microsoft Outlook, you may be familiar with the Tasks feature. You can use this feature to maintain a list of tasks that you are working on or tracking, and you can clear tasks when you complete them. Visual Studio .NET provides the same functionality through a Task List window, which keeps track of solution-level tasks that you must complete. Tasks are kept in the .suo project file so that you do not lose information when you close your Visual Studio .NET session. Any stored tasks are available to all developers that use the same .suo project files. Tasks can be added to your Task List in three ways: You can manually add tasks to the task list by typing in the top row that is always visible in the Task List window. Visual Studio .NET automatically adds tasks to the list when you attempt to build your application, when you upgrade from a Visual Basic 6.0 project, or at various other stages during the project. This allows you to keep track of what you must do to successfully complete your project. You can add tasks by creating comments in your code that use specific token strings defined in the Options dialog box, which is accessible from the Tools menu. The TODO, HACK, and UNDONE tokens have been created for you, but you can define your own. The following example shows a code section that uses the TODO token and a custom token named FIX_ASAP:
'TODO create icons for form 'FIX_ASAP bug in form code
24
The following screen shot shows how the Task List window displays information based on this example, with three extra items that have been added to the list manually:
You can use the View menu to specify which types of tasks to display in the Task List. The following screen shot shows how to use the Options dialog box to create the FIX_ASAP token. Notice that the token has been created so that the items in the Task List display a High priority icon.
25
Lead-in
The Visual Studio .NET IDE introduces a new form of assistance that displays Help links dynamically, based on your current requirements.
Automatically displays relevant Help topics based on focus and cursor placement Use the Options dialog box to configure the Dynamic Help window
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The Dynamic Help window automatically displays appropriate Help links to the .NET Help files, depending on where the cursor is and what text is highlighted. As you move from one window to another within the IDE, information displayed in the Dynamic Help window changes. If you are typing Visual Basic syntax, you see the appropriate Help topic for the syntax you are typing. For example, the results that the Dynamic Help displays for the following statement vary depending on where the cursor is positioned:
Dim x As Integer
Point out to students that the cursor position is not tracked if the Dynamic Help window is not displayed.
If the cursor is positioned within the Dim keyword, the Dynamic Help window displays links relevant to the Dim keyword at the top of the list. If the cursor is positioned within the Integer keyword, the Dynamic Help window displays links relevant to integer types at the top of the list.
26
You can use the Options dialog box on the Tools menu to configure the items that the Dynamic Help window displays. The following screen shot shows how to use the Options dialog box to configure the Dynamic Help window:
27
HTML and XML Document Outline window AutoComplete Color-coding Data View for manipulating data
Lead-in
Many of your Visual Basic .NET applications will use XML documents to store or retrieve information. The IDE provides several XML features that make it easier for you to use these types of documents.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Enterprise applications often use XML documents to specify information as part of the application architecture. The Visual Studio .NET IDE provides several useful features for creating and editing XML documents, as described in the following table.
XML feature Hypertext Markup Language (HTML) and XML Document Outline window AutoComplete Description Provides a view of the hierarchy of HTML and XML documents within the application. Automatically creates the closing tags when you create either HTML or XML starting tags. This feature can be switched off in the Options dialog box. Color-coding Data View for manipulating data Assists in distinguishing tags from data. Allows you to add items to your XML data hierarchy and edit existing information. Provides hyperlinks for navigation to lower-level items in the XML hierarchy.
There is a Customer.xml file in the DemoCode folder for this module. You can use this file to demonstrate the Document Outline window and color-coding features.
28
Topic Objective
Lead-in
You can use macros for repetitive tasks such as inserting comments Macro Explorer provides macro navigation The IDE provides samples: Toggle line numbering Saving/loading Window Views Debugging macros To record new macros, go to the Tools/Macros menu
You may be familiar with macros in Microsoft Word or Microsoft Excel. Now you can use macros in Visual Studio .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Macros allow users to perform repetitive tasks with the click of a button or menu item. The Visual Studio .NET IDE provides macros, so you can automate tasks that require tedious work, such as inserting standard comments into your code. The Macro Explorer allows you to edit, rename, delete, or run your macros within the IDE. Several sample macros are included in the IDE, including the following: Toggle line numbering macros Saving or loading Window Views macros Debugging macros You can use any of the sample macros in your projects by executing them in the Command window or placing them on menus or toolbars. To record your own macros 1. On the Tools menu, point to Macros, and then click Record TemporaryMacro. 2. Perform the actions that you wish to record, such as inserting comments in the current module. 3. Click Stop Recording on the Recorder toolbar to stop recording your macro. 4. Your macro is saved with a temporary name visible in the Macro Explorer. You can rename the temporary macro to save your macro with an appropriate name. Any macros you create are stored in a subdirectory of the Visual Studio Projects folder in My Documents.
29
Lead-in
This demonstration shows how to use Solution Explorer and Server Explorer, and how to edit an XML document in the Visual Studio .NET IDE.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use several features of the Visual Studio .NET IDE, including Solution Explorer, Server Explorer, and XML editing tools.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
30
Debugging Applications
Topic Objective
To introduce the topics covered in this lesson.
Lead-in
The new IDE provides enhanced debugging features based on those found in previous versions of Visual Basic.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The Visual Studio .NET IDE provides enhanced versions of many of the debugging features found in previous versions of Visual Basic, along with several powerful features found in Visual C++. After completing this lesson, you will be able to: Set breakpoints. Debug code in a Visual Basic .NET project. Use the Command window while designing and debugging applications.
31
Setting Breakpoints
To explain how to set breakpoints.
Topic Objective
Set breakpoints to halt code execution at a specific line Use the Breakpoint Properties dialog box to set conditions
Lead-in
Setting breakpoints in your project allows you to step into your code under a variety of conditions.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Breakpoints halt execution of code at a specific line. You can set breakpoints at design time or during a debugging session. There are several ways you can set a breakpoint: Click the margin to the left of the code window on the line containing the statement where you want the debugger to halt. On the Debug menu, click New Breakpoint, and choose from the various options. Place the cursor on the line where you want the debugger to halt. Press F9 to switch the breakpoint on or off. You can use the Breakpoint Properties dialog box to make a conditional breakpoint. This feature works in a way similar to watch expressions in previous versions of Visual Basic. You set a breakpoint condition that only halts execution when a particular condition is true or when a variable has changed.
32
The following screen shot shows a breakpoint condition that only halts when a variable x has a value of 10.
You may also want to halt execution only when the breakpoint has been reached and the breakpoint condition has been satisfied a specific number of times. This number is called the hit count. To set a breakpoint hit count 1. In the Breakpoint Properties dialog box, click Hit Count. 2. In the Breakpoint Hit Count dialog box, choose the type of hit count test that you want to perform from the drop-down combo box, enter the appropriate hit count value, and then click OK. The following screen shot shows how you specify that you want execution to stop the third time that the breakpoint is reached and the breakpoint condition is satisfied:
33
Debugging Code
Topic Objective
To discuss how to debug code and use the various debugging windows.
Use the Debug menu or toolbar to step through code Use the debugging windows: Locals: to view and modify local variables Output: to view output from the compiler Watch: to view watch expressions Call Stack: to view call history, including parameter information Breakpoints: to view, add, or temporarily disable breakpoints
Lead-in
Several aspects of debugging in Visual Basic .NET will be familiar to Visual Basic developers.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Debugging your code in Visual Basic .NET is similar to debugging code in previous versions of Visual Basic. When code execution stops at the breakpoint, you can step through the code by using the Debug menu or toolbar. All of the debugging windows found in previous versions of Visual Basic are available in Visual Basic .NET, but with some enhancements.
Debug window Locals Use this window to: View and modify variables. This window provides explicit details about objects, such as inheritance information. The tree view of this window is particularly useful for viewing values in an object hierarchy. Output View output information from the compiler, such as the number of compilation errors that occurred and what libraries were loaded. You can use the Debug.Writeline statement to print information to the Output window. This statement replaces the Debug.Print statement in previous versions of Visual Basic. Watch View and manipulate any watch expressions. To add values to the Watch window, type in the Name column of an empty row, or click Quick Watch on the Debug menu. This allows you to quickly add watch expressions during your debugging session. Unlike in previous versions of Visual Basic, you cannot set watch conditions. These have been replaced by breakpoints conditions in Visual Basic .NET.
34
35
Immediate mode Similar to the Immediate window Command mode Use Visual Studio IDE features Switching modes Use >cmd to change to Command mode Use immed to return to Immediate mode
Lead-in
The Command window combines features found in the Immediate window of previous versions of Visual Basic with a command-line utility.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Immediate mode, the Command window in Visual Basic .NET provides functionality similar to that found in the Immediate window in previous versions of Visual Basic. You can query local variables while debugging and change their values under certain conditions. You can also run procedures in your code or other .NET Framework class libraries while you are in Immediate mode. The Command window also has a second purpose. In Command mode, you can use features of the Visual Studio .NET IDE. The features you can use while in Command mode include the following: The Debug.Start command, to start debugging The Help command, to display the Visual Studio .NET documentation The Exit command, to quit the Visual Studio .NET IDE Any macros that you recorded Any macros that the IDE provides as samples To switch between the two modes of the Command window: Use the >cmd command to switch from Immediate mode to Command mode. You can issue single commands in Immediate mode by prefixing your command with the > symbol. Use the immed command to switch from Command mode to Immediate mode.
36
The following example shows various commands in both Immediate and Command mode. The window is initially in Immediate mode during a debugging session.
?newValue 12 newValue=44 ?newValue 44 >Debug.StopDebugging >cmd >help >Debug.Start >immed ?newValue 12
The following steps are executed in this code: 1. The example shows a local variable named newValue with a value of 12. 2. In Immediate mode, this value is changed to 44. 3. The variable is queried again to confirm the change. 4. A single command is issued to stop debugging. 5. The cmd command is used to switch to Command mode. 6. The help command is used to display the Visual Studio .NET documentation. 7. The Debug.Start command is used to start debugging. 8. The immed command is used to switch back to Immediate mode. 9. The newValue variable is tested again.
37
Topic Objective
Lead-in
This demonstration shows how to debug a simple Visual Basic .NET project.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the debugging features of the Visual Studio .NET IDE to debug a simple Visual Basic .NET project.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
38
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After completing this lesson, you will be able to: Locate syntax errors when you attempt to build your application. Select the best compilation option for building your Visual Basic .NET projects.
39
Topic Objective
The Task List displays compilation errors Displays error description, file, and line number Double-click the entry to view the error
Lead-in
You can immediately address syntax errors when you attempt to build your project.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET displays compilation errors as you type each statement in your application code. If you ignore these warnings and attempt to build your application, the Task List is displayed, with all build errors included on the list. Information about the error includes the error description, the file in which the error occurred, and the line number. The error description is the same information that you see if you position the cursor over the highlighted part of your code in the code window. You can edit the errors by double-clicking the appropriate entry in the Task List. This positions the cursor in the correct file and exact line where the error is located, so you can make the required modifications. As soon as you complete your changes and you move off the modified line, the Task List entries are updated.
40
Compilation Options
Topic Objective
To describe the options available when you compile a project.
Build configurations Debug provides debug information Release optimizes code and executable size Build options Build only builds changed projects Rebuild rebuilds project regardless of changes
Lead-in
There are several compilation options available to you when you compile your Visual Basic .NET projects.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The Visual Studio .NET IDE provides several compilation options for building your Visual Basic .NET projects.
Build Configurations
There are two types of build configurations for Visual Basic .NET projects: Debug During the development phase, you may want to build and test your applications by using compiled assemblies. The Debug configuration produces a .pdb file that contains debugging information. Other applications can use this file to debug your code. To assist these other applications, no optimizations are made to your code. Other applications have access to your complete and original code. Release After testing is completed, you will want to deploy your application to client computers. The Release configuration performs various code optimizations and attempts to minimize the size of the executable file. No debugging information is generated for a Release configuration build.
Build Options
You can choose what to build by selecting the appropriate Build menu options. Build The Build option only builds project items whose code has changed since they were last compiled. Rebuild The Rebuild option compiles all project items even if they have not been modified since they were last compiled. Use this option when you want to be sure your application contains the latest code and resources.
41
Objectives
After completing this lab, you will be able to: Use the Visual Studio .NET IDE. Create a simple Visual Basic .NET project. Set conditional breakpoints. Debug an application. Use the Task List and Command windows.
Prerequisites
Before working on this lab, you must have experience with developing applications in an earlier version of Visual Basic.
Scenario
In this lab, you will explore the Visual Studio .NET IDE and use its features to create a data connection and view event log information. You will create a simple Windows-based application and add a prewritten form to the project. Finally, you will debug the application by using the various debugging features of the IDE.
42
4. Click Test Connection to verify that you have successfully made the connection, and then click OK. 5. Click OK on the Data Link Properties dialog box. 6. If you are not familiar with the Data View window from previous versions of Visual Basic or Microsoft Visual InterDev, explore the list of tables, views, and stored procedures by expanding the newly created servername.Northwind.dbo data connection. To explore the Application event log 1. Under the Servers node of Server Explorer, expand the name of your computer. 2. Expand the Event Logs node, expand the Application node, and then expand the MSSQLSERVER node. 3. Select an EventLogEntry node and view the application entry information in the Properties window. If the Properties window is not visible, click Properties Window on the View menu. To explore the default IDE configuration options 1. On the Tools menu, click Options. 2. Spend several minutes becoming familiar with the default Environment settings. 3. When you are finished exploring, click Cancel.
43
44
45
To modify the breakpoint 1. While the form is displayed, move to the Breakpoints window in the IDE. 2. Right-click the breakpoint, and then click Properties. 3. Click Condition, and then set the following condition value:
Condition txtValue.Text Break When has changed
4. Click OK in the Breakpoint Condition dialog box, and then click OK in the Breakpoint Properties dialog box. 5. On the form, click Debug. This time your code should execute without debugging. 6. Change the value in the text box and click Debug. This will cause execution to halt because you have met the condition of the breakpoint. 7. On the Debug menu, click Continue to allow the execution to complete. 8. In the Breakpoints window, clear the breakpoint check box to disable the breakpoint. Verify that execution no longer halts, even if you change the value in the text box. To use the Command Window 1. Display the Command Window and enter the following command: >Debug.StopDebugging. The debugging session will end and the IDE will return to the design state. 2. If the Command Window is no longer displayed, on the View menu, point to Other Windows, and then click Command Window. 3. In the Command Window, enter the Exit command to quit Visual Studio .NET.
46
Review
To reinforce module objectives by reviewing key points.
Topic Objective
Describing the Integrated Development Environment Creating Visual Basic .NET Projects Using Development Environment Features Debugging Applications Compiling in Visual Basic .NET
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. List the file extensions for the following Visual Basic .NET files: Visual Basic .NET project files, classes, and modules. .vbproj, .vb, and .vb
2. Describe the purpose of namespaces and the Imports keyword. Namespaces organize the objects and items found in an assembly and prevent ambiguity when calling an object. The Imports keyword allows you to access an object from within a namespace without using the objects fully qualified name.
3. Describe the purpose of Server Explorer. Server Explorer allows you to view and manipulate databases and various server items, such as message queues, event logs, Windows services, and XML Web Services. You can also use Server Explorer to access these items from within your code.
47
4. The Object Browser is exactly the same as in previous versions of Visual Basic. True or false? If false, explain why. False. The Object Browser has been enhanced to include inheritance and interfaces in the object hierarchy.
5. Describe the purpose of a conditional breakpoint and how to create one. Conditional breakpoints halt execution when a particular condition is met, such as when a variable equals a certain value. To set a conditional breakpoint, you add a standard breakpoint, and then use the Breakpoint Properties dialog box to modify the conditions.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 90 Minutes Labs: 75 Minutes This module provides students with the knowledge needed to use many of the new language and syntax enhancements to the Microsoft Visual Basic language, including variable declaration and initialization, procedure syntax, structured exception handling, and assignment operator changes. In the labs, students will create a simple application that uses variables and procedures to add customers to a customer array. The students will then add structured exception handling to the application. After completing this module, students will be able to: Describe the changes to data types in Visual Basic .NET. Declare and initialize variables and arrays. Use shorthand syntax to assign values to variables. Implement functions and subroutines. Call the default properties of an object. Use the new TryCatchFinally statement to implement structured exception handling.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_03.ppt Module 3, Language and Syntax Enhancements Lab 3.1, Working with Variables and Procedures Lab 3.2, Implementing Structured Exception Handling
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the labs.
iv
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
vi
Module Strategy
Use the following strategy to present this module: Data Types This lesson shows some of the new data types and the changes to existing data types. This lesson also introduces the common type system, the differences between value and reference types, and the CType keyword that is essential for converting variables of one data type to another. Creating objects is not covered in this module, but it may be necessary to point out some simple syntax in the examples in which the New keyword is used. This topic will be covered in Module 4, Object-Oriented Design for Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. It may be worth pointing out that the new Microsoft .NET Framework classes provide alternative ways to perform many similar tasks that can be performed in the Visual Basic language. The System.Collections namespace contains several good examples of these classes. Using Variables This lesson shows how to declare and initialize variables in Visual Basic .NET and introduces changes to variable scope. The topic of data structures is introduced. This topic will be covered further in Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. Point out that Option Explicit is the default compiler option in Visual Basic .NET. Finally, introduce students to the new shorthand syntax for assignment operators. Functions, Subroutines, and Properties This lesson shows the changes to functions and subroutines, in addition to the changes to the calling syntax for object properties. Remind students that object property creation will be covered in Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. In the default property examples that use ADO Recordset objects, focus the discussion on the errors generated by incorrect use of default properties. Other errors may also be generated by assigning incorrect data types to other variables, but these errors should be ignored. Exception Handling This lesson shows the new structured exception handling syntax and explains why it is preferable to unstructured exception handling. To create exceptions by using the Throw statement, as used in the notes and labs, requires a basic understanding of object constructors that is not covered until Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. Point this out to students and provide a short explanation of this statement.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Data Types Using Variables Functions, Subroutines, and Properties Exception Handling
Lead-in
In this module, you will learn about the enhancements to the Visual Basic language and syntax in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Microsoft Visual Basic .NET version 7.0 introduces many language and syntax enhancements that help make it an excellent development tool for the Microsoft .NET platform. Some of these enhancements include: Incorporation of the .NET Framework type system, making Visual Basic .NET compatible with other languages in the .NET Framework. Enhancements to syntax for working with variables, thereby increasing the clarity and performance of code. Changes to functions, subroutines, and properties, making code easier to read and maintain. Structured exception handling, making Visual Basic .NET a more robust development language. After completing this module, you will be able to: Describe the changes to data types in Visual Basic .NET. Declare and initialize variables and arrays. Use shorthand syntax to assign values to variables. Implement functions and subroutines. Call the default properties of an object. Use the new TryCatchFinally statement to implement structured exception handling.
Data Types
Topic Objective
To explain the changes to data types in Visual Basic .NET.
Common Type System Comparing Value-Type and Reference-Type Variables New Data Types Changes to Existing Data Types Using CType to Convert Data Types
Lead-in
This lesson discusses changes to data types and how they are used in Visual Basic .NET code.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn about the data types available in Visual Basic .NET. After you complete this lesson, you will be able to: Explain the .NET Framework common type system and how it affects Visual Basic .NET development. Explain the difference between value-type variables and reference-type variables. Describe and use the data types available in Visual Basic .NET. Use the CType function to convert values from one data type to another.
Lead-in
Integrated in the common language runtime Shared by the runtime, compilers, and tools Controls how the runtime declares, uses, and manages types Includes a set of predefined data types Common type system objects are based on the System.Object class
The common type system provides predefined data types for the .NET Framework.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The .NET Framework is based on a new common language runtime. The runtime provides a common set of services for projects built in Microsoft Visual Studio .NET, regardless of the language. The common type system is an integral part of the runtime. The compilers, tools, and the runtime itself share the common type system. It is the model that defines the rules that the runtime follows when declaring, using, and managing types. The common type system establishes a framework that enables cross-language integration, type safety, and high-performance code execution. All objects in the common type system are based on the System.Object class, and all data types declared in Visual Basic .NET code correspond directly to a common type system data-type. For example, when you declare a variable of type Integer in Visual Basic .NET, it is the same as declaring a System.Int32 common type system data type. The keyword Integer is an alias for the Int32 data type, and it provides familiar syntax to Visual Basic developers.
Topic Objective
Value-Type Variables Directly contain their data Each has its own copy of data Operations on one cannot affect another Assignment creates a copy of the data Reference-Type Variables Store references to their data (known as objects) Two reference variables can reference the same object Operations on one can affect another
Lead-in
Value-type and referencetype variables have significant differences that developers need to understand.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** When you define a variable, you need to choose the right data type for your variable. The data type determines the allowable values for that variable, which, in turn, determine the operations that can be performed on that variable. The common type system supports both value-type and reference-type variables.
Value-Type Variables
Value-type variables directly contain their data. Each value-type variable has its own copy of data, so operations on one value-type variable cannot affect another variable. Examples of value-type variables include integers, doubles, floats, and structures.
Reference-Type Variables
Reference-type variables contain references to their data. The data is stored in an instance. Two reference-type variables can reference the same object, so operations on one reference-type variable can affect the object referenced by another reference-type variable. Examples of reference-type variables include strings, arrays, and classes.
Topic Objective
Visual Basic .NET Storage size data type Char Short Decimal 2 bytes 2 bytes 12 bytes
Value range 0 to 65535 (unsigned) -32,768 to 32,767 Up to 28 digits on either side of decimal (signed)
Lead-in
Three new data types are available in Visual Basic .NET: Char, Short, and Decimal.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip There are three new data types available in Visual Basic .NET: Char, Short, and Decimal.
The changes to Short and the other Integer data types are covered in more detail on the next slide. Point out that Decimal is a fixed-point type integer as opposed to Double and Single, which are floating point. Therefore, Decimal is more accurate for precise calculations.
Char
This data type stores a single Unicode character in a two-byte variable.
Short
In Visual Basic 6.0, a 16-bit integer is an Integer data type. In Visual Basic .NET, a 16-bit integer is designated as a Short.
Decimal
A Decimal data type is stored as a 96-bit (12-byte) fixed-point signed integer, scaled by a variable power of 10. The power of 10 specifies the precision of the digits to the right of the decimal point, and ranges from 0 to 28. This data type should be used when calculations are required that cannot tolerate rounding errors; for example, in financial applications. If no decimal places are required, the Decimal data type can store up to positive or negative 79,228,162,514,264,337,593,543,950,335. Using the full 28 places for precision, the largest value that can be stored is 7.9228162514264337593543950335 and the smallest non-zero value is positive or negative 0.0000000000000000000000000001.
Topic Objective
Visual Basic 6.0 Integer Long (32 bits, signed) (none) Variant Currency Date String (fixed length)
Visual Basic .NET Short Integer Long (64 bits, signed) Not supported: use Object Not supported: use Decimal No longer stored as a Double Not supported
Lead-in
Several data types from Visual Basic 6.0 have changed or are no longer supported.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Several data types from Visual Basic 6.0 have changed or are no longer supported in Visual Basic .NET. These changes make data types in Visual Basic .NET more consistent with data types used by other programming languages in the .NET Framework and in the runtime.
Integer
The Integer and Long data types in Visual Basic 6.0 have a different meaning in Visual Basic .NET, as described in the following table.
Integer size 16 bits, signed 32 bits, signed 64 bits, signed Visual Basic 6.0 data type Integer Long (None) Visual Basic .NET data type Short Integer Long .NET Framework and runtime type System.Int16 System.Int32 System.Int64
Variant
Visual Basic .NET updates the universal data type to Object for compatibility with the common language runtime.
Currency
The Currency data type is not supported in Visual Basic .NET. You can use the Decimal data type as a replacement. The Decimal data type uses 12 bytes of memory, and allows more digits on both sides of the decimal point.
Date
The Date data type is available in Visual Basic .NET but is not stored in the same format as it was in Visual Basic 6.0.
String
Fixed-length strings are no longer supported, but you can simulate this behavior by padding a string to the desired length with spaces, as shown in the following example:
'Create a string containing spaces Dim s As String = Space(10)
The type name String is an alias for the System.String class. Therefore, String and System.String can be used interchangeably. The String class represents a string of characters that cannot be modified after the text has been created. Methods that appear to modify a string value actually return a new instance of the string containing the modification. This can impact performance in applications performing a large number of repeated modifications to a string, so the System.Text.StringBuilder object is provided. This object allows you to modify a string without creating a new object, and is therefore a better choice if you are performing a large number of string manipulations. The following example shows how to create a StringBuilder variable and how to append values to it: Delivery Tip
Dim s As New System.Text.StringBuilder() s.Append("This") s.Append(" is") s.Append(" my") s.Append(" text!") MsgBox(s.ToString) 'generates "This is my text!"
Point out the StringBuilder class and the example shown in the notes.
Visual Basic 6.0 provides many string manipulation methods that are still available in Visual Basic .NET. The System.String class also has many predefined properties and methods that simulate this behavior by using an object-oriented approach. These properties and methods include Insert, Length, Copy, Concat, Replace, Trim, ToLower, and ToUpper. For more information, search for string methods in the Visual Studio .NET documentation.
Lead-in:
In Visual Basic .NET, you can convert any data type to any other data type by using the CType function.
Use CType to convert values from one data type to another data type Similar to CStr and CInt in Visual Basic 6.0 Syntax: CType (expression, typename)
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the CType function to convert any value from one data type to another data type. If the value is outside the range allowed by the type, an error will occur. The CType function is similar to the CStr and CInt conversion functions in Visual Basic 6.0, but it can be used for composite data type conversion in addition to elementary types.
Syntax
Use the following syntax to convert data types:
CType(expression, typename)
expression The expression argument can be any valid expression, such as a variable, a result of a function, or a constant value. typename The typename argument can be any expression that is valid within an As clause in a Dim statement, such as the name of any data type, object, structure, class, or interface.
Example
The following examples show how to convert a String value to an Integer, and how to convert to a data structure type:
Dim x As String, y As Integer x = "34" y = CType(x, Integer) Dim custNew as Customer 'Predefined structure type custNew = CType(data, Customer)
Using Variables
Topic Objective
To explain how to declare, initialize, and use variables and arrays in Visual Basic .NET.
Declaring and Initializing Variables and Arrays Declaring Multiple Variables Variable Scope Creating Data Structures Compiler Options Assignment Operators
Lead-in
This lesson explains the differences between declaring, initializing, and using variables in Visual Basic 6.0 and Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you complete this lesson, you will be able to: Declare and initialize variables. Explain changes to variable scope in Visual Basic .NET. Create data structures. Use compiler options effectively. Use a new shorthand syntax for assignment operators.
10
You can initialize variables when you declare them You can initialize arrays with a size, but they are no longer fixed You can dimension arrays before using ReDim
Dim Dim i i As As Integer Integer = = 21 21 Dim Dim dToday dToday As As Date Date = = Today( Today( ) ) 'Array 'Array declarations declarations Dim Dim Month(12) Month(12) As As Integer Integer 'Creates 'Creates array array with with 13 13 elements elements 'Initialize 'Initialize the the array array with with 12 12 elements elements Dim Dim aMonth( aMonth( ) ) As As Integer Integer = = {1,2,3,4,5,6,7,8,9,10,11,12} {1,2,3,4,5,6,7,8,9,10,11,12}
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you can use a different process to declare some types of variables, including arrays and strings. For example, you can declare and initialize variables in a single statement. For Your Information
Object declaration and initialization are covered in Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Most of this syntax is familiar to Visual Basic developers. However, there is a new optional initexpr argument that allows you to assign an initial value to a variable as long as the argument is not used in conjunction with the New keyword.
Examples
The following code shows how to declare and initialize variables in a single statement:
Dim Dim Dim Dim Dim i As Integer = 21 dToday As Date = Today( ) dblFloat As Double = 1232.23312 dBirthday As Date = #1/1/1995# iCalculate As Integer = i * 5
Delivery Tip
11
Redimensioning Arrays
In Visual Basic 6.0, you can only redimension an array if it is not dimensioned when it is declared. In Visual Basic .NET, you can redimension an array if it is dimensioned when it is declared.
'Error in Visual Basic 6.0 because you 'cannot redim a dimensioned array
Using the Preserve keyword will copy the original array into a new array, which can result in inefficient code. If you need to do this often, consider using the ArrayList class for a more efficient approach.
12
Topic Objective
Lead-in
When you declare multiple variables in one line of code, Visual Basic .NET interprets the code differently than previous versions of Visual Basic.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic 6.0, you can use a single line of code to declare multiple variables, but you may get unexpected results. Consider the following example:
Dim I, J, X As Integer
13
Variable Scope
Topic Objective
To explain the concept of block scope and how it is implemented in Visual Basic .NET.
Procedure scope Variables accessible to entire procedure Block scope Variables only accessible within that block Lifetime of block variable is entire procedure
Dim Dim iLooper iLooper As As Integer Integer 'Procedure 'Procedure level level variable variable
Lead-in
Visual Basic .NET introduces a new level of variable scope into the Visual Basic language: block scope.
For For iLooper iLooper = =1 1 to to 10 10 Dim iMax As Integer Dim iMax As Integer 'Block 'Block level level variable variable iMax iMax = = iLooper iLooper Next Next MsgBox 'This MsgBox (iMax) (iMax) 'This line line generates generates a a compiler compiler error error
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic 6.0, if you declare variables inside a block of code, they are accessible to the entire procedure that contains the block. This level of accessibility is referred to as procedure scope. In Visual Basic .NET, variables inside a block of code are only accessible to that block of code. This level of accessibility is referred to as block scope.
Example
Consider an example in which you need procedure scope for your variables.
Delivery Tip
Explain how the sample code would work in Visual Basic 6.0, and then explain how it would work in Visual Basic .NET.
14
To avoid unexpected results, it is recommended that you initialize the variable within the block. In the following example, True is displayed both times, as y is initialized within the block.
Dim iCounter As Integer For iCounter = 1 To 2 Dim y As Boolean = False y = Not y MsgBox(y) Next
15
Structures replace user-defined types Structures support many features of classes Use StructureEnd Structure to declare structures Declare structure members with an access modifier
Structure Structure Customer Customer Public Public CustID CustID As As Integer Integer Dim CustDayPhone Dim CustDayPhone As As String String Private Private CustNightPhone CustNightPhone As As String String End Structure End Structure
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic 6.0, you create user-defined types (UDTs) by using Type End Type syntax. In Visual Basic .NET, you create your own data types by creating data structures. To create a data structure, you use the Structure End Structure syntax. Delivery Tip The members of UDTs can only contain Public data types. Internal members of a data structure can contain Public, Friend, or Private data types. Therefore, you must declare internal members of a structure with one of these access modifiers, as shown in the following code:
Structure Customer Public CustID As Integer Dim CustDayPhone As String Private CustNightPhone As String End Structure
Point out that structures and access modifiers will be covered in more detail in Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
The syntax for using structures and classes in Visual Basic .NET is very similar. In fact, structures support most features of classes, including methods. Note For more information about data structures and access modifiers, see Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
16
Compiler Options
To explain how setting compiler options affects data types.
Topic Objective
Option Explicit Default option Option Strict Enforces strict type semantics and restricts implicit type conversion Late binding by means of the Object data type is not allowed Option Base 1 Not Supported Arrays must start at zero
Lead-in
Setting various compiler options can alter the way your data types behave.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The compiler options that you select affect many parts of your application. Two options directly influence how your data types will behave and how you should use them: Option Explicit and Option Strict. You set these options as On or Off at the beginning of a module by using the following code:
Option Explicit On Option Strict Off
Delivery Tip
Point out that if Option Explicit is left off in previous versions of Visual Basic, spelling mistakes can create variant variables instead of causing a compiler error.
Option Explicit
This option is on by default in Visual Basic .NET. When Option Explicit is enabled, you must explicitly declare all variables before using them. Undeclared variables generate a compiler error. Without this option, you may accidentally create unwanted variables as a result of spelling mistakes or other errors.
Option Strict
Option Strict is a new compiler option in Visual Basic .NET that controls whether variable type conversions are implicit or explicit. This option prevents the data inaccuracies that may result from implicit narrowing conversions. If you select this option, implicit widening type conversion, such as converting an Integer to a Long, is allowed. However, implicit narrowing type conversions, such as converting a numeric String to an Integer, or a Long to an Integer, cause a compiler error.
17
The following example shows that assigning a Double value to an Integer variable causes a compiler error with Option Strict enabled, because of implicit narrowing. However, assigning an Integer value to a Long variable will not cause an error because this is implicit widening.
Dim i As Integer, i1 As Double, lng As Long i1 = 12.3122 i = i1 'Causes a compiler error i = 256 lng = i 'No error because widening is acceptable
The following example shows a subroutine that takes an Integer argument but is passed a String value, resulting in a compiler error:
Sub TestLong(ByRef lng As Long) ... End Sub TestLong("1234") 'Causes a compiler error because narrowing is unacceptable
Late binding is not allowed under Option Strict. This means that any variable declared As Object can only use the methods provided by the Object class. Any attempt to use methods or properties belonging to the data type stored in the variable will result in a compiler error. The following example shows what will happen if you use late binding when Option Strict is enabled. A String value in an Object variable is allowed, but calling a method from the String class is not allowed.
Dim x As Object x = "MyStringData" 'Attempt to retrieve a character fails MsgBox(x.Chars(4))
Option Base 1
In Visual Basic .NET, all arrays must start with a lower bound of 0. Therefore, Option Base 0|1 is not a compiler option in Visual Basic .NET. This is consistent with all programming languages using the .NET Framework.
18
Assignment Operators
Topic Objective
To explain the new assignment operators.
Lead-in
Example: iResult += 25 iResult equals the existing value for iResult, plus 25
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET provides a shorthand syntax that you can use to assign values to variables. The standard assignment operators are still valid; the new syntax is optional.
Syntax
The original syntax and the shorthand version are shown below: Original: {variable} = {variable} {operator} {expression} Shorthand: {variable} {operator} = {expression} For example: Original: iResult = iResult + 25 Shorthand: iResult += 25
19
Shorthand Operators
The following table shows how the compiler will interpret the new shorthand operators.
Assignment operator *= /= += -= &= ^= \= Purpose Multiplies the value of a variable by the value of an expression and assigns the result to the variable. Divides the value of a variable by the value of an expression and assigns the result to the variable. Adds the value of a variable to the value of an expression and assigns the result to the variable. Can also be used for string concatenation. Subtracts the value of a variable from the value of an expression and assigns the result to the variable. Concatenates a string variable with the value of an expression and assigns the result to the variable. Raises the value of a variable to the power of an exponent and assigns the result to the variable. Divides the value of a variable by the value of an expression and assigns the integer result to the variable.
Example
The following example shows how to use the new assignment operators to concatenate character strings and provides the resulting string:
Dim myString As String = "First part of string; " myString &= "Second part of string" MsgBox (myString) 'Displays "First part of string; Second part of string"
20
Topic Objective
Lead-in
In this demonstration, you will learn how to declare and initialize variables, including basic data types, arrays, and data structures.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to declare and initialize different data types, including some basic data types, arrays, and data structures. You will also learn how to use block-scoped variables.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
21
Topic Objective
Calling Functions and Subroutines Passing Arguments ByRef and ByVal Optional Arguments Static Function and Static Sub Returning Values from Functions Using Default Properties
Lead-in
The way you create and use functions and subroutines and the way you use default object properties have changed in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip After you complete this lesson, you will be able to work with functions, subroutines, and default properties in Visual Basic .NET.
This lesson covers creating and using procedures, but it only covers using default object properties. For more information about creating properties, see Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
22
Visual Basic 6.0 You must follow complex rules regarding use of parentheses You must use parentheses when using a return value from a function Visual Basic .NET You must use parentheses to enclose the parameters of any function or subroutine You must include empty parentheses for procedures without parameters
Lead-in
In Visual Basic .NET, the rules for when to use parentheses when calling functions and subroutines are much simpler than in previous versions of Visual Basic.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In Visual Basic .NET, the syntax that you use to call a procedure is different from the syntax used in Visual Basic 6.0.
Point out that the inconsistent requirements for parentheses in previous versions of Visual Basic are often difficult for inexperienced developers.
23
Visual Basic 6.0 ByRef is the default passing mechanism Visual Basic .NET ByVal is the default passing mechanism
Lead-in
There are some important differences between the Visual Basic 6.0 and Visual Basic .NET mechanisms for passing parameters.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip When you define a procedure, you can choose to pass arguments to it either by reference (ByRef) or by value (ByVal). If you choose ByRef, Visual Basic passes the variables address in memory to the procedure, and the procedure can modify the variable directly. When execution returns to the calling procedure, the variable contains the modified value. If you choose ByVal, Visual Basic passes a copy of the variable to the procedure. If the procedure modifies the copy, the original value of the variable remains intact. When execution returns to the calling procedure, the variable contains the same value that it had before it was passed. There are some important differences between the Visual Basic 6.0 and Visual Basic .NET mechanisms for passing parameters.
Check whether the students understand the difference between ByRef and ByVal. If necessary, explain the differences on a whiteboard or flip chart.
24
Optional Arguments
Topic Objective
To explain changes in how you use optional arguments.
Lead-in
Visual Basic 6.0 You do not need to specify default values for optional parameters You can use the IsMissing function Visual Basic .NET You must include default values for optional parameters The IsMissing function is not supported
Function Function Add(Value1 Add(Value1 As As Integer, Integer, Value2 Value2 As As Integer, Integer, Optional Optional Value3 Value3 As As Integer Integer = = 0) 0) As As Integer Integer
There are some changes to how you use optional arguments in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Optional arguments allow you to choose whether or not to pass all parameters to a function or subroutine. There are some changes to how you use optional arguments in Visual Basic .NET.
Note You can use overloaded functions to provide the same functionality as optional arguments. For more information about overloading, see Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
25
Visual Basic 6.0 You can place Static in front of any Function or Sub procedure heading Local variables in a static function or static subroutine retain their values between multiple calls Visual Basic .NET Static functions and static subroutines are not supported You must explicitly declare all static variables
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Static variables are declared differently in Visual Basic .NET.
Check whether students understand static variables, and provide an example of a static counter variable if required.
26
Visual Basic 6.0 Use the function name to return the value Visual Basic .NET You can use the function name You can also use the Return statement
Lead-in
Visual Basic .NET provides flexibility in how you can return values from functions.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET provides flexibility in how you can return values from functions.
You can also use the Return statement to return the value. This avoids linking the return of the function to the function name, allowing for easier renaming of functions. The following example shows how to use the Return statement to return the value:
Function GetData( ) As String ... Return "My data" End Function
Note The Return statement exits the function immediately and returns the value to the calling procedure.
27
Visual Basic 6.0 Supports default properties on most objects Use Set to determine whether assignment is referring to the object or the default property Visual Basic .NET Supports default properties only for parameterized properties Do not need to differentiate between object and default property assignments Default properties are commonly used to index into collections
Lead-in
The syntax for calling the default properties of an object has been updated in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Visual Basic .NET updates default property support for simplification and improved readability.
The syntax for calling properties other than the default property has not changed. It is only the default properties that have been altered. Explain that Set is provided in Visual Basic 6.0 to determine whether code is referring to the object or the default property; therefore, it has been removed in Visual Basic .NET. Also note that property creation is covered in Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
28
Lead-in
You can call default properties only if the property takes parameters
Dim Dim rs rs As As ADODB.Recordset, ADODB.Recordset, Lab1 Lab1 As As Label Label 'initialization 'initialization rs.Fields.Item(1).Value rs.Fields.Item(1).Value = = Lab1.Text Lab1.Text rs.Fields(1).Value rs.Fields(1).Value = = Lab1.Text Lab1.Text rs.Fields(1) rs.Fields(1) = = Lab1.Text Lab1.Text Lab1 Lab1 = = "Data "Data Saved" Saved" 'Valid 'Valid 'Valid 'Valid 'Not 'Not valid valid 'Not 'Not valid valid
Here are some examples showing correct and incorrect syntax for using default properties.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The following examples show valid and invalid syntax for using default properties: Delivery Tip
Dim rs As ADODB.Recordset, Lab1 As Label 'initialization rs.Fields.Item(1).Value = Lab1.Text 'Valid because no defaults used rs.Fields(1).Value = Lab1.Text 'Valid because Item is parameterized rs.Fields(1) = Lab1.Text 'Not valid because Value is not parameterized Lab1 = "Data Saved" 'Not valid because Text is not parameterized
Explain every step of the example and ask why each line is valid or invalid.
29
Objectives
After completing this lab, you will be able to: Declare and initialize variables. Create and call functions and subroutines.
Prerequisites
Before working on this lab, you must be familiar with using variables, arrays, and procedures.
Scenario
In this lab, you will create a simple Microsoft Windows Forms application in which you can enter customer information into an array and then retrieve it. The application will consist of a single form that you use to input this information.
Solution Files
There are solution files associated with this lab. The solution files are in the install folder\Labs\Lab031\Solution folder.
30
31
32
3. Declare a private array called aCustomers to hold Customer elements with an initial size of one. To add a customer 1. Create the btnAddCustomer_Click event handler. 2. In the btnAddCustomer_Click event handler, create a local variable named cCustomer based on the information in the following table.
Variable name cCustomer Data type Customer
3. Assign the upper bound limit of the aCustomers array to the Id member of the cCustomer object. 4. Assign the Text properties of the text boxes to the corresponding members of the cCustomer variable as defined in the following table. Use the CDate function to convert the text property of txtDOB to the Date data type for use by the cCustomer.DateOfBirth member.
cCustomer member FirstName LastName DateOfBirth Text box txtFirstName txtLastName txtDOB
5. Using the UBound function for the array index, add the cCustomer variable to the aCustomers array.
33
6. Use the ReDim Preserve syntax and the UBound function to increase the size of the aCustomers array by one. This creates one more array element than is required. However, this is acceptable for this exercise. Important When you use the UBound function to increase the size of the array, you must add the integer value of 1 to the result of the UBound function. 7. Use the MsgBox function to display a message box that confirms that the customer has been added. 8. Clear the txtFirstName, txtLastName, and txtDOB text boxes. 9. Save the project. To test your application 1. On the first line of the btnAddCustomer_Click event handler, set a breakpoint. 2. On the Debug menu, click Start. 3. Enter customer details into the text boxes, and then click Add Customer. 4. When the code enters break mode, click Step Into on the Debug menu. 5. On the Debug menu, point to Windows, and then click Locals. In the Locals window, expand cCustomer and view the values of the variables as you step through the code. 6. Close the Customer application.
34
2. Return the Customer object stored in the iIndex position of the aCustomers array as the result of the function. To call the RetrieveCustomer function 1. In the btnRetrieve_Click event handler, declare three local variables as defined in the following table.
Variable name aCustomer sInput sMessage Data type Customer String String
2. Use the InputBox function to ask the user to enter a customer identification number, and then store the response in the sInput variable. 3. Use an If statement and the IsNumeric function to test whether the entered data is numeric. 4. If the data is numeric, call the RetrieveCustomer function, and then pass it the value of the sInput variable converted to an integer. 5. Store the return value of the RetrieveCustomer function in the aCustomer variable. 6. To create a message to be displayed to the user, concatenate the values of each of the aCustomer elements into the sMessage variable, and then display the string in a message box. 7. Save the project.
35
To test your application 1. On the Debug menu, click Clear All Breakpoints. 2. On the first line of the btnRetrieve_Click event handler, set a breakpoint. 3. Start the application, and then add three customers of your choice. 4. Click Retrieve. 5. On the Debug menu, click Step Into to step through the code until the InputBox displays. 6. In the InputBox, type 1 and click OK. Step through the code and confirm that the correct customer information is displayed. You should see details for the second customer that you entered. 7. Quit the application. 8. On the Debug menu, click Clear All Breakpoints, and then save your project. 9. Quit Visual Studio .NET.
36
Exception Handling
Topic Objective
To explain the extensions to exception handling in Visual Basic. NET.
Structured Exception Handling TryCatchFinally Using TryCatchFinally The System.Exception Class Filtering Exceptions Throwing Exceptions
Lead-in
Exception handling is an important topic in any application. Visual Basic .NET introduces a powerful new form of handling: structured exception handling.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn about the extensions to error handling (or exception handling) in Visual Basic .NET. After completing this lesson, you will be able to: Explain the advantages of the new exception handling system by comparing unstructured handling to structured handling. Use the TryCatchFinally statement in conjunction with the System.Exception class to implement structured exception handling. Create your own exceptions by using the Throw statement.
37
Disadvantages of unstructured error handling Code is difficult to read, debug, and maintain Easy to overlook errors Advantages of structured exception handling Supported by multiple languages Allows you to create protected blocks of code Allows filtering of exceptions similar to Select Case statement Allows nested handling Code is easier to read, debug, and maintain
Lead-in
Structured exception handling is new to Visual Basic .NET and offers many advantages over unstructured exception handling.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic developers are familiar with unstructured exception handling in the form of the On Error statement. With On Error, developers can check for and handle exceptions in several different ways by using exception labels, GoTo statements, and Resume statements.
Unstructured exception handling can make your code difficult to read, maintain, and debug, and may lead you to unintentionally ignore an error. For example, when you use the On Error Resume Next statement, you must remember to check the Err object after each action that can cause an error. If you do not check the value after each action, you may miss an initial error when a subsequent action also fails. This means you may handle an error incorrectly or unintentionally ignore an error. The Visual Basic language has been criticized because it lacks structured exception handling. Visual Basic .NET addresses this criticism by supporting structured exception handling, using the syntax TryCatchFinally.
38
You will look at the TryCatchFinally syntax in detail on the following slides. Provide an example of when you may want to nest an exception handler within the Catch block of another handler. This might happen when an exception has occurred and you need to test some code that may create another exception.
39
TryCatchFinally
Topic Objective
To explain the basics of the TryCatchFinally syntax.
... ... Try Try ' ' Include Include code code to to be be tried tried here here ' ' Can Can use use Exit Exit Try Try to to exit exit block block and and resume resume after after End End Try Try Catch Catch ' ' Define Define exception exception type type and and action action to to be be taken taken ' ' Can Can use use series series of of statements statements (multiple (multiple error error handling) handling) Finally Finally ' ' Optional Optional block block ' Define ' Define actions actions that that need need to to take take place place End End Try Try ... ...
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can implement structured exception handling in Visual Basic .NET by using the TryCatchFinally statement.
At this stage students might not know anything about class inheritance, so do not attempt to explain too much about how exceptions can inherit from the System.Exception class. Simply point out that there are multiple exception classes that are based on the main System.Exception class.
Syntax
The following code shows the structure of a simple TryCatchFinally statement:
Try ' Include code to be tried here ' You can use Exit Try to exit the code & resume after End Try Catch ' Define the exception type and the action to be taken ' You can use a series of statements (multiple error handling) Finally ' This block is optional ' Define actions that need to take place End Try
Try Block
Note the following as you examine this code: The TryEnd Try block surrounds an area of code that might contain an error. Code placed in this block is considered protected. If an exception occurs, processing is transferred to the nested Catch blocks. You can use the Exit Try keyword to instantly exit the TryEnd Try block. Execution will resume immediately after the End Try statement.
40
Catch Block
If an exception occurs in the Try block, execution will continue at the beginning of the nested Catch block. The Catch block is a series of statements beginning with the keyword Catch followed by an exception type and an action to be taken. The following are some guidelines for using the Catch block: You can choose to handle all exceptions in one Catch block. You can also declare multiple Catch blocks to filter the exception and handle particular errors, similar to how you might use Select Case in previous versions of Visual Basic. You can filter using the different exception classes defined by the .NET Framework and runtime, or by using your own exception classes. You can use a When statement to compare the exception to a particular exception number. If you use filtering for the exceptions but do not handle the actual exception that occurred, the exception is automatically raised up to the calling procedure (or to the user if no calling procedure exists). However, by using a Catch filter with the Exception class, you will catch all of the other exceptions that you have not included in your filters. This is the equivalent of a Case Else statement in a Select Case structure.
Finally Block
The Finally block is optional. If you include this block, it is executed after the Try block if no errors occurred, or after the appropriate Catch block has been processed. The Finally block is always executed. In this block, you can define actions that need to take place regardless of whether an exception occurs. This may include actions such as closing files or releasing objects. The Finally block is most often used to clean up operations when a method fails.
41
Using TryCatchFinally
Topic Objective
To explain a simple example of structured exception handling.
Sub Sub TrySimpleException TrySimpleException Dim Dim i1, i1, i2, i2, iResult iResult As As Decimal Decimal i1 i1 = = 22 22 i2 i2 = =0 0 Try Try iResult ' iResult = = i1 i1 / / i2 i2 ' Cause Cause divide-by-zero divide-by-zero error error MsgBox ' MsgBox (iResult) (iResult) ' Will Will not not execute execute Catch Catch eException eException As As Exception Exception ' ' Catch Catch the the exception exception MsgBox MsgBox (eException.Message) (eException.Message) ' ' Show Show message message to to user user Finally Finally Beep Beep End End Try Try End End Sub Sub
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The following example shows how to implement structured exception handling in Visual Basic .NET by using the TryCatchFinally syntax:
Sub TrySimpleException Dim i1, i2, iResult As Decimal i1 = 22 i2 = 0 Try iResult = i1 / i2 ' Cause divide by zero exception MsgBox (iResult) ' Will not execute Catch eException As Exception MsgBox (eException.Message) Finally Beep End Try End Sub ' Catch the exception ' Show message to user
42
The compiler processes this code as follows: 1. Processing begins by attempting the code in the Try block. 2. The code creates a divide-by-zero exception. 3. Execution passes to the Catch block, where a variable eException of type Exception class is declared. This variable will display information about the exception to the user. 4. The Finally code is executed after all processing in the Catch block is complete. The Finally code causes a beep to sound, signifying that processing is complete. Note Any variables declared in any of the three blocks are scoped as blocklevel variables. They cannot be accessed from outside of the block.
43
Lead-in
Information provided
Why the exception was thrown The name of the application or object that generated the exception Exception history For nested exceptions The appropriate Help file, URN, or URL The name of the exception, the exception message, the name of the inner exception, and the stack
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The System.Exception class in Visual Basic .NET, similar to the Err object in Visual Basic 6.0, provides information about a particular exception. When you use this class in your Catch blocks, you can determine what the exception is, where it is coming from, and whether there is any help available. Some of the most useful properties and methods of the System.Exception class are described in the following table.
Property or method Message property Description Use the Message property to retrieve information about why an exception was thrown. A generic message is returned if the exception was created without a particular message. Use the Source property to retrieve the name of the application or object that generated the exception. Use the StackTrace property to retrieve the stack trace of the exception as a string. Use the InnerException property to navigate to multiple nested exceptions. Nesting exceptions may be useful if a more specific (or general) exception needs to be generated while maintaining the information from the original exception. If only the original exception is required, use the GetBaseException method. Use the HelpLink property to retrieve the appropriate Help file, URN, or URL for the exception. (See the note following this table.) Use the ToString method to return the fully qualified name of the exception, the exception message (if there is one), the name of the inner exception, and the stack trace.
HelpLink property
ToString method
44
Note Uniform Resource Locators (URLs) and Uniform Resource Names (URNs) are both examples of Uniform Resource Identifiers (URIs). A URN is a unique identifier that is not necessarily (but can be) in the form of a URL. They can be any combination of characters that is unique. Large organizations are more likely than individuals to use URNs because the guarantee of uniqueness is more difficult to achieve.
45
Filtering Exceptions
To explain a more advanced example of Try...Catch... Finally syntax that filters exceptions.
Topic Objective
Lead-in
Lets look at a more advanced example of Try...Catch...Finally syntax that involves filtering.
Dim Dim x, x, y, y, z z As As Integer, Integer, bSucceeded bSucceeded As As Boolean Boolean = = True True Try Try 'Perform 'Perform various various operations operations on on variables variables ... ... Catch Catch eException eException As As DivideByZeroException DivideByZeroException MsgBox("You MsgBox("You have have attempted attempted to to divide divide by by zero.") zero.") bSucceeded bSucceeded = = False False Catch Catch eException eException As As OverflowException OverflowException MsgBox("You MsgBox("You have have encountered encountered an an overflow.") overflow.") bSucceeded bSucceeded = = False False ... ... Catch Catch When When Err.Number Err.Number = = 11 11 MsgBox("Error MsgBox("Error occurred.") occurred.") bSucceeded bSucceeded = = False False Finally Finally If If bSucceeded bSucceeded Then Then ... ... End End If If End Try End Try
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip To learn more about structured exception handling in Visual Basic .NET, consider a more advanced example. In this example, errors are filtered based on the class of the exception.
This example is more complex because it uses filtering to catch different exceptions. Explain that DivideByZeroException, OverflowException, and ConstraintException are all examples of exception classes that are based on (inherit from) the System.Exception class. One of the Catch blocks checks the exception number by using a When statement. Also point out that the last Catch block uses the ToString method of the exception class.
46
Example
The following example shows how to use filtering to handle several different exceptions in one Try...Catch...Finally statement:
Sub TryComplexException( ) Dim x, y, z As Integer, bSucceeded As Boolean = True Try 'Perform various operations on variables ... Catch eException As DivideByZeroException MsgBox("You have attempted to divide by zero!") bSucceeded = False Catch eException As OverflowException MsgBox("You have encountered an overflow.") bSucceeded = False Catch eException As ConstraintException MsgBox(eException.ToString) bSucceeded = False Catch When Err.Number = 11 MsgBox("Error occurred") bSucceeded = False Finally If bSucceeded Then MsgBox("Success!") Else MsgBox("Failure") End If End Try End Sub
As you examine this code, note the following: For demonstration purposes, a test is made against various exception classes such as DividebyZeroException, OverflowException, and ConstraintException. These classes are all derived from the System.Exception class. One of the Catch blocks checks the exception number, Err.Number, by using the When statement. The last Catch block uses the ToString method of the Exception class. Note that if the exception does not meet any of the filter expressions, it will be passed up to the calling procedure. Using System.Exception as a Catch type would catch other unexpected exceptions.
47
Throwing Exceptions
Topic Objective
To explain how to throw your own exceptions.
Lead-in
You can raise your own exceptions by using the Throw statement.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In Visual Basic 6.0, you can use the Raise method of the Err object to raise your own exceptions. You can use this method to create a business logic error or to propagate an error after previously trapping it. Visual Basic .NET introduces the Throw statement, which allows you to create your own exceptions. The Throw statement provides similar functionality to the Err.Raise method.
You can also create your own exception classes that inherit from the System.Exception class. For more information, see Module 4, ObjectOriented Design for Visual Basic .NET and Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Example
The following example shows how to throw an exception in Visual Basic .NET:
Try If x = 0 Then Throw New Exception("x equals zero") End If Catch eException As Exception MsgBox("Error: " & eException.Message) End Try
Delivery Tip
This is an example of using object constructors for the Exception class. They will be covered in Module 4, Object-Oriented Design for Visual Basic .NET and Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
This example will throw an exception if the value of the variable x is zero. The If statement creates a new Exception object and passes a string containing an exception description to the object constructor. This means that the Catch block can handle the exception as it would deal with a normal system exception. If a Throw statement is not executed within a Try block, the exception will be raised to the calling procedure. Note For more information about object constructors, see Module 5, ObjectOriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
48
Topic Objective
Lead-in
In this demonstration, you will learn how to use structured exception handling in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the TryCatchFinally statement to implement structured exception handling. You will also learn how to check values of the System.Exception class and how to throw your own exceptions.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
49
Objectives
After completing this lab, you will be able to: Create structured exception handling. Throw your own exceptions.
Prerequisites
Before working on this lab, you must: Complete Lab 3.1. Be familiar with using the TryCatchFinally statement for structured exception handling.
Scenario
In this lab, you will add structured exception handling to the application that you created in Lab 3.1.
50
51
To add exception handling to the RetrieveCustomer function 1. In the RetrieveCustomer function, add a TryCatchFinally code block around the existing code. 2. In the Catch block, create a variable named eOutOfRange of type IndexOutOfRangeException. This catches an exception when a user tries to access an array that does not exist. 3. Add the following line to the Catch block:
Throw New Exception ("Invalid Customer Id", eOutOfRange)
This throws a new exception that includes a specific message, while keeping the original exception as an inner exception. The Try...Catch...Finally block in the btnRetrieve_Click event handler catches this exception. 4. Delete the Finally block. It serves no purpose in this procedure. To display the inner exception in the btnRetrieve_Click event handler 1. In the btnRetrieve_Click event handler, modify the Catch block to display additional information about the exception, including the Message, the ToString, and the GetBaseException.Message members of the eException variable. 2. Save your project. To test your application 1. Start the application, and add only one customer. 2. Click Retrieve. When you enter break mode, step through the code. 3. When asked for the customer identification number, enter the value 20 in the InputBox, and then click OK. 4. Step through the code and confirm that this generates an exception in the RetrieveCustomer function and that it is handled inside the function, but then is raised to the btnRetrieve_Click event handler. 5. Quit the application. 6. Close Visual Studio .NET.
52
Review
Topic Objective
To reinforce module objectives by reviewing key points.
Data Types Using Variables Functions, Subroutines, and Properties Exception Handling
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. Declare and initialize an array that contains the following strings: one, two, three, four.
Dim myArray( ) As String = {"one", "two", "three", "four"}
2. What types of variables are created by the following declaration if Option Strict is off?
Dim a, b As Integer, c
The variable c remains equal to 1 because the default passing mechanism is by value.
53
4. Assuming you have an open Recordset called rs and a TextBox control called txtData, which of the following statements will create a compiler or run-time error with Option Strict off? Why?
a. txtData.Text = rs(0) b. txtData.Text = rs.Fields.Item(0) c. txtData.Text = rs.Fields(0).Value
Statement (a) will fail because rs(0) returns a Field object; the Fields collection is the default property of the Recordset object. This cannot be assigned to the Text property of the txtData TextBox because the data types are not compatible. Statement (b) will fail because Value is the default property of the Field object, and it does not take a parameter. This causes the compiler to attempt to assign the Field object to the txtData.Text property, resulting in an error. Statement (c) will succeed because Item is the default property of the Fields object, and it does take a parameter.
5. What is the method or property of the System.Exception class that retrieves the most information about an exception? The ToString method provides the fully qualified class name, and the error message (if available), the name of the inner exception, and the stack trace of the exception.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 75 Minutes Lab: 45 Minutes This module explains the basic concepts that students need to understand to take advantage of the object-oriented enhancements to Microsoft Visual Basic .NET. It describes how to create use cases and class diagrams to model the system. It focuses on the areas that Visual Basic developers may be familiar with but need to understand fully so they can use encapsulation, inheritance, interfaces, and polymorphism. In the lab, students will use Microsoft Visio to create diagrams for classes, attributes, operations, and relationships based on given use case descriptions. Important Visio is part of the Enterprise Architect edition of Visual Studio .NET. To complete the demonstrations and labs, this edition must be installed on all classroom machines. After completing this module, students will be able to: Describe the basics of object-oriented design. Explain the concepts of encapsulation, inheritance, interfaces, and polymorphism. Create classes based on use cases. Model classes for use in Visual Basic .NET by using Visio.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_04.ppt Module 4, Object-Oriented Design for Visual Basic .NET Lab 4.1, Creating Class Diagrams from Use Cases
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the practice. Complete the lab.
iv
Product class
Attributes Name Image Full Description Manufacturer Price Operations RetrieveDetails(ID)
Order Class
Attributes Product ID Quantity Delivery Date Operations ConfirmOrder( )
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
To create the Visio drawing 1. Open Microsoft Visio. In the Category list, click Software. In the Template list, click UML Model Diagram to create an empty drawing. 2. On the View menu, click Grid so that the grid lines are not displayed. To create the use case diagram 1. In the Shapes toolbox, click the UML Use Case tab, and then use the shapes to create the following actors and use cases. Set the name for each item by double-clicking the item and changing the Name property.
Type System Boundary Actor Web User Sales Agent Credit Card Agency Database Use Case Web Log On Place Order Process Payment Name
2. Arrange the items so that only the use cases are displayed within the system boundary.
vi
3. Use the tools in the Shapes toolbox to create associations between the following items.
Shape Communicates Communicates Communicates Communicates Communicates Uses Communicates Link from Web User actor Web User actor Sales Agent actor Web Log On use case Place Order use case Place Order use case Process Payment use case Link to Web Log On use case Place Order use case Place Order use case Database actor Database actor Process Payment use case Credit Card Agency actor
4. Select all of the associations, right-click any of the selected associations, and then click Shape Display Options. Clear all of the End options check boxes, select Apply to the same selected UML shapes in the current drawing window page, and click OK. This will remove the association multiplicities and end names from the diagram. 5. Double-click the Web User actor, and then type the following description into the Documentation box: A Web user customer who can place orders over the Internet. 6. Double-click the Web Log On use case, and then type the following description into the Documentation box: A customer logs on to the system using an e-mail address and password. The e-mail address and password are then validated by the database. If they are not valid, an error message is displayed to the customer. If they are valid, a welcome screen is displayed. 7. On the File menu, click Save, and then go to the install_folder\DemoCode\ Mod04\Use Cases folder. Rename the file UseCase.vsd, click Save, and then click OK.
vii
To create the UML classes 1. Open Visio, and then open the drawing you saved from the use case demonstration. 2. In Model Explorer, right-click Top Package, point to New, and then click Static Structure Diagram. 3. In the Shapes toolbox, click the UML Static Structure tab, and then use the Class tool to create the following classes: Customer Credit Card Account Order Order Item To create the associations 1. In the Shapes toolbox, click the Binary Association tool to create an association from the Customer class to the Order class. Point out that the multiplicity end will be determined by the order in which you create the association. Double-click the association, and in the UML Association Properties dialog box, set the following values.
Association ends First item in list Second item in list Multiplicity value 1 0..*
2. Create an association from the Customer class to the Credit Card Account class. In the UML Association Properties dialog box, set the following values.
Association ends First item in list Second item in list Multiplicity value 1 0..*
3. Use the Composition tool to create an aggregation between the Order and Order Item classes. In the UML Association Properties dialog box, set the following values.
Association ends First item in list Second item in list Multiplicity value 1 1..*
4. Explain that this multiplicity setting is appropriate because an Order must contain at least one Order Item to be valid. 5. Click the Customer-Credit Card Account association, hold down the SHIFT key, and click the Customer-Order association. Right-click any of the selected associations, and then click Shape Display Options. Clear the First end name and Second end name check boxes, select Apply to the same selected UML shapes in the current drawing window page, and then click OK. 6. Repeat this process for the composition association.
viii
To modify the Customer class 1. Double-click the Customer class, and in the UML Class Properties dialog box, type the following description into the Documentation box: The Customer class stores information about a particular customer and allows logging on to the system. 2. In the Categories list, click Attributes, and then click the first line in the list of attributes. Use this list to add the following attributes and set the following properties.
Attribute CustomerID Email Password Type VB::Integer VB::String VB::String Visibility private public public
In the Categories list, click Operations, and then click the first line in the list of operations. Use this list to add an operation called LogOn, specifying a return type as VB::Boolean. Click the Properties button to get to the Documentation box, and then type the following text: The LogOn method validates an e-mail address and a password for a customer. If the validation is successful, the attributes of the Customer object will be retrieved from the database. The method returns a success or failure Boolean flag. 3. In the Categories list in the UML Operation Properties dialog box, click Parameters. Create new parameters based on the following values.
Parameter Email Password Type VB::String VB::String Kind in in
4. Close the UML Operations Properties dialog box and the UML Class Properties dialog box by clicking OK. 5. Point out that there is much more that could be done to complete this class diagram. 6. On the File menu, click Save As, and go to the install_folder\DemoCode\ Mod04\Class Diagrams folder. Rename the file ClassDiagrams.vsd, click Save, and then quit Visio.
ix
Module Strategy
Use the following strategy to present this module: Designing Classes This lesson introduces the concept of use cases and how they can be used to model a system. It also shows how classes, attributes, and operations can be derived from these use cases. It should be noted that many of the examples used throughout the module are open to different interpretations. Instructors should be able to discuss various interpretations from students. Object-Oriented Programming Concepts This lesson introduces the basic concepts of object-oriented design, including encapsulation, association, aggregation, and class diagrams. Some of the topics covered may be relatively basic for some students; however, these areas are essential for those new to class design. Cover this lesson quickly if the student knowledge level is appropriate. Advanced Object-Oriented Programming Concepts This lesson covers more advanced object-oriented concepts, such as inheritance (or generalization), interfaces, and polymorphism. Some students may already be familiar with these advanced topics, but these topics are essential for using Visual Basic .NET to its full capability, so this lesson should not be rushed. Using Microsoft Visio This lesson shows how Visio can help you model a system, particularly with use cases and class diagrams. Students who have used other tools such as Visual Modeler will find some familiar features, but they will also find Visio to be a more powerful tool. The module focuses on the creation of use case diagrams and class diagrams (also known as static structure diagrams), but there are many other areas of interest that you can discuss if time permits. Note that code generation and reverse engineering are supported in this version of Visio, but that neither are demonstrated.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Designing Classes Object-Oriented Programming Concepts Advanced Object-Oriented Programming Concepts Using Microsoft Visio
Lead-in
In this module, you will learn about object-oriented design and how it can help you to create your Visual Basic .NET applications.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Developers using Microsoft Visual Basic version 4.0 and later have had some exposure to the benefits of an object-oriented approach to programming, but it is only now that you can take full advantage of an object-oriented paradigm if you so choose. To use these new capabilities, you must be familiar with objectoriented programming concepts. This module explains the areas that you must understand to create object-oriented solutions in Visual Basic .NET. In this module, you will learn how to begin the class design process by using use cases. You will then learn about some common object-oriented programming concepts, including inheritance, interfaces, and polymorphism. Finally, you will learn how to document your system design by using Microsoft Visio to build use cases and class diagrams. After completing this module, you will be able to: Describe the basics of object-oriented design. Explain the concepts of encapsulation, inheritance, interfaces, and polymorphism. Create classes based on use cases. Model classes for use in Visual Basic .NET by using Visio. Note Visio is part of the Enterprise Architect edition of Visual Studio .NET.
This module does not cover all aspects of objectoriented programming. It concentrates on areas Visual Basic developers need to know to apply object-oriented design techniques when building applications. Given this, you should refer students to other reference books on object-oriented design.
Designing Classes
Topic Objective
To provide an overview of the topics covered in this lesson.
Use Case Diagrams Use Case Diagram Example Use Case Descriptions Extending Use Cases Converting Use Cases into Classes
Lead-in
This lesson discusses use cases and how they can be used to begin the class design process.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the Unified Modeling Language (UML) to help you analyze requirements by graphically showing interactions within the system. After completing this lesson, you will be able to: Design classes for use in applications created in Visual Basic .NET. Begin the process of designing classes by using use cases. Derive classes based on an existing use case.
Lead-in
Use cases Provide a functional description of major processes Use a non-technical language to describe the process Show a boundary around the problem to be solved Actors Graphically describe who or what will use the processes
Use case diagrams are the first step in designing classes for your solution.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** A use case is a collection of possible sequences of interactions in a system. Use case diagrams are an integral part of designing a modern software application. You can use the Unified Modeling Language (UML) to help you analyze requirements by graphically showing interactions within the system. Use case diagrams consist of individual use cases and actors.
Actors
An actor graphically represents who or what will use the system. An actor is often a role that a person plays when interacting with a particular process of the system. Actors request functionality of the system by way of a use case and can use many different use cases. Multiple actors can also use the same use case. Four categories of actors include: Principal actors People who use the main system functions. Secondary actors People who perform administration or maintenance tasks. External hardware Hardware peripheral devices that are part of the application domain and must be used. Other systems Other systems with which the system must interact. Identifying actors can help you understand what the system should do and who can use each section of the system. Actors provide a starting point for designing security permissions for the different roles that interact with the system. An actor can also represent another software application or even a hardware device that interacts with the new system.
Topic Objective
Sales System
Retrieve Customer Orders
Lead-in
A simple use case diagram is made up of one or more use cases, actors, and the communications between them.
Internet Client
Add Customer
Database
Telesales Agent
Remove Customer
*****************************ILLEGAL FOR NON-TRAINER USE****************************** A simple use case diagram is made up of one or more use cases, actors, and the communications between them.
Point out the different actors and what they represent. Note that the Database actor is not a person but that this is acceptable. Also point out and briefly describe each use case. Dont give precise details about the use cases because this is covered in more detail later in this module. These use cases are not identical to the cargo system and are meant to be fairly generic.
Topic Objective
Lead-in
Use case descriptions provide information about a particular scenario. Here is an example of one of those scenarios from the previous use case diagram.
A user requests the orders for a customer by using a particular customer ID. The ID is validated by the database, and an error message is displayed if the customer does not exist. If the ID matches a customer, the customers name, address, and date of birth are retrieved, in addition to any outstanding orders for the customer. Details about each order are retrieved, including the ID, the date, and the individual order items that make up an order.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Use case descriptions provide information about a particular scenario. Here is an example of a scenario from the use case diagram in the preceding topic .The Retrieve Customer Orders use case description reads as follows: Delivery Tip A user requests the orders for a customer by using a particular customer ID. The ID is validated by the database, and an error message is displayed if the customer does not exist. If the ID matches a customer, the customers name, address, and date of birth are retrieved, in addition to any outstanding orders for the customer. Details about each order are retrieved, including the ID, the date, and the individual order items that make up an order. By working through this use case description, you can see that it starts with a request from a user to perform a certain action. Some validation then takes place, and an error message is displayed if appropriate. If the validation succeeds, information about the customer, the customers orders, and the order items for an order are retrieved and displayed to the user. Notice that the precise details of how information is retrieved and displayed are not mentioned. The point of a use case description is simply to describe the business process, not provide all information for the developer. From this use case description, various classes can be derived that will become the first version of the detailed design for the system solution.
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Instead of developing a separate use case for every process, you can reuse use cases. This is a less repetitive approach and can save you a lot of time. Two keywords that you can use to extend use cases are as follows: Delivery Tip uses The uses keyword allows an existing use case to be reused by other use cases. This means that if a use case needs to perform some sort of action that has been created elsewhere, there is no need to duplicate the effort. The slide shows how the Add Customer use case might use the Check Customer Exists use case that has been defined for reuse. This means that the Check Customer Exists use case can be called directly from an actor or reused from other use cases. extends The extends keyword allows a use case to describe a variation on normal behavior in an existing use case. In other words, it allows a new use case to perform a similar action to an existing use case, except that the new use case builds on the existing one, performing a more complex action. The illustration shows how the Remove Customer use case can be extended to remove the inactive customers who have not placed orders within two months.
The uses syntax is straightforward, but the extends syntax is more complex. Point out that extends is mainly used to give a more precise description of a general use case. It is particularly useful if the extending use case deals with an unusual situation.
Topic Objective
Use case descriptions provide the basis for initial class design Nouns = classes or attributes A user requests the orders for a customer by using a particular customer ID. The ID is validated by the database, and an error message is displayed if the customer does not exist. If the ID matches a customer, the customers name, address, and date of birth are retrieved, in addition to any outstanding orders for the customer. Details about each order are retrieved, including the ID, the date, and the individual order items that make up an order. Verbs = operations (methods) Example: ValidateCustomer, RetrieveOrders, RetrieveOrderItems
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can create initial class designs by finding the nouns and verbs in use case descriptions. You can begin to identify classes or attributes for classes by finding the nouns in the use case description. You can begin to identify processes that can become operations or methods in a class by finding the verbs in the use case description.
Creating classes, attributes, and operations based on use case descriptions can be a subjective process. Make it clear to the students that this is only a preliminary draft of a class design.
Based on the use case description, you might conclude that the following classes and attributes are possible.
Class User Customer Attributes <Unknown at this stage> CustomerID Name Address Date of Birth Orders Order ID Date Order Items Order Items <Unknown at this stage>
These are only possible classes and attributes based on the use case description, and they may be removed or modified in later design stages.
10
Topic Objective
Lead-in
This practice allows you to work in pairs to derive some classes and attributes from a use case description.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this practice, you will work in pairs to select classes and some attributes or operations based on the following use case descriptions. When you have finished, the instructor and class will discuss the results as a group. Delivery Tip
Students will work in pairs and then discuss the outcome as a group. While there should not be too many variations in the answers, you should expect different interpretations and be able to explain why a given student answer is correct or incorrect. Expected answers are given in the Instructor Notes for this module.
11
Comparing Classes to Objects Encapsulation Abstraction Association Aggregation Attributes and Operations
Lead-in
There are several objectoriented programming concepts that you must be familiar with when developing classes for Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This lesson introduces several important concepts of object-oriented design that will improve the way you design your Visual Basic .NET solutions. After completing this lesson, you will be able to: Distinguish between objects and classes. Describe encapsulation, association, and aggregation. Explain how properties and methods are used to define a class and the different levels of scope that make them accessible or inaccessible. Explain how classes are represented in class diagrams along with their relationships to each other.
12
Lead-in
Classes and objects are closely related. We cannot talk about an object without regard to its class. However, there are some important differences between them.
A class is a template or blueprint that defines an objects attributes and operations and that is created at design time
Class
An object is a running instance of a class that consumes memory and has a finite lifespan
Object
12
123
245 245
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The object-oriented terms class and object often create some confusion because they can be easily misused by developers when describing a system.
It may be useful to discuss the differences between objects and classes with another example that is relevant to Visual Basic developers. A button is defined internally in Visual Basic as being rectangular, as having a caption, and as having the ability to be clicked. This is an example of a class. You can place as many instances of a button on a form as you want, and changing the caption of one doesnt affect the others. These are examples of objects. Likewise, clicking one instance of a button does not cause the others to be clicked.
Class
A class is an abstract data type containing data, a set of functions to access and manipulate the data, and a set of access restrictions on the data and on the functions. You can think of a class as a template or a blueprint for an object. This blueprint defines attributes for storing data and defines operations for manipulating that data. A class also defines a set of restrictions to allow or deny access to its attributes and operations. A car is an example of a class. We know that a car has attributes, such as the number of wheels, the color, the make, the model, and so on. We know that it also has operations, including unlock door, open door, and start engine.
Object
Objects are instances of classes. A single blueprint or class can be used as a basis for creating many individual and unique objects. If you consider classes and objects in Visual Basic terms, a class is created at design time and will exist forever, whereas an object is instantiated at run time and will only exist as long as required during the application execution. For example, an instance of a car would contain specific information for each attribute, such as number or wheels equals four, color equals blue, and so on. Objects exhibit three characteristics: Identity Behavior State
13
Identity
One object must be distinguishable from another object of the same class. Without this characteristic, it would be impossible to tell the difference between the two objects, and this would cause great difficulties for developers. This difference could be a simple identifier such as a unique ID number assigned to each object, or several of each objects attributes could be different from those of the other objects.
A particular car could be the same make, model, and color as another car, but the registration numbers cannot be identical. This difference provides a way to distinguish two otherwise identical cars.
Note You do not have to generate these unique identifiers yourself, as when you create an object, Visual Basic maintains identity for you.
Behavior
Objects exist to provide a specific behavior that is useful. If they did not exhibit this characteristic, we would have no reason to use them. The main behavior or purpose of a car is to transport people from one location to another. If the car did not provide this behavior, it would not perform a useful function.
State
State refers to the attributes or information that an object stores. These attributes are often manipulated by an objects operations. The objects state can change by direct manipulation of an attribute, or as the result of an operation. A well-designed object often only allows access to its state by means of operations because this limits incorrect setting of the data. A car keeps track of how far it has traveled since it was created in the factory. This data is stored internally and can be viewed by the driver. The only way to alter this data is to drive the car, which is an operation that acts upon the internal state.
14
Encapsulation
To explain the concept of encapsulation.
Topic Objective
Lead-in
How an object performs its duties is hidden from the outside world, simplifying client development Clients can call a method of an object without understanding the inner workings or complexity Any changes made to the inner workings are hidden from clients
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Encapsulation is the process of hiding the details about how an object performs its duties when asked to perform those duties by a client. This has some major benefits for designing client applications: Delivery Tip Client development is simplified because the clients can call a method or attribute of an object without understanding the inner workings of the object. Any changes made to the inner workings of the object will be invisible to the client. Because private information is hidden from the client, access is only available by means of appropriate operations that ensure correct modification of data.
To continue with the Visual Basic button example, we do not know how a button receives a click event from Microsoft Windows, just that it does and that we can use it.
Example
Driving a car is an example of encapsulation. You know that when you press the accelerator the car will move faster. You do not need to know that the pedal increases the amount of fuel being fed into the engine, producing more fuel ignition and thereby speeding up the output to the axle, which in turn speeds up the cars wheels, which has the final effect of increasing your speed. You simply need to know which pedal to press to have the desired effect. Likewise, if the car manufacturer changes the amount of fuel being mixed with oxygen to alter the combustion, or creates a drive-by-wire accelerator pedal, you do not need to know this in order to increase your speed. However, if the manufacturer replaces the accelerator pedal with a sliding throttle device, similar to what you would find in an aircraft, you may need to know about it!
15
Abstraction
To explain the concept of abstraction.
Topic Objective
Lead-in
Abstraction is selective ignorance Decide what is important and what is not Focus on and depend on what is important Ignore and do not depend on what is unimportant Use encapsulation to enforce an abstraction
Abstraction allows you to concentrate on what is important in your objects and ignore what is not.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Abstraction is the practice of focusing only on the essential aspects of an object. It allows you to selectively ignore aspects that you deem unimportant to the functionality provided by the object. A good abstraction only provides as many operations and attributes as are required to get the job done. The more operations and attributes provided, the more difficult to use the object becomes. If an object is simple to use because it includes only the essential operations, there is a greater possibility that it can be reused by other applications. A good abstract design will also limit a clients dependency on a particular class. If a client is too dependent on the way an operation is performed by an object, any modification to the internal aspects of that operation may impact the client, requiring that additional work be completed. This is often known as the principle of minimal dependency.
16
Association
To use association to examine relationships between classes.
Topic Objective
Lead-in
A class depends on another class to perform some functionality Roles are the direction of the association Multiplicity determines how many objects can participate in a relationship
Classes rarely exist in isolation and are often dependent on other classes for certain functions. Association is one way to link classes together.
Multiplicity
Customer
0..*
Order
Association
*****************************ILLEGAL FOR NON-TRAINER USE****************************** An association is a relationship between two classes. It represents a dependency, in that one class needs another class to accomplish a specific function. The slide shows an example of an association between a Customer class and an Order class. In this relationship, it does not make sense to be able to create an order that does not belong to a particular customer, so we would specify that the Order class is dependent on the Customer class. The association shows this relationship.
Roles
A role is the direction of an association between two classes. The illustrated association between Customer and Order contains two inherent roles: one from Customer to Order, and another from Order to Customer. Roles can be explicitly named by using a label, or implied if not included on a diagram like that of the class name.
Multiplicity
Multiplicity is used to define a numeric constraint on an association that restricts how many objects exist within the relationship. If no multiplicity values are specified, there is an implicit one-to-one relationship between the classes.
17
In the illustration on the slide, a customer can place many orders. This relationship is signified by the 0..* multiplicity range on the Order end. As no multiplicity value is specified at the Customer end, an implicit value of one is assumed, signifying that an order can only have one customer. The following table lists the other possibilities for multiplicity.
Symbol * 0..1 1..* 2-3, 6 {constraint} Meaning Many (zero or more) Optional (zero or one) One or more Specific possibilities Rules including well-known constraints like Order or Mandatory, or other unique business rules specific to your solution.
18
Aggregation
Topic Objective
To examine the concept of aggregation.
Lead-in
A complex class containing other classes A part-of relationship Example: An Order class contains an OrderItem class An OrderItem class is a part of an Order class
Order
Some classes are more complex than others. Aggregation describes a complex class that is made up from other simpler classes.
*
Aggregation
OrderItem
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Aggregation represents a relationship where simple objects form parts of a more complex whole object. This type of relationship is often used when an object does not make any sense in its own right, such as Order Item in the example on the slide. An Order Item needs to exist as part of a more complex object, such as an Order. The Order itself is only useful as a complete object that includes individual Order Items. The Order Item class can be referred to as the part classifier and the Order class as the aggregate classifier. You can also specify the number of parts that make up the whole by using multiplicity on an aggregation relationship. The slide shows that an Order can be made up of one or more Order Items. The words aggregation and composition are sometimes used as though they are synonyms. In UML, composition has a more restrictive meaning than aggregation: Aggregation Use aggregation to specify a whole/part relationship in which the lifetimes of the whole and the parts are not necessarily bound together, the parts can be traded for new parts, and parts can be shared. Aggregation in this sense is also known as aggregation by reference. Composition Use composition to specify a whole/part relationship in which the lifetimes of the whole and the parts are bound together, the parts cannot be traded for new parts, and the parts cannot be shared. Composition is also known as aggregation by value.
This topic may cause some discussion because the formal definitions of aggregation and composition cause much disagreement between UML experts. Do not go into too much detail because the differences are not significant to Visual Basic .NET development. In addition, be aware that leading UML experts still debate the definitions of association, aggregation, and composition.
19
Lead-in
Attributes are the data contained in a class Operations are the actions performed on that data Accessibility: Public (+), Private (-), Protected (#)
Classes usually contain data and functions that act upon this data. These are known as attributes and operations.
Customer
-CustomerID: Long +Name: String +DOB: Date +AddCustomer( ) +GetDetails(ID: Integer) -CheckValid( ): Boolean
Attributes
Save Operation No parameters Load Operation Integer parameter CheckValid Operation Boolean return value
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Classes are usually made up of data and actions performed on this data. These are known as attributes and operations respectively, but developers also call them properties and methods. These attributes and operations are also defined with an accessibility setting.
Attributes
Attributes are the data members of the class. They can be of any data type, including String, Decimal, or even another class. Each attribute will also have an accessibility option specified, as shown in the following table. In Visual Basic .NET, public attributes will be implemented as either class-level variables or, more appropriately, as class properties that encapsulate internal variables.
Operations
Operations are the actions performed on internal data within the class. They can take parameters, return values, and have different accessibility options specified in the same way that attributes can. In Visual Basic .NET, these are implemented as either functions or subroutines.
Accessibility
Attributes and operations can be defined with one of the access modifiers in the following table.
Value Public (+) Protected (#) Private (-) Meaning Accessible to the class itself and to any client of the class. Only accessible to a child class when used for inheritance. (Inheritance will be covered later in this module.) Only accessible by code within the class that defines the private attribute or operation.
20
Lead-in
There are some other important concepts that you must understand to take full advantage of the objectoriented capabilities of Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This lesson introduces some advanced concepts of object-oriented design: inheritance, interfaces, and polymorphism. After completing this lesson, you will be able to: Explain inheritance Define interfaces Define polymorphism
21
Inheritance
Topic Objective
To explain the concept of inheritance.
Inheritance specifies an is-a-kind-of relationship Multiple classes share the same attributes and operations, allowing efficient code reuse Examples:
A customer is a kind of person An employee is a kind of person
base class
Lead-in
Inheritance is an important concept for object-oriented developers because it allows great flexibility in solution design.
Person
derived classes
Customer
Employee
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Inheritance is the concept of reusing common attributes and operations from a base class in a derived class. If the base class does not contain implementation code and will never be instantiated as an object, it is known as an abstract class. The example below shows an inheritance relationship between the Customer, Employee, and Person classes. The Person superclass has attributes defined as Name, Gender, and Date of Birth and contains the operations Create, Remove, and Validate. These are all attributes and operations that could equally be applied to a Customer or Employee subclass, providing a good deal of reuse.
Person
Inheritance is a key new feature of Visual Basic .NET, so it may be worthwhile to give as many examples as required for students to understand the concept. Visual Basic .NET exceptions are an example of inheritance. All exceptions inherit from the Exception class. Many exceptions do not extend this class, such as System.Exception and Application.Exception. Others do, including the WebException and XMLException exceptions, which contain extra properties pertinent to their data types. Other examples include the following: AnimalDog and Cat. VehicleCar and Boat. CompanyVendor and Supplier
Customer
Employee
Specialization occurs when a subclass is created and includes attributes or operations specific to that class.
22
The Customer class has the extra attributes CustomerID, CreditRating, and LastContacted in addition to the inherited ones from the Person superclass. It also defines its own operation named AddOrder that is specific to the Customer class. Having an operation called AddOrder would not make sense for either the Person class or the Employee class. The Employee class has the extra attributes EmployeeID, Department, and Manager. It also defines a unique operation named Pay that would not be required in either the Person superclass or the Customer subclass. If a superclass is not an abstract class and contains some implementation code, the subclass can inherit the code from the superclass or override it by providing its own code. This reuse of code is known as implementation inheritance and is the most powerful form of reuse. Although implementation inheritance is very useful, it can lead to class diagrams and code that are complex and difficult to read. You should ensure that implementation inheritance is used appropriately and not overused. Note Visual Basic 6.0 does not support implementation inheritance, but Visual Basic .NET does. For more information, see Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
23
Interfaces
To explain interfaces from an object-oriented point of view.
Topic Objective
Interfaces only define the method signatures Classes define the implementation of the code for the Interface methods Interface inheritance means only the Interface is inherited, not the implementation code
Person
{abstract}
Lead-in
Interfaces are similar to abstract classes in that they contain no implementation code.
Employee
Public Sub Create( ) implementation code End Sub
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Interfaces are similar to abstract classes. They define the method signatures used by other classes but do not implement any code themselves. Delivery Tip Interface inheritance means that only the method signatures are inherited and that any implementation code is not. You would need to create separate code in the appropriate inherited method of each derived class to achieve any required functionality. Reuse is therefore more limited in interface inheritance as compared to implementation inheritance because you must write code in multiple locations.
Do not try to explain interfaces from a COM point of view. Concentrate on the fact that an interface defines only the method signatures and not the implementation code.
24
Polymorphism
Topic Objective
To explain the objectoriented concept of polymorphism.
Lead-in
The same operation behaves differently when applied to objects based on different classes Often based on Interface inheritance Classes inherit from interface base class Each derived class implements its own version of code Clients can treat all objects as if they are instances of the base class, without knowledge of the derived classes
Polymorphism is an objectoriented concept that some Visual Basic developers will be familiar with.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Polymorphism is the ability to call the same method on multiple objects that have been instantiated from different subclasses and generate differing behavior. This is often achieved by using interface inheritance. If two subclasses inherit the same interface, each of them will contain the same method signatures as the superclass. Each one will implement the code in an individual way, allowing different behavior to be created from the same method.
Customer
Inherited Sub Create() do specific customer code End Sub
Employee
Inherited Sub Create() do specific employee code End Sub
In the above example, the Customer and Employee classes have inherited from the Person superclass. Each class implements its own version of the Create method differently, but, because they both inherit the same interface, a client could treat both classes the same.
25
Visio Overview Use Case Diagrams Class Diagrams Creating Class Diagrams
Lead-in
Visual Studio .NET Enterprise Architect includes a built-in modeling tool: Visio.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This lesson introduces the Visual Studio .NET modeling tool: Visio. After completing this lesson, you will be able to: Use Visio to help you design your system solution.
26
Visio Overview
To give an overview of the capabilities of Visio.
Topic Objective
Lead-in
Supports: Use case diagrams Class or static structure diagrams Activity diagrams Component diagrams Deployment diagrams Freeform modeling
Visio provides many ways to help design and document your system.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visio allows you to design and document your solution from the initial analysis and design stages all the way to the final deployment of your enterprise system. Delivery Tip It supports many different models, including the following.
Use cases and class diagrams have already been discussed, so briefly review these models but concentrate on the other models.
Activity Diagrams
This UML diagram provides a view of the systems workflow between activities in a process. They can be used to model the dynamic aspects of the system, usually based on one or more use case descriptions. You can use initial states, transitions, decisions, and final states to model this view.
Component Diagrams
This UML diagram allows you to model physical aspects of a system, such as the source code, executables, files, and database tables. You can use interfaces, components, packages, and dependencies to model this view.
27
Deployment Diagrams
This UML diagram gives a view of the physical nodes (computational devices) on which the system executes. This type of diagram is especially useful when the system will involve more than one computer, such as in an enterprise solution. Nodes, component instances, and objects are the main shapes used in this diagram.
Freeform Modeling
Visio allows you the flexibility to create freeform models that do not need to adhere to the UML standards. This allows you to create a diagram that incorporates common UML shapes such as classes and components in addition to non-UML shapes such as COM and flowchart shapes. You have the option to validate all or part of your model to see whether it conforms to UML semantics.
28
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visio allows you to create fully featured use case diagrams that include: Actors. Use cases. Relationships, including association, dependency, and inheritance. These relationships include attributes such as multiplicity, navigability, and stereotype. Notes to help store additional information. You can add descriptions to all of the objects listed above to fully document your model. You can also add any non-UML shapes from the various stencil tabs to create a freeform model.
29
Topic Objective
Lead-in
Creating use cases is one of the initial design steps you will take in Visio.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a use case diagram in Visio. Note that the use cases created in the demonstration do not represent a completed model; this exercise is for demonstration purposes only.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
30
Class Diagrams
Topic Objective
To examine an example of a class diagram.
Lead-in
Customer * Order
1..*
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Class diagrams allow you to graphically put all of these relationships together in a single place. With some refinement, class diagrams will help a designer or developer model the system in enough detail to enable code to be generated and development to begin. The ability to interpret a class diagram is vital in modern software development. The slide shows that a single Customer class is associated with between zero and many Order classes. An Order class is made up of (or aggregated with) Order Item classes. The multiplicity for this relationship shows that there must be at least one Order Item for an Order to be valid, but that there can be an unlimited number of Order Items on the Order. Finally, each Order Item is associated with a single Product, but a Product can be associated with many Order Items. Note Class diagrams are also known as static structure diagrams in Visio and in some other UML modeling tools.
Explain the different parts of the class diagram, pointing out that you could argue that a customer does not exist unless it has at least one order. The various relationships may also provide discussion because some could be designed as composition, aggregation, or association. Such discussion should be limited because the purpose of the illustration is to examine notation and the overall look of a class diagram.
31
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visio allows you to create extensive class diagrams that include the following elements: Classes. Abstract classes or interfaces. Class attributes with accessibility (private, protected, and public), initial value, and stereotype (data type). Class operations with accessibility and parameters (detailed in the following text). Operation parameters with direction (in, out, inout, and return) and stereotype (data type). Relationships between objects, including association, dependency, aggregation, composition, and inheritance. These relationships include attributes such as multiplicity, navigability, and stereotype. Notes to help store additional information. You can add descriptions to all of the objects listed above to fully document your model. You can also add any non-UML shapes from the various Toolbox tabs to create a freeform model.
32
Topic Objective
Lead-in
Class diagrams are particularly helpful for creating Visual Basic .NET enterprise solutions.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a class diagram in Visio. Note that the classes created in the demonstration do not represent a completed model. This exercise is for demonstration purposes only.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
33
Topic Objective
Lead-in
In this lab, you will look at the use cases for the Cargo system. You will then create class diagrams in Visio for those use case descriptions.
Objectives
After completing this lab, you will be able to: Create classes based on use cases. Use Visio to create class diagrams.
Prerequisites
Before working on this lab, you must have: Knowledge of use cases and class diagrams. Familiarity with modeling tools.
Scenario
The Cargo system will provide the basis for many of the remaining lab exercises in this course. It is based on a simple Internet system for collecting and delivering customer packages. Web customers can log on to the system and create a delivery. Customers can also contact the company by means of a telephone sales operator who can process the order in a similar fashion. More information about the system is detailed in the use case diagram provided to you. However, while the labs are based on this scenario, you will not create a completed system during this course. In this lab, you will view the descriptions of existing use cases to help you understand the system. You will then create classes based on those descriptions.
34
35
36
4. Create a generalization relationship from the Special Package class to the Package class by using the Generalization tool.
37
To hide the association end names 1. Select all the binary associations, right-click any of the selected associations, and then click Shape Display Options. Clear the First end name and Second end name check boxes, select Apply to the same selected UML shapes in the current drawing window page, and click OK. This will remove the end names from the diagram. 2. Save the drawing.
38
To create the LogOn operation 1. In the Operations category, click the first line in the list of operations. Add an operation called LogOn with a return type of VB::Boolean. 2. Click Properties, and then add the following description in the Documentation box: Attempts to log on a customer and retrieve his or her details based on e-mail address and password. 3. In the Parameters category, create new parameters based on the following values.
Parameter Email Password Type VB::String VB::String Kind in in
39
To create the AddCustomer operation 1. Create the AddCustomer operation with a return type of VB::Integer. 2. Click Properties, and then add the following description in the Documentation box: Adds a new customer to the database based on the input parameters. 3. In the Parameters category, create new parameters based on the following values.
Parameter Email Password FirstName LastName Company Address Type VB::String VB::String VB::String VB::String VB::String VB::String Kind in in in in in in
4. Click OK to return to the UML Class Properties dialog box. To create the GetDetails operation 1. Create the GetDetails operation with a return type of <None>. 2. Click Properties, and then add the following description in the Documentation box: Returns the customer details based on the CustomerID received. 3. In the Parameters category, create new parameters based on the following values.
Parameter CustomerID Type VB::Integer Kind in
4. Click OK to return to the UML Class Properties dialog box, and then click OK to return to the drawing.
40
To generate Visual Basic .NET source code 1. On the UML menu, point to Code, and then click Generate. 2. Select Visual Basic as the Target language. Select Add Classes to Visual Studio Project, and then in the Template list, click Class Library. Rename both the Project and the Solution as Cargo. 3. Click Browse, locate the install_folder\Labs\Lab041\Ex03\Starter folder, and then click OK. 4. Select the Customer class only for code generation, and click OK. 5. Save the drawing and quit Visio. To view the code 1. Open Microsoft Visual Studio .NET. 2. On the File menu, point to Open, and then click Project. Set the folder location to install_folder\Labs\Lab041\Ex03\Starter, click Cargo.sln, and then click Open. 3. View the code for Customer.vb. 4. Quit Visual Studio .NET.
41
42
Review
To reinforce module objectives by reviewing key points.
Topic Objective
Designing Classes Object-Oriented Programming Concepts Advanced Object-Oriented Programming Concepts Using Microsoft Visio
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. An actor must be a person that interacts with the system. True or false? False. An actor can also be another system or a part of a system.
2. Define the object-oriented term encapsulation. Encapsulation is the hiding of the details about how an object performs various operations.
3. Define the object-oriented term inheritance. Inheritance is the reuse of the methods and attributes of a general class in more specialized classes.
43
4. Describe freeform modeling. Freeform modeling is the ability to use UML and non-UML shapes in a Visio diagram.
5. In the following use case description, what are the likely classes and attributes? A user requests a listing of grades from a school based on a particular student ID. The ID is validated by the database, and an error message appears if the student ID does not exist. If the ID matches a student, the students name, address, and date of birth are retrieved, in addition to the grades. The user is prompted to verify the information, and the grades are displayed if the verification succeeds. An error message is displayed if the user is unable to verify the information. Three verification attempts are allowed before the user is automatically logged off. The user is automatically logged off after five minutes of inactivity.
Class User Student Attributes <Unknown at this stage> StudentID Name Address Date of Birth Grades Grades ID
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 90 Minutes Labs: 105 Minutes This module provides students with the knowledge required to create objectoriented applications that use many of the new features of Microsoft Visual Basic .NET, such as inheritance, overloading, shared members, and event handling. In the first lab, students will create part of the Customer class for the Cargo system that they designed in Lab 4.1, Creating Diagrams from Use Cases. They will define the properties, methods, and constructors, based on those shown in Lab 4.1. Finally, they will write the code in a form to test the Customer class. In the second lab, students will create a base class called Package and a derived class called SpecialPackage. The classes contain some pre-written code, including the properties. Students will add methods to both classes and create the inheritance relationship. They will then complete a pre-written form to test their classes. After completing this module, students will be able to: Define classes. Instantiate and use objects in client code. Create classes that use inheritance. Define interfaces and use polymorphism. Create shared members. Create class events and handle them from a client application.
iv
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_05.ppt Module 5, Object-Oriented Programming in Visual Basic .NET Lab 5.1, Creating the Customer Class Lab 5.2, Inheriting the Package Class
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the labs.
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
Creating Classes
To examine the Employee class 1. Open the Classes.sln solution in the install folder\DemoCode\ Mod05\Classes folder. 2. View the code for the Employee class and point out the private variables, the properties, and the multiple constructors. Specifically point out the EmployeeId read-only property. To test the New Employee code 1. Run the project. 2. Enter values for the First Name and the Last Name. 3. Click the New Employee button on the form. The code will enter break mode at the preset breakpoint. 4. Step through the code, and explain each line as you go. Include the Dispose method but not the Finalize method. Point out that, in a real situation, the Dispose method would be used for saving data and closing a database connection. To test the Existing Employee code 1. Enter a positive integer value for the Id (any number will work), and then click the Existing button. 2. Step through the code and point out that this time the constructor takes the intEmpID as a parameter, so it can load the data from a database immediately. 3. Step through the code until the object has been instantiated, and then press F5 to allow the remaining code to run.
vi
To test the Improved New Employee code 1. Click the Improved New button on the form, and then step through the code when execution halts at the preset breakpoint. 2. Point out that the constructor takes strFirstName and strLastName as parameters so that it can create a new Employee immediately. 3. Step through the initialization code, and then press F5 to display the form again. 4. Click the Close button to close the form and stop the application. Explain that this will cause all remaining objects to be destroyed, and that the Finalize methods will execute. Remind students that the Finalize method should only be used when resources need to be manually reclaimed (such as database connections) because it creates more work for the garbage collector. In this case the Finalize method calls the Dispose method again to ensure that the resources have been reclaimed in case the class user has forgotten to call the Dispose method explicitly. The Finalize method is not necessary if the class user has called the Dispose method. A call to GC.SuppressFinalize within the Dispose method would have stopped the Finalize method from executing and would therefore have improved performance. 5. Quit the Microsoft Visual Studio .NET integrated development environment (IDE).
It is possible that the finalizers may run in the middle of this demonstration. If this happens, explain to the students how the thread gets commandeered for finalization, and note the reduced occurrences of the Finalize method when you click Close.
Inheritance
To examine the Person class 1. Open the Inheritance.sln solution in the install folder\DemoCode\ Mod05\Inheritance folder. 2. View the code for the Person class, and point out the private variables, the properties, and the methods. 3. View the code for the Employee class, and point out that it is a simplified version of the class used in the previous demonstration in that it has only one constructor. Show that it inherits from the Person class and only stores the EmployeeID value. Also, point out that the FirstName and LastName properties are not defined in this class.
vii
To test the project 1. Run the project. 2. Type values in the First Name and the Last Name boxes. 3. Click the New Person button on the form. The code will enter break mode at the first preset breakpoint. 4. Step through the code, explaining each line of code as you go. This will include the Dispose method and the Finalize method when the GC.Collect method is executed. 5. Point out that the Finalize method also calls the Dispose method of the Person class by means of the MyClass object. 6. Enter a positive integer value for the Id (any number will work), and click Existing Emp. 7. Point out that this time many of the inherited properties of the Person class are called rather than those of Employee. 8. Step through the code until the form appears again. 9. Close the form and quit the Visual Studio .NET IDE.
viii
To test the application 1. Run the project. 2. Click the New Employee button on the form. The Visual Basic .NET process will halt at the first preset breakpoint. 3. Step through the code, explaining each line as you go. Point out that both the Employee class and the IPerson interface are used to access the various members. The perPerson.Save method is called first to show what happens if you use the IPerson interface. The empEmployee.SaveEmployee method shows that you can use any name that you choose for the implemented method. 4. Click the New Student button on the form. The code will enter break mode at the preset breakpoint. 5. Step through the code, explaining each line as you go. Point out the similarity in the calling code for the IPerson methods of both the Student and Employee objects, and explain how this aids code reuse. 6. Close the form and quit the Visual Studio .NET IDE.
Handling Events
To view the code 1. Open the Events.sln solution in the install folder\DemoCode\Mod05\Events folder. 2. View the code for the Employee class, and point out the DataChanged event in the declarations section and its purpose. In the FirstName property, point out the raising of the event and the purpose of the code that checks the blnCancelled value. 3. View the code for the frmEmployee form, and point out the module-level variable that uses WithEvents. 4. Click the Class Name combo box, and then click empEmployee. In the Method Name combo box, click DataChanged. Examine the default event handler code, and point out the Handles keyword in the function declaration. To test the events 1. Run the project. 2. Click the WithEvents button on the form. The code will enter break mode at the preset breakpoint. 3. Step through the code, explaining each line of code as you go. This will include the RaiseEvent code in the Employee class. 4. Click the AddHandler button on the form. The code will enter break mode at the preset breakpoint. 5. Explain the AddHandler statement, and examine the EmployeeDataChange method at the end of the code for the form. 6. Continue debugging as the events are raised to the EmployeeDataChange method. 7. Close the form and quit the Visual Studio .NET IDE.
ix
Module Strategy
Use the following strategy to present this module: Defining Classes This lesson describes how to create classes in Visual Basic .NET. Students will learn how to declare methods and properties, and how to overload class members. When you introduce students to class constructors and destructors, including multiple constructors, point out that the Finalize method should only be used when resources need to be manually reclaimed (such as database connections) because this method adds overhead to the disposing of objects. Some of this lesson contains simple tasks such as how to create classes and methods. Cover these areas quickly so that more time can be spent on new features, such as the syntax for defining properties and constructors. Creating and Destroying Objects This lesson describes how to declare, instantiate, and initialize objects. Contrast this approach to the approach used in previous versions of Visual Basic to show the usefulness of constructors. Introduce garbage collection as an important change in the way objects are destroyed. Ensure that students understand this process, because many developers will be unaware of the potential dangers. Present the Dispose method as a suggested way to handle issues raised by garbage collection. Point out that the notes present two common techniques for creating the Dispose method, and that the IDisposable interface provides a more consistent approach. If time permits, you may want to show students the GC Class topic in the Visual Studio .NET documentation. Use the instructor-led demonstration to demonstrate how to create classes that contain multiple constructors. In this demonstration, you will also show how to instantiate and use classes from calling code. Inheritance This lesson explains how to use the new Visual Basic .NET class inheritance features. Introduce students to member overriding, the MyBase keyword, and the MyClass keyword. These important features will be new to many students, so be prepared to demonstrate different scenarios to reiterate the concepts. Use the instructor-led inheritance demonstration to show how to use the various keywords to create a simple Person class that is used as a base class for an Employee class.
Interfaces This lesson explains how to define interfaces in Visual Basic .NET and examines the various ways to achieve polymorphism. Use the instructor-led polymorphism demonstration to show how to use interfaces to define an IPerson interface that is then implemented by Student and Employee classes. This lesson will be a challenge for many students. You will need to gauge the level of understanding and decide how much time to spend on the material and the demonstration. Tell students where they can find additional information about this topic, possibly including books or white papers. For more information about interfaces and polymorphism, search for interfaces and polymorphism in the Visual Studio .NET documentation and at http://msdn.microsoft.com Working with Classes This lesson shows how to create shared members, events, and delegates. The Event Handing topic mentions the AddressOf operator but does not explain it in depth because it is not new to Visual Basic .NET. Some students, however, may require a more detailed explanation. Students may also find the concept of delegates to be difficult. A detailed example is provided in the student notes, and you may need to go through this example with the students. This example is also provided in the DemoCode folder, although no instructions accompany this code. Use the instructor-led demonstration to show how to define and handle events in a simple class.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes
Lead-in
In this module, you will learn how to implement objectoriented programming in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this module, you will learn how to implement object-oriented programming in Microsoft Visual Basic .NET version 7.0. You will learn how to define classes, their properties, and their methods. You will learn about the life cycle of an object, from creation to destruction. You will also learn how to work with classes by using inheritance, interfaces, polymorphism, shared members, events, and delegates. After completing this module, you will be able to: Define classes. Instantiate and use objects in client code. Create classes that use inheritance. Define interfaces and use polymorphism. Create shared members. Create class events and handle them from a client application.
This module introduces many important new features of Visual Basic .NET. Ensure that students fully understand these concepts before moving on to the next module.
Defining Classes
Topic Objective
To provide an overview of the topics covered in this lesson.
Procedure for Defining a Class Using Access Modifiers Declaring Methods Declaring Properties Using Attributes Overloading Methods Using Constructors Using Destructors
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn how to define classes in Visual Basic .NET. After completing this lesson, you will be able to: Specify access modifiers (scope) for classes and their procedures. Declare methods and properties within a class. Use attributes to provide metadata about your code. Pass different parameters to one method by using overloading. Create and destroy objects.
Add a class to the project Provide an appropriate name for the class Create constructors as needed Create a destructor, if appropriate Declare properties Declare methods and events
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** To define a class in Visual Basic .NET, you can follow this general procedure: Delivery Tip 1. Add a class to the project. 2. Provide an appropriate file name for the class when you add it. This will name both the file and the class itself. If you do not change the file name when you add it, you can change the class name at any time by changing the class definition in the code window. 3. Create constructors as needed. 4. Create a destructor if appropriate. 5. Declare properties. 6. Declare methods and events. Note In Visual Basic .NET, you can define more than one class in a single file. You are not limited to one class per file, as you are in previous versions of Visual Basic, because classes are a block level construct.
Point out that you can define as many classes as you need in a module. You are not limited to one class per file, as you are in previous versions of Visual Basic.
Lead-in
Before looking at the details for defining classes, you need to understand how access modifiers affect classes.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use access modifiers to specify the scope of the variables and procedures in the class that you define. Visual Basic .NET retains three access modifiers that are used in previous versions of Visual Basic and adds two more: Protected and Protected Friend. The following table defines the five access modifiers available in Visual Basic .NET.
Access modifier Public Private Friend Protected Definition Accessible everywhere. Accessible only within the type itself. Accessible within the type itself and all namespaces and code within the same assembly. Accessible within the class itself and, if other classes are inheriting from the class, within any derived classes. Protected members are available outside of an assembly when inherited by derived classes. The union of Protected and Friend. Accessible to code within the same assembly and to any derived classes regardless of the assembly to which they belong.
Protected Friend
Note Inheritance in Visual Basic .NET is described in detail in the Inheritance lesson of this module.
Declaring Methods
Topic Objective
To explain how to declare methods in a class.
Lead-in
The syntax for declaring methods in a class has not changed in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You use the same syntax to declare a method in Visual Basic .NET that you used in Visual Basic 6.0, as shown in the following example:
Public Class TestClass Public Sub TestIt(ByVal x As Integer) ... End Sub Public Function GetIt( ) As Integer ... End Function End Class
Declaring Properties
To explain how to declare properties in a class.
Topic Objective
Lead-in
The syntax for declaring class properties has changed significantly in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The syntax for declaring class properties has changed significantly in Visual Basic .NET.
This is an animated slide. It begins by showing the property syntax. Click the slide to reveal a ReadOnly example.
When you create a property declaration, the Visual Basic .NET Code Editor inserts a template for the remainder of the property body.
Example
The following example shows how to declare a property called MyData of type Integer. The Get block returns an unseen local variable called intMyData by using a Return statement. The Set block uses the Value parameter to store the passed-in property value to the intMyData local variable.
Private intMyData As Integer Public Property MyData( ) As Integer Get Return intMyData End Get Set (ByVal Value As Integer) intMyData = Value End Set End Property
You cannot use the Set block when defining read-only properties because the property cannot be updated. The compiler will generate an error if you attempt to do this.
You cannot use the Get block when defining write-only properties because the property is not readable. The compiler will generate an error if you attempt to do this.
Using Attributes
Topic Objective
To explain how to use attributes.
Lead-in
Extra metadata supplied by using < > brackets Supported for: Assemblies, classes, methods, properties, and more Common uses: Assembly versioning, Web Services, components, security, and custom
<Obsolete("Please <Obsolete("Please use use method method M2")> M2")> Public Public Sub Sub M1( M1( ) ) 'Results in warning in IDE when used by client 'Results in warning in IDE when used by client code code End End Sub Sub
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use attributes to provide extra information or metadata to the developers who read your code. In Visual Basic .NET, you use angular brackets (< and >) to specify an attribute. Delivery Tip You can apply attributes to many items within your application, including assemblies, modules, classes, methods, properties, parameters, and fields in modules, classes, and structures. Here are some examples of how to use attributes: In assemblies, you can specify metadata including the title, description, and version information of the assembly. When creating a Web Service, you can define which methods are accessible as part of the service, in addition to adding descriptions to the methods. When designing Windows Forms controls, you can specify information to display in the property browser, or you can set the Toolbox icon. For components that use enterprise services, you can set transaction and security settings. Functionality is provided by the Microsoft .NET Framework to allow you to create your own custom attributes and use them as you want in your applications. Note For more information about creating custom attributes, see Writing Custom Attributes in the Microsoft Visual Studio .NET documentation.
Discuss some of the common uses for attributes, but point out that we will cover individual attributes throughout the course.
10
Example
The following example shows how to use the Obsolete attribute to warn developers that a method can no longer be used. An optional message is displayed in the Task List window if a developer attempts to use this method. Using the Obsolete method will not create an error when the application is compiled, but will generate a warning as follows:
<Obsolete("Please use method M2")> Public Sub M1( ) 'Results in warning in IDE when used by client code End Sub
Note All attributes are simply classes that inherit from the Attribute class and provide constructors. The Obsolete class provides a single constructor that takes a string as the parameter.
11
Overloading Methods
Topic Objective
To introduce the concept and syntax of overloading in Visual Basic .NET.
Lead-in
Overloading is a powerful object-oriented feature that allows multiple methods to have the same name but accept different parameters.
Specified parameters determine which method to call The Overloads keyword is optional unless overloading inherited methods
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Overloading is a powerful object-oriented feature that allows multiple methods to have the same name but accept different parameters. Overloading allows calling code to execute one method name but achieve different actions, depending on the parameters you pass in. For overloading to occur, the method signature must be unique. You can achieve this by changing the number of parameters in the signature or by changing the data types of the parameters. Changing the way a parameter is passed (that is, by value or by reference) does not make a signature unique, nor does changing a function return data type. You can optionally specify a method as overloaded with the Overloads keyword. If you do not use the keyword, the compiler assumes it by default when you declare multiple methods that have the same name. However, when overloading a method from an inherited class, you must use the Overloads keyword. Note Overloading a method from an inherited class will be discussed in the Inheritance lesson of this module.
Students who are familiar with Microsoft Visual C++ will understand operator overloading. You might want to ask for examples from these students.
12
The following example shows how to overload a method. This code allows different types of information (string, integers, and so on) to be displayed by calling the Display method of a class and passing in different parameters.
Public Function Display(s As String) As String MsgBox("String: " & s) Return "String" End Sub Public Function Display(i As Integer) As Integer MsgBox("Integer: " & i) Return 1 End Function
When you call the Display method, the parameters you specify determine which overloaded method will be called. Without using overloading, you need two different methods, such as DisplayString and DisplayInteger, to accept the different types of parameters in the preceding example. Note If the Option Strict compiler option is on, you must explicitly declare values as specific types when passing them to the overloaded methods as parameters, and the compiler can identify which instance of the method to call. If Option Strict is off and a generic variable (such as Object) is passed as a parameter, the decision of which instance of the method to call is left until run time. For more information about overload resolution, see Procedure Overloading in the Visual Studio .NET documentation.
13
Using Constructors
To explain the concept and syntax of class constructors.
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In Visual Basic 6.0, you place initialization code in the Class_Initialize event of your class. This code is executed when the object is instantiated, and you can use it to set initial values of local variables, to open resources, or to instantiate other objects. In Visual Basic .NET, you control the initialization of new objects by using procedures called constructors. The Sub New constructor replaces the Class_Initialize event and has the following features: The code in the Sub New block will always run before any other code in a class. Unlike Class_Initialize, the Sub New constructor will only run once: when an object is created. Sub New can only be called explicitly in the first line of code of another constructor, from either the same class or a derived class using the MyBase keyword.
This is an animated slide. It begins by showing the first example. Click the slide to reveal an example of overloading.
The change in Visual Basic .NET from the Class_Initialize event to the Sub New constructor means you can overload the New subroutine and create as many class constructors as you require. This is useful if you want to initialize your object when you instantiate it. To do this in Visual Basic 6.0, you must call methods or properties after the object is created.
14
Overloading Constructors
You can overload constructors just as you can overload any other method in a class. However, you cannot use the Overloads keyword when overloading constructors. The following example shows how to overload the New subroutine and create multiple class constructors:
Public Sub New( ) intValue = 1 End Sub 'Perform simple initialization
Public Sub New(ByVal i As Integer) 'Perform more complex initialization intValue = i End Sub Public Sub New(ByVal i As Integer, _ ByVal s As String) intValue = i strValue = s End Sub
15
Using Destructors
To explain destructors and their syntax in Visual Basic .NET.
Topic Objective
Sub Finalize replaces Class_Terminate event Use to clean up resources Code executed when destroyed by garbage collection Important: destruction may not happen immediately
Protected Protected Overrides Overrides Sub Sub Finalize( Finalize( ) ) 'Can close connections or other 'Can close connections or other resources resources conn.Close conn.Close End End Sub Sub
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you can control what happens during the destruction of objects by using procedures called destructors. Delivery Tip The new Finalize destructor replaces the Class_Terminate event found in previous versions of Visual Basic. This subroutine is executed when your object is destroyed, and you can use it to clean up open resources, such as database connections, or to release other objects in an object model hierarchy. The following example shows how to use the Finalize destructor:
Protected Overrides Sub Finalize( ) 'Can close connections of other resources conn.Close End Sub
Point out that the Finalize method should only be used where necessary so it doesnt cause unnecessary processing during object clean-up.
Note You will learn about the Overrides keyword in the Inheritance lesson in this module. Delivery Tip In Visual Basic 6.0, the Class_Terminate event runs when an object is no longer being referenced by any variables. You use the Set x = Nothing statement to release a particular reference. When all the references are gone, the event executes and resources can be cleaned up. In Visual Basic .NET, when you set an object reference to Nothing, you still release variables. However, the object may not be destroyed until a later stage due to the introduction of garbage collection.
Point out that garbage collection is covered in more depth in the next lesson.
16
Instantiating and Initializing Objects Garbage Collection Using the Dispose Method
Lead-in
In this lesson, you will learn about creating and destroying objects.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn about creating and destroying objects. After completing this lesson, you will be able to: Instantiate and initialize objects. Explain the role that garbage collection plays in the object life cycle. Use the Dispose method to destroy an object and safely clean up its resources.
17
Lead-in
The method for instantiating and initializing objects has changed in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can now instantiate and initialize objects in one line of code. This means you can write simpler and clearer code that can call different class constructors for multiple variables. Delivery Tip
This is an animated slide. It begins by showing the first part of the example. Click the slide to reveal the following sections: 1. c2 example 2. c3 example 3. c4 and c5 example
Example 1
The following example shows how to declare a variable in one line and instantiate it in a following line. Remember that the Set keyword is no longer needed.
'Declare but do not instantiate yet Dim c1 As TestClass 'Other code c1 = New TestClass( ) 'Instantiate now
Example 2
The following example shows how to declare, instantiate, and initialize an object in one statement. The default constructor for the class will be executed. Delivery Tip
'Declare, instantiate & initialize using default constructor Dim c2 As TestClass = New TestClass( )
Ensure that students are aware of the differences between the behavior of the following statement in Visual Basic .NET as opposed to previous versions of Visual Basic: Dim x As New TestClass
18
Example 3
The following example performs the same functionality as Example 2. It looks similar to code from previous versions of Visual Basic, but behaves quite differently.
'Declare, instantiate & initialize using default constructor Dim c3 As New TestClass
Example 4
The following examples show how to declare, instantiate, and initialize objects in single statements. Both statements call alternative constructors for the class.
'Declare, instantiate & initialize using alternate constructor Dim c4 As New TestClass(10) Dim c5 As TestClass = New TestClass(10)
19
Garbage Collection
Topic Objective
To explain garbage collection and how it affects object lifetime.
Background process that cleans up unused variables Use x = Nothing to enable garbage collection Detects objects or other memory that cannot be reached by any code (even circular references!) Allows destruction of object No guarantee of when this will happen Potential for resources to be tied up for long periods of time (database connections, files, and so on) You can force collection by using the GC system class
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In previous versions of Visual Basic, object destruction is based on a reference count. References are removed when you set the object to Nothing or when the variable goes out of scope. When all references to an object have been removed, the object is destroyed. This is effective in most situations, but some objects, such as those left orphaned in a circular reference relationship, may not be destroyed. In Visual Studio .NET, setting an object reference to Nothing or allowing it to go out of scope removes the link from the variable to the object and allows garbage collection to take place. This background process traces object references and destroys those that cannot be reached by executing code, including objects that are not referenced. Some time after the garbage collection has run, the object destructor code will run (the Finalize method discussed earlier in this module.) Garbage collection provides several performance advantages: It cleans up circular references and improves code performance because objects do not need to keep a reference count. Because reference counting is no longer required, the time taken to instantiate an object is reduced. The time taken to release an object variable reference is reduced. No storage is required for the reference count, which means that the amount of memory that an object uses is also reduced.
20
It is important to note that garbage collection introduces a time delay between when the last reference to an object is removed and when the collector destroys the object and reclaims the memory. This time delay can be quite significant if the object is holding open resources that may affect the scalability or performance of the application, such as database connections. You can force the collection of unused objects by using the GC (Garbage Collector) system classs Collect method as follows:
GC.Collect( )
However, using the Collect method is not generally recommended because forcing garbage collection may result in poor performance due to the unnecessary collection of other unused objects. Occasionally it is appropriate to use the Collect method when you know that you have created garbage, but this should be done with caution.
21
Lead-in
One way to overcome the time-delay issue of finalization is to use a standard method such as the Dispose method.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Because of the potential time delay created by finalization, you may want to create a standard method called Dispose for your class. Many Visual Studio .NET objects use this method to clean up resources. When client code has no further need for an objects resources, it can directly call code placed in the Dispose method of the object. If the client code does not call the Dispose method explicitly before garbage collection occurs, the Finalize method of the class can also call the Dispose method. For this reason you should write your Dispose method to be safely callable multiple times without throwing an exception.
This is an animated slide. It begins by showing the Dispose example. Click the slide to reveal the client code example. Point out that you must be cautious when executing code in the Finalize method if resources have been cleaned up in a Dispose method.
Example
The following simple example shows how to create a Dispose method to manually release resources:
'Class code Public Sub Dispose( ) 'Check that the connection is still open ... conn.Close 'Close a database connection End Sub Protected Overrides Sub Finalize( ) Dispose( ) 'Optional call to Dispose End Sub 'Client code Dim x as TestClass = New TestClass( ) ... x.Dispose( ) 'Call the object's dispose method
22
23
' Dispose(disposing As Boolean) executes in two distinct ' scenarios. If disposing is true, the method has been called ' directly or indirectly by a user's code. Managed and ' unmanaged resources can be disposed. ' If disposing equals false, the method has been called by the ' runtime from inside the finalizer and you should not ' reference other objects. Only unmanaged resources can be ' disposed. Overloads Protected Overridable Sub Dispose(disposing As _ Boolean) ' Check to see if Dispose has already been called. If Not (Me.disposed) Then ' If disposing equals true, dispose all managed ' and unmanaged resources. If (disposing) Then ' Dispose managed resources. Components.Dispose() End If ' Release unmanaged resources. If disposing is false, ' only the following code is executed. CloseHandle(handle) handle = IntPtr.Zero ' Note that this is not thread safe. ' Another thread could start disposing the object ' after the managed resources are disposed,
24
25
26
Topic Objective
Lead-in
This demonstration will show you how to define classes and instantiate and destroy objects.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to define a simple class that uses multiple constructors. You will also learn how to instantiate and use the class from within client code.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
27
Objectives
After completing this lab, you will be able to: Create classes. Instantiate, initialize, and use classes from calling code.
Prerequisites
Before working on this lab, you should be familiar with creating classes in Visual Basic .NET.
Scenario
In this lab, you will begin creating the Cargo system. You will create the Customer class and a test application to instantiate, initialize, and test the class.
28
2. Add the following public properties, and use these to access the private variables created in the previous step.
Property name CustomerID FirstName LastName Email Password Address Company Read/Write access Read-only Read-write Read-write Read-write Read-write Read-write Read-write Data type Integer String String String String String String
29
To define the class methods 1. Add the following methods to the class definition.
Method name LogOn Type Public Sub Parameters
ByVal strEmail As String ByVal strPassword As String ByVal strEmail As String ByVal strPassword As String ByVal strFName As String ByVal strLName As String ByVal strCompany As String ByVal strAddress As String <RETURN VALUE> As Integer <None> ByVal intID As Integer
AddCustomer
Public Function
New New
2. On the File menu, point to Open, and then click File. In the Files of type list, click Text Files. Click Code.txt, and then click Open. 3. Locate the LogOn code in Code.txt. Copy the procedure code to the LogOn method of the Customer class. 4. Locate the AddCustomer code in Code.txt. Copy the procedure code to the AddCustomer method of the Customer class. To complete the class constructors 1. In the Customer class, locate the default constructor definition (the Sub New without parameters), and initialize the intCustomerID variable to -1. 2. Locate the alternative constructor code in Code.txt. Copy the procedure code to the parameterized constructor of the Customer class. 3. Save the project.
30
31
To test the LogOn code 1. Set a breakpoint on the first line of the btnLogOn_Click procedure. 2. On the Debug menu, click Start. On the menu form, click Test Logon to display the test form, and then type the following values in the appropriate text boxes.
Text box E-mail Password Value [email protected] password
3. Click the Logon button, and step through the procedure. 4. Confirm that your code retrieves the customer information and displays it correctly in the text boxes. Close the logon form. 5. Click Test Logon and enter the following incorrect values in the appropriate text boxes.
Textbox E-mail Password Value [email protected] john
6. Click the Logon button, and step through the procedure. 7. Confirm that your code causes an exception to be generated and handled by the form. 8. Close the logon form and then quit the application. Remove the breakpoint on btnLogOn_Click.
32
4. Save the project. To test the Retrieve code 1. Set a breakpoint on the first line of the btnRetrieve_Click procedure. 2. On the Debug menu, click Start. On the menu form, click Test Get Details to display the test form, and then type the value 1119 in the CustomerID text box. 3. Click the Retrieve button, and step through the procedure. 4. Confirm that your code retrieves the customer information and displays it correctly in the text boxes. 5. Click the Clear Data button to reset the information, and then type the value 1100 in the CustomerID text box. 6. Click the Retrieve button, and step through the procedure. 7. Confirm that your code causes an exception to be generated and handled by the form. 8. Click the Close button and then quit the application. Remove the breakpoint on btnRetrieve_Click.
33
4. Save the project. To test the Add Customer code 1. Set a breakpoint on the first line of the btnNew_Click procedure. 2. On the Debug menu, click Start. On the menu form, click Test New Customer to display the test form. 3. Enter values in all text boxes. 4. Click the New Customer button, and step through the procedure. 5. Confirm that your code passes the information to the procedure correctly, and that a new ID is returned. 6. Click the Close button and quit the application. Remove the breakpoint on btnNew_Click. 7. Close Visual Studio .NET.
34
Inheritance
Topic Objective
To provide an overview of the topics covered in this lesson.
What Is Inheritance? Overriding and Overloading Inheritance Example Shadowing Using the MyBase Keyword Using the MyClass Keyword
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this lesson, you will learn how to implement class inheritance. After completing this lesson, you will be able to: Inherit from an existing class. Override and overload some base class methods in a derived class. Use the MyBase keyword to access the base class from a derived class. Use the MyClass keyword to ensure that you call the correct class.
Inform students that although inheritance is an important new feature of Visual Basic .NET, you can continue to create classes without inheritance, as in previous versions of Visual Basic.
35
What Is Inheritance?
Topic Objective
To explain the keywords and syntax for class inheritance.
Derived class inherits from a base class Properties, methods, data members, events, and event handlers can be inherited (dependent on scope) Keywords Inherits inherits from a base class NotInheritable cannot be inherited from MustInherit instances of the class cannot be created; must be inherited from as a base class Protected member scope that allows use only by deriving classes
Lead-in
Inheriting a class allows you to use the features of a base class without rewriting the code.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In Visual Basic .NET, you can use inheritance to derive a class from an existing base class. The derived class can inherit all the base class properties, methods, data members, events, and event handlers, making it easy to reuse the base class code throughout an application.
Point out that inheritance can be used to create highly reusable code. However, many applications do not need inheritance and can perform perfectly well without it. Make clear that if inheritance is used, students should not create complex hierarchies that will become unmanageable.
36
'Accessible only in this class or a derived class Protected strName As String ... End Class
Note The derived class is also known as a subclass, and the base class is known as a superclass in Unified Modeling Language (UML) terminology.
37
Derived class can override an inherited property or method Overridable can be overridden MustOverride must be overridden in derived class Overrides replaces method from inherited class NotOverridable cannot be overridden (default) Use Overload keyword to overload inherited property or method
Lead-in
You may want to implement your own logic in a derived class rather than use that of the base class. This is called overriding. You can also extend members of the base class with the Overload keyword.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip When a derived class inherits from a base class, it inherits all the functions, subroutines, and properties of the base class, including any implementation in the methods. Occasionally you may want to create implementation code specific to your derived class rather than using the inherited methods. This is known as overriding. You can also overload methods defined in the base class with the Overloads keyword.
Point out that examples are shown in the student notes but that a fuller example will be discussed on the next slide.
Overriding
Use the following keywords to create your own implementation code within a derived class: Overridable To create your own special implementation of the derived class, specify the Overridable keyword in a base class member definition for a function, subroutine, or property, as shown in the following example:
Public Overridable Sub OverrideMethod( ) MsgBox("Base Class OverrideMethod") End Sub
MustOverride To create a base class member that must be overridden in all derived classes, define the member with the MustOverride keyword. Only the member prototype can be created in the base class, with no implementation code. You can only use this keyword in a base class that is marked as MustInherit. The following example shows how to define a method that must be overridden:
Public MustOverride Sub PerformAction( )
MustOverride methods are useful in base classes because they allow you to define baseline functionality without locking in implementation details that can make them difficult to extend.
38
Overrides To specify that a derived class method overrides the implementation of the base class method, use the Overrides keyword. If the base class method that is being overridden is not marked as Overridable, a compile-time error will occur. The method signature must exactly match the method being overridden, except for the parameter names. The following example shows how to declare a derived class method that overrides the base class implementation:
Public Overrides Sub OverrideMethod( ) MsgBox("Derived Class OverrideMethod") End Sub
Note You can override methods by selecting (Overrides) in the Class Name drop-down list in the IDE, and then selecting the method you want to override. NotOverridable Base class members without the Overridable keyword are, by default, not overridable. However, if a base class member is marked as overridable, then the member will be overridable in any derived classes based on the immediate deriving class. To prevent this behavior, mark the overridden method in the derived class as NotOverridable. This will stop subsequent inheritance from overriding the method. The following example shows how to declare a derived class method that overrides the base class implementation but does not allow any further overriding:
Public NotOverridable Overrides Sub OverrideMethod( ) MsgBox("Derived Class OverrideMethod") End Sub
Overloading
You can create a method in a derived class that overloads a method defined in a base class by using the Overloads keyword. Just as for overloading methods within the same class, the method signatures must include different parameters or parameter types. The following example shows how to overload a method from a base class:
Public Overloads Sub Other(ByVal i As Integer) MsgBox("Overloaded CannotOverride") End Sub
Note that the base class method does not need to be marked as Overridable to be overloaded.
39
Inheritance Example
Topic Objective
To provide an example of inheritance.
Public Public Class Class BaseClass BaseClass Public Public Overridable Overridable Sub Sub OverrideMethod( OverrideMethod( )) MsgBox("Base MsgBox("Base OverrideMethod") OverrideMethod") End End Sub Sub Public Public Sub Sub Other( Other( ) ) MsgBox("Base MsgBox("Base Other Other method method not not overridable") overridable") End End Sub Sub End End Class Class Public Public Class Class DerivedClass DerivedClass Inherits Inherits BaseClass BaseClass Public Public Overrides Overrides Sub Sub OverrideMethod( OverrideMethod( )) MsgBox("Derived MsgBox("Derived OverrideMethod") OverrideMethod") End End Sub Sub End End Class Class Dim Dim x x As As DerivedClass DerivedClass = = New New DerivedClass( DerivedClass( ) ) x.Other( 'Displays x.Other( ) ) 'Displays "Base "Base Other Other method method not not overridable" overridable" x.OverrideMethod( x.OverrideMethod( ) ) 'Displays 'Displays "Derived "Derived OverrideMethod" OverrideMethod"
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** There are three parts to this inheritance example: Delivery Tip Code for the base class Code for the derived class Code for the calling client
This is an animated slide. It begins by showing an example of code for base class. Click the slide to reveal the following sections: 1. Derived class example 2. Client code example Explain the example from the slide, and then look at the examples in the notes.
40
The following table explains the methods used in the preceding code.
Method PerformAction OverrideMethod Other Declared as MustOverride Overridable NotOverridable (by default) Description Any implementation for this method must be created in the deriving class. Any implementation for this method can be overridden as a derived class. Any implementation for this method cannot be overridden in a derived class. NotOverridable is the default for any method.
Because the PerformAction method was marked as MustOverride in the base class, it must be overridden in this derived class. This derived class also marks the method as NotOverridable so that no other class can override this method if DerivedClass is used as a base class for inheritance. The method OverrideMethod is overridden in this derived class. Any calls to OverrideMethod will result in the derived class implementation being executed rather than the base class implementation. The Other method cannot be overridden, but can be overloaded by the derived class using the Overloads keyword.
Calling Code
The preceding example defines and instantiates a DerivedClass variable. The following example shows how to call all the individual methods for the derived class. The results are shown as comments in the code.
Dim x As DerivedClass = New DerivedClass( ) x.Other( ) 'Displays "Base Other method not overridable" x.Other(20) 'Displays "Overloaded Other" x.OverrideMethod( ) 'Displays "Derived OverrideMethod" x.PerformAction( ) 'Displays "Derived PerformAction"
41
Shadowing
To describe the concept of shadowing and explain how to shadow a method in a derived class.
Topic Objective
Lead-in
Class Class aShadowed aShadowed Inherits Inherits aBase aBase Public Public Shadows Shadows Sub Sub M1(ByVal M1(ByVal ii As As Integer) Integer) 'Clients 'Clients can can only only see see this this method method ... ... End End Sub Sub End End Class Class Dim Dim x x As As New New aShadowed( aShadowed( ) ) x.M1( 'Generates x.M1( ) ) 'Generates an an error error x.M1(20) 'No x.M1(20) 'No error error
*****************************ILLEGAL FOR NON-TRAINER USE****************************** When a derived class inherits from a base class, it can either override a method on the base class or shadow it. Overriding replaces the existing method based on the method name and signature. Shadowing effectively hides the method in the base class, based solely on the method name. This means shadowing a method also hides any overloaded methods within the base class. You can shadow a method regardless of whether the base method is specified as overridable. To learn how shadowing works, consider an example of a derived class that shadows a method from the base class. The method in the base class has not been specified as overridable.
42
The following example shows a base class that defines a single method called M1. The derived class declares an M1 method that automatically shadows the base class method and accepts a single argument. The client code can only access the shadowed method that accepts the argument, and an error will be generated if it attempts to access the base class method.
Class aBase Public Sub M1( ) 'Non-overridable by default ... End Sub End Class Class aShadowed Inherits aBase Public Shadows Sub M1(ByVal i As Integer) 'Clients can only see this method ... End Sub End Class 'Client Code Dim x As New aShadowed( ) x.M1( ) 'Generates an error because method is hidden x.M1(20) 'No error
43
Lead-in
Refers to the immediate base class Can only access public, protected, or friend members of base class Is not a real object (cannot be stored in a variable)
Public Public Class Class DerivedClass DerivedClass Inherits Inherits BaseClass BaseClass Public Public Overrides Overrides Sub Sub OverrideMethod( OverrideMethod( ) ) MsgBox("Derived OverrideMethod") MsgBox("Derived OverrideMethod") MyBase.OverrideMethod( MyBase.OverrideMethod( ) ) End End Sub Sub End End Class Class
Sometimes you need to access the base class from a derived class.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the MyBase keyword to access the immediate base class from which a derived class is inheriting. When using MyBase, you should be aware of some limitations: Delivery Tip It refers only to the immediate base class in the hierarchy. You cannot use MyBase to gain access to classes higher in the hierarchy. It allows access to all of the public, protected, or friend members of the base class. It is not a real object, so you cannot assign MyBase to a variable. If a derived class is overriding a method from a base class but you still want to execute the code in the overridden method, you can use MyBase. This is a common practice for constructors and destructors. The following example shows how to use the MyBase keyword to execute a method as implemented in the base class:
Public Class DerivedClass Inherits BaseClass Public Sub New() MyBase.New() 'Call the constructor of the base class intValue = 1 End Sub Public Overrides Sub OverrideMethod() MsgBox("Derived OverrideMethod") MyBase.OverrideMethod() 'Call the original method End Sub End Class
Calling the constructor of a base class is a common use of the MyBase keyword.
44
Lead-in
It is important that you call the correct class in inheritance. The MyClass keyword can help you call the right one.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can use the MyClass keyword to ensure that a base class implementation of an overridable method is called, rather than that of a derived class. MyClass always refers to the class within which the current code is running. When using MyClass, you should be aware of the following limitations: It allows access to all of the public, protected, or friend members of the deriving class. It is not a real object, so you cannot assign MyClass to a variable.
Point out the important note in the student notes regarding the differences between the MyClass and Me keywords.
Example
The following example shows how to call a base class method from a derived class by using the MyClass keyword:
Public Class BaseClass Public Overridable Sub OverrideMethod( ) MsgBox("Base OverrideMethod") End Sub Public Sub Other( ) MyClass.OverrideMethod( ) End Sub End Class
Public Class DerivedClass Inherits BaseClass Public Overrides Sub OverrideMethod( ) MsgBox("Derived OverrideMethod") End Sub End Class Dim x As DerivedClass = New DerivedClass( ) x.Other( )
45
Output
The output from the execution of the preceding code is as follows:
Base OverrideMethod
Flow of Execution
The code in the example is executed as follows: 1. The Other method is called on the DerivedClass object, but because there is no implemented code in the derived class, the base class code is executed. 2. When the MyClass.OverrideMethod call is executed, the OverrideMethod subroutine is implemented in the base class. 3. Execution returns to the client code. Important The Me keyword in previous versions of Visual Basic is not the same as the MyClass keyword. The Me keyword has the same effect as if no keyword were used. In the example in this topic, the derived class implementation would be executed even if Me were used within the base class.
46
Demonstration: Inheritance
To demonstrate class inheritance.
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will see how to define a base class with a mixture of overridable and non-overridable methods. You will see how to derive a class that inherits from the base class, and how to use the MyBase keyword.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
47
Interfaces
Topic Objective
To provide an overview of the topics covered in this lesson.
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this lesson, you will learn how to use interfaces to achieve polymorphism. After completing this lesson, you will be able to: Define an interface by using the Interface keyword. Add member signatures that define the properties, methods, and events that your interface supports. Implement an interface by using the Implements keyword.
This lesson assumes some knowledge about interfaces and polymorphism. The topic is not covered extensively because interfaces and polymorphism are not new to Visual Basic .NET. You should ensure that students are aware of additional appropriate information.
48
Defining Interfaces
Topic Objective
To explain how to create interfaces in Visual Basic .NET.
Interfaces define public procedure, property, and event signatures Use the Interface keyword to define an interface module Overload members as for classes
Interface Interface IMyInterface IMyInterface Function Function Method1(ByRef Method1(ByRef s s As As String) String) As As Boolean Boolean Sub Sub Method2( Method2( ) ) Sub Sub Method2(ByVal Method2(ByVal i i As As Integer) Integer) End End Interface Interface
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** An interface defines signatures for procedures, properties, and events but contains no implementation code. These signatures define the names of the members, the parameter details, and the return values. Interfaces form a binding contract between clients and a server. This contract enables a client application to ensure that a class will always support particular member signatures or functionality, and this aids in the versioning of components. Delivery Tip In Visual Basic 6.0, interfaces are created automatically whenever a public class is compiled as part of a COM component. This functionality works fine in most situations; however, you need to create a class in order to define an interface, which is not always necessary from a developers perspective. Visual Basic .NET introduces the Interface keyword, which allows you to explicitly create an interface without creating a class. Interfaces can be defined in the Declarations section of any module. This new approach creates a visible distinction between a class and an interface, and this makes the concept clearer for the developer. You can use overloading when you define interfacesjust as you use it to define classesto create multiple versions of a member signature with different parameters.
Check student understanding of the concept of interfaces. Give a brief review if necessary, with a simple example of interfaces (such as the IPerson, Student, Employee example used in the notes).
49
Example
The following example shows how to define an interface that includes three method signatures, two of which are overloaded:
Interface IMyInterface Function Method1(ByRef s As String) As Boolean Sub Method2( ) Sub Method2(ByVal i As Integer) End Interface
An interface can also inherit another interface if you use the Inherits keyword before any member signatures are defined. If an interface is inherited from the above example, it will contain all of the base interface signatures, in addition to those defined in the new interface definition.
50
Achieving Polymorphism
Topic Objective
To explain how to use polymorphism in Visual Basic .NET.
Polymorphism Many classes provide the same property or method A caller does not need to know the type of class the object is based on Two approaches Interfaces Class implements members of interface Same approach as in Visual Basic 6.0 Inheritance Derived class overrides members of base class
Lead-in
Visual Basic .NET combines a traditional use of interfacesto create polymorphismwith the new class inheritance features.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Polymorphism is achieved when multiple classes provide the same properties or methods and the calling code does not need to know what type of class the object is based on. This creates a form of reuse because you can write generic client code to handle multiple types of classes without knowing about the methods of each individual class. You can use two different approaches to achieve polymorphism in Visual Basic .NET: interfaces and inheritance. Delivery Tip
The code shown in the student notes is demonstrated immediately after this topic.
Interfaces
In Visual Basic 6.0, you can achieve polymorphism by creating an abstract classwith the sole purpose of defining an interfaceand then implementing that interface in other classes by using the Implements keyword. This approach allows multiple classes to share the same interface and allows classes to have multiple interfaces. In Visual Basic .NET, you do not need abstract classes to achieve polymorphism. You can create interfaces explicitly by using a combination of the Interface and Implements keywords.
51
Example
The following example shows how to implement polymorphism in Visual Basic .NET. As you examine this code, note the following: The IPerson interface defines two member signatures: LastName and Display. The Employee class implements the IPerson interface and both of its members. By using the Implements keyword for each individual method, you can specify your own name for the method and it will still be executed if a client application requests the original name of the interface.
Interface IPerson 'IPerson interface definition Property LastName( ) As String Sub Display( ) End Interface Class Employee 'Employee class definition Implements IPerson 'Implements IPerson interface Private strName As String Private strCompany As String 'This method is public but also implements IPerson.Display Public Sub Display( ) Implements IPerson.Display MsgBox(LastName & " " & Company,, "Employee") End Sub 'This property is private but implements IPerson.LastName Private Property LastName( ) As String _ Implements IPerson.LastName Get Return strName End Get Set (ByVal Value As String) ... End Set End Property Public Property Company( ) As String ... End Property End Class
52
The following code shows how the Employee class and IPerson interface could be used in a client application or within the same assembly as the class and interface definitions. An Employee object is instantiated and details specific to the employee, such as the Company property, are assigned. An IPerson interface variable is then assigned to the Employee object to access methods that can only be accessed through the IPerson interface, such as the LastName property. Both calls to the Display methods actually call the same code within the Employee class, as shown in the previous example.
Dim perPerson As IPerson, empEmployee As New Employee( ) empEmployee.Company = "Microsoft" perPerson = empEmployee perPerson.LastName = "Jones" perPerson.Display( ) 'Call the display method on the interface empEmployee.Display( ) 'Display method is defined as public
Inheritance
Another way to achieve polymorphism with Visual Basic .NET is to use class inheritance. A base class can be created that contains member signatures and that optionally contains implementation code that can be inherited in a derived class. The derived class must then override the individual methods with its own implementation code, achieving unique functionality while retaining a common method signature. Note For more information about polymorphism, search for Polymorphism in the Visual Studio .NET documentation.
53
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create an interface and implement it to achieve polymorphism in two separate classes.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
54
Using Shared Data Members Using Shared Procedure Members Event Handling What Are Delegates? Using Delegates Comparing Classes to Structures
Lead-in
This lesson examines how to work with classes in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn how to work with classes. After completing this lesson, you will be able to: Use shared data members to share data across class instances. Use shared procedure members. Define and handle class events. Use delegates in event handling. Describe how structures differ from classes.
55
Topic Objective
Lead-in
Shared data members allow data sharing for all instances of a class.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In Visual Basic 6.0, you can share data among objects by using a module file and a global variable. This approach works, but there is no direct link between the objects and the data in the module file, and the data is available for anyone to access. In Visual Basic .NET, you can use shared data members to allow multiple instances of a class to refer to a single instance of a class-level variable. You can use shared members for counters or for any common data that is required by all instances of a class. An advantage of shared data members is that they are directly linked to the class and can be declared as public or private. If you declare data members as public, they are accessible to any code that can access the class. If you declare the data members as private, provide public shared properties to access the private shared property.
This is an animated slide. It begins by showing the Shared example code. Click the slide to reveal an example of client code.
56
The following example shows how you can use a shared data member to maintain interest rates for a savings account. The InterestRate data member of the SavingsAccount class can be set globally regardless of how many instances of the class are in use. This value is then used to calculate the interest on the current balance.
Class SavingsAccount Public Shared InterestRate As Double Public Name As String, Balance As Double Sub New(ByVal strName As String, _ ByVal dblAmount As Double) Name = strName Balance = dblAmount End Sub Public Function CalculateInterest( ) As Double Return Balance * InterestRate End Function End Class
The following code shows how a client application can use the SavingsAccount class in the previous example. As you examine this code, note the following: The InterestRate can be set before and after any instances of the SavingsAccount object are created. Any changes to the InterestRate will be seen by all instances of the SavingsAccount class.
Sub Test( ) SavingsAccount.InterestRate = 0.003 Dim acct1 As New SavingsAccount("Joe Howard", 10000) Dim acct2 As New SavingsAccount("Arlene Huff", 5000) MsgBox(acct1.CalculateInterest, , "Interest for " & _ acct1.Name) MsgBox(acct2.CalculateInterest, , "Interest for " & _ acct2.Name) End Sub
57
The following example shows how to implement a public shared property for a private shared data member:
Class SavingsAccount Private Shared InterestRate As Double Shared Property Rate( ) Get Return InterestRate End Get Set(ByVal Value) InterestRate = Value End Set End Property End Class
The following code shows how a client application can use the shared property in the previous example:
SavingsAccount.Rate = 0.003
58
Lead-in
Share procedures without declaring a class instance Similar functionality to Visual Basic 6.0 global classes Can only access shared data
'TestClass 'TestClass code code Public Public Shared Shared Function Function GetComputerName( GetComputerName( ) ) As As String String ... ... End End Function Function 'Client 'Client code code MsgBox(TestClass.GetComputerName( MsgBox(TestClass.GetComputerName( )) ))
You can create shared procedure members that allow you to call the method without creating an instance of the class.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can use shared procedure members to design functions that can be called without creating an instance of the class. Shared procedures are particularly useful for creating library routines that other applications can easily access. This concept is similar to the GlobalMultiUse and GlobalSingleUse classes used in Visual Basic 6.0. As described in the previous topic, shared members can only access data that is marked as Shared. For example, a shared method cannot access a module level variable that is marked as Dim, Private, or Public.
Point out that this feature is often used for library routines.
Example
The following example shows how a commonly used function, such as GetComputerName, can be created as a shared procedure member so that a client application can easily use it. The client only needs to reference the method prefixed by the class name because no instance of the class is required.
'TestClass code Public Shared Function GetComputerName( ) As String ... End Function 'Client code MsgBox(TestClass.GetComputerName( ))
59
Event Handling
To introduce event-handling options that are new in Visual Basic .NET.
Topic Objective
Defining and raising events: same as Visual Basic 6.0 WithEvents keyword: handles events as in Visual Basic 6.0 In Visual Basic .NET, works with Handles keyword to specify method used to handle event AddHandler keyword: allows dynamic connection to events
Dim Dim x x As As New New TestClass( TestClass( ), ), y y As As New New TestClass( TestClass( ) ) AddHandler x.anEvent, AddressOf HandleEvent AddHandler x.anEvent, AddressOf HandleEvent AddHandler AddHandler y.anEvent, y.anEvent, AddressOf AddressOf HandleEvent HandleEvent ... ... Sub Sub HandleEvent(ByVal HandleEvent(ByVal i i As As Integer) Integer) ... ... End End Sub Sub
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** As a Visual Basic developer, you are familiar with creating events. However, Visual Basic .NET provides powerful new event handling features with the addition of the Handles, AddHandler and RemoveHandler keywords.
Example
The following example shows how to define and raise an event:
'TestClass code Public Event anEvent(ByVal i As Integer) Public Sub DoAction( ) RaiseEvent anEvent(10) End Sub
You can use the WithEvents keyword in the same way that you used it in Visual Basic 6.0. However, in Visual Basic .NET you also use the Handles keyword to specify which method will be used to handle an event. You can link an event to any handler, whether it is the default handler or your own method. This approach allows you to link multiple events with a single method handler, as long as the parameters match those of the events.
60
Example
The following example shows how you can use WithEvents in conjunction with the new Handles keyword to link an event with a handler.
'Client code Dim WithEvents x As TestClass Dim WithEvents y As TestClass Private Sub Button1_Click(...) Handles Button1.Click x = New TestClass( ) y = New TestClass( ) x.DoAction( ) y.DoAction( ) End Sub Private Sub HandleEvent(ByVal x As Integer) _ Handles x.anEvent, y.anEvent ... End Sub
Syntax
The syntax for AddHandler is shown below.
AddHandler object.EventName, AddressOf methodName
Example
The following example shows a single method handler called HandleEvent being used for two instances of TestClass:
Dim x As New TestClass( ), y As New TestClass( ) AddHandler x.anEvent, AddressOf HandleEvent AddHandler y.anEvent, AddressOf HandleEvent
61
Syntax
The syntax for RemoveHandler is shown below.
RemoveHandler object.EventName, AddressOf methodName
Note AddressOf creates a reference to a procedure that can be passed to appropriate methods. It was introduced in previous versions of Visual Basic. For more information about AddressOf, search for AddressOf in the Visual Studio .NET documentation.
62
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to define and raise events in a class and how to handle them in client code.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
63
Topic Objective
Objects that call the methods of other objects Similar to function pointers in Visual C++ Reference type based on the System.Delegate class Type-safe, secure, managed objects Example: Useful as an intermediary between a calling procedure and the procedure being called
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The common language runtime supports objects called delegates that can call the methods of other objects dynamically. Delegates are sometimes described as type-safe function pointers because they are similar to the function pointers used in other programming languages. Unlike function pointers, Visual Basic .NET delegates are a reference type based on the class System.Delegate and can reference both shared methods (methods that can be called without a specific instance of a class) and instance methods. Delegates provide the same flexibility as function pointers in Microsoft Visual C++ without the risk of corrupted memory because they are type-safe, secure, managed objects. Delegates are useful when you need an intermediary between a calling procedure and the procedure being called. For example, you might want an object that raises events to be able to call different event handlers under different circumstances. Unfortunately, the object raising events cannot know ahead of time which event handler is handling a specific event. Visual Basic .NET allows you to dynamically associate event handlers with events by creating a delegate for you when you use the AddHandler statement. At run time, the delegate forwards calls to the appropriate event handler.
64
Using Delegates
Topic Objective
To provide an example of how to use delegates in event handling.
Lead-in
Delegate keyword declares a delegate and defines parameter and return types
Delegate Delegate Function Function CompareFunc( CompareFunc( _ _ ByVal ByVal x x As As Integer, Integer, ByVal ByVal y y As As Integer) Integer) As As Boolean Boolean
Lets look at an example of how you can use delegates in event handling.
Methods must have the same function parameter and return types Use Invoke method of delegate to call methods
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You use the Delegate keyword to declare a delegate function signature that defines the parameter and return types. Only methods that have the same function parameter and return types can be used with a particular delegate object.
Example
To learn how delegates work, consider an example that shows how to declare a delegate function signature, create methods to accept the parameter types you have defined, and call the functions by using the delegate object. The final part of this example shows how to use the delegate to perform a bubble sort.
The following code shows how to create a delegate function called CompareFunc, which takes two Integer parameters and returns a Boolean value.
Delegate Function CompareFunc( _ ByVal x As Integer, ByVal y As Integer) As Boolean
Creating Methods
After you create a delegate, you can then create methods that accept the same parameter types, as follows:
Function CompareAscending( _ ByVal x As Integer, ByVal y As Integer) As Boolean Return (y > x) End Function Function CompareDescending( _ ByVal x As Integer, ByVal y As Integer) As Boolean Return (x > y) End Function
65
Calling Methods
After you create the necessary functions, you can write a procedure to call these two functions by using a delegate object as follows:
Sub SimpleTest( ) Dim delDelegate As CompareFunc delDelegate = New CompareFunc(AddressOf CompareAscending) MsgBox(delDelegate.Invoke(1, 2)) delDelegate = New CompareFunc(AddressOf CompareDescending) MsgBox(delDelegate.Invoke(1, 2)) End Sub
66
The following code shows how to call the bubble sort procedure:
Sub TestSort( ) Dim a( ) As Integer = {4, 2, 5, 1, 3} BubbleSort(1, a) 'Sort using 1 as ascending order MsgBox(a(0) & a(1) & a(2) & a(3) & a(4), , "Ascending") BubbleSort(2, a) 'Sort using 2 as descending order MsgBox(a(0) & a(1) & a(2) & a(3) & a(4), , "Descending") End Sub
67
Lead-in
Classes
Can define data members, properties, and methods Support constructors and member initialization Support Finalize method Extensible by inheritance Reference type
Structures
Can define data members, properties, and methods No default constructor or member initialization Do not support Finalize method Do not support inheritance Value type
Classes and structures have similar functionality, but classes provide a more powerful basis for objectoriented development.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Classes and structures are similar in several ways: both can define data members, properties, and methods. However, classes provide some advanced features that developers can use.
Classes Initialization Finalize method Inheritance Data type Supports constructors and member initialization. Support Finalize method. Extensible by inheritance. Reference data type. When an object variable is passed to a function, the address reference of the data is passed rather than the data itself. Assigning one class variable to another points both variables to the same object. Any updates to either variable will therefore affect the other. Structures No default constructor and no initialization of members. Do not support Finalize method. You must manually release resources. Do not support inheritance. Value data type. When a structure variable is passed to a function, the actual data must be copied to the function. Assigning one structure variable to another creates an actual copy of the structure. Updates to one of the variables will therefore not affect the other.
68
Objectives
After completing this lab, you will be able to: Create base classes. Create derived classes that use inheritance. Use inherited classes from calling code.
Prerequisites
Before working on this lab, you should be familiar with inheritance in Visual Basic .NET.
Scenario
In this lab, you will continue creating the Cargo system. You will create the Package base class, the SpecialPackage derived class, and the test application. Some of the code has been created for you.
69
70
To inherit from the Package class 1. At the top of the SpecialPackage class, locate the list of private variables. Insert the following line immediately before the variable declarations:
Inherits Package
This will create the relationship between the Package base class and the derived class SpecialPackage. 2. Add the following methods to the SpecialPackage class definition:
Method name GetDetails Type
Public Overrides Sub Public Overloads Function
Parameters
ByVal intID As Integer
CreatePackage
ByVal intDeliveryID As Integer ByVal strDescription As String ByVal strDimensions As String ByVal strInstructions As String ByVal strWeight As String ByVal dblValue As Double ByVal blnOxygen As Boolean ByVal strTemperature As String ByVal strTimeLimit As String ByVal strExtra As String <RETURN VALUE> As Integer ByVal intID As Integer
DeletePackage
To implement the GetDetails method 1. Locate the GetDetails method declaration and add code to call the MyBase.GetDetails method, passing the intID as the parameter to retrieve the simulated Package details. 2. After the call to MyBase.GetDetails, assign the following values to the SpecialPackage properties to simulate a returned record from the database:
Property OxygenRequired Temperature TimeLimit ExtraInstructions Value True 80 5 hours Feed if time limit exceeded
71
To implement the CreatePackage method 1. Locate the CreatePackage method declaration, and add code to call the MyBase.CreatePackage method, passing in the following values as the parameters to create the simulated Package record.
Parameter Name Value
2. After the call to MyBase.CreatePackage, assign the following values to the SpecialPackage properties to simulate the update to the database.
Property OxygenRequired Temperature TimeLimit ExtraInstructions Value blnOxygen strTemperature strTimeLimit strExtra
3. After the property value assignments, use the MsgBox function to display the message Special instructions added. 4. Return the PackageID as the return value of the CreatePackage method. To implement the DeletePackage method 1. Locate the DeletePackage method declaration, and insert code to use the MsgBox function to display the message Deleting special package details to simulate the deletion of the SpecialPackage database record. 2. After the displaying the message, call the MyBase.DeletePackage method, passing intID as the parameter, to simulate the deletion of the Package record. 3. Save the project.
72
txtDeliveryID.Text txtDescription.Text txtDimensions.Text txtInstructions.Text txtValue.Text txtWeight.Text txtExtra.Text txtTemperature.Text txtTimeLimit.Text chkOxygen.Checked
DeliveryID Description Dimensions Instructions Value Weight ExtraInstructions Temperature TimeLimit OxygenRequired
73
To use the Package object 1. In the false block of the If statement, set the Checked property of chkSpecial to False, and declare and instantiate a Package variable called aPackage. 2. Call the GetDetails method of the aPackage object, passing in the Text property of txtID as the parameter. (Use the CInt function to convert the text value into an Integer.) 3. Display the properties of the aPackage object in the appropriate textboxes. Use the information in the following table to assign the text box values to the properties of the aPackage object.
Control Property of aPackage
txtDeliveryID.Text txtDescription.Text txtDimensions.Text txtInstructions.Text txtValue.Text txtWeight.Text txtExtra.Text txtTemperature.Text txtTimeLimit.Text chkOxygen.Checked
4. Save the project. To test the Retrieve button code 1. Set a breakpoint on the first line of the btnRetrieve_Click procedure. On the Debug menu, click Start. 2. Enter the value 18 in the Package ID box, click the Retrieve button, and then step through the procedure. 3. Confirm that your code retrieves the package information and displays it correctly in the text boxes. 4. Click the Clear Data button to reset the information. 5. Enter the value 33 in the Package ID box, click the Retrieve button, and step through the procedure. 6. Confirm that your code retrieves the special package information and displays it correctly in the text boxes. 7. Click the Close button to quit the application. Remove the breakpoint on btnRetrieve_Click.
74
75
To create a SpecialPackage object 1. In the true part of the If statement, declare and instantiate a SpecialPackage variable called aPackage. 2. Call the overloaded CreatePackage method of the aPackage object and store the return value in the Text property of the txtID box. (Use the CStr function to convert the Integer to a String.) Pass the following values as parameters to the method.
Parameter intDeliveryID strDescription strDimensions strInstructions strWeight dblValue blnOxygen strTemperature strTimeLimit strExtra Value CInt(txtDeliveryID.Text) txtDescription.Text txtDimensions.Text txtInstructions.Text txtWeight.Text CDbl(txtValue.Text) chkOxygen.Checked txtTemperature.Text txtTimeLimit.Text txtExtra.Text
3. Save the project. To test the standard Package code 1. Set a breakpoint on the first line of the btnNew_Click procedure. 2. On the Debug menu, click Start. 3. Enter the following values.
Control DeliveryID Description Instructions Dimensions Weight Value Value 11 Software None NA NA 50
4. Click the New button, and step through the procedure. 5. Confirm that the code correctly passes the values to the package class. 6. Click the Clear Data button.
76
2. Click the New button, and step through the procedure. 3. Confirm that the code passes the values to the SpecialPackage class correctly. 4. Click the Close button to quit the application, and remove the breakpoint on btnNew_Click.
77
78
Review
Topic Objective
To reinforce module objectives by reviewing key points.
Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. Create code that defines multiple constructors for a Person class. The first constructor will not take any arguments. The second will take two string values: FirstName and LastName.
Class Person Sub New( ) 'Default constructor End Sub Sub New(ByVal FirstName As String, _ ByVal LastName As String) 'Second constructor End Sub End Class
2. Garbage collection occurs immediately after all references to an object are removed. True or false? If false, explain why. False. Garbage collection may happen at any time after all object references have been removed.
79
3. Describe the functionality of the MyBase keyword. MyBase is used in a derived class to access methods and properties in the immediate base class.
4. What is a potential problem that may result from the following class code sample? How can you rewrite the code to resolve the problem?
Class Person Private Sub Save( ) 'Save the local data in a database End Sub Sub Dispose( ) Save( ) End Sub Protected Overrides Sub Finalize( ) Dispose( ) MyBase.Finalize( ) End Sub End Class
The Dispose method can be called directly from a client and might be called again when the object is destroyed by garbage collection. This would result in the Save method being called twice, which may create data inconsistencies. To avoid this, use the SuppressFinalize method of the GC class to stop the Finalize method being called after Dispose. Add the line "GC.SuppressFinalize()" in the Dispose method after the Save line as follows):
Sub Dispose() Save() GC.SuppressFinalize() End Sub
80
5. You can create an interface explicitly in Visual Basic .NET. True or false? If false, explain why. True. You can create an interface explicitly by using the InterfaceEnd Interface statement block.
The code will not compile correctly because the signature of the event does not match the signature of the delegate in the AddHandler statement.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 120 Minutes Lab: 45 Minutes This module provides students with the knowledge needed to create Microsoft Windows-based applications. In the lab, students will continue working with the Cargo system. The Customer class from Lab 5.1 has been enhanced for students, and a CustomerList class has been provided to iterate through the customers. The basic Customer form has been provided, but it requires further development. After completing this module, students will be able to: Describe the benefits of Windows Forms. Use the new properties and methods of Windows Forms. Write event-handling code. Use the new controls and control enhancements. Add and edit menus. Create a form that inherits from another form.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_06.ppt Module 6, Using Windows Forms Lab 6.1, Creating the Customer Form
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the practice. Complete the lab.
iv
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
Using Controls
To examine the frmControls code 1. Open the ControlsDemo.sln solution in the install folder\DemoCode\ Mod06\ControlsDemo\Starter folder. 2. Open the design window for frmControls.vb. The purpose of the form is to show the effects of the anchor and dock styles to a Button control. Point out the Anchoring and Docking menus and their menu items. Also, point out the FlatStyle property of the btnClose button in the Properties window. 3. View the code window for the frmControls.vb form. 4. View the Sub ProcessAnchorMenus procedure and examine the code, pointing out that multiple menus are being handled by the one procedure. 5. View the Sub ApplyAnchoring procedure and examine the code. 6. View the Sub ApplyDocking procedure and examine the code.
To test the frmControls form 1. Run the project. 2. Resize the form to show that the Close button does not move. This is because the Top and Left menu items of the Anchoring menu are checked by default. Resize the form to its original size. 3. Use the Anchoring menu to demonstrate the following:
Checked Anchoring menu items No items checked Bottom and Right checked Top, Left, Bottom, and Right checked Purpose Close button stays approximately in the middle of the form. Close button stays close to the bottom and right of the form. Close button grows in direct relation to the form.
4. Using the Docking menu, test each docking option, beginning with the Top menu item and finishing with the Fill menu item. Show the effects these settings have on the Close button. 5. Click the Close button to quit the application. To examine the frmDemo code 1. Open the design window of the frmDemo.vb form. 2. In the Properties window, view the Anchor properties for each control on the form. 3. Open the code window for frmDemo.vb. 4. Locate the Sub New procedure and explain the following line:
Me.MinimumSize = Me.Size
To test the frmDemo form 1. Run the project. 2. On the Other menu, click Display and resize the form to show how the controls behave and how the MinimumSize property affects the form. 3. Close both forms to quit the application.
vi
To add ToolTip, Help, and NotifyIcon controls to frmControls 1. Open the design window for frmControls.vb, and add the following controls to the form, setting the appropriate properties.
Control HelpProvider NotifyIcon Property Name Name Icon Value hpHelp niTray C:\Program Files\Microsoft Visual Studio.NET\ Common7\Graphics\icons\Elements\Cloud.ico (or any available icon) ttToolTip
ToolTip
Name
2. Open the code window for frmControls.vb. 3. Locate the Sub New procedure, and uncomment and explain the lines of code beginning with the following:
'Dim cmTrayMenu As ContextMenu, mItem As MenuItem
To test the ToolTip, Help, and TrayIcon controls 1. Run the application. 2. Pause the mouse over the Close button control to view the ToolTip. 3. Press F1 to display the Help string. 4. Right-click the TrayIcon in the Windows System Tray, and then click Exit. 5. Close Visual Studio .NET.
vii
To test the application 1. Run the project. 2. Click an item in the ListBoxFrom control. Hold down the left mouse button to drag the item to the ListBoxTo control. Point out that the icon is displayed as the Move operation when over the control. Release the item over the control, and debug the code at the preset breakpoint to show the removal of the item from ListBoxFrom. 3. Press F5 to allow execution to continue. 4. Repeat the drag process from the ListBoxFrom control to the ListBoxTo control, but hold down the CTRL key while dragging the control. Point out that the icon is now displayed as the Copy operation when over the ListBoxTo control. Release the item over the list box and debug the code at the preset breakpoint to show that the item is not removed from ListBoxFrom. 5. Click the Close button on the form to close the debugging session. 6. Close the Visual Studio .NET integrated development environment (IDE).
2. Open the code window for frmBase.vb. 3. Locate the btnOK_Click event handler, and change the procedure declaration to be as follows:
Protected Overridable Sub btnOk_Click()
viii
To create the inherited form 1. On the Project menu, click Add Inherited Form to create a new inherited form. Rename the form frmInherited.vb and click Open. Select the frmBase form as the base form, and click OK. 2. Open the design window for the frmInherited.vb form and point out the differences between the Public and Friend controls by resizing the lblProductName label and attempting to resize the btnSysInfo button (which should not resize). 3. Open the code window for frmInherited.vb. 4. Locate the Sub New procedure, and add the following lines before the End Sub:
Me.Text = "About My Application" txtLicensedTo.Text = "Karen Berge" lblProductName.Text = "My Wonderful Application" btnSysInfo.Visible = False
5. Open the modMain.vb file and change the startup form to frmInherited.
Application.Run(New frmInherited( ))
To test the application Run the project, and test the OK button that will close the application. To override the OK button 1. Open the code window for frmInherited.vb. 2. Click (Overrides) in the Class Name box at the top of the code window. Select the btnOk_Click method from the Method Name box. 3. Add the following code to the event handler:
MessageBox.Show("Closing the inherited form.", "Close") MyBase.btnOk_Click(sender, e)
To test the overridden OK button Run the project and test the OK button, confirming that the message box is displayed and the form is then closed, returning to the IDE.
ix
To modify the base form 1. Open the design window for the frmBase.vb form. 2. From the Toolbox, add a Button control just beneath the btnSysInfo button, setting the following properties of the new button.
Property Name Text FlatStyle Image Value btnCall (Empty string) Popup C:\Program Files\Microsoft Visual Studio.NET\Common7\ Graphics\icons\Comm\Phone01.ico
3. Double-click the new button to edit its btnCall_Click event handler, adding the following line:
MessageBox.Show("Dialing help line.", "Help Line")
To test the modified application 1. Run the project and confirm that the new button is automatically displayed in the inherited form before exiting the application. 2. Close Visual Studio .NET.
Module Strategy
Use the following strategy to present this module: Why Use Windows Forms? This lesson shows some of the benefits of using Windows Forms rather than Microsoft Visual Basic forms. This lesson provides an overview because some of these topics are addressed in more detail later in the module. GDI+, printing support, accessibility, and the extensible object model are not covered in any more detail in this module. Extensibility will be covered when user controls are discussed in Module 9, Developing Components in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. Structure of Windows Forms This lesson shows how to use the new Windows Forms object model to create Windows-based applications. Emphasize the object model hierarchy because it is this object-oriented approach that provides the power of Windows Forms. Ensure that students are comfortable with the anatomy of the form code because this may confuse or concern students whose background is limited to Visual Basic. The lesson also discusses various form properties, methods, and events, as well as how to handle those events. Finally, dialog boxes are examined to point out the subtle differences between Visual Basic .NET dialog boxes and those of previous versions of the Visual Basic language. Using Controls This lesson shows how to use some of the new and enhanced controls in a Windows Form. Creating menus with the Menu Designer is not explicitly covered, although you may want to quickly demonstrate the new designer if students have not already used it. The lesson also examines some of the user assistance controls and the new technique for drag-and-drop operations. Windows Form Inheritance This lesson shows how to use visual inheritance through the Windows Forms class library. If students are comfortable with the concept of class inheritance, they will have no trouble extending that knowledge to visual inheritance. The process for creating base forms and inherited forms is examined, as are the effects that modification to a base form can have on those that inherit from it.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Why Use Windows Forms? Structure of Windows Forms Using Windows Forms Using Controls Windows Forms Inheritance
Lead-in
In this module, you will learn about Visual Basic .NET Windows Forms.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This module describes the new Microsoft Windows Forms that are provided by the Microsoft .NET Framework. Windows Forms are the Microsoft Visual Basic .NET version 7.0 equivalent to Visual Basic forms. You will learn about the new features available in Windows Forms and how to make changes to forms and controls, and their properties, methods, and events. You will also learn how to create some of the standard Windows dialog boxes. Finally, you will learn about visual inheritance, which allows you to use objectoriented techniques within your forms. After completing this module, you will be able to: Describe the benefits of Windows Forms. Use the new properties and methods of Windows Forms. Write event-handling code. Use the new controls and control enhancements. Add and edit menus. Create a form that inherits from another form.
Lead-in
Rich set of controls Flat look style Advanced printing support Advanced graphics support GDI+
Accessibility support Visual inheritance Extensible object model Advanced forms design
Windows Forms provide many enhancements over previous versions of Visual Basic forms.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Windows Forms provide many enhancements over standard Visual Basic forms, including: Rich set of controls By using classes in the System.Windows.Forms namespace, you can create Visual Basic .NET applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. This namespace provides the Form class and many other controls that can be added to forms to create user interfaces. Many additional controls are included that were previously only available through external libraries (.ocxs) or third-party products. Some existing controls now allow simple access to properties and methods from the object model instead of requiring complex application programming interfaces (APIs) to perform extended functionality. Flat look style Windows Forms allow you to create applications that use the new flat look style as seen previously in Microsoft Money 2000. Advanced printing support Windows Forms provide advanced printing support through the PageSetupDialog, PrintPreviewControl, PrintPreviewDialog, and PrintDialog controls.
Delivery Tip
Advanced graphics supportGDI+ The System.Drawing namespace provides access to GDI+ basic graphics functionality. GDI+ provides the functionality for graphics in Windows Forms that are accessible in the .NET Framework. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces. You can take full advantage of these system classes to create applications that provide the user with a richer graphical environment. Accessibility support Windows Forms provide accessibility properties for controls so that you can develop applications that people with disabilities can use. Visual inheritance Windows Forms are classes and can benefit from inheritance. Windows Forms can be inherited in derived forms that automatically inherit the controls and code defined by the base form. This adds powerful reuse possibilities to your applications. Extensible object model The Windows Forms class library is extensible, so you can enhance existing classes and controls with your own functionality. You can also create your own designers, similar to the docking or anchoring designers, that will work in the Microsoft Visual Studio .NET integrated development environment (IDE). Advanced forms design Developers have traditionally spent much time writing code to handle form resizing, font changes, and scrolling. Windows Forms provide much of this functionality with built-in properties for docking, anchoring, automatic sizing, and automatic scrolling. These new features allow you to concentrate on the functions of your applications.
GDI+ allows high-powered graphics to be used in Windows Formsbased applications. This allows developers to use any type of graphics file within their applications and to use techniques such as alpha blending, color gradients, and anti-aliasing.
Windows Forms Class Hierarchy Using the Windows.Forms.Application Class Examining the Code Behind Windows Forms
Lead-in
Windows Forms at first appear to be similar to Visual Basic 6.0 forms, but there are structural differences.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Windows Forms appear similar to Visual Basic 6.0 forms, but the structure of the Windows Form code is different from previous Visual Basic forms. This is because the Windows Forms library in the .NET Framework is object oriented. After completing this lesson, you will be able to: Describe several of the classes in the Windows Forms class hierarchy. Use the Windows.Forms.Application class to manage your application at run time. Interpret the code generated by Windows Forms.
Topic Objective
Lead-in
The .NET Framework provides many built-in classes for Windows Forms development.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The .NET Framework provides all of the classes that make up Windows Formsbased applications through the System.Windows.Forms namespace. The inheritance hierarchy provides many common features across the .NET Windows Forms classes, providing a consistent set of properties and methods for many controls and forms. Some of the classes are examined below. Delivery Tip
This is not a definitive list of classes, just the relevant ones for this module.
Control
The Control class is the fundamental base class for other controls. It provides the basic functionality for a control, such as sizing, visibility, and tab order.
ScrollableControl
The ScrollableControl class inherits directly from the Control class and provides automatic scrolling capabilities for any control that requires scroll bars.
ContainerControl
The ContainerControl class inherits directly from the ScrollableControl class and adds tabbing and focus management functionality for controls that can host other controls.
Form
The Form class inherits directly from the ContainerControl class and represents any window displayed in the application. The properties and methods provided by the Form class allow you to display many different types of forms, including dialog boxes and multiple-document interface (MDI) forms. All Windows Forms are derived from this class because it provides the basic functionality required by forms.
UserControl
The UserControl class also inherits directly from the ContainerControl class and provides an empty control that you can use to create your own controls by using the Windows Forms Designer. Note For information about creating controls, see Module 9, Developing Components in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the Windows.Forms.Application class for managing your application at run time, in a similar way to using the App object in Visual Basic 6.0. You cannot instantiate this class in your code because a single instance exists for the duration of your application at run time.
The following example shows how to use the Application class to start your application, keep it running after the first form is closed, and end the application. You must remember to change the Startup Object property of the project from the name of a form to Sub Main for this to work.
Sub Main( ) Dim frmFirst as New Form1( ) frmFirst.Show( ) ' Displays the first form Application.Run( ) ' Allows the application to continue after the form is closed End Sub Private Sub LastForm_Closing (ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing ' Any cleanup code for the application Application.Exit End Sub
Using DoEvents
The Application class also provides the DoEvents method. This method is similar to the DoEvents function in Visual Basic 6.0, but it is now implemented as a method of the Application object. You use this method to allow other messages in the message queue to be processed during the handling of a single event in your code. By default, when your form handles an event, it processes all code in that event handler and will not respond to other events that may be occurring. If you call the DoEvents method in that code, your application will have a chance to handle these other events, such as the repainting of a form that has had another window dragged over it. You will typically use this method within loops to ensure that other messages are processed. Warning When you use the DoEvents method, be careful not to re-enter the same code. This will cause your application to stop responding.
10
Topic Objective
Lead-in
The structure of the code behind a Windows Form is different from that of a Visual Basic 6.0 form.
Class Inherits from System.Windows.Forms.Form Constructor Sub New( ) Initializer Sub InitializeComponent( ) Destructor Sub Dispose( )
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The structure of the code behind a Windows Form differs from the structure of the code behind a Visual Basic 6.0 form because of the object-orientation of the .NET Framework. Delivery Tip
It may be useful to open a blank form in Visual Basic .NET and discuss these items in more depth. However, the first demonstration can also be used to perform this task.
Imports
At the top of the code, you may find a list of Imports statements, which you can use to provide access to functionality contained within namespaces in referenced external assemblies. If you do not use an Imports statement, then all references to classes in external assemblies must use fully qualified names. Using Imports allows you to specify an alias to be used for the namespace. The following example shows how to use the Imports statement to declare an alias of Winforms for the System.Windows.Forms namespace. This statement allows you to use the alias in place of the full name for the rest of the forms code.
Imports Winforms = System.Windows.Forms
Class
A form is an instance of a class in Visual Basic .NET, so all the code belonging to the form is enclosed within a Public Class definition. This structure allows you to implement visual inheritance by creating forms that inherit from other forms.
Inherits System.Windows.Forms.Form
Forms inherit from the System.Windows.Forms.Form class. If you create a form in Visual Studio .NET, this inheritance is automatic, but if you create forms elsewhere, you must manually add the Inherits statement. This gives you the standard functionality of a form but allows you to override methods or properties as required.
11
Constructor
In Visual Basic 6.0, you use the Form_Initialize and Form_Load events to initialize your forms. In Visual Basic .NET, the Form_Initialize event has been replaced with the class constructor Public Sub New.
Initializer
As in previous versions of Visual Basic, you can assign many property values at design time. These design-time values are used by the run-time system to provide initial values. In Visual Basic 6.0, properties are initialized through the run-time system, and the code is not visible to the developer. In Visual Basic .NET, the Windows Form Designer creates a subroutine called InitializeComponent that contains the settings you define in the properties window at design time. This subroutine is called from the class constructor code.
Destructor
In previous versions of Visual Basic, you use the Form_Terminate and Form_Unload events to provide finalization code. In Visual Basic .NET, these events have been replaced with the class destructor Public Sub Dispose and the Form_Closed event. When a form is shown non-modally, Dispose is called when the form is closed. When you show forms modally, you must call the Dispose method yourself.
12
Topic Objective
Using Form Properties Using Form Methods Using Form Events Handling Events Creating MDI Forms Using Standard Dialog Boxes
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Using Windows Forms is similar to using Visual Basic 6.0 forms, but there are a number of new properties, methods, and events. In this lesson, you will learn how to use the new form properties, methods, and events. You will also learn how to use MDI forms and standard Windows dialog boxes.
13
Topic Objective
DialogResult Font Opacity MaximumSize and MinimumSize TopMost AcceptButton and CancelButton
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Windows Forms have many new powerful properties that previously would have required API calls to achieve a similar functionality. Many properties are inherited from classes such as the Control, ScrollableControl, and ContainerControl classes, and some properties are defined by the Form class itself.
DialogResult
Windows Forms allow you to easily create your own customized dialog boxes. You can create customized dialog boxes by setting the DialogResult property for buttons on your form and displaying the form as a dialog box. Once the form is closed, you can use the DialogResult property of the form to determine which button was clicked. The following example shows how to use the DialogResult property of a Windows Form:
Form1.ShowDialog( ) 'The DialogResult property is updated when a button is pressed and the form closed If Form1.DialogResult = DialogResult.Yes Then 'Do something End If Form1.Dispose( )
Font
The Font property of a Windows Form behaves slightly differently than that of a Visual Basic 6.0 form. Controls inherit Font.BackColor and Font.ForeColor from their parent control. If the font is not set on a control, then the control inherits the font from the parent. This allows you to change the font on the form, and have all controls on the form automatically pick up that new font.
14
Opacity
By default, all Windows Forms are 100 percent opaque. In Windows 2000 and Windows XP, it is possible to create forms that are transparent or translucent. You can do this by changing the Opacity property of a form. This holds a double value between 0 and 1, with 1 being opaque and 0 being transparent. The following example shows how to make a form 50% opaque:
Me.Opacity = 0.5
TopMost
The TopMost property allows your form to remain on top of all other windows, even when it does not have the focus. This is what the Windows Task Manager does by default. In previous versions of Visual Basic, this frequently used feature can be achieved only by using API calls. In Visual Basic .NET, you simply assign a Boolean property of a Windows Form. The following example shows how to toggle the TopMost property:
Me.TopMost = Not Me.TopMost
15
Lead-in
Close
If If blnEndApp blnEndApp = = True True Then Then Me.Close( Me.Close( ) ) End End If If
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Windows Forms provide several new methods in addition to supporting some existing methods from previous versions of Visual Basic, such as Hide and Refresh.
Close
This method is similar to the Unload method in Visual Basic 6.0. You can use it to close the current form and release any resources it is holding. The following example shows how to use the Close method of a Windows Form:
If blnEndApp = True Then Me.Close( ) End If
16
17
Lead-in
The Windows Forms framework provides a series of familiar and notsofamiliar form events.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Many events from previous versions of Visual Basic are unchanged in Visual Basic .NET, such as mouse and focus events (although these events do have different parameters). Several events have been replaced with slightly different events from the .NET Framework to become standard across the .NET-compatible languages. A number of new events have also been added to allow further flexibility when designing Windows Formsbased applications. In this topic, you will take a closer look at these changes.
18
Closing
This event is similar to the Visual Basic 6.0 Unload event. It occurs when the form is being closed and allows you to cancel the closure through the use of the CancelEventArgs argument. The following example shows how to use the Closing event to query whether the user wants to end the application:
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing If MessageBox.Show("Do you really want to close this form?", "Closing", MessageBoxButtons.YesNo) = DialogResult.No Then e.Cancel = True End If End Sub
Closed
The Closed event occurs after the Closing event but before the Dispose method of a form. You can use it to perform tasks such as saving information from the form. The following example shows how to use the Closed event to store information in a global variable:
Private Sub Form2_Closed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Closed strName = "Charlie" End Sub
19
Handling Events
Topic Objective
To explain how to handle events in Windows Forms.
Lead-in
Using AddHandler
AddHandler AddHandler btnNext.Click, btnNext.Click, AddressOf AddressOf NavigateBtnClick NavigateBtnClick
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In previous versions of Visual Basic, you create event handlers by selecting the object and event from the Object and Procedure boxes in the Code Editor. You can create event handlers in Visual Basic .NET the same way, although to create some of the common event handlers for forms, you need to access the (Base Class Events) group in the Object box. You can also add event handlers programmatically by using the AddHandler keyword.
Point out the benefits of the different approaches, particularly that of the ability to handle multiple control events from the one handler. Ensure that students understand the two common arguments that are sent to event handlers: The sender argument: the object that raised the event. The e argument: common types of arguments, such as EventArgs or MouseEventArgs.
20
Note The signature of an event is the list of variables passed to an eventhandling procedure. For a procedure to handle multiple events, or to handle events from multiple controls, the argument list must be identical for each event or else a compilation error will occur.
Using AddHandler
The AddHandler keyword allows you to add event handling to your form or control at run time by using one of two techniques, as is described for classes in Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET. It is similar to the Handles keyword in that it also allows you to use one event-handling procedure for multiple events or multiple controls. With AddHandler, however, you do not need to declare the control variable by using the WithEvents modifier. This allows a more dynamic attaching of events to handlers. The following example shows how to use the AddHandler keyword to assign control events to procedure:
Private Sub NavigateBtnClick(ByVal sender As System.Object, ByVal e As System.EventArgs) MessageBox.Show("Moving record") End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load AddHandler btnNext.Click, AddressOf NavigateBtnClick AddHandler btnPrevious.Click, AddressOf NavigateBtnClick End Sub
Note The RemoveHandler keyword removes an event handler from a form or controls event. For more information about RemoveHandler, see Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
21
Lead-in
In this practice, you will create a simple form in order to observe the events of the form.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this practice, you will create a Windows-based application containing a single form that displays event information in the Debug Output window. To create the application 1. Open Microsoft Visual Studio .NET. 2. On the File menu, point to New, and then click Project. Set the location to install folder\Practices\Mod06, and rename the solution FormEvents. 3. Create event handlers for the following form events, and enter the specified code in the code window.
Event Code
Debug.WriteLine("Activated") Debug.WriteLine("Closed") Debug.WriteLine("Deactivated") Debug.WriteLine("Size changed")
To test the application 1. On the Debug menu, click Start. 2. On the View menu, point to Other Windows, and then click Output to display the Debug Output window. 3. Perform the following actions on the form: Resize, Minimize, Restore, and Close. (Ensure that you can view the activity in the Debug Output window as you perform each action.) 4. Close Visual Studio .NET.
22
Lead-in
23
24
25
Lead-in
MsgBox
If If MsgBox("Continue?", MsgBox("Continue?", MsgBoxStyle.YesNo MsgBoxStyle.YesNo + + MsgBoxStyle.Question, MsgBoxStyle.Question, "Question") "Question") = = MsgBoxResult.Yes MsgBoxResult.Yes Then Then ... ... End End If If
There are several ways to display a dialog box and retrieve input from a user.
MessageBox Class
If If MessageBox.Show("Continue?", MessageBox.Show("Continue?", "Question", "Question", MessageBoxButtons.YesNo, MessageBoxButtons.YesNo, MessageBoxIcon.Question) MessageBoxIcon.Question) = = DialogResult.Yes DialogResult.Yes Then Then ... ... End End If If
InputBox
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Modal forms or dialog boxes require that users close the window before they can continue interacting with other windows in the application. You can create them in any of three different ways.
MsgBox
The traditional MsgBox function used by Visual Basic developers is still provided in the .NET Framework. You use the same syntax that you used in previous versions, except you define the display style by the MsgBoxStyle enumeration and the resulting user decision by the MsgBoxResult enumeration. The following example shows how to use the MsgBox function:
If MsgBox("Continue?", _ MsgBoxStyle.YesNo + MsgBoxStyle.Question, _ "Question") _ = MsgBoxResult.Yes Then ... End If
26
MessageBox Class
In the .NET Framework, you use the MessageBox class for displaying a simple message in a dialog box. It provides a Show method and integer constants for controlling the display style of the message box. You can compare the resulting user decision to the System.Windows.Forms.DialogResult enumeration, as shown in the following example:
If MessageBox.Show("Continue?", "Question", _ MessageBoxButtons.YesNo, MessageBoxIcon.Question) _ = DialogResult.Yes Then ... End If
The Show method allows extra flexibility by allowing you to optionally specify a different form as the owner of the dialog box.
InputBox
The InputBox function is still supported in Visual Basic .NET and has not changed from previous versions of Visual Basic.
27
Topic Objective
Lead-in
This demonstration shows how to use properties and methods of a Windows Form.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the properties and methods of a Windows Form, including owner forms and automatic scrolling.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
28
Using Controls
Topic Objective
To provide an overview of the topics covered in this lesson.
New Controls Using Control Properties Using Control Methods Creating Menus Providing User Help Implementing Drag-and-Drop Functionality
Lead-in
Many controls have undergone enhancements in Visual Basic .NET, and new controls have been added to the Toolbox.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET introduces several new controls and many enhancements to the way you use existing controls. After completing this lesson, you will be able to: Describe the new controls in the developers Toolbox. Apply new properties and methods to existing controls. Use menus to improve user interaction with your application. Implement a Help system for your application. Create drag-and-drop operations.
29
New Controls
Topic Objective
To explain some of the new controls in Visual Basic .NET.
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET provides many controls that will be familiar to Visual Basic developers, in addition to some new controls to help you create your Windows Formsbased applications. There are also some controls provided in the default Toolbox that are only available by using ActiveX controls in Visual Basic 6.0, such as the CommonDialog controls and the Windows common controls library.
CheckedListBox
The CheckedListBox control allows you to use a list box with check boxes beside each item. This is a commonly used control in Windows and was previously available through the Style property of a standard ListBox. The following example shows how you can use the CheckedItems property to access the selected items in the list:
Dim intTotalChecked As Integer For intTotalChecked = 0 To _ CheckedListBox1.CheckedItems.Count - 1 Messagebox.Show(CheckedListBox1.CheckedItems _ (intTotalChecked).ToString) Next
30
LinkLabel
Using the LinkLabel control, you can display hyperlinks on a form. You can specify the Text of the hyperlink and the VisitedLinkColor and LinkColor of links. The default event for a LinkedLabel control is the LinkClicked event. The following example shows how you can use this to display a Web page in a WebBrowser control:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load LinkLabel1.Text = "www.microsoft.com" LinkLabel1.LinkColor = Color.Blue LinkLabel1.VisitedLinkColor = Color.Purple End Sub Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked AxWebBrowser1.Navigate(LinkLabel1.Text) End Sub
Splitter
Splitter controls have become a common feature of Microsoft applications over the last few years. Visual Basic .NET provides a built-in control to allow the user to resize the different sections of your form without any need for resizing code. To use the Splitter control, you must perform the following steps: 1. Add the control to be resized to a container. 2. Dock the control to one side of the container. 3. Add the Splitter to the container. 4. Dock the Splitter to the side of the control to be resized. After completing these steps, when you rest the mouse pointer on the edge of the control, the pointer will change shape and the control can be resized.
31
ToolTip
In Visual Basic 6.0, most built-in controls have a ToolTip property that allows you to attach textual Help to a control. This is implemented by means of the ToolTip control in Visual Basic .NET. You can use one ToolTip control to implement ToolTips on many controls on your form. The following example shows how to link the ToolTip text to be used with a particular control in the Form_Load event:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load ToolTip1.SetToolTip(Button1, "Click to confirm") ToolTip1.SetToolTip(Button2, "Click to cancel") End Sub
NotifyIcon
The NotifyIcon control is a component that displays an icon in the notification area of the Windows taskbar, like the Windows Volume Control icon. The component is placed in the component tray of the Windows Forms Designer for a particular form. When that form is displayed at run time, the icon will display automatically in the notification area and will be removed when the Dispose method of the NotifyIcon component is called. A ContextMenu can be associated with the component so that users can right-click on the icon and select options from the menu. Note For more information about other new controls, search for Controls in the Visual Basic .NET documentation.
32
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Many of the Windows Forms controls share some new common properties because they inherit from the same base classes.
Positioning
In Visual Basic 6.0, you regularly have to write code to cope with the resizing of a form. If a user maximizes a form at run time, the controls will stay in their original position relative to the top left corner of a form. This means that if you have a set of command buttonsfor example, OK and Cancelpositioned either in the top right corner of a form or across the bottom of a form, you need to write your own code to reposition these controls. In Visual Basic .NET, this type of functionality is built into the controls and form classes. Anchor property In Visual Basic .NET, you can anchor a control to the top, bottom, left, or right side of a form (or any combination). This means that at design time you can use the Properties window to anchor a control, and you no longer need to write repositioning code in the Resize event of a form. Resizing Because you can anchor any or all of the sides of a control, you can effectively resize a control to correspond to the resizing of a form. If you have a form containing a picture box that you want to fill the form, you can anchor it to all sides, and it will remain the same distance from the edges of the form at all times. This feature cannot override the size restrictions applied to some of the Visual Basic .NET controls, such as the height of a combo box. Location property This property allows you to specify the location of a control with respect to the top left corner of its container. The property takes a Point data type, which represents an x and y coordinate pair. This property replaces the Top and Left properties used in Visual Basic 6.
33
Text Property
In earlier versions of Visual Basic, you used different methods to set the text displayed in the various controls. For instance, Forms and Label controls have a Caption property, whereas TextBox controls have a Text property. In Visual Basic .NET, any textual property of a control is determined by the Text property. This provides consistency within Visual Basic, and with the other .NET-compatible languages. The following example shows how to initialize a Button control in the Form_Load or InitializeComponent procedures.
Button1.Top = 20 Button1.Height = 50 Button1.Left = 20 Button1.Width = 120 Button1.Text = "Click Me"
34
Topic Objective
Lead-in
Focus
TextBox1.Focus( TextBox1.Focus( ) ) TextBox1.SelectAll( TextBox1.SelectAll( ) )
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Many of the Windows Forms controls share some new common methods because they inherit from the same base classes.
Focus
You can use this method to set the focus to a specific control. It is similar to the SetFocus method used in Visual Basic 6.0. The following example shows how to check the Text property of a TextBox control and return focus to the control if the text is not valid:
If TextBox1.Text <> "password" Then MessageBox.Show("Incorrect password") TextBox1.Focus( ) TextBox1.SelectAll( ) End If
When trapping focus events, you should use the Enter and Leave events, rather than the GotFocus and LostFocus events.
35
Creating Menus
Topic Objective
To explain the new changes to menu creation.
Lead-in
Menu classes Creating menus at design time Use the Menu Designer Creating menus at run time
Dim Dim mnuMain mnuMain As As New New MainMenu( MainMenu( ) ) Dim Dim mnuItem1 mnuItem1 As As New New MenuItem, MenuItem, mnuItem2 mnuItem2 As As New New MenuItem( MenuItem( ) ) mnuItem1.Text = "File" mnuItem1.Text = "File" mnuMain.MenuItems.Add(mnuItem1) mnuMain.MenuItems.Add(mnuItem1) mnuItem2.Text mnuItem2.Text = = "Exit" "Exit" mnuMain.MenuItems(0).MenuItems.Add(mnuItem2) mnuMain.MenuItems(0).MenuItems.Add(mnuItem2) AddHandler AddHandler mnuItem2.Click, mnuItem2.Click, AddressOf AddressOf NewExitHandler NewExitHandler Menu = mnuMain Menu = mnuMain
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, the process of creating menus is very different from that of Visual Basic 6.0. You can have more than one menu system per form, which reduces the complexity of creating dynamic menus, and you can create ContextMenus directly without designing them as top-level menus first.
Menu Classes
There are three main classes that you will use when creating menus: MainMenu You use the MainMenu class to create a standard Windows menu bar at the top of a form. ContextMenu You use the ContextMenu class to define pop-up menus associated with particular controls. MenuItem You use the MenuItem class to define menu items within a MainMenu or a ContextMenu.
36
You can use the Menu Designer to create your menus at design time, which is something you cannot do in Visual Basic 6.0. You can also design and edit your menus in-place, rather than in a separate dialog box.
37
Topic Objective
Lead-in
ErrorProvider control Error icon appears next to control, and message appears like a ToolTip when mouse pauses over icon Used mainly for data binding HelpProvider control Points to .chm, .hlp, or .html Help file Controls provide Help information by means of HelpString or HelpTopic properties
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET allows you to create user Help in a number of ways by using controls. Each of these controls is placed in the component tray for an individual form. Delivery Tip
Discuss the relevant methods of each control that are used to set information, as mentioned in the student notes.
ErrorProvider Control
The ErrorProvider control indicates to the user that a control has an error associated with it by displaying a small icon near the control. When the user pauses the mouse over the icon, a ToolTip showing the error message appears. ErrorProvider can also be used with bound data. You can set your own error messages manually, as shown in the following example, or when working with bound data, you set the DataSource property of the ErrorProvider to automatically pick error messages up from the database.
Public Sub TextBox1_Validating(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating If TextBox1.Text = "" Then ErrorProvider1.SetError(TextBox1, _ "Please enter a value for the text box") Else ErrorProvider1.SetError(TextBox1, "") End If End Sub
The Validating event is raised whenever the next control receives focus, providing that the next control has CausesValidation property set to True, allowing the Text property of the control to be tested. If this property contains an empty string, the ErrorProvider will display an exclamation icon next to the control and update the ToolTip for the error. If the error message is an empty string, the icon does not appear.
38
HelpProvider Control
You can use the HelpProvider control to display a simple pop-up Help window or online Help from a Help file specified by the HelpProvider.HelpNamespace property. This Help is automatically activated when the user presses the F1 Help key while a control has focus.
Using SetShowHelp
You can also turn Help on or off for an individual control by using the SetShowHelp method of the HelpProvider control as shown in this example:
Sub SetTextboxHelp( ) HelpProvider1.SetHelpString(TextBox1, "This is my help") HelpProvider1.SetShowHelp(TextBox1, True) 'True = On End Sub
39
Topic Objective
Lead-in
This demonstration shows the effects of the layout properties of controls, and various other aspects of using controls in Windows Forms.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the layout properties of a Button control. You will also learn how to handle control events from multiple controls in one event handler. Finally, you will learn how to provide simple user assistance with the HelpProvider and ToolTip controls, and how to programmatically create a context menu.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
40
Starting the process Use the DoDragDrop method in the MouseDown event of the originating control Changing the drag icon Set the AllowDrop property of the receiving control to True Set the Effect property of the DragEventsArg in the DragOver event of the receiving control Dropping the data Use the Data.GetData method to access the data
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Drag-and-drop techniques in Visual Basic .NET are significantly different from those of previous versions of Visual Basic.
41
42
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use drag-and-drop operations within a simple application.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
43
Why Inherit from a Form? Creating the Base Form Creating the Inherited Form Modifying the Base Form
Lead-in
Visual Basic .NET introduces the concept of visual inheritance to Visual Basic developers.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET introduces the concept of visual inheritance to Visual Basic developers. This type of inheritance can improve code reuse in your applications and provide them with a standard appearance and behavior. After you complete this lesson, you will be able to use visual inheritance to: Create a form that inherits from a given base form. Modify a base form from which other forms have inherited.
44
Topic Objective
Lead-in
A form is a class, so it can use inheritance Applications will have a standard appearance and behavior Changes to the base form will be applied to derived forms Common examples: Wizard forms Logon forms
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You will likely need to create forms that are similar to forms you have created before. In previous versions of Visual Basic, you can create templates on which to base your forms. In Visual Basic .NET, you can inherit from existing forms. Inheriting from a form is as simple as deriving one class from another, because a form is simply a class with an extra visual component. This technique allows you to define a base form that can be derived from in order to create a standard appearance and behavior of your applications. It also shares the same benefits as class inheritance, in that code can be reused from the base form in all of the derived forms. Any changes that you make to the base form can be applied to any of the derived forms, making simple updates to multiple forms easy. You can use visual inheritance whenever forms behave in a similar way or need to have a standard appearance. Common examples of these types of forms are wizards and logon forms.
45
Lead-in
1. 2. 3.
Carefully plan the base form Create the base form as for a normal form Set the access modifiers property of controls Private Control can only be modified in the base form Protected Control can be modified by deriving form Public Control can be modified by any code module Friend Control can be modified within the base form project
4. 5.
Add the Overridable keyword to appropriate methods Build the solution for the base form
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The base form serves as the template for your standard form. You design and code the form in the usual way, to perform whatever functionality you want to be inherited. After you have created the base form, you can build your solution to make the form accessible, and then inherit from it. When creating a base form, use the following process: 1. Carefully plan the base form. Changes are easier to make before any forms inherit from your base form because making changes afterwards will require extra retesting. 2. Create the base form as you would a normal form. Create the base form using the same techniques you would use to create a normal form. 3. Set the access modifiers property of controls. Private controls cannot have their properties modified outside of the base form. Public controls can have their properties modified by any form or code module without restriction. Protected controls can have their properties modified by the deriving form. Friend controls can have their properties modified within the base form project. 4. Add the Overridable keyword to appropriate methods. Any method that can be overridden in a derived form must be marked as overridable in the base form. 5. Build the solution for the base form. You cannot create a form that inherits from a base form until the base form has been built.
46
Lead-in
Ensure that the base form is as complete as possible Reference the assembly Create a new Inherited Form item Change control properties where necessary Override methods or events as required
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you have designed your base form and built the solution, you are ready to begin deriving forms. To do this, you simply add a new item to the project by clicking Inherited Form in the Add New Item window. This will run the Inheritance Picker for you. When inheriting from a base Windows Form, consider the following guidelines carefully: Ensure that the base form is as complete as possible. Make any last minute changes to the base form before inheriting from it. Reference the assembly. If the base form is not in the same project, you must make a reference to the appropriate assembly. Create a new Inherited Form item. Add a new Inherited Form item to your project, selecting the base form in the Inheritance Picker dialog box. A list of available base forms is shown, and you can browse for other assemblies. Change control properties where necessary. You can programmatically change public and protected controls, and you can use the Properties window of the Windows Forms Designer for a derived form. Private and Friend controls cannot be altered outside of the base form project. Override methods or events as required. If methods or event handlers have been marked as overridable, you can implement your own code in the derived form.
47
Topic Objective
Changing the base form Changes affect derived forms when rebuilt Checking derived forms Verify changes before rebuilding application Retest after rebuilding application
Lead-in
You can modify your base form after it has been inherited.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The derived form is linked directly to the base form; it is not a copy of the base form. This means that changes you make to the base form will be reflected in the derived form when the project is rebuilt. You can quickly update a series of forms that contain the same code or visual elements by making the changes in the base form. However, you may find that changes that are valid in the base form can introduce errors into the derived forms. For example, any overridden method that calls a method on the MyBase object may expect a certain behavior, and careful retesting is needed to validate this expectation. This is true of all types of inheritance, not just visual inheritance.
48
Topic Objective
Lead-in
This demonstration shows how to achieve visual inheritance by using Windows Forms.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a base form specifically for inheritance purposes. You will learn how to inherit from the form and how to override properties and methods of the base form controls. Finally, you will learn how to modify the base form after it has been used for inheritance and learn the effects the base form modifications have on the derived form.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
49
Objectives
After completing this lab, you will be able to: Use Windows Forms in an application. Use the layout properties of controls. Create menus. Provide user assistance by means of ToolTips.
Prerequisites
Before working on this lab, you must have designed forms in previous versions of Visual Basic.
Scenario
In this lab, you will continue working with the Cargo system. The Customer class from Lab 5.1 of Course 2373B, Programming with Microsoft Visual Basic .NET, has been enhanced for you, and a CustomerList class has been provided so you can iterate through the customers. The basic Customer form has been provided for you, but it requires further development.
50
2. On the Debug menu, click Start. 3. Step through the code by using the F11 key (to step into procedures) and the F10 key (to step over procedures) until you understand how the application loads the customer information into the list. Press F5 to resume execution. 4. Click different customers in the list, and observe the resulting behavior. 5. Click Close to quit the application, and remove the breakpoint from the Sub New procedure.
51
To set the layout properties of the controls 1. Open the frmCustomer.vb design window, and set the Anchor properties of the following controls to the following values in the Properties window.
Control lstCustomers txtID txtEmail txtTitle txtFName txtLName txtAddress txtCompany btnClose Anchor value Top, Bottom, Left Top, Left, Right Top, Left, Right Top, Left, Right Top, Left, Right Top, Left, Right Top, Left, Right Top, Left, Right Bottom, Right
2. Set the following properties for the form and controls in the Properties window.
Object txtAddress txtAddress txtAddress frmCustomer Property Multiline AcceptsReturn Size.Height CancelButton Value True True 60 btnClose
3. Open the frmCustomer.vb code window. 4. Add the following line immediately before the end of the Sub New procedure:
Me.MinimumSize = Me.Size
To test the project 1. Run the project. 2. Resize the form to confirm that all controls are anchored correctly and that the MinimumSize property limits the form size so that all controls are visible. 3. Click the Close button to quit the application.
52
5. Create the Click event handler for the mnuFileLoad menu item.
53
6. From the Sub New procedure, cut the existing code for loading customers, and paste it into the new event handler (making sure to leave the MinimumSize code that was added in the previous exercise as it is). Your code should now look as follows:
Public Sub New( ) MyBase.New( ) 'This call is required by the Windows Forms Designer. InitializeComponent( ) 'Add any initialization after the InitializeComponent() call Me.MinimumSize = Me.Size End Sub Private Sub mnuFileLoad_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Handles _ mnuFileLoad.Click 'create the customerlist object custList = New CustomersList( ) 'load the customers custList.LoadCustomers( ) 'populate the list box with customers PopulateListBox( ) LoadCustomer(0) End Sub
7. Locate the existing btnClose_Click event handler, and rename the procedure CloseForm, leaving the arguments unchanged, and adding the following statement after the existing Handles clause. This allows both events to be handled by the same procedure.
, mnuFileExit.Click
8. Save the project. To add ToolTip user assistance 1. Open the frmCustomer.vb design window. 2. Using the Toolbox, add a ToolTip control, renaming it ttCustomerList. 3. Using the Properties window, set the ToolTip property for lstCustomers to Select a customer to display the full details. To test the application 1. On the Debug menu, click Start. 2. On the File menu, click Load Customers. 3. Rest the mouse pointer on the Customer list to confirm that the ToolTip appears. 4. On the File menu, click Exit to quit the application.
54
5. Disable this menu item until there are entries in the list box, as shown in the following code:
mItem.Enabled = False
6. Add an event handler for the new mItem object by using the AddHandler function, as shown in the following code:
AddHandler mItem.Click, AddressOf onDeleteClick
7. Assign the new context menu to the ContextMenu property of the lstCustomers control, as shown in the following code:
lstCustomers.ContextMenu = cmListBox
8. Before the Catch statement in the LoadCustomer procedure, enable the context menu as shown in the following code:
lstCustomers.ContextMenu.MenuItems(0).Enabled = True
To create the event handler for the context menu item 1. At the end of the form definition, create a new private subroutine called onDeleteClick that accepts the following arguments:
ByVal sender As Object, ByVal e As System.EventArgs
MessageBoxButtons.YesNo MessageBoxIcon.Question
55
3. Use an If statement to test the result of the MessageBox.Show method against the value DialogResult.Yes. In the True section, enter the following code:
custList.RemoveAt(lstCustomers.SelectedIndex) PopulateListBox( )
4. Insert an If statement into the procedure to test to see whether the number of items in lstCustomers is zero. (Hint: Use the lstCustomers.Items.Count property). 5. In the True section, disable the Delete menu item. 6. Save the project. To test the application 1. On the Debug menu, click Start. 2. On the File menu, click Load Customers. 3. Select, and then right-click a customer, and click Delete. 4. When the confirmation message appears, click Yes. 5. On the File menu, click Exit to quit the application. 6. Close and exit Visual Studio .NET.
56
3. Create the Click event handler for the mnuHelpAbout menu item, and add the following code:
Dim aboutForm As New frmAbout( ) aboutForm.ShowDialog( )
57
To test the About box form 1. On the Debug menu, click Start. 2. On the Help menu, click About. 3. Click OK to close the About Form dialog box. 4. Click Close to quit the application. 5. Close Visual Studio .NET.
58
Review
Topic Objective
To reinforce module objectives by reviewing key points.
Why Use Windows Forms? Structure of Windows Forms Using Windows Forms Using Controls Windows Forms Inheritance
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. Identify some of the benefits of Windows Forms. Rich set of controls, GDI+ support, advanced layout possibilities, accessibility support, advanced printing support, visual inheritance, extensibility.
2. The ContainerControl class is the fundamental base class for all other controls. True or false? False. The Control class is the fundamental base class for all other controls.
3. Write the code to access the path from which an executable is running.
Dim strAppPath as String strAppPath = Application.StartupPath
4. Describe an owned form. An owned form is always displayed on top of its owner. It is minimized or closed when the owner is minimized or closed.
59
5. Write code to make the code behind a button called btnOK execute when a user presses RETURN.
Me.AcceptButton = btnOK
6. List two ways to provide Help to the user. ErrorProvider, HelpProvider, or ToolTip controls.
7. Write code to create a Help menu with one menu itemAbout at run time.
Dim mnuMain As New MainMenu( ) Dim mnuItem1 As New MenuItem( ) Dim mnuItem2 As New MenuItem( )
Menu = mnuMain
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 120 Minutes Labs: 105 Minutes This module provides students with the knowledge needed to create Web-based applications. In the first lab, students will create several Web Forms for logging on or registering as a customer of the Cargo system. In the second lab, students will create a Web Service that provides information about customers and allows the addition of new customers to the system. The labs use predefined classes that replicate data storage and retrieval. After completing this module, students will be able to: Explain and take advantage of the benefits of ASP.NET and its various libraries in application development. Create Web Form applications. Use HTML server controls and Web server controls. Create Web Services. Use Web Services from a browser or from another client application.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_07.ppt Module 7, Building Web Applications Lab 7.1, Creating the Customer LogOn Web Forms Lab 7.2, Creating and Using the CustomerService Web Service Multimedia presentation, How Web Services Work, file 2373_How Web Services Work.htm on the Student Materials compact disc
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the labs.
iv
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes. These demonstrations show the creation of simple Web Forms and simple Web Services. If students have previous experience with ASP.NET Beta 1, consider using validation controls in the Web Forms demonstration, and analyze the client-side proxy files generated in the Using a Web Service demonstration.
6. To describe the purpose of each TextBox, add Normal style text above each box, as shown in the following table.
TextBox txtFullName txtEmail txtPassword txtConfirm Describing text Please enter your full name: Please enter your e-mail address: Please enter a password: Please confirm the password:
8. Examine the WebForm1.aspx file in the HTML view of the HTML Designer, and describe the @ Page directive at the top of the page and the HTML syntax within the page, including the control declarations. 9. In the design window, double-click btnSubmit to display the Code Editor, and then explain the code in this module. 10. Add the following code to the btnSubmit_Click event handler, and then explain the uses of the session variable and Response object.
Session("FullName") = txtFullName.Text Response.Redirect("Welcome.aspx")
To create the welcome page 1. Add another Web Form named Welcome.aspx to the project, add a single Label control to it, and then set the (ID) property of the control to lblWelcome. 2. Locate the Page_Load event handler in the Welcome.aspx.vb code module, and add the following code:
lblWelcome.Text = "Welcome " & Session("FullName")
To test the application 1. Run the application. 2. Type values in the text boxes, and then click Submit, viewing the results. 3. Quit the application. 4. Quit Visual Studio .NET.
vi
2. Build the project, but do not run it. To test the Web Service 1. Right-click QueryUsers.asmx in Solution Explorer, and then click View in Browser. 2. Click the GetUserName hyperlink and examine the HTML description page. Enter an e-mail address in the input field for the GetUserName method and click Invoke and view the Extensible Markup Language (XML) results. Close this window. 3. Return to the first HTML description page, and click the Service Description link to view the Web Services Description Language (WSDL) document. Describe the document, briefly pointing out the basic sections of the document before closing the window. To add descriptions to the Web Service and methods 1. In the QueryUsers.asmx.vb code module, modify the class definition to read as follows:
<WebService(Namespace := "http://tempuri.org/", _ Description:="This service deals with user information.")> Public Class QueryUsers
2. Locate the GetUserName method and modify the WebMethod attribute to read as follows:
<WebMethod(Description:="Looks up a name based on the e-mail.")>
3. To display the new HTML description page, rebuild the project and view QueryUsers.asmx in the browser as before, pointing out the new descriptions. 4. Close Visual Studio .NET.
vii
Delivery Tip
This demonstration uses the Web Service from the previous demonstration. If you have not created the web service, you must open Services.sln in install folder\DemoCode\Mod07\ Services\Solution and build the project. Then you can substitute Services/Solution for Services/Starter/Services in the folder paths in this demonstration.
Delivery Tip
In step 6, do not go into too much detail regarding the proxy class file. Students can explore this individually if they want to.
6. In Solution Explorer, click Show All Files and view the Reference.vb file that acts as the proxy class for the client application. Explain that this file allows client code to be written as if it were normal Visual Basic .NET code, allowing the use of Microsoft IntelliSense and early binding. 7. Create the btnSubmit_Click event handler in frmUserDetails.vb, and add the following code, explaining the purpose of each line.
Dim qu As New UserServices.QueryUsers( ) MessageBox.Show(qu.GetUserName(txtEmail.Text), _ "Result from the Service") qu = Nothing
To test the client application 1. Run the project. 2. Click Submit to view the results of the call to the Web Service. 3. Exit the form and the Visual Studio .NET integrated development environment (IDE).
viii
Multimedia Presentation
This section provides multimedia presentation procedures that do not fit in the margin notes or are not appropriate for the student notes.
Module Strategy
Use the following strategy to present this module: Introduction to ASP.NET This lesson introduces ASP.NET and shows some of the benefits over Active Server Pages (ASP). Emphasize that this is primarily an overview lesson; most of these topics are addressed in more detail throughout the module. For more in-depth information about ASP.NET, refer students to Course 2063A, Introduction to ASP.NET. Creating Web Form Applications This lesson shows how to create Web Forms applications. Students examine the structure of a Web Form, including some of the important directives that are used within the page definition. Compare HTML controls to Web server controls, and highlight some individual controls for discussion, such as the validation controls and the AdRotator control. Finally, introduce students to event handling for ASP.NET server controls. Building Web Services This lesson describes the open standards and protocols that enable Web Services, in addition to how to create Web Services and their methods by using the WebMethod attribute. The student notes show how to include method and Web Service descriptions within these attributes. Point these lessons out to students. Use the instructor-led demonstration to show students how to create a simple Web Service and its discovery document. Using Web Services In this lesson, you examine how to use a Web Service from a client, including the process of discovery and the exploration of service descriptions. Explain to students how they can access this information from a browser and from a rich client such as Visual Basic .NET. Use the demonstration and animation at the end of the module to give students examples of possible scenarios for Web Services, and elicit suggestions for other Web Services from the students.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Introduction to ASP.NET Creating Web Form Applications Building Web Services Using Web Services
Lead-in
In this module, you will learn about building Web applications with Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Using Microsoft Visual Basic .NET and ASP.NET, you can create a new generation of dynamic, powerful Web applications. Delivery Tip After completing this module, you will be able to: Explain and take advantage of the benefits of ASP.NET and its various libraries in application development. Create Web Form applications. Use HTML server controls and Web server controls. Create Web Services. Use Web Services from a browser or from another client application.
Developers who are familiar with the ASP model will find the transition to ASP.NET to be fairly easy.
Introduction to ASP.NET
Topic Objective
To provide an overview of the topics covered in this lesson.
Overview of ASP.NET Using Response and Request Objects Maintaining Client-Side State Maintaining Server-Side State Managing an ASP.NET Application Overview of ASP.NET Security Using Global Events with Global.asax
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip ASP.NET introduces many improvements upon traditional approaches to Web development. Its extensive framework of classes enables you to rapidly create powerful, scalable, manageable, and secure Internet applications. After you complete this lesson, you will be able to: Describe the advantages that ASP.NET provides over its predecessor, Active Server Pages (ASP). Use two important ASP.NET objects: Request and Response. Use the various client-side and server-side state facilities that are available in ASP.NET applications. Explain basic concepts in managing and securing ASP.NET applications. Use the Global.asax application file for global events.
This lesson provides an overview of ASP.NET and its benefits without going into much detail about any one topic. Most items are covered in more depth later in the module.
Overview of ASP.NET
Topic Objective
To discuss the key features provided by ASP.NET.
Code behind development Intuitive approach to development similar to Windows Forms Code can be compiled using any .NET-compatible language Significant performance improvement ASP.NET pages run side-by-side with ASP pages Files with the .aspx extension run side-by-side with current ASP applications on IIS Automatic support for multiple browsers Rich DHTML, HTML 3.2, and small devices ASP.NET namespaces provide rich functionality Built-in support for Web Services
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** For several years, Web developers have used ASP to produce Internet applications containing dynamic content. ASP.NET is the evolution of this technology, and it provides many benefits to Web developers: Code-behind support ASP.NET uses an event-driven programming model familiar to Visual Basic and ASP developers. Web Forms use the drag-and-drop style of page creation. You can modify code behind the controls on Web Forms in the same way that you do on Visual Basic forms. This code resides in a separate file to separate the content from the code. Code can be compiled from any Microsoft .NET-compatible language You can create your ASP.NET applications by using any of the .NET compatible languages, including Visual Basic .NET, C#, and Microsoft JScript. While ASP contains scripts that are interpreted when you execute a page, ASP.NET code is compiled rather than interpreted. This allows early binding, strong typing, and just-in-time (JIT) compilation to native code. These factors greatly improve the performance of ASP.NET applications, particularly when you have an increased number of clients. ASP.NET pages run side-by-side with ASP pages ASP.NET uses the .aspx file extension to allow ASP.NET pages to run sideby-side with existing ASP pages on Internet Information Services (IIS). The ASP.NET runtime will only process files with .aspx extensions; .asp files will be processed with the original ASP engine. You can easily migrate existing .asp files to .aspx files without making many changes to the code.
Automatic support for multiple browsers ASP.NET applications have the ability to render information differently to suit the capabilities of different browsers. You can create your application in the same way for both a simple browser that only supports HTML 3.2 and for an enhanced browser that supports dynamic HTML (DHTML), such as Microsoft Internet Explorer 4.0. You can even use Visual Basic .NET to create Web applications that will run on small devices such as Handheld PCs because of the ability of the ASP.NET Web server controls to render themselves appropriately for each client browser. ASP.NET namespaces provide rich functionality The ASP.NET framework provides several namespaces that allow you to use powerful built-in features, such as the ability to communicate between browser and server, to increase application performance by caching information, and to fully secure a Web site. The framework provides Web Service capabilities to allow access to your system services, and provides many predefined controls for use on Web Forms. Built-in support for Web Services ASP.NET includes built-in support for Web Services, enabling developers to build loosely coupled applications that use Simple Object Access Protocol (SOAP) for application-to-application communication.
The System.Web namespace provides common Web functionality Requesting information from the client Request object
Dim Dim strValue strValue As As String String = = Request.Form("txtInput") Request.Form("txtInput")
Lead-in
The Response and Request objects provide the ability to communicate between the server and the browser.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the System.Web namespace to access many of the classes that provide the base functionality of ASP.NET applications. Many of these classes are similar to those used by developers in ASP applications and have been enhanced in ASP.NET. You can use the Response and Request objects, provided by the System.Web namespace, to communicate between the client browser and the server computer. Both of these objects provide new properties and methods for their equivalent objects in ASP.
Maintaining control state across multiple requests Set EnableViewState property of control Use the StateBag class to store extra data
ViewState("TempData") ViewState("TempData") = = 25 25
Lead-in
You can use several approaches to maintain client-side state in ASP.NET applications.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Web pages are generally regarded as stateless devices, meaning that they do not remember any values between being displayed, destroyed, and displayed again. However, in ASP.NET you can choose to maintain state for a Web page when you need to. You can do this by using view state at the page and control level.
When the page is sent to the browser, a hidden variable is included, as shown in the following example:
<input type="hidden" name="__VIEWSTATE" value="dONnU=" />
Application object maintains application-level state Data for use by all users
Application("App_StartTime") Application("App_StartTime") = = Now Now
Lead-in
You can use several approaches to maintain server-side state in ASP.NET applications.
Session object maintains session-level state Data for use by a single client browser Data recoverable by means of Windows Service or SQL Server database
Session("Session_StartTime") Session("Session_StartTime") = = Now Now
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Some parts of your Web application may need to maintain cross-request state. For example, a shopping cart application may need to maintain information about a customer order through multiple visits to a page before the items are purchased. You can maintain state at either the application or session level.
You can use the HttpApplicationState class to store application-level information. You can use the intrinsic Application object during a Web request to share global data across the application. The default Item property of this object stores and retrieves a collection of objects, allowing anything from a string to a user-defined object to be maintained for the lifespan of the application. Application state is not shared across a Web farm or a Web garden. Note A Web farm is an application that is hosted across multiple computers. A Web garden is an application that is hosted on a single computer with multiple processors.
Example
The following example shows how to store the start time of the application and then displays the information at a later stage:
Application("App_StartTime") = Now ... Response.Write("Application Started: " & _ Application("App_StartTime"))
Example
You can use the intrinsic Session object to access this state information. The following example shows how to use session state to store a start time that can be retrieved at a later stage during the users session:
Session("Session_StartTime") = Now ... Response.Write("Session started: " & _ Session("Session_StartTime"))
10
Configuring ASP.NET applications XML configuration file Web.config Human-readable and writeable Stored with the application Deploying ASP.NET applications XCOPY the pages, components, and configuration No registration required Updating ASP.NET applications Copy new files over old files No update utility, restart, or reboot required Live update keeps applications running
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** ASP.NET applications are simple to configure, deploy, and maintain. Delivery Tip
Deployment is covered in more depth in Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET.
11
12
Security settings stored in web.config file Out-of-box authentication support Windows authentication Basic, Digest, or Integrated Microsoft Passport authentication Forms (Cookie) authentication Role-based security architecture
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Most companies need to secure their Web applications so that users can only perform actions they are authorized to perform. The required levels of security can include simple public access to Web pages, secure validation of credit card information, and secure access for trading partners. The System.Web.Security namespace provides all aspects of ASP.NET security.
Security is a complicated topic and is only briefly covered in this lesson. Direct students to additional material as often as possible.
Digest Integrated
13
The following example shows how to specify Windows authentication in the Web.config file:
<authentication mode="Windows" />
Note For more information about the different types of authentication, see Designing Secure Web-Based Applications for Microsoft Windows 2000, by Michael Howard, Microsoft Press. Microsoft Passport authentication. Passport authentication requires the user to have a Microsoft Passport that can be created on the Internet. This approach benefits users because they use the same sign-in name and password for any Web site that uses this type of authentication. Note For more information about passports, go to http://www.passport.com/Business. Forms (Cookie) authentication. Web sites that require users to logon to the system from an HTML form usually store a cookie on the client computer. The cookie is used for subsequent visits to the site and the information can then be used for whatever purpose the site requires. This type of authentication is ideal for querying user details against a database in an e-commerce situation.
Note For more information about role-based security, see ASP.NET Authorization in the Visual Studio .NET documentation.
14
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can initialize state for application-level or session-level data by using the Global.asax application file. This application file enhances the Global.asa application file used in ASP. Avoid using local variables to store information, because ASP.NET may create multiple instances of the global class. If you need to store information, use application-state or session-state.
Application-Level Events
ASP.NET provides several events to initialize state at the application level, including the following: Application_Start This event is activated when the first user attempts to gain access to access your Web application. Any subsequent requests will not activate this event even if multiple instances of the Global class have been instantiated. This event is particularly useful for initializing application-state information. Application_BeginRequest This event is activated whenever a request for a URL is received from a client application. Application_EndRequest This event is activated whenever a request for a URL has been completed. Application_End This event is activated when the last instance of the Global class is destroyed so that any final resources can be cleaned up.
15
Session-Level Events
ASP.NET also provides session-level events, including the following: Session_Start This event is activated at the beginning of a new client session and is useful for initializing session-state information. Session_End This event is activated when a client session ends after a period of inactivity or if the Session.Abandon method is explicitly called as part of your application code.
Example
The following example shows how you could use these events in conjunction with state management objects to initialize stateful data:
Sub Application_Start(ByVal sender As Object, _ ByVal e As EventArgs) 'Initialize the application-level counter Application("SessionCounter") = 0 End Sub Sub Session_Start(ByVal sender As Object, _ ByVal e As EventArgs) 'Increment the application-level counter Application("SessionCounter") = _ Application("SessionCounter") + 1 'Assign new value to session-level data Session("StartTime") = Now End Sub Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) 'Decrement the application-level counter Application("SessionCounter") = _ Application("SessionCounter") - 1 End Sub
16
Structure of Web Forms Using HTML Controls Advantages of Web Server Controls Using Web Server Controls Handling Events
Lead-in
Web Forms create the visual interaction between the server computer and the user in the same way that HTML and script did previously, but in a compiled and more maintainable fashion.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Traditionally, you create Web applications by using a combination of static HTML pages and dynamic content provided by client-side and server-side script. ASP.NET provides Web Forms to improve and enhance Web applications. After you complete this lesson, you will be able to: Describe the files that constitute a Web Form. Use the different types of controls available on a Web Form, including HTML and Web server controls. Write code in event handlers that will execute on the server.
17
Topic Objective
Lead-in
Web Forms separate declarative tags from logic The .aspx file contains HTML and other tags The code-behind file contains logic and event handling
Because ASP pages often contain script mixed with HTML tags, they can be difficult to maintain. ASP.NET solves this issue by separating the HTML tags from the page logic.
<tags>
code
Logon.aspx Logon.aspx.vb
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Because ASP pages often contain HTML tags mixed with user interface eventhandling script, they can be difficult to maintain. When developing applications with the Visual Studio .NET Integrated Development Environment (IDE), ASP.NET Web Forms consist of two separate files: the .aspx file for HTML and other tags, and the code-behind file for the code that executes as a result of user interaction. Because the tags and the code are separated in ASP.NET, you can more easily locate bugs and maintain code.
Point out that, when the application is built and deployed, the .aspx files are copied, but the .aspx.vb files are compiled into the appropriate DLL file. Alternatively, developers can include both code and HTML tags within a single .aspx file by using the <script> tag. This approach provides less separation between the code and tags, but does not require a DLL file to be built and deployed with the application.
18
19
Lead-in
Direct relationship to preexisting HTML tags Client side by default Server side with runat=server directive Properties correspond one-to-one with HTML, weakly typed Defined with HTML tag
<input <input type=text type=text id="text1" id="text1" value="some value="some text" text" runat="server"> runat="server">
ASP.NET provides two main types of controls for you to use: HTML controls and Web controls.
You can manipulate control properties programmatically from server-side code when the control is marked to run on the server. These properties correspond directly to their equivalent HTML tag predecessors. For example, the HTML tag <INPUT> supports an attribute called Value, and the HTMLInputText class supports an equivalent Value property.
20
You can set other properties of the HTML control by using the Attributes collection property of the control. This type of property setting is considered weakly typed because the collection only stores and retrieves String values, as shown in the following example:
HTMLTable1.Attributes("bgColor") = "Green" 'Weakly typed
To specify the programmatic accessor that identifies the control in the server code, use the ID attribute. To set the initial display value of the text field, use the VALUE attribute.
21
Automatic browser detection Detect capabilities of client and render accordingly Strongly typed, consistent object model Enables compile-time type checking Declared with XML tags Server side only using runat=server directive
<asp:textbox <asp:textbox id="text2" id="text2" text="some text="some text" text" runat="server"> runat="server"> </asp:textbox> </asp:textbox>
Lead-in
The second type of control that ASP.NET includes is the Web server control.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In addition to HTML controls, ASP.NET Web Forms also provide Web server controls. Web server controls run exclusively on the server, and provide the following advantages: Automatic browser detection Web server controls can render themselves differently to suit the capabilities of different browsers. For example, a control may send dynamic HTML (DHTML) to a rich browser (HTML 4.0 and later), and send HTML and script to a more basic client browser. This is known as creating uplevel and downlevel capability. Strongly typed, consistent object model Web server controls are strongly typed, so compile-time checking of code provides you with accurate error messages before the application is built. With Web controls, you can use a consistent object model, which is similar to Windows Forms controls. For example, you can set the BackColor property of a Button control explicitly by using a strongly typed constant, as shown in the following example.
Button.BackColor = Color.Green 'Strongly typed
22
Declared with XML tags You declare Web server controls by using an XML tag. This tag references the asp namespace and specifies information regarding the type of Web control, a programmatic identifier through use of the ID attribute, and any initial values. The following example shows the syntax for creating a simple TextBox Web control whose ID is text2 and whose initial TEXT value is some text.
<asp:TextBox id="text2" text="some text" runat="server"> </asp:TextBox>
Rich functionality Web server controls include enhanced versions of traditional HTML form controls such as Button and TextBox, as well as complex controls such as Calendar, DataGrid, and AdRotator (advertisement rotator). These controls do not correspond directly to HTML elements or attributes.
23
Lead-in
Intrinsic controls List controls for repetition Validation controls validate input Rich controls simplify common Web page requirements
There are several types of Web server controls available in ASP.NET Web Forms.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip ASP.NET Web server controls can be separated into four main categories: intrinsic, list, validation, and rich controls. The table below explains each of these categories.
Category Intrinsic controls Definition Provides the basic functionality for user interaction with the browser. Many of these controls are similar to the corresponding HTML controls, but their enhanced properties and methods allow a more powerful and consistent programming style. List controls Validation controls Used for repetition when displaying any type of list. Provides simple control validation that displays a message to the user without making a return trip to the server. Simplifies common Web page requirements. DropDownList, ListBox, Repeater, DataGrid RequiredFieldValidator, RangeValidator, RegularExpressionValida tor, CompareValidator AdRotator, Calendar Examples Button, TextBox, CheckBox
Pick one or two individual controls for discussion, particularly a validation control and rich control.
Rich controls
24
This validation control is rendered in client-side script when the page is displayed so that return trips to the server are not required simply for control validation.
25
The following example shows the information required in the XML file to rotate the advertisements:
<Advertisements> <Ad> <ImageUrl>images/graphic1.gif</ImageUrl> <NavigateUrl>http://www.example1.microsoft.com</NavigateUrl> <AlternateText> Click here for products page 1 </AlternateText> <Keyword>Products 1</Keyword> <Impressions>80</Impressions> </Ad> <Ad> <ImageUrl>images/graphic2.gif</ImageUrl> <NavigateUrl>http://www.example2.microsoft.com</NavigateUrl> <AlternateText> Click here for products page 2 </AlternateText> <Keyword>Products 2</Keyword> <Impressions>80</Impressions> </Ad> </Advertisements>
The HTML produced by these controls when rendered may be substantially different from the object model that developers code against. The following segment of a Web Form shows how the HTML syntax looks when viewed in the HTML design window for a Web Form containing a RadioButtonList.
<form id="WebForm1" method="post" runat="server"> <asp:RadioButtonList id="RadioButtonList1" runat="server"> <asp:ListItem Value="One">One</asp:ListItem> <asp:ListItem Value="Two">Two</asp:ListItem> </asp:RadioButtonList> </form>
26
The following HTML is generated when the Web Form is rendered in Internet Explorer version 6.0. It shows that the RadioButtonList control is rendered in a table with HTML input tags and labels.
Example
<form name="WebForm1" method="post" action="WebForm1.aspx" id="WebForm1"> <table id="RadioButtonList1" border="0"> <tr><td> <input type="radio" id="RadioButtonList1_0" value="One" name="RadioButtonList1" /> <label for="RadioButtonList1_0">One</label> </td></tr> <tr><td> <input type="radio" id="RadioButtonList1_1" value="Two" name="RadioButtonList1" /> <label for="RadioButtonList1_1">Two</label> </td></tr> </table> </form>
Note For information about creating Web Form controls, see Module 9, Developing Components in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
27
Handling Events
Topic Objective
To explain how to handle events in Web Forms.
Event handlers contain code for user interactions Page events: Init, Load, PreRender, UnLoad
Private Private Sub Sub Page_Load(ByVal Page_Load(ByVal Sender Sender As As System.Object, System.Object, _ _ ByVal e As System.EventArgs) Handles ByVal e As System.EventArgs) Handles MyBase.Load MyBase.Load If If Not Not IsPostBack IsPostBack Then Then 'IsPostBack 'IsPostBack is is also also available available via via 'Me' 'Me' 'Perform action first time page is displayed 'Perform action first time page is displayed End End If If End Sub End Sub
Lead-in
Handling events in Web Forms is similar to traditional Visual Basic event handling.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Interacting with users is one of the primary reasons for creating ASP.NET Web Forms. You program various events to handle these interactions as you do in traditional Visual Basic development. The Web page itself can execute code, and so can the many events raised by different objects, including all of the server controls.
Page Events
Every Web Form inherits from the Page class, which provides several useful events indirectly from other inherited classes such as the Control and TemplateControl classes. Several of these events are included in the following list, in the order in which they occur when a user accesses a page: Init This event occurs as the first step in the page lifecycle, when the page is initialized. You use this event to initialize local variables. Do not use this event to access view state information or controls on the page, because they may not be created or accessible at this point. Load This event occurs after the Init event and before the PreRender events are raised. You can use this event to view state information or access controls. PreRender This event occurs when the page is about to render its contents to the Web browser. Use it to perform any pre-rendering steps before the view state is saved. Unload This event occurs when the page is unloaded, after rending has occurred. Use it for removing any resources created throughout the request.
28
Control Events
Server controls are based on the WebControl class, which is based on the System.Web.UI.Control class. The Page class is also based indirectly on the System.Web.UI.Control class, through the TemplateControl class. Therefore, server controls share the events described in the preceding Page Events section. Individual controls also add their own events to the object model to allow easier interaction with the user. Examples include the simple Click event for the Button class, the TextChanged event for the TextBox class, and the SelectedIndexChanged event for the ListControl class. Delivery Tip Some controls post their events to the server immediately, such as the Click event of the Button class. Other controls, such as the TextChanged event of the TextBox class, may only register their events when other means are used to post events to the server. These events are stored and then raised sequentially to the server code when the post event is triggered. You can alter this behavior by setting the AutoPostBack property of the control to True. In this way, you can raise events immediately regardless of the default behavior. In the case of a TextBox control, this means the event will be posted every time the text value is modified and the control loses focus.
Discuss when events are raised by explaining the AutoPostBack property, as shown in the example in the notes.
29
The preceding code is processed as follows: 1. When the user types a value into the txtInput control and tabs to the btnPost control, the TextChanged event is held back until the button is clicked. 2. This posts to the Web Form and executes first the txtInput_TextChanged handler and then the btnPost_Click handler. 3. The page is then displayed again with the event order written as part of the page, using the Response.Write method. 4. The post will now occur as soon as the user changes the value and tabs out of the txtInput control because the txtInput.AutoPostBack property has been set to True. Important Using the AutoPostBack property for multiple controls on the same form will slow down the performance of the application because of the need for multiple trips to the server.
30
Topic Objective
Lead-in
This demonstration shows how to create a simple Web Form application that posts information to the Server by using Web server controls.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a simple Web Form application that uses Web server controls for posting data to the server.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
31
Objectives
After completing this lab, you will be able to: Create a Web Forms application. Create Web Forms. Use Web controls, such as the validation controls. Use the Session state object.
Prerequisites
Before working on this lab, you must be familiar with creating Web Forms in Visual Basic .NET.
Scenario
In this lab, you will create Web Forms that register and logon customers for the Cargo system. The WebCustomer class is provided for you to use as a basis for your Web application. It provides some existing customer details to test your application and allows you to add new customers. Any customer details added are only valid for a single test session because they are not persisted to disk at this time.
32
5. From the Web Forms toolbox, insert the following controls, separated by line breaks.
Control Hyperlink Property (ID) Text NavigateUrl Hyperlink (ID) Text NavigateUrl Value lnkExisting I am an existing customer LogOn.aspx lnkNewCustomer I am a new customer NewCustomer.aspx
33
4. From the Web Forms toolbox, insert the following controls, and set their properties as shown in the following table.
Control TextBox RequiredFieldValidator Property (ID) (ID) ErrorMessage ControlToValidate TextBox RegularExpressionValidator (ID) (ID) ErrorMessage ControlToValidate ValidationExpression Value txtFullName rfvName Please enter your full name txtFullName txtEmail revEmail Your e-mail address is invalid txtEmail Click the browse button and select Internet E-mail Address Dynamic rfvEmail Please enter an e-mail address txtEmail Dynamic txtPassword
34
ControlToValidate ValidationExpression
Display RequiredFieldValidator (ID) ErrorMessage ControlToValidate Display TextBox CompareValidator (ID) TextMode (ID) ErrorMessage ControlToValidate ControlToCompare Display RequiredFieldValidator (ID) ErrorMessage ControlToValidate Display Button (ID) Text
35
5. Create your Web Form so that it looks like the following illustration.
6. Double-click btnSubmit, and add the following code to the btnSubmit_Click event handler:
Dim newCust As New WebCustomer( ) newCust.AddCustomer(txtEmail.Text, txtPassword.Text, _ txtFullName.Text) Session("User_FullName") = newCust.FullName Response.Redirect("Welcome.aspx")
36
4. From the Web Forms toolbox, insert the following controls, separated by line breaks, arranging them with their related text values.
Control TextBox RegularExpressionValidator Property (ID) (ID) ErrorMessage ControlToValidate ValidationExpression Value txtEmail revEmail Your e-mail address is invalid txtEmail Click the browse button and select Internet E-mail Address Dynamic rfvEmail Please enter an e-mail address txtEmail Dynamic txtPassword Password rfvPassword Please enter a password txtPassword Dynamic
Display RequiredFieldValidator (ID) ErrorMessage ControlToValidate Display TextBox RequiredFieldValidator (ID) TextMode (ID) ErrorMessage ControlToValidate Display
37
6. Double-click the btnSubmit button, and add the following code to the btnSubmit_Click event handler:
Dim existingCustomer As New WebCustomer( ) lblNotFound.Visible = False Try existingCustomer.LogOn(txtEmail.Text, txtPassword.Text) Session("User_FullName") = existingCustomer.FullName Response.Redirect("Welcome.aspx") Catch ex As Exception lblNotFound.Text = ex.Message lblNotFound.Visible = True Finally existingCustomer = Nothing End Try
38
4. Open the Code Editor for Welcome.aspx.vb, and locate the Page_Load event handler. Enter the following code:
lblWelcome.Text = "Welcome " & _ Session("User_FullName")
39
To test existing customers 1. In Solution Explorer, right-click DefaultPage.aspx, and click Set As Start Page. 2. On the Debug menu, click Start. 3. Click the I am an existing customer hyperlink. 4. Click Submit to view the validation messages. 5. Enter the following values.
Text box E-mail Password Value [email protected] password
6. Click Submit to view the welcome message. 7. Use the Back button of the browser to return to the first page. To test new customers 1. Click the I am a new customer hyperlink. 2. Enter your full name, e-mail address and the password TRY. Use the TAB key to exit the field. The error message will appear. 3. Type a valid password and confirm it. 4. Click Submit to view the welcome message. 5. Close the browser.
40
3. Open the Code Editor for LogOn.aspx.vb, and locate the btnSubmit_Click event handler. Add the following code after the call to the existingCustomer.LogOn method:
If chkSave.Checked = True Then Response.Cookies("User_FullName").Value = _ existingCustomer.FullName Response.Cookies("User_FullName").Expires = _ Now.AddMonths(1) End If
To retrieve the cookie for a customer Open the code window for DefaultPage.aspx.vb, and locate the Page_Load event handler. Add the following code.
If Not (Request.Cookies("User_FullName") Is Nothing) Then Session("User_FullName") = _ Request.Cookies("User_FullName").Value Response.Redirect("Welcome.aspx") End If
41
To test the application 1. On the Debug menu, click Start. 2. Click the I am an existing customer hyperlink. 3. Enter the following values.
Control E-mail Password Save details Value [email protected] password Checked
4. Click Submit to view the welcome message. 5. Close the browser. 6. On the Debug menu, click Start. 7. Confirm that the Welcome page is the first page displayed and that it displays the correct user details. 8. Close Internet Explorer and close Visual Studio .NET.
42
What Are Web Services? Creating a Web Service Enabling Web Service Discovery Deploying and Publishing a Web Service
Lead-in
Creating Web Services with Visual Basic .NET enables you to quickly and easily provide your customers with access to your business services.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Internal client applications have been able to access shared components for many years, but allowing external client applications access has been a difficult challenge for both developers and administrators. Web Services allow you to easily provide access to your application logic across the Internet without any special configuration of firewalls or corporate networks by using the HTTP protocol. After you complete this lesson, you will be able to: Describe how the Internet and open standards such as XML and Hypertext Transfer Protocol (HTTP) enable Web Services to be used by any client application, regardless of its location or operating system. Create a Web Service by using Visual Basic .NET. Enable discovery of Web services. Deploy and publish your Web Services.
43
Components accessible by means of the Internet rather than distributed COM Built using open Internet protocols Consumers send and receive XML messages Defined in terms of the message order and format Site offers a description of the Web Services it offers Search for a site that offers a Web Service with a given capability
XML, XSD, HTTP, SMTP SOAP Web Services Description Language Discovery Document UDDI
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Components have traditionally been accessible only through local area networks by means of object-model specific protocols such as DCOM. This limitation is partly due to the complexity involved in allowing external access through ports to the internal network, as well as the dependence on both parties using a particular protocol. Web Services remove this limitation by allowing access to components by means of the Internet and HTTP while still maintaining security. The supporting framework for Web Services provides the following: Open Internet protocols Web Services use open Internet protocols such as XML, XML Schema Definition (XSD), HTTP, and Simple Mail Transfer Protocol (SMTP) to transmit messages. This allows any client application to use a Web Service regardless of the operating system it is running on or the language it is written in. XML messages and SOAP Delivery Tip
SOAP, XML, WSDL, and discovery are discussed in more detail throughout this module.
This is an animated slide. Click the slide to reveal the following sections: 1. Components accessible by means of the Internet rather than DCOM 2. XML, XSD, HTTP, SMTP 3. SOAP 4. WSDL 5. Discovery 6. UDDI
SOAP is an industry standard for using XML to represent data and commands in an extensible way. Web Services do not have to use SOAP to specify the message formats; HTTP GET and HTTP POST mechanisms can also be used. These mechanisms are not as powerful as SOAP, but they can be used by all HTTP clients. SOAP supports extra functionality, including passing classes, datasets, and by-reference parameters to a Web Service. Messages defined by Web Services Description Language (WSDL) Web Services must provide a contract that client applications can rely upon to accurately describe the services methods and their arguments. WSDL is an XML-based way to describe the contract information that can be read by all client applications that can work with XML.
44
Service descriptions available through discovery The discovery specification describes a standard way for service providers to publish Web Service contracts. It also describes how developers and developer tools can discover these contract documents. Universal Discovery Description and Integration (UDDI) The need to locate available services for an entire industry or individual company has led to the UDDI project, which creates a framework for Web Service integration by providing a distributed directory of Web Services. This distributed directory enables registration and discovery of Web Services through an assortment of predefined SOAP messages.
45
Topic Objective
1.
Add a Web Service module to the project The .asmx file contains WebService directive
Lead-in
<%@ <%@ WebService WebService Language="vb" Language="vb" Codebehind="User.asmx.vb" Codebehind="User.asmx.vb" Class="WebApp.User"%> Class="WebApp.User"%>
2. 3.
Create a Web Service description Add public subroutines or functions to .asmx.vb file Add WebMethod attribute to procedure definitions
<WebMethod()> <WebMethod()> Public Public Function Function AddUser() AddUser() As As String String 'Functionality to add a user and return new 'Functionality to add a user and return new ID ID Return Return strNewId strNewId End Function End Function
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip To create a Web Service in Visual Basic .NET, use the following process: 1. Add a Web Service module to your project. 2. Create a Web Service description. 3. Add public subroutines and functions to the module, and add the WebMethod attribute to the procedure definitions. 4. Create the remaining code as usual.
Ask students for examples of Web Services that they could create for their current server applications. Suggestions include: 1. E-commerce applications with ordering and shipping. 2. Application integration between existing applications. 3. Workflow solutions that incorporate Microsoft BizTalk Server 2000 for document exchange.
The .asmx.vb file The .asmx.vb file contains the code that executes when you invoke a Web Service method as if it were a regular class definition. The class inherits from the System.Web.Services.WebService class and provides direct access to common ASP.NET objects such as Application, Server, Session, and User.
46
Note Inheriting from System.Web.Services.WebService is not a requirement for a Web Service to work. Delivery Tip
Point out the ways to add descriptions for the service and individual methods, as they are not mentioned in the slide.
You can add a description for each method by specifying the Description argument of the WebMethod attribute, as shown in the following example:
<WebMethod(Description:="This method performs an action")> _ Public Sub PerformAction( ) ... End Function
Tip If you already have components that you want to convert to Web Services, you can simply create a wrapper Web Service module that calls your preexisting components and returns any results.
47
Topic Objective
Discovery document Enables location and interrogation of Web Service descriptions Contains links to resources that describe services Stores information in XML format Created manually or dynamically
<?xml <?xml version="1.0" version="1.0" ?> ?> <discovery <discovery xmlns="http://schemas.xmlsoap.org/disco/" xmlns="http://schemas.xmlsoap.org/disco/" ...> ...> <contractRef <contractRef ref="http://www.nwtraders.msft/Shopping/User.asmx?wsdl" ref="http://www.nwtraders.msft/Shopping/User.asmx?wsdl" docRef="http://www.nwtraders.msft/Shopping/User.asmx" docRef="http://www.nwtraders.msft/Shopping/User.asmx" xmlns="http://schemas.xmlsoap.org/disco/wsdl/" xmlns="http://schemas.xmlsoap.org/disco/wsdl/" /> /> ... ... </discovery> </discovery>
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip A Web Service is not very useful if other developers do not know that the service exists. Locating and interrogating Web Services is known as discovery. It is through the discovery process that client applications learn that a Web Service exists, what its capabilities are, and how to properly interact with it.
The slide shows a dynamic discovery document as explained in the student notes.
Delivery Tip
Point out that discovery is not required for a Web Service to work, and that you may not want to use a discovery document if you want to keep your services private.
Using this type of discovery document, you can explicitly expose only those Web Services that you want to be publicly available. This type of discovery document uses the .disco file extension.
48
You can use this type of discovery document to exclude particular folders from the dynamic discovery process. The folders excluded in the previous example are those used for Microsoft FrontPage Extensions and any Web references used by the project, but you can manually list as many folders as you want. The preceding dynamic discovery document will produce the following results when queried by a client application:
<?xml version="1.0" encoding="utf-8"?> <discovery xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.xmlsoap.org/disco/"> <contractRef ref="http://www.nwtraders.msft /Shopping/User.asmx?WSDL" docRef="http://www.nwtraders.msft/Shopping/User.asmx" xmlns="http://schemas.xmlsoap.org/disco/scl/" /> <soap address="http://www.nwtraders.msft/Shopping/User.asmx" xmlns:q1="http://tempuri.org/ binding="q1:Service1Soap" xmlns="http://schemas.xmlsoap.org/disco/soap/" /> </discovery>
Note A discovery document is not required for creating a Web Service. Another site could be used to describe the service, or there may not be a publicly available means of finding the service if it is only intended for private use.
49
Topic Objective
Lead-in
Deploying a Web Service Copy .asmx, Web.config, and any components to an IIS virtual directory Publishing a Web Service The discovery document is copied to IIS virtual directory Dynamic discovery document produced by ASP.NET generates information for all services in all subfolders Manually created discovery document returns only explicitly defined information
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Once you create your Web Service, you can deploy it to a Web server and then publish it. Delivery Tip
Ensure that students have a basic understanding of how IIS and virtual directories work. Demonstrate these processes if appropriate.
50
Topic Objective
Lead-in
This demonstration shows how to create a simple Web Service and how to add descriptions to the service and its methods.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a simple Web Service and add descriptions to the service and its methods.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
51
Exploring Web Services Invoking a Web Service from a Browser Invoking a Web Service from a Client
Lead-in
Web Services are a key component of the .NET Framework. In this lesson, you will learn how to discover and use a Web Service from a client application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Web Services are an important component of the .NET Framework. Visual Basic .NETbased client applications enable you to easily discover and use Web Services. After you complete this lesson, you will be able to: Discover and interrogate a Web Service by using discovery and WSDL documents. Call a Web Service from an Internet browser. Pass the service parameters to a Web Service. Reference a discovery document from Visual Basic .NET. Create client code that interacts with the Web Service.
52
HTML description page Describes Web Service methods and arguments Provides simple test utility for methods Displays additional descriptions from attributes Appears when you enter Web Service URL
http:// webservername/virtualdirectory/webservice.asmx http:// webservername/virtualdirectory/webservice.asmx
Lead-in
You can access information about Web Services in the HTML description page.
WSDL describes methods, arguments, and responses Generated by using Web Service URL with ?WSDL switch
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Exploring Web Services involves looking at two parts of the system: the HTML description page and the WSDL document.
53
You can view the description page by entering the Web Service URL in a browser by using the following syntax:
http://webservername/virtualdirectory/webservice.asmx
You can also view the description page within Visual Studio .NET by rightclicking the .asmx file in Solution Explorer, and then clicking View In Browser. Near the top of the HTML description page, there is also a Service Description hyperlink to the WSDL document.
It is possible to read and interpret the WSDL document, but it is not necessary to understand the document to use a Web Service.
54
Topic Objective
Enter the URL for the Web Service with parameters Syntax: http://webservername/vdir/webservicename.asmx/ MethodName?parameter=value Example:
http://www.nwtraders.msft/Shopping/User.asmx/AddUser?strName=Joe http://www.nwtraders.msft/Shopping/User.asmx/AddUser?strName=Joe
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You invoke a Web Service from a browser by entering the URL of the service, specifying the method name to run, and specifying any parameter values.
Syntax
You use the following syntax to invoke a Web Service:
http://webservername/vdir/webservicename.asmx/ MethodName?parameter=value
Example
The following example shows how to invoke a Web Service. This code calls the AddUser method of the User.asmx Web Service in the Shopping virtual directory on the nwtraders.msft Web server. It also passes in a parameter value of the user name Joe.
http://www.nwtraders.msft/Shopping/User.asmx/ AddUser?strName=Joe
The Web Service will return XML output containing the results of the execution as shown in the following example. The results show a String value of 43-124-21 being returned as the new identity of the added user.
<?xml version="1.0" ?> <string xmlns="http://tempuri.org/">43-124-21</string>
This approach uses the HTTP-GET protocol and would most commonly be used for testing purposes; real application-to-application communication would use the more powerful SOAP protocol.
55
Topic Objective
Visual Basic .NET creates a proxy class for early binding Steps required: 1. Add a Web reference 2. Enter the URL for the .asmx file 3. Create client code that uses appropriate namespaces
Sub Sub btnSubmit_Click() btnSubmit_Click() Handles Handles btnSubmit.Click btnSubmit.Click Dim usr As New Services.User() Dim usr As New Services.User() 'Services 'Services is is the the given given namespace namespace MessageBox.Show(usr.AddUser(txtName.Text)) MessageBox.Show(usr.AddUser(txtName.Text)) End End Sub Sub
Lead-in
Invoking a Web Service from a client application created in Visual Studio .NET is a simple process.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can invoke a Web Service from a client application in several ways, depending on the client. If the client is written in Visual Basic .NET, you can use the following process for either a Windows Forms or a Web Forms application: 1. Add a Web reference to the Web Service. 2. Enter the URL for the .asmx file. 3. Create your client code for accessing a component. Use the appropriate namespaces. When you add a Web reference to your client project, Visual Basic .NET creates a proxy class that hides the complexity of calling a Web Service. This proxy allows you to use early binding when connecting to the service, as if the components were accessible within a local assembly.
Remind students that early binding allows the most efficient type of calls to a component.
56
Example
In the following example, the required Web Service has taken a Web reference, and the Web reference has been renamed as the Services namespace. A command button named btnSubmit and a TextBox named txtName have been placed on a Windows Forms form with the following code for the btnSubmit_Click event handler:
Private Sub btnSubmit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSubmit.Click 'Services is the given namespace Dim usr As New Services.User( ) MessageBox.Show(usr.AddUser(txtName.Text)) End Sub
When the preceding code is executed, a new user is created. The txtName text box specifies the name of the new user, and the AddUser method creates a message box that displays the new identity.
57
Topic Objective
Lead-in
This demonstration shows how to use Web Services from both simple and rich clients, including Visual Basic .NET-based applications.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to access a Web Service from a simple browser client as well as from a rich Visual Basic .NET-based, Windows-based application.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
58
Topic Objective
Lead-in
This animation describes how rich clients, such as Visual Basic .NET-based applications, can use Web Services.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this animation, you will see how you can use Web Services in your Microsoft Visual Basic .NETbased applications, how the Web Services Description Language provides information about the Web Services, and how Visual Basic .NET uses SOAP to create proxies.
To start the animation, click the animation icon in the slide. The step-by-step instructions for showing this multimedia animation are in the instructor notes for this module.
59
A discovery document contains information in XML format about one or more Web sites that provide Web Services. The document contains URL links to descriptive documents or contracts for a specific Web Service. Visual Basic .NET automatically creates a discovery document when you create a Web Service. The client application uses the discovery document to locate individual services and contracts. With this information, the client can explore the contract documents to find the requirements of the Web Service methods. These contracts are also in XML format, but they follow specific standards that have been established to describe the methods, arguments, and return values of a Web Service. ASP.NET uses the Web Services Description Language, or WSDL, to describe the services available. WSDL documents describe the details of each method for three different protocols: HTTP-Get, HTTP-Post, and the Simple Object Access Protocol (SOAP). From these requirements, the Visual Basic .NET client automatically constructs a proxy class to ease communication between the developers client code and the service. Visual Basic .NET applications use the SOAP method descriptions when creating this proxy. SOAP supports some enhanced features such as byreference parameters and the ability to pass objects, structs, and ADO.NET DataSets. The Visual Basic .NET client application can then call the proxy class as if it were talking directly to the real service. In fact, the proxy hides all of the network communications. The proxy then makes requests to the Web Service, passing any parameters across the Internet as SOAP messages. The Web Service processes the incoming request and performs the required action. If values need to be sent back to the client, the Web Service creates these values and returns them as SOAP messages. The message is received by the proxy and converted into .NET base types that the Visual Basic .NET client can work with. This layer of abstraction allows developers to work with a Web Service as if it were a component running locally to the client. So, using Web Services, the Web server receives XML messages by means of ASP.NET. The Web server activates Web Service functions using SOAP, and the name change tasks are performed.The newlywed will be able to enter her name in one location that: Uses the discovery process to find out what services are available. Uses the ASP.NET WSDL to define methods to call, the address of the SOAP endpoint, schemas for SOAP messages and responses, and the data types returned. Creates a proxy client class. In this animation, you saw how you can use Web services in your Visual Basic .NET applications, how the Web Service Description Language provides information about the Web service, and how Visual Basic .NET uses SOAP to create proxies.
60
Topic Objective
Lead-in
In this lab, you will create a simple Web Service and then access the service by using a browser and a Visual Basic .NET-based application.
Objectives
After completing this lab, you will be able to: Create Web Services. Consume Web Services from a rich client.
Prerequisites
Before working on this lab, you must be familiar with creating Web Services in Visual Basic .NET.
Scenario
In this lab, you will create a Web Service that allows retrieval and storage of customer details. You will also create a Windows Forms application to test the Web Service methods. Web Services are often used by other Web Services or Web Form applications. A Windows Forms application will be used as the test application in this lab to contrast using a class from a form with using a Web Service from a form. The Customer class from Lab 5.1, Creating the Customer Class, of Course 2373B, Programming with Microsoft Visual Basic .NET, is provided and will be used as a basis for the Web Services application to replicate data retrieval and storage. The test form from the same lab has been modified and supplied to test these lab exercises.
61
62
To define the Web Service methods 1. On the File menu, point to Open, and then click File. 2. In the Files of type box, click Text Files. 3. Set the folder location to install folder\Labs\Lab072\Ex01\Starter, click Code.txt, and then click Open. 4. Copy all of the code in Code.txt into the Web Service class definition in CustomerService.asmx. 5. Examine each of the three methods to ensure that you understand the purpose of the code. 6. Add the WebMethod attribute to each of the three method definitions. This will change them from standard methods into Web Service methods. 7. Add the following descriptions to each WebMethod attribute, using the same syntax as that used for the WebService attribute shown in step 3 of the previous procedure.
Method AddCustomer GetDetails LogOn Description Adds a customer to the system. Retrieves customer details based on the Customer ID. Retrieves customer details based on logon details.
63
To test the Web Service 1. Build the project. 2. In Solution Explorer, right-click CustomerService.asmx, and then click View in Browser to display the HTML description page. 3. Click the Service Description hyperlink and examine the WSDL document. 4. Click the Back button on the Web toolbar to move back to the HTML description page. 5. Click the hyperlink for each method of the Web Service to view the method details. Note that you can only test the AddCustomer method from this page because it is the only method that does not use by-reference parameters. 6. Test the AddCustomer method by entering any information for the input fields and then clicking Invoke. View the XML results to confirm that the value 1200 was generated and returned.
64
65
4. Assign the following values to the text boxes following the call to the LogOn method.
Text box txtID txtFName txtLName txtAddress txtCompany Value CStr(intId) strFName strLName strAddress strCompany
5. Destroy the cusCustomer reference by using the Nothing keyword. 6. Save the project. To test the LogOn code 1. On the Debug menu, click Start. 2. Click the Test Logon button to display the test form. 3. Enter the following values in the appropriate text boxes.
Text box E-mail Password Value [email protected] password
4. Click the Logon button and confirm that the customer information is displayed correctly in the text boxes. 5. Close the application.
66
4. Assign the following values to the text boxes following the call to the GetDetails method.
Text box txtEmail txtPassword txtFName txtLName txtAddress txtCompany Value strEmail strPassword strFName strLName strAddress strCompany
5. Destroy the cusCustomer reference by using the Nothing keyword. 6. Save the project.
67
To test the Retrieve code 1. On the Debug menu, click Start. 2. Click the Test Get Details button to display the test form. 3. Enter the value 1119 in the CustomerID text box, and then click the Retrieve button. 4. Confirm that your code retrieves the customer information and displays it correctly in the text boxes. 5. Close the application.
68
4. Destroy the cusCustomer reference by using the Nothing keyword. 5. Save the project. To test the AddCustomer code 1. On the Debug menu, click Start. 2. Click the Test New Customer button to display the test form. 3. Enter values in all the text boxes. 4. Click the New Customer button, and confirm that an ID is displayed in the message box. Note that adding customers does not actually add a customer to the system, because this part of the application is hard-coded. 5. Close the application.
69
70
6. Save the project. To test the LogOn code 1. On the Debug menu, click Start. 2. Enter the following values in the appropriate text boxes.
Textbox E-mail Password Value [email protected] karen
3. Click the Submit button to confirm that the error message is displayed. 4. Enter the following values in the appropriate text boxes.
Textbox E-mail Password Value [email protected] password
5. Click the Submit button, and confirm that the correct name is displayed on the Welcome page. 6. Close the browser and Visual Studio .NET.
71
Review
Topic Objective
To reinforce module objectives by reviewing key points.
Introduction to ASP.NET Creating Web Form Applications Building Web Services Using Web Services
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. Describe some of the features of ASP.NET. Compiled code, multiple browser clients, session state that supports Web farms, and easy deployment.
2. Explain why updates to an ASP.NET application do not require you to restart IIS. No items are locked by IIS, so updating does not require you to restart IIS.
3. Create a line of code that uses the Response object to retrieve a userCounter session variable and display it to the user.
Response.Write("Value: " & Session("userCounter").ToString)
72
5. What attribute do you add to class methods when creating a Web Service? WebMethod.
6. Visual Basic .NET allows early binding to a Web Service. True or false? True. Setting a Web reference to a discovery document allows Visual Basic .NET to create a proxy class that allows early binding in the client application.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 120 Minutes Lab: 60 Minutes This module provides students with the knowledge needed to create highperformance data access applications in Microsoft Visual Basic .NET. It begins with a discussion about the need for ADO.NET and the benefits it brings to the development environment. Students will then learn about ADO.NET providers and the objects they supply. Students will then learn about the DataSet object. Students will learn how to add, update, and delete data by using it. Students will then learn how to use data designers and data binding in Microsoft Windows Forms and Web Forms. Finally, students learn how Extensible Markup Language (XML) integrates with ADO.NET. After completing this module, students will be able to: List the benefits of ADO.NET. Create applications by using ADO.NET. List the main ADO.NET objects and their functions. Use Microsoft Visual Studio .NET data designers and data binding. Explain how XML integrates with ADO.NET.
iv
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_08.ppt Module 8, Using ADO.NET Lab 8.1, Creating Applications That Use ADO.NET
Preparation Tasks
To prepare for this module: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstrations. Complete the practice. Complete the lab.
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
2. Locate the comment Add code to set CommandText and Connection properties of the command, and add the following lines of code:
comSQL.CommandText = "Select FirstName, LastName from " _ & "Customers" comSQL.Connection = conSQL
3. Locate the comment Add code to execute the command, and add the following line of code:
readerSQL = comSQL.ExecuteReader( )
4. Locate the comment Add code to loop through the records, add each to the listbox, and add the following lines of code:
Do While readerSQL.Read lstCustomers.Items.Add _ (readerSQL.Item("FirstName").ToString & " " & _ readerSQL.Item("LastName").ToString) Loop
To test the code 1. Run the application, and then click Display. You should see a list of customers in the Cargo database. 2. Quit the application, and quit Visual Studio .NET.
vi
4. Save the project. To test the form 1. In the project Properties window, change the Startup object to DataForm1. 2. Run the application. 3. Click Load to load the data into the form. 4. Change the CompanyName field to Microsoft, and then move on to the next record. Move back, and verify that the change has been saved in the local DataSet. 5. Click Add, and type sample data in each text box. Move away from that record, and verify that there are now 22 records in the form. 6. Move back to your new record, and then click Delete. Verify that there are now 21 records in the form. 7. Quit the application.
vii
viii
Module Strategy
Use the following strategy to present this module: ADO.NET Overview This lesson provides an overview of ADO.NET, including the advantages it provides. Some students who are familiar with the Microsoft .NET Framework will be aware of these benefits, but others will need to know why ADO.NET is worth learning. .NET Data Providers This lesson introduces the four main objects within the data providers. The first two objects this lesson describes, Connection and Command, are similar to their Microsoft ActiveX Data Objects (ADO) counterparts, but be sure to point out the differences needed in the code. The third object, the DataReader, is similar to the default ADO cursor, the firehose cursor. Students often find this similarity helpful when they are learning about the DataReader. The fourth object, the DataAdapter, is primarily used to populate DataSets and to update the data source from DataSets. Simply point out its syntax here because you will provide a thorough explanation of its uses in the next lesson. The DataSet Object This lesson begins with a review of disconnected data. Again, if students seem to be aware of the issues, then only explain the topic briefly. This lesson then describes how to use the main objects within a DataSet: DataTable objects and DataRelation objects. Students might try to equate a DataSet with an ADO Recordset, and you need to ensure that they understand that a DataSet contains a collection of tables that are sometimes related. Finally, you will explain how to update data in the DataSet and how to propagate those changes to the data source. Students need to be aware that the data is disconnected, which means that any changes the students make are local and that they need to explicitly pass the changes back to the source. Data Designers and Data Binding This lesson covers some of the new graphical user interface (GUI) features for data access in Visual Basic .NET. Remind students that all of these features simply automate the coding that they have learned so far and that they can create things by using the tools and then customize the code for their own purposes. The lesson also covers how to use data binding in both Windows Forms and Web Forms. These techniques are distinctly different from those of Visual Basic 6.0, so ensure that you cover the topics adequately.
ix
XML Integration This lesson relies on the students knowledge of XML. Ensure that they have some understanding of it before embarking on the topics, or you may confuse them. The main things they need to know are how an XML document is hierarchical, what it looks like, and why XML is so important for developers. The topics about schemas should be relatively easy because students will either be aware of database or XML schemas, and the importance of validation. The final topic is only designed to explain the links between DataSets and XmlDataDocument. Do not get involved in a long discussion about XmlDataDocument, because it is not necessary to be able to use ADO.NET.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
ADO.NET Overview .NET Data Providers The DataSet Object Data Designers and Data Binding XML Integration
Lead-in
In this module, you will learn how to use ADO.NET from Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this module, you will learn how to use ADO.NET from Microsoft Visual Basic .NET version 7.0. You will learn about the Microsoft .NET providers included in the .NET Framework and about how to use the DataSet object. You also will learn how to use the Microsoft Visual Studio .NET data designers and how to bind data to Microsoft Windows Forms and Web Forms. Finally, you will learn about the integration of Extensible Markup Language (XML) with ADO.NET. After completing this module, you will be able to: List the benefits of ADO.NET. Create applications using ADO.NET. List the main ADO.NET objects and their functions. Use Visual Studio .NET data designers and data binding. Explain how XML integrates with ADO.NET.
ADO.NET Overview
Topic Objective
To provide an overview of the topics covered in this lesson.
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** ActiveX Data Objects for the .NET Framework (ADO.NET) provide many enhancements for accessing data in a disconnected environment. ADO.NET contains objects that are similar to those of ADO, allowing you to update your skills easily. In this lesson, you will learn where ADO.NET is within the .NET Framework, and about the benefits ADO.NET provides. After completing this lesson, you will be able to: Describe the role of ADO.NET in the .NET Framework. List the major benefits of ADO.NET.
Introduction to ADO.NET
To discuss ADO.NET and its place in the .NET Framework.
Topic Objective
Lead-in
ASP.NET
Windows Forms
Class Framework
Drawing
XML
Data Data
ADO.NET
*****************************ILLEGAL FOR NON-TRAINER USE****************************** ADO.NET is a set of classes that allow .NET -based applications to read and update information in databases and other data stores. You can access these classes through the System.Data namespace provided by the .NET Framework. ADO.NET provides consistent access to a wide variety of data sources, including Microsoft SQL Server databases, OLE DBcompliant databases, non-relational sources such as Microsoft Exchange Server, and XML documents. Earlier data access methods, such as Data Access Object (DAO), concentrate on tightly coupled, connected data environments. One of the main purposes of ADO.NET is to enhance the disconnected data capabilities. Many of the common ADO objects that you have worked with correlate to ADO.NET objects, although there are also many new classes to enhance the data access model. ADO.NET uses .NET data providers to link your applications to data sources. .NET data providers are similar to the OLE DB providers used in ADO, although they are primarily concerned with moving data into and out of a database rather than providing interfaces over all of a databases functionality. ADO.NET includes two .NET data providers: SQL Server .NET Data Provider For use with SQL Server 7.0 and later. OLE DB .NET Data Provider For use with data sources exposed by OLE DB. The ADO.NET data providers contain tools to allow you to read, update, add, and delete data in multitier environments. Most of the objects in the two libraries are similar and are identified by the prefix on their name. For example, SqlDataReader and OleDbDataReader both provide a stream of records from a data source.
Benefits of ADO.NET
Topic Objective
To discuss the benefits of using ADO.NET.
Lead-in
Similar to ADO Designed for disconnected data Intrinsic to the .NET Framework Supports XML
*****************************ILLEGAL FOR NON-TRAINER USE****************************** ADO.NET provides many benefits to experienced Visual Basic developers, including: Similar programming model to that of ADO This makes it easy for Visual Basic developers who are familiar with ADO to update their skills. You can still use ADO in Visual Basic .NET, so you can keep existing code, but use the features of ADO.NET in new projects. Designed for disconnected data Delivery Tip
You may find that you need to expand on the problems that were faced when transmitting data as COM objects, such as dependency on a Windowsbased client over a local area network.
ADO.NET is designed for working with disconnected data in a multitier environment. It uses XML as the format for transmitting disconnected data, which makes it easier to communicate with client applications that are not based on Windows. Intrinsic to the .NET Framework Because ADO.NET is intrinsic to the .NET Framework, you have all the advantages of using the .NET Framework, including ease of cross-language development. Supports XML ADO and XML have previously been incompatible: ADO was based on relational data, and XML is based on hierarchical data. ADO.NET brings together these two data access techniques and allows you to integrate hierarchical and relational data, as well as alternate between XML and relational programming models.
Using the Connection Object Using the Command Object Using the Command Object with Stored Procedures Using the DataReader Object Using the DataAdapter Object
Lead-in
The .NET Data Providers allow access to specific types of data sources.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The .NET data providers allow access to specific types of data sources. You can use the System.Data.SQLClient namespace to access SQL Server 7.0 and later databases, and the System.Data.OLEDB namespace to access any data source exposed through OLE DB. Each of these providers contains four main objects that you can use to connect to a data source, read the data, and manipulate the data prior to updating the source. After completing this lesson, you will be able to: Use the Connection object to connect to a database. Use the Command object to execute commands and, optionally, to return data from a data source. Use the DataReader object to create a read-only data stream. Use the DataAdapter object to exchange data between a data source and a DataSet.
Lead-in
You can use the Connection object to connect to a specific data source.
SqlConnection
Dim Dim conSQL conSQL As As New New SqlClient.SqlConnection( SqlClient.SqlConnection( ) ) conSQL.ConnectionString conSQL.ConnectionString = = "Integrated "Integrated Security=True;" Security=True;" & &_ _ "Data "Data Source=LocalHost;Initial Source=LocalHost;Initial Catalog=Pubs;" Catalog=Pubs;" conSQL.Open( conSQL.Open( ) )
*****************************ILLEGAL FOR NON-TRAINER USE****************************** To connect to a database, you set the connection type, specify the data source, and connect to the data source. When you are finished working with the data, you close the connection. 1. Set the connection type. You can use the Connection object to connect to a specific data source. You can use either the SqlConnection object to connect to SQL Server databases or the OleDbConnection object to connect to other types of data sources. 2. Specify the data source. After you set the connection type, you use the ConnectionString property to specify the source database and other information used to establish the connection. The format of these strings differs slightly between the SqlClient namespace and the OleDb namespace. 3. Connect to the data source. Each Connection object supports an Open method that opens the connection after the connection properties have been set, and a Close method that closes the connection to the database after all transactions have cleared.
SqlConnection
The SqlConnection object is optimized for SQL Server 7.0 and later databases by bypassing the OLE DB layer. It is recommended that you use this object, not OleDbConnection, when working with these types of data sources. The SQL Client .NET Data Provider supports a ConnectionString format that is similar to ADO connection strings. This consists of name-value pairs providing the information required when connecting to the data source. The following table lists the most commonly used pairs.
Keyword name Connection Timeout (or Connect Timeout) Initial Catalog User ID Password (or Pwd) Data Source (or Server or Address or Addr or Network Address) Integrated Security (or Trusted_Connection) Description Length of time to wait for a connection to succeed before returning an error. Name of the database. SQL Server logon account (if using SQL Server security). SQL Server password (if using SQL Server security). Name or network address of SQL Server. Default value 15 seconds
False
The following example shows how to connect to a SQL Server database by using the SQL Client .NET Data Provider:
Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( )
OleDbConnection
The OleDbConnection object exposes methods similar to those of the SqlConnection object, but certain data sources will not support all the available methods of the OleDbConnection class. The OLE DB .NET Data Provider uses a ConnectionString that is identical to that of ADO, except that the Provider keyword is now required, and the URL, Remote Provider, and Remote Server keywords are no longer supported. The following example shows how to connect to an Access database by using the OLE DB .NET Data Provider: Delivery Tip
Dim conAccess As New OleDb.OleDbConnection( ) conAccess.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\NWind.MDB" conAccess.Open( )
If you demonstrate this code, ensure that NWind.mdb is in the specified path.
Note The examples in the remainder of this module use the SQL Client namespace. For more information about the OLE DB namespace, search for OleDBConnection in the Visual Basic .NET documentation.
Topic Objective
Lead-in
Once you have established a connection to your data source, you can use the Command object to execute SQL statements.
Dim Dim commSQL commSQL As As New New SqlClient.SqlCommand( SqlClient.SqlCommand( ) ) commSQL.Connection = commSQL.Connection = conSQL conSQL commSQL.CommandText commSQL.CommandText = = "Select "Select Count(*) Count(*) from from Authors" Authors" MessageBox.Show(commSQL.ExecuteScalar( MessageBox.Show(commSQL.ExecuteScalar( ).ToString) ).ToString)
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the ADO.NET Command object to execute commands and, optionally, to return data from a data source. You can use the SqlCommand with SQL Server databases and the OleDbCommand with all other types of data sources.
Creating Commands
You can create a command in one of two ways: Use the Command constructor, passing the Connection name as an argument. Use the CreateCommand method of the Connection object. You can use the CommandText property of the Command object to set and retrieve the SQL statement being executed. You can use any valid SQL statement with the specified data source, including data manipulation, definition, and control statements.
10
Executing Commands
You can only execute a Command within a valid and open connection. The Command object provides four methods that you can use to execute commands: ExecuteReader
Do not go into detail about the DataReader object at this time because it will be covered later in this lesson.
Delivery Tip
Use this method when the query will return a stream of data such as a Select statement returning a set of records. This method returns the records in a SqlDataReader or OleDbDataReader object. ExecuteScalar Use this method when the query will return a singleton value; for example, a Select statement returning an aggregate value. It executes the query and returns the first column of the first row in the result set, ignoring any other data that is returned. This method requires less code than using the ExecuteReader method and accessing a single value from the SqlDataReader object. ExecuteNonQuery Use this method when the query will not return a result; for example, an Insert statement. ExecuteXMLReader Use this method when the query includes a valid FOR XML clause. This is only valid when using the SQLCommand object. The following example shows how to use the Command object to query a database and retrieve data:
Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) Dim commSQL As New SqlClient.SqlCommand( ) commSQL.Connection = conSQL commSQL.CommandText = "Select Count(*) from Authors" MessageBox.Show(commSQL.ExecuteScalar( ).ToString)
This code determines how many rows are present in the Authors table of the Pubs database and displays the result.
11
1. Create a Command object 2. Set the CommandType to StoredProcedure 3. Set the CommandText property 4. Use the Add method to create and set parameters 5. Use the ParameterDirection property 6. Call ExecuteReader 7. Use records, and then close DataReader 8. Access output and return parameters
Lead-in
Many databases will contain stored procedures that you want to execute.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can also use the Command object to execute stored procedures in a database. You may need to perform some additional steps when preparing the Command to allow for the use of parameters in the stored procedure. Use the following steps to execute a stored procedure with the Command object: Delivery Tip 1. Create a Command object. 2. Set the CommandType property to StoredProcedure. 3. Set the CommandText property. 4. Use the Add method to create and set any parameters. 5. Use the ParameterDirection property to set parameter type. 6. Call the ExecuteReader method. 7. Use the DataReader object to view or manipulate the records, and close it when finished. 8. Access any output and return parameters.
Talk through these steps with respect to the code example below.
12
The following example shows how to execute a stored procedure using ADO.NET.
Imports System.Data.SqlClient Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) Dim commSQL As New SqlClient.SqlCommand( ) commSQL.Connection = conSQL commSQL.CommandType = CommandType.StoredProcedure commSQL.CommandText = "byroyalty" Dim paramSQL As New SqlClient.sqlParameter( _ "@percentage", SqlDbType.Int) paramSQL.Direction = ParameterDirection.Input paramSQL.Value = "30" commSQL.Parameters.Add(paramSQL) Dim datRead As SqlClient.SqlDataReader datRead = commSQL.ExecuteReader( ) Do While datRead.Read( ) MessageBox.Show(datRead(0).ToString) Loop datRead.Close( ) End Sub
Delivery Tip
Do not go into detail about the DataReader object at this point because it will be covered later in this lesson.
Tip If you are running a query that will only return one row, you can improve the performance of your application by returning this data as output parameters from a stored procedure.
13
Topic Objective
Reading data
Dim Dim commSQL commSQL As As New New SqlClient.SqlCommand( SqlClient.SqlCommand( ) ) commSQL.Connection commSQL.Connection = = conSQL conSQL commSQL.CommandText commSQL.CommandText ="Select ="Select au_lname,au_fname au_lname,au_fname from from authors" authors" Dim Dim datRead datRead As As SqlClient.SqlDataReader SqlClient.SqlDataReader datRead datRead = = commSQL.ExecuteReader( commSQL.ExecuteReader( ) ) Do Do Until Until datRead.Read datRead.Read = = False False MessageBox.Show(datRead.GetString(1) MessageBox.Show(datRead.GetString(1) & &" "" "_ _ & & datRead.GetString(0)) datRead.GetString(0)) Loop Loop datRead.Close( datRead.Close( ) )
Lead-in
The DataReader object gives you fast, efficient access to a stream of data.
Reading Data
You can instantiate the DataReader object by using the ExecuteReader method of the Command object. After you create the DataReader, you can call the Read method to obtain data in the rows. You can access the columns by name, ordinal number, or native type in conjunction with ordinal number. You must ensure that you use the Close method of the DataReader object before accessing any output or return parameters from a stored procedure.
14
The following example shows how to retrieve data by using the DataReader object:
Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) Dim commSQL As New SqlClient.SqlCommand( ) commSQL.Connection = conSQL commSQL.CommandText = "Select au_lname, au_fname from authors" Dim datRead As SqlClient.SqlDataReader datRead = commSQL.ExecuteReader( ) Do Until datRead.Read = False MessageBox.Show(datRead(1).ToString & " " & _ datRead(0).ToString) Loop datRead.Close( )
Retrieving Data
Because you will often know the data types of your return data, you can use the Get methods to retrieve data in columns by specifying their data type. This approach can improve application performance because no type conversion is required, but your data and output types must be identical. The following example shows how to use the GetString method to retrieve data. With GetString, you no longer need the ToString method shown in the preceding example.
Do Until datRead.Read = False MessageBox.Show(datRead.GetString(1) & " " & _ datRead.GetString(0)) Loop
15
The following example shows how to execute the stored procedure MultiResult and access the information contained in each result set:
Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) Dim commSQL As New SqlClient.SqlCommand( ) commSQL.Connection = conSQL commSQL.CommandType = CommandType.StoredProcedure commSQL.CommandText = "MultiResult" Dim datRead As SqlClient.SqlDataReader datRead = commSQL.ExecuteReader( ) Do Do Until datRead.Read = False MessageBox.Show(datRead.GetString(1)) Loop Loop While datRead.NextResult datRead.Close( )
16
Topic Objective
Lead-in
The DataAdapter serves as the link between a data source and a DataSet. It is used to retrieve data and insert it into DataTable objects for disconnected use.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the DataAdapter object to exchange data between a data source and a DataSet. You can use it to retrieve appropriate data and insert it into DataTable objects within a DataSet, and to update changes from the DataSet back into the data source.
17
The following example shows how to use Connection and Command objects to instantiate a DataAdapter:
Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) Dim comSQL As New SqlClient.SqlCommand( ) comSQL.Connection = conSQL comSQL.CommandText = "Select * from authors" Dim adaptSQL As New SqlClient.SqlDataAdapter( ) adaptSQL.SelectCommand = comSQL
18
19
Topic Objective
Lead-in
Having reviewed the code to retrieve data by using ADO.NET, you will now see the code working.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to retrieve data from a SQL Server database by using the SQLDataReader object in a Visual Basic .NETbased application.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
20
Disconnected Data Review The DataSet Object Populating DataSets Using Relationships in DataSets Using Constraints Updating Data in the DataSet Updating Data at the Source
Lead-in
You have just seen how to populate a DataSet by using a DataAdapter. Now you will learn how to use this object.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** DataSets are the primary object that you will work with when accessing disconnected sets of data. They are similar in concept to groups of ADO disconnected recordsets, but in ADO.NET, there are many enhancements, including the ability to relate tables together. In this lesson, you will learn how to create DataSets and populate tables within them. You will also learn how to edit these tables and propagate those changes to the data source. After completing this lesson, you will be able to: Create DataSets and populate tables within them. Edit tables within DataSets. Propagate changes to the data source.
21
Topic Objective
DAO DAO
Lead-in
RDO RDO
Connected Connected and and disconnected disconnected environments environments COM COM Marshalling Marshalling
ADO ADO
ADO.NET ADO.NET
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Each new data access technology has improved on the concept of disconnected data, but ADO.NET is the first one to provide a truly enterprise-wide solution.
The slide associated with this topic is an animated slide. It begins by showing only the DAO information. The other boxes are revealed on subsequent mouse clicks.
22
Delivery Tip
ADO.NET is designed for use in the Internet world, whereas COM may not be supported by all tiers, and may not be transmitted through firewalls. The disconnected architecture has been updated from the previous two-tier, RDO, and ADO architectures. ADO.NET uses XML as its transmission format. This is a text-based format, alleviating the problems associated with the transmission of COM objects and ensuring true cross-platform interoperability. ADO.NET provides you with a new object for the caching of data on the client computer. This object is known as a DataSet. This object is automatically disconnected from the data source but maintains the ability to later update the source based on changes made at the client.
23
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The DataSet object is a disconnected, memory resident cache of data. It is structured in a similar manner to a database in that it contains DataTable, DataRelation, and Constraint objects.
DataSets
A typical use of a DataSet is through Web Services. A client application will make a request for data to a Web Service that will populate a DataSet (using a DataAdapter) and return it to the client. The client can then view and modify the DataSet by using properties and methods that are consistent with database operations, and then pass it back to the Web Service. The Web Service will then update the database with the clients changes. The DataSet is transmitted between tiers as XML, which means that it can be also be used by nonADO.NET clients.
24
Populating DataSets
Topic Objective
To discuss how to create and populate DataSets.
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Because a DataSet is simply a memory resident representation of data, you do not necessarily need to take it from a traditional data source, such as a relational database management system (RDBMS) or a message store. You can create it at run time to manipulate data created within an application, or you can use it to view XML data.
Populating DataSets from XML data will be covered in the last lesson of this module.
25
The addition of data and constraints to this table will be covered later in this lesson.
26
Topic Objective
Creating relationships
Dim Dim relPubsTitle relPubsTitle As As New New DataRelation("PubsTitles", DataRelation("PubsTitles", _ _ datPubs.Tables("Publishers").Columns("pub_id"), datPubs.Tables("Publishers").Columns("pub_id"), _ _ datPubs.Tables("Titles").Columns("pub_id")) datPubs.Tables("Titles").Columns("pub_id")) datPubs.Relations.Add(relPubsTitle) datPubs.Relations.Add(relPubsTitle)
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The basis of most RDBMSs is the ability to relate tables to each other. ADO.NET provides this ability within DataSets through the DataRelation class. Each DataRelation object contains an array of DataColumn objects that define the parent column or columns, or primary key, and the child column or columns, or foreign key, in the relationship. Referential integrity is maintained by the relationship, and you can specify how to deal with related changes.
27
Creating Relationships
The following example shows how to create a relationship between two DataTable objects in a DataSet. The same DataAdapter is used to populate the DataTable objects, and then a DataRelation is created between the two.
Dim conSQL As New SqlClient.SqlConnection( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) Dim adaptSQL As SqlClient.SqlDataAdapter Dim datPubs As New DataSet( ) adaptSQL = New SqlClient.SqlDataAdapter("Select pub_id," & _ "pub_name, city, state from publishers", conSQL) adaptSQL.Fill(datPubs, "Publishers") adaptSQL = New SqlClient.SqlDataAdapter("Select pub_id," & _ "title, type, price from titles", conSQL) adaptSQL.Fill(datPubs, "Titles") Dim relPubsTitle As New DataRelation("PubsTitles", _ datPubs.Tables("Publishers").Columns("pub_id"), _ datPubs.Tables("Titles").Columns("pub_id")) datPubs.Relations.Add(relPubsTitle)
28
Using Constraints
Topic Objective
To explain the importance of constraints and how to use them.
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can create your own constraints within a DataSet, or you can copy the existing constraints from the data source. Each of these options is available to you in ADO.NET.
ForeignKeyConstraint
This constraint controls what happens to a child row when a parent row is updated or deleted. You can specify different behaviors for different circumstances. The following table shows the values for the DeleteRule and UpdateRule properties of the ForeignKeyConstraint.
Value Cascade SetNull SetDefault None Description Deletes or updates any child records based on the parent record. Sets related values to DBNull. Sets related values to their defaults. Does not affect related rows.
29
The following example shows how to apply a foreign key constraint with specific actions between two tables in an existing DataSet. If a row in the parent table is deleted, the child value will be set to DBNull. If a row in the parent table is updated, the child values will be also be updated.
Dim colParent As DataColumn Dim colChild As DataColumn Dim fkcPubsTitles As ForeignKeyConstraint colParent = datPubs.Tables("publishers").Columns("pub_id") colChild = datPubs.Tables("titles").Columns("pub_id") fkcPubsTitles = New _ ForeignKeyConstraint("PubsTitlesFKConstraint", colParent, _ colChild) fkcPubsTitles.DeleteRule = Rule.SetNull fkcPubsTitles.UpdateRule = Rule.Cascade datPubs.Tables("titles").Constraints.Add(fkcPubsTitles) datPubs.EnforceConstraints = True
UniqueConstraint
This constraint can be added to one column or to an array of columns. It ensures that all values in the column or columns are unique. When this constraint is added, ADO.NET verifies that the existing data does not violate the constraint and maintains the setting for all changes to that DataTable. The following example shows how to add a UniqueConstraint to a column:
Dim ucTitles As New UniqueConstraint("UniqueTitles", _ datPubs.Tables("titles").Columns("title")) datPubs.EnforceConstraints = True
30
Note Constraints are automatically added to columns when you create a relationship between them. A UniqueConstraint is added to the primary key, and a ForeignKeyConstraint is added to the foreign key.
31
Adding rows
Dim Dim drNewRow drNewRow As As DataRow DataRow = = datPubs.Tables("Titles").NewRow datPubs.Tables("Titles").NewRow 'Populate 'Populate columns columns datPubs.Tables("Titles").Rows.Add(drNewRow) datPubs.Tables("Titles").Rows.Add(drNewRow)
Lead-in
Once you have access to data, you are likely to want to be able to change some of it.
Editing rows
drChangeRow.BeginEdit( drChangeRow.BeginEdit( ) ) drChangeRow("Title") drChangeRow("Title") = = drChangeRow("Title").ToString drChangeRow("Title").ToString & &" " 1" 1" drChangeRow.EndEdit( ) drChangeRow.EndEdit( )
Deleting data
datPubs.Tables("Titles").Rows.Remove(drDelRow) datPubs.Tables("Titles").Rows.Remove(drDelRow)
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you have created a DataSet of DataTables, you might want to add, update, and delete data. Any changes you make to the data are stored in memory and later used to apply the changes to the data source.
Adding Rows
Use the following steps to add new rows to a table: 1. Instantiate a DataRow object by using the NewRow method of the DataTable. 2. Populate the columns with data. 3. Call the Add method of the DataRows collection, passing the DataRow object. The following example shows how to add rows to a DataSet:
Dim drNewRow As DataRow = datPubs.Tables("Titles").NewRow drNewRow("title") = "New Book" drNewRow("type") = "business" datPubs.Tables("Titles").Rows.Add(drNewRow)
32
Editing Rows
Use the following steps to edit existing rows: 1. Call the BeginEdit method of the row. 2. Change the data in the columns. 3. Call EndEdit or CancelEdit to accept or reject the changes. The following example shows how to edit data in an existing column:
Dim drChangeRow As DataRow = datPubs.Tables("Titles").Rows(0) drChangeRow.BeginEdit( ) drChangeRow("Title") = drChangeRow("Title").ToString & " 1" drChangeRow.EndEdit( )
Deleting Data
Use either of the following methods to delete a row: Remove method Call the Remove method of the DataRows collection. This permanently removes the row from the DataSet. Delete method Call the Delete method of the DataRow object. This only marks the row for deletion in the DataSet, and calling RejectChanges will undo the deletion. The following example shows how to delete an existing row from a DataSet:
Dim drDelRow As DataRow = datPubs.Tables("Titles").Rows(0) datPubs.Tables("Titles").Rows.Remove(drDelRow)
33
Topic Objective
Lead-in
After you have updated your DataSet, you will want to replicate those changes to the data source.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you have updated the tables in your DataSet, you will want to replicate those changes to the underlying data source. To do this, you use the Update method of the DataAdapter object, which is the link between DataSet and data source. The Update method, like the Fill method, takes two parameters: the DataSet in which the changes have been made and the name of the DataTable in which the changes are. It determines the changes to the data and executes the appropriate SQL command (Insert, Update or Delete) against the source data.
34
The following example shows how to use the InsertCommand property to add a row to the Titles table in the Pubs database:
Dim conSQL As New SqlClient.SqlConnection( ) Dim adaptSQL As SqlClient.SqlDataAdapter Dim datPubs As New DataSet( ) conSQL.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" conSQL.Open( ) adaptSQL = New SqlClient.SqlDataAdapter("Select pub_id," & _ "title_id, title, type, price from titles", conSQL) adaptSQL.Fill(datPubs, "Titles") Dim drNewRow As DataRow = datPubs.Tables("Titles").NewRow drNewRow("title_id") = "hg3454" drNewRow("title") = "New Book" drNewRow("type") = "business" datPubs.Tables("Titles").Rows.Add(drNewRow) Dim comm As New SqlClient.SqlCommand("Insert titles" & _ "(title_id, title, type) values (@title_id,@title,@type)") comm.Parameters.Add("@title_id", SqlDbType.VarChar, 6, _ "title_id") comm.Parameters.Add("@title", SqlDbType.VarChar, 80, "title") comm.Parameters.Add("@type", SqlDbType.Char, 12, "type") adaptSQL.InsertCommand = comm adaptSQL.Update(datPubs, "titles")
35
Note Even though the automatically generated commands can simplify your coding, you will improve performance by using the InsertCommand, UpdateCommand, and DeleteCommand properties.
36
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this practice, you will update existing data in a SQL Server database by using automatically generated commands. To review the application 1. Open Microsoft Visual Studio .NET. 2. On the File menu, point to Open, and then click Project. Set the location to install folder\Practices\Mod08\DataSets\Starter, click DataSets.sln, and then click Open. 3. Run the application, and click Populate DataSet and Refresh List from Data Source. Note that the list on the left displays data from a DataSet, and the list on the right uses a DataReader object. Quit the application. 4. Review the code in Form1.vb to see how the DataSet was created. To update the local DataSet 1. In the btnEditName_Click procedure, locate the comment add code to update the dataset here. 2. Add the following lines below the comment to update the local dataset:
objDataTable = dsCustomers.Tables("customers") objDataRow = objDataTable.Rows(iCust) objDataRow("lastname") = strNewName
37
To automatically generate a command 1. In btnUpdate_Click procedure, locate the comment add code to update the data source here. 2. To generate the update command automatically, add the following lines below the comment:
Dim sqlCommBuild As New _ SqlClient.SqlCommandBuilder(adaptCustomers) adaptCustomers.Update(dsCustomers, "customers")
To test your code 1. Run the application, and click Populate DataSet and Refresh List from Data Source. 2. Click the first name in the Local DataSet box. Click Edit Name, type your last name, and then click OK. Click Refresh List from DataSet, and note that the change has been made to the local dataset. Click Refresh List from Data Source, and note that the underlying data source still contains the original data. 3. Click Update Changes. Click Refresh List from Data Source, and verify that the changes have now been replicated to the underlying data source. 4. Quit the application, and quit Visual Studio .NET.
38
Designing DataSets Data Form Wizard Data Binding in Windows Forms Data Binding in Web Forms
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Data binding has been an important part of Visual Basic data development for a long time. The tools included in Visual Basic .NET have been enhanced to allow easier creation of data-bound forms and to take advantage of the new features in ADO.NET. After completing this lesson, you will be able to: Describe the data designers available in Visual Basic .NET. Create data-bound Windows Forms and Web Forms.
39
Designing DataSets
Topic Objective
To discuss how to create connections, commands, and DataSets by using the Visual Basic designers.
DataAdapter Configuration Wizard Generates a DataAdapter object in the InitializeComponent procedure for use in your code Generate DataSet Tool Generates a DataSet based on data from an existing DataAdapter
Lead-in
Visual Basic .NET includes a number of designers to simplify the process of DataSet creation.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Visual Basic .NET includes a number of designers to simplify the process of DataSet creation. These include the Connection Wizard, DataAdapter Configuration Wizard, and the Generate DataSet Tool. Delivery Tip
Remind students that these wizards just automate the manual process that they have learned about already.
40
Again, once created, you can use this DataSet in the usual way in your code.
41
Information required: Name of DataSet Connection to be used Which tables or views, and which columns within them How to display the data Which buttons to create
Lead-in
You can use the Data Form Wizard to automatically bind data to controls on a form.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the Data Form Wizard to automatically bind data to controls on a form. You can specify to use an existing DataSet in the project, which will then use your pre-written methods for data access, or to create a new DataSet based on information supplied to the wizard. If you want to create a new DataSet, the Data Form Wizard will require the following information: Name of the DataSet to create Connection to be used (you can create a new connection at this point) Which tables or views to use (if more than one, you can also identify the relationship between them) Which columns to include on the form How to display the data (data grid or bound controls) Whether to include navigation and editing buttons
42
Topic Objective
Lead-in
In this demonstration, you will learn how to use the Data Form Wizard to create a data-bound form from a new DataSet.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the Data Form Wizard to create a data-bound form from a new DataSet.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
43
Topic Objective
Lead-in
Simple binding
da da = = New New SqlClient.SqlDataAdapter("Select SqlClient.SqlDataAdapter("Select au_lname, au_lname, " "& &_ _ "au_fname "au_fname from from authors", authors", sqlconn) sqlconn) da.Fill(ds, da.Fill(ds, "authors") "authors") TextBox1.DataBindings.Add("Text", TextBox1.DataBindings.Add("Text", _ _ ds.Tables("authors"), ds.Tables("authors"), "au_fname") "au_fname")
Windows Forms data binding allows for more control over the appearance of your application than applications created with the Data Form Wizard.
Complex binding
da da = = New New SqlClient.SqlDataAdapter("Select SqlClient.SqlDataAdapter("Select au_lname, au_lname, " "& &_ _ "au_fname from authors", sqlconn) "au_fname from authors", sqlconn) da.Fill(ds, da.Fill(ds, "authors") "authors") DataGrid1.DataSource DataGrid1.DataSource = = ds.Tables("authors") ds.Tables("authors")
*****************************ILLEGAL FOR NON-TRAINER USE****************************** If you want more control over the appearance of your forms, you can use data binding to design them yourself. There are two general types of binding that can be used: simple binding and complex binding. Both can be performed at design time by using the Properties window or at run time by using code.
Simple Binding
You use simple binding to link a control to a single field in a DataSet. For example, you would use simple binding for a TextBox control. Using the DataBindings property of a data-aware control, you can specify which DataSet and which field to bind to which property.
44
Complex Binding
You use complex binding to link a control to multiple fields in a DataSet. For example, you would use complex binding for a DataGrid control. These controls have a DataSource property that allows you to specify the table to be used. The following example shows how to use the DataSource property of a DataGrid control:
Dim sqlconn As New SqlClient.SqlConnection( ) Dim da As SqlClient.SqlDataAdapter Dim ds As New DataSet( ) sqlconn.ConnectionString = "Integrated Security=True;" & _ "Data Source=LocalHost;Initial Catalog=Pubs;" sqlconn.Open( ) da = New SqlClient.SqlDataAdapter("Select au_lname, " & _ "au_fname from authors", sqlconn) da.Fill(ds, "authors") DataGrid1.DataSource = ds.Tables("authors")
Delivery Tip
Updating Data
As with manual coding of data access, changing values in data-bound forms only applies to the local DataSet. To write these changes to the underlying data source, you must add your own code by using the Update method of the DataAdapter.
45
Topic Objective
Lead-in
Use impersonation
<identity <identity impersonate="true" impersonate="true" userName="Karen" userName="Karen" password="Password"/> password="Password"/>
Few Web applications can function without some sort of data display.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Most data displayed on Web Forms will be read only, so you do not need to incorporate the overhead of using a DataSet in your Web Form applications; you can use the more efficient DataReader object instead. If you want your users to be able to edit data on the Web Form, you must code the edit, update, and cancel events yourself.
Use Impersonation
You must configure impersonation when connecting to SQL Server from a Web form. To do this, add an <identity> tag similar to the following example to the Web.config file:
<identity impersonate="true" userName="Karen" password="Password"/>
The DataGrid will not be visible until you call the DataBind method.
46
XML Integration
Topic Objective
To provide an overview of the topics covered in this lesson.
Why Use Schemas? Describing XML Structure Creating Schemas Using XML Data and Schemas in ADO.NET DataSets and XmlDataDocuments
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Traditionally, XML and ADO data have been two distinct entities, but ADO.NET brings them together and allows you to work with both types in the same way. XML is tightly integrated into the .NET platform. You have already seen how DataSets are transmitted by using XML format, and now you will learn how DataSets are literally represented as XML and how their structure is defined in an XML Schema Definition (XSD). After completing this lesson, you will be able to: Describe what an XML schema is. Explain why XML schemas are useful to the Visual Basic .NET developer. Create schemas. Manipulate XML data within an ADO.NET DataSet by means of an XMLReader.
This lesson assumes that students have reasonable knowledge of XML and an awareness of its associated technologies. You may find that you need to provide more background information if students are not familiar with these concepts.
47
Topic Objective
Define format of data Use for validity checking Advantages over DTDs XML syntax Reusable types Grouping
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** When working with traditional database applications, you often need to write validation code to ensure that the data you are inputting matches the database schema. If you do not do this, then you need to write error-handling code for the potential errors that may occur. Either way, there must be some way of checking. The solution to this problem when you are working with XML data is XML schemas. XML schemas are similar in concept to database schemas. They define the elements and attributes that may appear in your XML documents, and how these elements and attributes relate to each other. Schemas are very important to ensure that the data you are using conforms to your specification. When loading XML data, you can check it against the schema to validate that none of the data entering your system is in an incorrect format. This is becoming more of an issue as business-to-business and business-to-customer commerce becomes more prevalent in the Internet world.
48
Visual Studio .NET uses XSD to create schemas. This syntax is currently at working-draft status at the World Wide Web Consortium (W3C), but it has many advantages over document type definitions (DTDs). Delivery Tip XML syntax DTDs are written using a DTD syntax, which is not related to any of the other Internet standards currently in use. XSD uses XML syntax, which enables developers to validate data without needing to learn yet another language. Reusable types XSD allows you to define complex data types and reuse those within your schema. Grouping You can specify that a set of elements always exists as a group and stipulate the order in which they must appear.
If students are not familiar with DTDs, do not spend too much time justifying the use of a new technology to them.
49
Schemas can describe: Elements in the document Attributes in the document Element and attribute relationships Data types The order of the elements Which elements are optional
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Schemas describe the structure of an XML document, and you can use them to validate data within that document. A schema document can describe all or some of the following: Elements and attributes contained within the XML document Element and attribute relationships Data types The order of the elements Which elements are optional For example, consider the following XML document:
<?xml version="1.0" ?> <pubs> <Publishers> <pub_id>0736</pub_id> <pub_name>Lucerne Publishing</pub_name> <city>Boston</city> <state>MA</state> <country>USA</country> </Publishers> <Publishers> <pub_id>0877</pub_id> <pub_name>Litware, Inc.</pub_name> <city>Washington</city> <state>DC</state> <country>USA</country> </Publishers> </pubs>
50
This document consists of a <pubs> element containing individual <Publishers> elements. Each of these contains a <pub_id>, <pub_name>, <city>, <state>, and <country> element. This defines the structure of the document. After the XML document is linked to a schema document describing the structure, the schema can be used to verify data being input into the document. The following example shows the schema generated for this document:
<?xml version="1.0" ?> <xsd:schema id="pubs" targetNamespace="http://tempuri.org/Publishers.xsd" xmlns="http://tempuri.org/Publishers.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xsd:element name="pubs" msdata:IsDataSet="true" msdata:EnforceConstraints="False"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="Publishers"> <xsd:complexType> <xsd:sequence> <xsd:element name="pub_id" type="xsd:string" minOccurs="0" <xsd:element name="pub_name" type="xsd:string" minOccurs="0" <xsd:element name="city" type="xsd:string" minOccurs="0" <xsd:element name="state" type="xsd:string" minOccurs="0" <xsd:element name="country" type="xsd:string" minOccurs="0" </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>
51
Creating Schemas
To discuss how to create schemas in Visual Basic .NET.
Topic Objective
Creating schemas from existing XML documents Creating schemas from databases Working with schemas Validating XML documents against schemas
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Schemas are automatically generated for you when you work with DataSets. You may find that there are situations when you want to create your own. One example would be when you are exchanging data with a business partner and want to define the structure of that data.
52
53
Lead-in
Accessing XML data by means of ADO.NET solves an issue that developers have had in the past.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** One of the issues experienced by developers in the past has been trying to manipulate XML data within their applications. In earlier data access technologies, there was no ability to do this. In ADO.NET, you can populate a DataSet from an XML document. This allows you to access the data in a simple fashion.
54
Typed DataSets also provide compile-time type checking and better performance than untyped DataSets. Note DataSets created using the XML Designer tools are automatically typed.
55
Topic Objective
Lead-in
XML developers have traditionally used the XML DOM to manipulate their XML documents.
XmlDataDocument
sync
DataSet
XmlReader
XmlReader
Managed Provider
XML Documents
XML Documents
Data Source
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip XML developers have traditionally used the Document Object Model (DOM) to manipulate their XML documents. This is a standard COM interface to XML data, and it allows access to the elements and attributes contained within the document. The XmlDataDocument in the .NET Framework extends the DOMDocument object in the XML DOM to allow .NET developers to use the same functionality. This object is tightly integrated with the ADO.NET DataSet, and loading data into either object synchronizes it with the other. Any manipulation of data by means of the DataSet or the XmlDataDocument is synchronized in the other. Therefore, if you add a row to the DataSet, an element is added to the XmlDataDocument, and vice versa.
This topic is not meant to cover how to use XmlDataDocuments but to simply provide an overview of the link with DataSets.
56
Topic Objective
Lead-in
This demonstration will show you how to use an XML schema to validate and XML document.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this demonstration, you will learn how to create an XML schema from an existing XML document, and how to then use the schema to validate the document.
57
Objectives
After completing this lab, you will be able to: Retrieve, insert, and update data by using ADO.NET. Use data binding on a Web Form. Use the XML Designer to create a typed dataset.
Prerequisites
Before working on this lab, you must be familiar with: Creating Visual Basic .NET Windows Forms and Web Forms. Using ADO.NET data readers. Using ADO.NET DataSets. Working with XML and XSD.
Scenario
In this lab, you will use ADO.NET to access data for the Cargo application. You will create both Windows Forms and Web Forms that access both customer and invoice information. You will also use the XML Designer to create a typed DataSet.
58
59
6. Save the project. To create the Cargo class 1. On the Project menu, click Add Class. 2. Rename the class Cargo.vb, and then click Open. 3. At the top of the class, add an Imports statement to reference the System.Data.SqlClient namespace. 4. In the Cargo class, create private class-level variables, using the information in the following table.
Variable name dstCargo conCargo Type DataSet SqlConnection
60
To create the connection 1. Create a constructor for the class. 2. Instantiate the conCargo Connection object. 3. Using the information in the following table, set the ConnectionString property of conCargo.
Name Data Source Initial Catalog Integrated Security Value localhost Cargo True
To create the GetCustomers method 1. Create a method called GetCustomers for the class. The method takes no arguments and has no return value. 2. In this method, declare and instantiate a SqlDataAdapter object called adpCust. Pass the following information to the constructor.
Argument selectCommandText selectConnection Value Select CustomerID, FirstName, LastName, CompanyName, Email, Address from Customers conCargo
3. Instantiate the DataSet object. 4. Use the Fill method of adpCust to pass the following information.
Argument dataSet srcTable Value dstCargo CustTable
To create the CustList property 1. Define a read-only property called CustList that returns a DataTable. 2. In the Get clause, return the CustTable table from dstCargo. 3. Save and build the project.
61
To populate the list box 1. Open the frmCustomer Code Editor. 2. Declare and instantiate a private class-level variable called objCargo of type Cargo. 3. Create the frmCustomer_Load event handler. 4. Call the GetCustomers method of the objCargo object. 5. Add the following code to loop through the customers and populate the list box:
Dim CurRows( ) As DataRow, CurRow As DataRow CurRows = objCargo.CustList.Select( ) For Each CurRow In CurRows lstCustomers.Items.Add(CurRow("FirstName").ToString & _ " " & CurRow("LastName").ToString) Next
6. Call the SetSelected method of lstCustomers to select the first item in the list. To populate the text boxes 1. Create the lstCustomers_SelectedIndexChanged event handler. 2. Declare an Integer variable called RowNum, and then store the SelectedIndex property of the list box in the variable. 3. Declare a DataRow variable called CurRow, and then store the row identified by RowNum in it by using the following line of code:
objCargo.CustList.Rows(RowNum)
4. Using the information in the following table, populate the text boxes with data from this row.
Text box txtID txtCompany txtEmail txtAddress Column name CustomerID CompanyName Email Address
5. Save the project. To test the application 1. On the Build menu, click Build CustomerProject, and resolve any build errors. 2. On the Debug menu, click Start. You should see that the list box and text boxes are populated with data. 3. Click on a different customer in the list and verify that the text boxes display the relevant data. 4. Quit the application. 5. Quit Visual Studio .NET.
62
3. Using the information in the following table, declare and initialize a variable.
Name editRow Type DataRow Initialization Value
dstCargo.Tables("CustTable").Rows(RowNum)
63
5. Update the data in the DataSet with the arguments passed to the procedure. Use the information in the following table.
editRow item CompanyName Email Address Argument strCompany strEmail strAddress
6. Call the EndEdit method of the editRow object. To update the underlying data 1. Using the information in the following table, declare and instantiate a variable.
Name commUpdate Type SqlCommand Construction Value
"Update customers set CompanyName= @company, email=@email, address=@address where customerid=@id", conCargo
2. Use the Add method of the commands Parameters collection to create parameters for this command. Use the information in the following table.
parameterName @id @company @email @address sqlDbType SqlDbType.Int SqlDbType.VarChar SqlDbType.VarChar SqlDbType.VarChar size 4 50 255 255 sourceColumn CustomerID CompanyName Email Address
3. In the GetCustomers procedure, locate the declaration for adpCust. 4. Remove the declaration for adpCust (leaving the instantiation code), and then declare adpCust as a class-level variable. 5. In the EditDetails procedure, set the UpdateCommand property of adpCust to the commUpdate command. 6. Call the Update method of adpCust, and pass it the existing DataSet and the name of the DataTable object.
64
To call the EditDetails method 1. Open the frmCustomer.vb code window, and create a handler for the btnSave_Click event. 2. Add code to call the EditDetails method of the objCargo object to pass the appropriate parameters. Use the information in the following table.
Parameter RowNum ID strCompany strEmail strAddress Value lstCustomers.SelectedIndex txtID.Text txtCompany.Text txtEmail.Text txtAddress.Text
3. Set the ReadOnly property of the following text boxes to True. txtCompany txtEmail txtAddress To test your code 1. Run the application. 2. Click Edit Details, replace the company name with Microsoft, and then click Save. 3. Quit the application. 4. Run the application again, and verify that the changes have been saved. 5. Quit the application. 6. Quit Visual Studio .NET.
65
66
To create the connection 1. Open the code window for WebForm1.aspx. 2. Add an Imports statement to access the System.Data.SqlClient namespace. 3. Locate the Page_Load procedure, and declare a procedure-level variable, using the information in the following table.
Name sqlConn Type SqlConnection
4. Instantiate the connection object, and then set the ConnectionString property, using the information in the following table.
Name Data Source Initial Catalog Integrated Security Value localhost Cargo True
5. Call the Open method of the connection object. To bind the data 1. In the Page_Load procedure, declare and instantiate a SqlCommand object called comInvoices, and pass the parameters listed in the following table.
Parameter cmdText Connection Value Select * from Invoices sqlConn
2. Declare a SqlDataReader object called drInvoices. 3. Call the ExecuteReader method of the command object, and store the results in drInvoices. 4. Set the DataSource property of the DataGrid to drInvoices. 5. Call the DataBind method of the DataGrid. To test your code 1. Run the application and verify that the invoices are displayed in a grid on the Web Form. 2. Close Internet Explorer, and then close Visual Studio .NET.
67
To create the schema 1. In the Solution Explorer, click InvoiceApp. On the Project menu, click Add New Item. 2. In the Templates box, click XML Schema, rename the item to InvSchema.xsd, and then click Open. 3. In Server Explorer, expand Data Connections, expand the connection that you just created, expand Tables, and then click Invoices. 4. Drag Invoices onto the Schema Designer. 5. Review the schema in both XML view and Schema view. To create the DataSet 1. In Schema view, on the Schema menu, click Generate Dataset. 2. In Solution Explorer, click Show All Files, and expand InvSchema.xsd. You will see that an InvSchema.vb file has been created containing code to generate a typed DataSet. 3. Review the code in InvSchema.vb.
68
To create the form 1. Open the design window for Form1.vb. 2. Add three Label controls, three TextBox controls, and a Button control to the form. Use the information in the following table to set their properties.
Control Label1 Label2 Label3 TextBox1 TextBox2 TextBox3 Button Property Name Text Name Text Name Text Name Text Name Text Name Text Name Text Value lblInvoiceID Invoice ID lblCustomerID Customer ID lblAmount Amount txtInvoiceID <empty> txtCustomerID <empty> txtAmount <empty> btnFill Fill
3. From the Data tab of the Toolbox, add a DataSet control to the form, using the information in the following table.
Setting Type of DataSet Name Value Typed InvoiceApp.Document
To populate the DataSet 1. Create an event handler for the btnFill_Click event. 2. Declare and instantiate a SqlClient.SqlConnection object called sqlConn using the information in the following table.
Name Data Source Initial Catalog Integrated Security Value localhost Cargo True
3. Call the Open method of sqlConn. 4. Declare and instantiate a SqlClient.SqlDataAdapter object called sqlAdapt using the information in the following table.
Parameter selectCommandText selectConnection Value Select * from Invoices sqlConn
69
5. Declare and instantiate a variable, using the information in the following table.
Name invTable Type Document.InvoicesDataTable
To populate the text boxes 1. In btnFill_Click, add code to populate the text boxes with the appropriate data. Use the information in the following table.
Control txtInvoiceID txtCustomerID txtAmount Text property Document1.Invoices(0).InvoiceID Document1.Invoices(0).CustomerID Document1.Invoices(0).Amount
2. Build and save the project. To test your code 1. Run the application. 2. Click Fill, and verify that the text boxes are correctly populated with data. 3. Quit the application, and quit Visual Studio .NET.
70
Review
Topic Objective
To reinforce module objectives by reviewing key points.
ADO.NET Overview .NET Data Providers The DataSet Object Data Designers and Data Binding XML Integration
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. State three benefits that ADO.NET has over earlier data access technologies. It is part of the .NET Framework, it is designed for disconnected data, and it is integrated with XML.
2. You have the following code in your application. What would you do to make the code more efficient? Why?
Dim sqlConn As New SqlClient.SqlConnection("Integrated Security=True;Data Source=LocalHost;Initial Catalog=Pubs;") sqlConn.Open( ) Dim sqlAdapt As New SqlClient.SqlDataAdapter("Select au_lname from authors", sqlConn) Dim sqlDataSet As New DataSet( ) sqlAdapt.Fill(sqlDataSet, "Authors") Dim i As Integer For i = 0 To sqlDataSet.Tables("Authors").Rows.Count - 1 MessageBox.Show(sqlDataSet.Tables("Authors").Rows(i).Item(0 ).ToString) Next
You should replace the DataSet with a DataReader because a DataReader is more efficient for read-only, forward-only data access. This is because a DataReader only holds one record in memory at a time.
71
3. If you change the contents of a DataTable in a DataSet, will those changes be reflected in the underlying data source? Why, or why not? The changes will only be reflected if you explicitly call the Update method of the DataAdapter. If you do not do this, the changes are made locally in the DataSet, which has no permanent connection to the source.
4. You have the following code in the Page_Load event of a Web Form, but the DataGrid does not appear. What is wrong, assuming all objects are correctly declared and instantiated?
sqlReader = sqlComm.ExecuteReader DataGrid1.DataSource( ) = sqlReader
You have neglected to call the DataBind method of the DataGrid, as shown in the following line of code:
DataGrid1.DataBind( )
5. Write the code to load an XML document called Books.xml into a DataSet.
Dim ds As New DataSet( ) ds.ReadXml("books.xml")
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 90 Minutes Labs: 90 Minutes This module provides students with the knowledge required to create and use different types of components by using Microsoft Visual Basic .NET. In the first lab, students will create a serviced component that retrieves customer information based on the customers e-mail address and password. Students will register this component with Component Services and set constructor string properties of the component by using the Component Services console. They will then test the serviced component with a simple Windows-based application. In the second lab, students will create a Web user control that requests logon information from a customer. They will place the user control on a Web Form and use the serviced component that they created in the first lab to retrieve the customer information so that it can be displayed on a welcome screen. After completing this module, students will be able to: Describe the different types of components that they can create in Visual Basic .NET. Create components that can be used by managed and unmanaged client applications. Create serviced components. Create component classes. Create Microsoft Windows Forms controls. Create Web Forms user controls. Use threading to create multithreaded applications.
iv
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_09.ppt Module 9, Developing Components in Visual Basic .NET Lab 9.1, Creating a Serviced Component Lab 9.2, Creating a Web Forms User Control
Preparation Tasks
To prepare for this module: Read all of the materials for this module. Complete the labs.
Demonstrations
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
vi
To view the test harness 1. Open Visual Studio .NET. 2. Open the TestPooling.sln project in the install folder\DemoCode\Mod09\ ObjectPoolingComponent\TestPooling folder. 3. Add a project reference to install folder\DemoCode\Mod09\ ObjectPoolingComponent\bin\ObjectPoolingComponent.dll. 4. View the form code, examining each method. To test the component 1. Run the project. 2. Click Pooling and explain the messages that appear. 3. Click No Pooling and explain the messages that appear. 4. Quit the application. 5. Run the project again, and show that this time there are no new objects created. 6. Quit the application, and then quit Visual Studio .NET. Important If you have previously run this demonstration on the same machine, you may find that the serviced component is already installed. Remove the Object Pooling application from the Component Services console before rerunning this demonstration.
vii
To create a Toolbox icon for the component Delivery Tip 1. Add a reference to the System.Drawing.dll assembly. 2. Modify the class definition to read as follows:
<System.Drawing.ToolboxBitmap("")> _ Public Class Stopwatch
Point out that the extra reference must be added to allow you to use the ToolboxBitmap attribute from the System.Drawing namespace in projects built on this type of project template.
3. In Solution Explorer, drag the Timer01.ico file and place it between the string quotes in the ToolboxBitmap("") code. Point out that adding the bitmap as an assembly resource may be a better approach, because it will not rely on the icon file being available in the correct location. However, for this demonstration, this approach is acceptable. To build the component 1. Build the project. 2. Close the project. To modify the test harness 1. Open the TestComponentClasses.sln project in the install folder\DemoCode\Mod09\Stopwatch\Starter\TestStopwatch folder. 2. On the Toolbox, click the General tab. 3. On the Tools menu, click Customize Toolbox, and then click the .NET Framework Components tab. 4. Click Browse to browse for ComponentClasses.dll in the install folder\DemoCode\Mod09\Stopwatch\Starter\bin folder, click Open and then click OK. 5. In the design window, open Form1, and then drag the Stopwatch component from the Toolbox to the form. 6. In the Properties window for the component, change the name of the component to sWatch and set the EnabledEvents property to True. Point out the property description provided by the Description attribute. 7. Examine the code in the form. To test the component 1. Run the project, ensuring that the Output window is visible in the background. 2. Click Start Stopwatch, and point out the events being displayed in the Output window. Click Tick Events to turn off the events. 3. Click Stop Stopwatch to display the amount of time that has passed since the Start method was called on the Stopwatch component. 4. Quit the application, and then quit Visual Studio .NET. Important If you have previously run this demonstration on the same computer, you may find that the Stopwatch component is already available in the Toolbox. To ensure that the demonstration functions correctly, reset the Toolbox by using the Customize Toolbox dialog box.
viii
3. Click the Undo button four times, and view the changes in each text box. 4. Close the form and quit Visual Studio .NET.
ix
4. Save the project. To use the user control 1. Open WebForm1.aspx in the Design view, and then drag the SimpleControl.ascx file from Solution Explorer to the top left corner of WebForm1. 2. In the HTML view of WebForm1.aspx, locate the following code:
<uc1:SimpleControl id="SimpleControl1" runat="server">
3. Add the following attribute to the tag to set the LabelValue property of the control:
LabelValue="Enter a value:"
4. Return to the Design view, drag a Button control from the Toolbox to the Web Form, and place it well below the SimpleControl. Change the following properties of the Button control to the following values.
Button property Text (ID) Value Get Value btnGet
5. In the Code Editor for WebForm1, add the following variable declaration immediately after the button declaration:
Protected WithEvents SimpleControl1 As SimpleControl
6. Create a Click event handler for btnGet and enter the following code:
Response.Write(SimpleControl1.TextValue)
7. Save the project. To test the control 1. Run the project. 2. Type a value into the text box, and then press the Get Value button to display the result. 3. Quit the application and Visual Studio .NET.
xi
Module Strategy
Use the following strategy to present this module: Components Overview This lesson provides an overview of creating components with Visual Basic .NET, and of how they can work with both managed and unmanaged clients. Many students will be interested in how a Visual Basic 6.0based client application can use a Visual Basic .NET component, so spend some time on the topic of using components in unmanaged client applications. Strongnamed assemblies are covered in Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET, but a simple explanation will be required in this lesson. The lesson ends with an overview of Microsoft .NET Remoting. Do not discuss this topic in detail. Instead, refer students to the Visual Studio .NET documentation or other to courses, such as Module 13, Remoting and Web Services, in Course 2415A, Programming the Microsoft .NET Framework with Visual Basic .NET (Prerelease). Creating Serviced Components This lesson relies on the students knowledge of MTS or Component Services. Ensure that all students have some awareness of these technologies, and briefly review the overall purpose of serviced components, such as providing predefined functionality for developers to use. You will then examine several aspects of serviced components, including transactions, object pooling, constructor strings, and security. Most of these should not be new to MTS or Component Services developers, but the way that the information is specified has changed. Object pooling is a significant enhancement for Visual Basic, and will be new to many students because previous versions of Visual Basic could not take advantage of this technique. Use the demonstration at the end of the lesson to reinforce this concept. End the lesson with an overview of other services provided by Component Services and of how to configure an assembly to run as a serviced application. This information will minimize the amount of administration required when installing Visual Basic .NET serviced applications. Creating Component Classes This lesson examines component classes and their uses within a Visual Basic .NETbased application. Students will learn about the architecture of a component class and how to create one. Although this is a small lesson, make sure students recognize the benefits of these types of components.
xii
Creating Windows Forms Controls This lesson relies on students having created Windows user controls in previous versions of Visual Basic. Discuss some of the ways user controls can be created and how attributes can be specified to assist other developers who use the user controls. There are other ways to create controls (such as creating controls from scratch) that are not covered because of time constraints. Direct students to the product documentation for further information regarding these topics. Creating Web Forms Controls This lesson examines how to create Web Forms user controls within an ASP.NET Web application. The lesson is quite short as the creation of these controls is very similar to the creation of Web Forms and Windows Forms user controls. Point out to students that they can also create user controls based on Web Forms simply by copying the controls from the Web Form to the Web user control. There are other types of Web user controls called Custom controls that are not covered in this course. Refer students to the online help documentation for more information. Threading This lesson examines basic concepts of using threading in a Visual Basic .NETbased application. Most Visual Basic students are not familiar with threads, so be sure to explain the basic concepts first. Discuss the advantages of using threading and how to create and use threads in a Visual Basic .NETbased application. The lesson ends by raising some of the issues that students must be aware of when using threads. Be sure to point out that threading is a powerful yet potentially dangerous technique, and that students can choose whether or not to use it in their applications.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Components Overview Creating Serviced Components Creating Component Classes Creating Windows Forms Controls Creating Web Forms User Controls Threading
Lead-in
In this module, you will learn how to create components in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** As a Microsoft Visual Basic developer, you probably already know how to develop and use components in your applications. In Visual Basic .NET version 7.0, you can use the new design-time features to easily create components and extend their functionality. After completing this module, you will be able to: Describe the different types of components that you can create in Visual Basic .NET. Create components that can be used by managed and unmanaged client applications. Create serviced components. Create component classes. Create Microsoft Windows Forms controls. Create Web user controls. Use threading to create multithreaded applications.
Components Overview
Topic Objective
To provide an overview of the topics covered in this lesson.
Types of Components Using Modules As Components Using Classes As Components Using Components in Unmanaged Client Applications .NET Remoting Overview
Lead-in
This lesson explains the types of components that you can create in a Visual Basic .NETbased application and how you can make them visible to unmanaged client applications. It also provides an overview of .NET Remoting for component communication.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you can create several types of components that are accessible from both managed client applications (those built on the services of the Microsoft .NET Framework common language runtime) and unmanaged client applications (for example, client applications created in Visual Basic 6.0). After you complete this lesson, you will be able to: Describe the types of components that you can create in Visual Basic .NET. Use modules and classes as components. Use Visual Basic .NETbased components in unmanaged environments. Explain the key concepts of .NET Remoting.
Types of Components
To explain the different types of components that you can create in Visual Basic .NET.
Topic Objective
Structures Modules Classes Component classes Serviced components User controls Windows Forms user controls Web Forms user controls
Lead-in
You can create several types of components in a Visual Basic .NETbased application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you can create several different types of components, including: Delivery Tip Structures Modules Classes Component classes Serviced components User controls
Point out that this module focuses on how to create and use component classes, serviced components, and user controls. The other component types are mentioned for reference purposes.
Structures
You can use structures as components by declaring them as public when you define them. Structures support many features of classes, including properties, methods, and events, but are value types, so memory management is handled more efficiently. Structures do not support inheritance.
Modules
You can use modules as components by declaring them as public when you define them. Declaring modules as public allows you to create code libraries that contain routines that are useful to multiple applications. You can also use modules to create reusable functions that do not apply to a particular component, class, or structure. If you have used the GlobalMultiUse or GlobalSingleUse classes in previous versions of Visual Basic, the concept of a code library is not new to you. These classes provide the same functionality in Visual Basic .NET; the client code does not need to qualify these classes by the class name to call the functions.
Classes
You can use classes as components by declaring them as public within an assembly. You can use public classes from any .NET-based client application by adding a reference to the component assembly. You can extend the functionality of classes through mechanisms such as properties, methods, and events. Classes are also extensible through inheritance, which allows applications to reuse existing logic from these components.
Component Classes
A class becomes a component when it conforms to a standard for component interaction. This standard is provided through the IComponent interface. Any class that implements the IComponent interface is a component. Component classes allow you to open your class in a visual designer, and they allow your class to be sited onto other visual designers.
Serviced Components
Serviced components are derived directly or indirectly from the System.EnterpriseServices.ServicedComponent class. Classes configured in this manner are hosted by a Component Services application and can automatically use the services provided by Component Services.
User Controls
User controls are components that are created by a developer to be contained within Windows Forms or Web Forms. Each user control has its own set of properties, methods, and events that make it suitable for a particular purpose. You can manipulate user controls in the Windows Forms and Web Forms designers and write code to add user controls dynamically at run time, just as you can for the controls provided as part of the .NET Framework. Note In this module, you will learn how to create and use component classes, serviced components, and user controls. For more information about structures, modules, and classes, see Module 5, Object-Oriented Programming in Visual Basic .NET, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Lead-in
Declare the module as public Reference and import the assembly into client code
Public Public Module Module MyMathFunctions MyMathFunctions Public Public Function Function Square(ByVal Square(ByVal lng lng As As Integer) Integer) As As Long Long Return Return (lng (lng * * lng) lng) End End Function Function ... ... End End Module Module 'Client 'Client code code Imports Imports MyAssembly MyAssembly ... ... Dim Dim x x As As Long Long = = Square(20) Square(20)
In Visual Basic .NET, you can use modules as components outside of the assembly in which they are defined.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you can use modules as components outside of the assembly in which they are defined. To make this possible, declare the module as public when you define it. You then need to create a reference in the client assembly to the component assembly and use the Imports statement to allow access to the module methods. The following example shows how to create a public module named MyMathFunctions that defines the function Square. This module is defined within the MyAssembly assembly. The module can then be used as a component in client code, as shown in the second part of the example.
Public Module MyMathFunctions Public Function Square(ByVal lng As Long) As Long Return (lng * lng) End Function ... End Module 'Client code Imports MyAssembly ... Dim x As Long = Square(20)
Note For more information about assemblies, see Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET. For the purposes of this module, you can think of them as similar to Visual Basic 6.0 Microsoft ActiveX dynamic-link libraries (DLLs).
Lead-in
Declare the class as public Reference and import the assembly into client code
Public Public Class Class Account Account Public Public Sub Sub Debit(ByVal Debit(ByVal AccountId AccountId As As Long, Long, Amount Amount As As Double) Double) 'Perform 'Perform debit debit action action End End Sub Sub Public Public Sub Sub Credit(ByVal Credit(ByVal AccountId AccountId As As Long, Long, Amount Amount As As Double) Double) 'Perform 'Perform credit credit action action End End Sub Sub End End Class Class 'Client 'Client code code Imports Imports MyAssembly MyAssembly Dim Dim x x As As New New Account( Account( ) ) x.Debit(1021, x.Debit(1021, 1000) 1000)
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use classes as components outside of the assembly in which they are defined by marking the class as public. You then reference the component assembly from the client assembly, and use the Imports statement to allow direct access to the class. The following example shows how to create a public class called Account that defines the Debit and Credit methods. This class is defined in the MyAssembly assembly. A separate client assembly then references the assembly, and the class can then be used to created object instances.
Public Class Account Public Sub Debit(ByVal AccountId As Long, Amount As Double) 'Perform debit action End Sub Public Sub Credit(ByVal AccountId As Long, Amount As Double) 'Perform credit action End Sub End Class 'Client code Imports MyAssembly Dim x As New Account( ) x.Debit(1021, 1000)
Setting assembly properties Generate a strong name Select Register for COM Interop in Build options Exposing class members to COM and Component Services Define and implement interfaces Use the ClassInterface attribute with AutoDual value Use the COMClass attribute
Lead-in
You can use COM to make all Visual Basic .NET components accessible from unmanaged clients, if you follow some simple steps.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip You can create Visual Basic .NET components that can be used by unmanaged client applications. This interoperability allows you to use Component Services features such as object pooling and transactions. In order to expose your components to COM and Component Services, you must set specific assembly properties and create your classes appropriately.
Remind students that assemblies and strong names will be covered in Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET.
After you have generated the key file, you can add it to the project and reference it in AssemblyInfo.vb by using the following code:
<Assembly: AssemblyKeyFile("KeyFile.snk")>
Your assembly will then be strong-named the next time you build it. Note For more information about creating strong-named assemblies, see Module 10, Deploying Applications, in Course 2373B, Programming with Microsoft Visual Basic .NET.
Verify that students understand what dual interfaces are, and give a brief explanation if required.
10
Client AppDomain
Marshal By Reference
Client Code
Server AppDomain
Lead-in
The .NET Framework provides several services that are used in remoting.
Formatter
Server Proxy
Channel
Marshal By Value
Client Code
Formatter
Server Object Copy
Channel
Channel
Remoting Boundary
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Previous versions of Visual Basic use COM and the distributed version of COM (DCOM) to communicate with components in different processes or on different computers. Visual Basic .NET uses .NET Remoting to allow communication between client and server applications across application domains. Delivery Tip The .NET Framework provides several services that are used in remoting: Communication channels are responsible for transporting messages to and from remote applications by using either a binary format over a Transmission Control Protocol (TCP) channel or Extensible Markup Language (XML) over a Hypertext Transfer Protocol (HTTP) channel. Formatters that encode and decode messages before they are transported by the channel. Proxies that forward remote method calls to the proper object. Remote object activation and lifetime support for marshal-by-reference objects that execute on the server. Marshal-by-value objects that are copied by the .NET Framework into the process space on the client to reduce cross-process or cross-computer round trips. Note For more information about .NET Remoting, see .NET Remoting Technical Overview in the Microsoft Visual Studio .NET documentation.
Point out that this topic only presents an overview. Module 13, Remoting and Web Services, in Course 2415A, Programming the Microsoft .NET Framework with Visual Basic .NET (Prerelease), covers this topic in more depth.
11
Hosting Components in Component Services Using Transactions Using Object Pooling Using Constructor Strings Using Security Using Other Component Services Configuring Assemblies for Component Services
Lead-in
This lesson examines .NET components that are hosted by Component Services.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After completing this lesson, you will be able to: Describe the requirements for hosting .NET-based components in a Component Services application. Enable transaction processing in your components. Use object pooling to improve performance for objects that need extra resources. Use security attributes to specify how components interact with Component Services security. Add constructors to control how a component is initialized. Explain how to use other Component Services, such as Just-In-Time activation, from Visual Basic .NET components. Set assembly-level attributes to improve the installation of your application.
12
Lead-in
Add a reference to System.EnterpriseServices in your assembly The System.EnterpriseServices namespace provides: ContextUtil class ServicedComponent class Assembly, class, and method attributes
To enable components to be hosted in Component Services, the .NET Framework provides several items that you need to include in your assembly and classes.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You must add a project reference to the System.EnterpriseServices namespace if you want to host a Visual Basic .NET component in a Component Services application. This namespace provides the main classes, interfaces, and attributes for communicating with Component Services. The System.EnterpriseServices namespace provides the following features.
Feature ContextUtil class Usage Use this class to participate in transactions and to interact with security information. The functionality of this class is similar to the functionality of the ObjectContext class in Visual Basic 6.0. ServicedComponent All component classes that need to be hosted within a Component class Services application must inherit this class. This class defines the base type for all context bound types and implements methods similar to those found in the IObjectControl interface used in Visual Basic 6.0based Component Services applications. Assembly, class, and method attributes You can define several assembly attributes for Component Services interrogation in the AssemblyInfo.vb file. These values are used to set the application name and description and other values when the application is installed as a Component Services application. Several class and method attributes are also defined by the System.EnterpriseServices namespace, including TransactionAttribute, AutoCompleteAttribute, ObjectPoolingAttribute, and ConstructionEnabledAttribute.
Note The Attribute part of an attribute name is optional, so, for example, you can use either AutoComplete or AutoCompleteAttribute in your code.
13
Using Transactions
Topic Objective
To examine how components can utilize Component Services transactions.
Transaction attribute specifies how a class participates in transactions ContextUtil class provides transaction voting AutoComplete attribute avoids using the SetAbort, SetComplete, and ContextUtil methods
<Transaction(TransactionOption.Required)> <Transaction(TransactionOption.Required)> Public Public Class Class Account Account Inherits Inherits ServicedComponent ServicedComponent Public Public Sub Sub Debit(...) Debit(...) 'Perform 'Perform debit debit action action ContextUtil.SetComplete( ContextUtil.SetComplete( ) ) End End Sub Sub <AutoComplete( <AutoComplete( )> )> Public Public Sub Sub Credit(...) Credit(...) 'Perform 'Perform credit credit action action 'No 'No SetComplete SetComplete because because AutoComplete AutoComplete is is on on End End Sub Sub End End Class Class
Lead-in
Various objects and attributes enable Visual Basic .NET components to use Component Services transactions.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Transactions are often required to maintain data integrity and to synchronize updates to data in multiple data sources. You can enable transaction processing in serviced components by including the appropriate attributes and classes in your component code.
RequiresNew Supported
14
SetComplete
EnableCommit
15
Processing Transactions
To avoid using the SetAbort and SetComplete methods of ContextUtil, you can set the AutoComplete attribute of specific methods of the component. If no exceptions occur during the method execution, the object behaves as if SetComplete has been called. If exceptions do occur, the object behaves as if SetAbort has been called.
16
Topic Objective
Object pooling allows objects to be created in advance ObjectPooling attribute specifies MinPoolSize and MaxPoolSize ServicedComponent provides CanBePooled method
<ObjectPooling(Enabled:=True, <ObjectPooling(Enabled:=True, MinPoolSize:=5, MinPoolSize:=5, _ _ MaxPoolSize:=50)> MaxPoolSize:=50)> _ _ Public Public Class Class Account Account Inherits Inherits ServicedComponent ServicedComponent ... ... Protected Protected Overrides Overrides Function Function CanBePooled( CanBePooled( ) ) As As Boolean Boolean Return Return True True End End Function Function End Class End Class
Lead-in
Various attributes and interfaces enable Visual Basic .NET components to use object pooling.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you use the ObjectPooling attribute and the ServicedComponent base class to create serviced components that use object pooling.
17
18
19
Lead-in
Specify the ConstructionEnabled attribute to indicate that a construction string is required Override the Construct method to retrieve information
<ConstructionEnabled(True)>Public <ConstructionEnabled(True)>Public Class Class Account Account Inherits ServicedComponent Inherits ServicedComponent Protected Protected Overrides Overrides Sub Sub Construct(ByVal Construct(ByVal s s As As String) String) ' Called ' Called after after class class constructor constructor ' Use ' Use passed passed in in string string End Sub End Sub End End Class Class
Component Services provides constructor strings to serviced components that are accessible in Visual Basic .NET components through the .NET Framework.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use a constructor string to control how serviced components are initialized. This allows you to specify any initial information the object needs, such as a database connection string, by using the Component Services management console. You can use the ConstructionEnabled attribute to enable this process in a serviced component. Your Visual Basic .NET component can then receive this constructor information because the inherited ServicedComponent class provides the overridable Construct method.
20
Using Security
Topic Objective
To explain how Component Services security is accessible in Visual Basic .NET components.
Security configuration attributes enable security and role configuration SecurityCallContext class provides role checking and caller information
<ComponentAccessControl(True), <ComponentAccessControl(True), SecurityRole("Manager")> SecurityRole("Manager")> __ Public Public Class Class Account Account Inherits Inherits ServicedComponent ServicedComponent Public Public Function Function GetDetails( GetDetails( ) ) As As String String With SecurityCallContext.CurrentCall With SecurityCallContext.CurrentCall If If .IsCallerInRole("Manager") .IsCallerInRole("Manager") Then Then Return Return .OriginalCaller.AccountName .OriginalCaller.AccountName End End If If End End With With End End Function Function End End Class Class
Lead-in
Component Services provide security information that Visual Basic .NET components can use.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** When working with serviced components, you can use pre-defined attributes and objects to configure and test security options.
21
22
The following example shows how use SecurityCallContext to determine whether security is enabled, check whether a caller is in the Manager role, and return the AccountName string from the OriginalCaller property, which is a SecurityIdentity instance.
<ComponentAccessControl(True), SecurityRole("Manager")> _ Public Class Account Inherits ServicedComponent Public Function GetDetails( ) As String If ContextUtil.IsSecurityEnabled Then With SecurityCallContext.CurrentCall If .IsCallerInRole("Manager") Then Return .OriginalCaller.AccountName End If End With End If End Function End Class
23
Other Component Services include: Just-in-time activation Queued components Shared properties Synchronization
Lead-in
Component Services provides several other services that you can use in Visual Basic .NET components.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Component Services provides a series of other services that you can use from Visual Basic .NET components.
Just-in-Time Activation
When just-in-time (JIT) activation is enabled, an object is automatically instantiated when a method is called on a serviced component (activation), and then automatically deactivated when the method is complete (deactivation). When this option is enabled, an object does not maintain state across method calls, and this increases the performance and scalability of the application. You can override the Activate and Deactivate methods inherited from the ServicedComponent class to perform custom functionality during JIT. If object pooling is enabled, the activation occurs when an existing object has been taken from the pool, and the deactivation occurs when the object is placed back in the pool. JIT is automatically enabled if a component is transactional, and it cannot be disabled. You can manually enable or disable JIT for non-transactional components by using the JustInTimeActivation attribute.
Queued Components
Queued components provide asynchronous communication. This allows client applications to send requests to queued components without waiting for a response. The requests are recorded and sent to the server, where they are queued until the application is ready to use the requests. These requests are then played back to the application as if they were being sent from a regular client. You can mark an application for queuing by using the assembly-level ApplicationQueuing attribute. Mark individual components with the InterfaceQueuing attribute.
24
Shared Properties
You can use the Shared Property Manager (SPM) components to share information among multiple objects within the same application process. Use the SPM components as you use them from components created in Visual Basic 6.0.
Synchronization
Distributed applications can receive simultaneous calls from multiple clients. Managing these simultaneous requests involves complex program logic to ensure that resources are accessed safely and correctly. Component Services provides this service automatically to components that use transactions. You can also use the Synchronization attribute to specify this behavior.
25
Setting assembly attributes ApplicationName Description ApplicationActivation: library or server application AssemblyKeyFile Using Regsvcs to register and create Component Services applications Regsvcs.exe myApplication.dll Using Lazy Registration Application registered on first use by client
Lead-in
Setting assembly-level Component Services attributes helps define how your application will behave when you deploy it under Component Services.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can specify some assembly level attributes that provide information when your assembly is installed as a Component Services application. The information is stored in the AssemblyInfo.vb file that is part of your Visual Basic .NET project.
Assembly attribute ApplicationName Usage If you use this attribute to specify the name of the application, a Component Services application with the same name when your assembly is deployed and installed. Use this attribute to set the Component Services application description value when the assembly is deployed and installed. Use this attribute to specify whether you want to implement your Component Services application as either a library or a server application. The acceptable values for this attribute are ActivationOption.Server or ActivationOption.Library. AssemblyKeyFile Use this attribute to specify the name and location of the file that contains the key pair used to generate a shared name.
Description
ApplicationActivation
26
Automatic registration If you do not register your application manually, registration will automatically occur when a client application attempts to create an instance of a managed class that inherits from the ServicedComponent class. All of the ServicedComponent classes within your assembly will then be registered as part of the Component Services application. This is known as Lazy Registration.
27
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a serviced component that uses object pooling and how to call the component from a managed client.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
28
Objectives
After completing this lab, you will be able to: Create a serviced component. Reference a serviced component.
Prerequisites
Before working on this lab, you must be familiar with creating and using components in MTS or Component Services.
Scenario
In this lab, you will create a serviced component based on a preexisting class. The class contains a single method that customers use to logon. You will register this assembly with Component Services and create a test harness application that references and tests your component. The test harness will use a preexisting form that allows you to enter a customers e-mail address and password to retrieve the customer details by using the component.
29
30
To add the serviced component assembly attributes 1. Open AssemblyInfo.vb. 2. At the beginning of the file, add an Imports statement that references the System.EnterpriseServices namespace. 3. Add the following assembly attributes.
Assembly attribute ApplicationName Description ApplicationActivation Parameters Customers Customer Component ActivationOption.Server
To generate a key file 1. Click start, point to All Programs, point to Microsoft Visual Studio .NET, point to Visual Studio .NET Tools, and then click Visual Studio .NET Command Prompt. 2. In the Visual Studio .NET Command Prompt window, navigate to install folder\Labs\Lab091\Ex01\Starter. 3. Use the following command to create a Strong Name Key for your component:
sn.exe k CustomerComponent.snk
4. Leave the Command Prompt window open. You will use it in the next exercise. To link the key file to the component 1. Open AssemblyInfo.vb. 2. Add the following assembly attribute:
<Assembly: AssemblyKeyFile("CustomerComponent.snk")>
To compile the assembly On the Build menu, click Build Solution, and then quit Visual Studio .NET.
31
3. Close the Command Prompt window. To confirm that the assembly is now a serviced component application 1. Open Control Panel, click Performance and Maintenance, click Administrative Tools, and then double-click Component Services. 2. Expand Component Services, expand Computers, expand My Computer, and then expand COM+ applications. 3. Right-click the Customers application, and then click Properties. Your screen should appear similar to the following screen shot.
32
4. Confirm that the assembly-level attributes that you specified in your project have been set in the application. 5. Close the Customers Properties dialog box. To set properties for the Customer component 1. Expand the Customers application, and locate CustomerComponent.Customer within the list of components. 2. Right-click the CustomerComponent.Customer component, and then click Properties. 3. Click the Transactions tab to view the transactional setting for the class. 4. Click the Activation tab, set the Constructor String to the following value, and then click OK:
Data Source=LocalHost;Initial Catalog=Cargo;Integrated Security=True;
33
3. Call the LogOn method of the cust object, passing in the following values.
Parameter Email Password Value txtEmail.Text txtPassword.Text
4. Use the ds Dataset object to store the value returned from the LogOn method.
34
To test the application 1. On the Debug menu, click Start. 2. Enter the following values.
TextBox E-mail Password Value [email protected] password
3. Click Log on, and confirm that a record is successfully retrieved from the component. 4. Click Close to quit the test harness application. 5. Quit Visual Studio .NET.
35
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After completing this lesson, you will be able to: Describe the architecture of a component class. Create a component class.
36
Topic Objective
Lead-in
Component classes offer several features not included in standard Visual Basic .NET classes.
se System.ComponentModel.Component a B ass Cl
ed Component Classes v i r es De ass Predefined Classes Cl
Custom Classes
IComponent Interface
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In addition to supporting classes and structures, the System namespace provides a library of components designed to make component development easy. When you create a component class based on the ComponentModel.Component base class, you automatically inherit the basic architecture for your class.
IComponent Interface
The IComponent interface allows you to create custom components or to configure existing components such as the MessageQueue or Timer components within the visual designer for your component. After you place any existing components on your component (siting), you can access them in your component code in the same way as you can when they are placed in the component tray of a Windows Form.
37
38
Lead-in
1. Inherit the System.ComponentModel.Component Perform any initialization in constructor Override Dispose method 2. Add any sited components Use Server Explorer or Toolbox items 3. Create required functionality Properties, methods, and events 4. Build the assembly
Creating a component class is similar to creating a standard class item, but there are a few extra steps.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The procedure for creating a component class with Visual Basic .NET is similar to the procedure for creating standard classes, but there are a few extra steps. Delivery Tip 1. Inherit the System.ComponentModel.Component class. The Component Class template item contains the required code to inherit the System.ComponentModel.Component class, including the constructor code required to add your component class to a container. Add any initialization code for your component class as part of the construction process by placing code in the prewritten Sub New method. You can override the Dispose method of the inherited Component class to free any resources before the instance of your component is destroyed. 2. Add any sited components. If your component class requires other components in order to fulfill its purpose, you can add them within the Design view by dragging them from the Toolbox or Server Explorer to your component class. These components can then be programmatically accessed from within the code for your component class. 3. Create required functionality. Your component class can provide public properties, methods, and events to allow the user of your component to interact with it at both design time and run time. 4. Build the assembly. Building the assembly enables other managed clients to make a reference to your component.
Point out the sample code in the student notes, but explain that a demonstration immediately follows this topic.
39
The following example shows how to create a component class that is derived from the System.ComponentModel.Component class. It extends the functionality of the standard Timer class by defining additional properties and events.
Imports System.ComponentModel Public Class Hourglass Inherits System.ComponentModel.Component Public Event Finished(...) Private WithEvents localTimer As System.Timers.Timer Public Sub New( ) MyBase.New( ) 'This call is required by the Component Designer. InitializeComponent( ) 'Initialize the timer for 1 minute (60000 milliseconds) localTimer = New System.Timers.Timer( ) localTimer.Enabled = False localTimer.Interval = 60000 End Sub Public Property Enabled( ) As Boolean Get Return localTimer.Enabled End Get Set(ByVal Value As Boolean) localTimer.Enabled = Value End Set End Property Private Sub localTimer_Tick(...) Handles localTimer.Elapsed 'Raise the finished event after localtimer_Tick is raised RaiseEvent Finished( ) End Sub Public Overloads Overrides Sub Dispose( ) 'Disable the localTimer object localTimer.Enabled = False localTimer.Dispose( ) MyBase.Dispose( ) End Sub End Class
Delivery Tip
Point out that inheriting from the Timer class would also produce a similar component.
40
When examining the code, note the following: The component behaves as an hourglass that raises a Finished event one minute after it is enabled. The component can be turned on by using the Enabled property at design time or run time. The localTimer is initialized as part of the Sub New constructor and set for a timer interval of 60,000 milliseconds, or one minute. The Dispose method is overridden to ensure that the localTimer object is safely disposed of.
41
Topic Objective
Lead-in
This demonstration shows how to create a stopwatch component class and use it from another application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a component class that can be used by another assembly.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
42
Inheriting from the UserControl Class Inheriting from a Windows Forms Control Providing Control Attributes
Lead-in
This lesson examines how to create Windows Forms controls in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In previous versions of Visual Basic, you can create ActiveX controls that can be reused by different client applications. In Visual Basic .NET, you can also use inheritance to create controls. After completing this lesson, you will be able to: Create a control based on the System.Windows.Forms.UserControl class. Create a control based on an existing Windows Forms control. Add attributes to your controls that enable advanced design-time functionality.
43
Inherit from System.Windows.Forms.UserControl Add required controls to designer Add properties and methods that correspond to those of constituent controls Add any additional properties and methods No InitProperties, ReadProperties, or WriteProperties Property storage is automatic
Lead-in
In Visual Basic .NET, you can inherit from the UserControl class to create the same type of user controls that you can create in Visual Basic 6.0.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In previous versions of Visual Basic, you can create a unique new control by placing one or more existing controls onto a UserControl designer. You can then create custom properties, methods, and events to set and retrieve values for the contained controls. This type of control is useful when several forms require the same layout of controls, such as forms for addresses or contact details.
44
Example
The following example shows how to create a simple user control that contains a label and a text box:
Public Class LabelAndTextControl Inherits System.Windows.Forms.UserControl Public Property TextBoxText( ) As String Get Return TextBox1.Text End Get Set(ByVal Value As String) TextBox1.Text = Value End Set End Property Public Property LabelText( ) As String Get Return Label1.Text End Get Set(ByVal Value As String) Label1.Text = Value End Set End Property ... 'Windows Form Designer generated code End Class
The TextBox1 and Label1 controls are privately declared variables within the user control that are only accessible using the public properties TextBoxText and LabelText.
45
Allows enhanced version of a single control Inherit from any System.Windows.Forms control
Public Public Class Class MyTextBox MyTextBox Inherits Inherits System.Windows.Forms.TextBox System.Windows.Forms.TextBox Private Private strData strData As As String String Public Property HiddenData( Public Property HiddenData( ) ) As As String String Get Get Return Return strData strData End End Get Get Set(ByVal Value Set(ByVal Value As As String) String) strData = Value strData = Value End End Set Set End End Property Property ... ... End End Class Class
Lead-in
Inheritance makes it easy for you to enhance an existing control in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In previous versions of Visual Basic, you can create enhanced versions of an existing control by placing an instance of the control on the UserControl designer. You can then create public properties, methods, and events that correspond to the equivalent items of the constituent control, adding any custom items to create your enhanced behavior. In Visual Basic .NET, you can create a control that inherits from any System.Windows.Forms class, such as the TextBox or Label class. Because this approach uses inheritance, there is no need to create public properties, methods, and events that map to the constituent control. This greatly reduces the amount of code required. You only need to create any extra functionality, as described for user controls in the previous topic. The following example shows how to create a control that inherits from SystemWindows.Forms.TextBox and adds a public property:
Public Class MyTextBox Inherits System.Windows.Forms.TextBox Private strData As String Public Property HiddenData( ) As String Get Return strData End Get Set(ByVal Value As String) strData = Value End Set End Property ... End Class
46
This code creates a new control that inherits all of the TextBox class functionality and adds a property called HiddenData. Note For some existing controls, you can create a new graphical front end by overriding the OnPaint method of the base class. However, some controls, such as the TextBox control, are painted directly by Windows and cannot be overridden.
47
System.ComponentModel provides control attributes Class level DefaultProperty, DefaultEvent, ToolboxBitmap Property level Category, Description, DefaultValue
Imports Imports System.ComponentModel System.ComponentModel <ToolboxBitmap("C:\txticon.ico"), <ToolboxBitmap("C:\txticon.ico"), DefaultEvent("Click")> DefaultEvent("Click")> __ Public Public Class Class MyTextBox MyTextBox Inherits Inherits System.Windows.Forms.UserControl System.Windows.Forms.UserControl <Category("Appearance"), <Category("Appearance"), __ Description("Stores Description("Stores extra extra data"), data"), __ DefaultValue("Empty")> DefaultValue("Empty")> __ Public Public Property Property HiddenData( HiddenData( ) ) As As String String ... ... End End Property Property ... ... End End Class Class
Lead-in
Control attributes can be used to supply extra information about the control and its properties, methods, and events.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In previous versions of Visual Basic, you can use the Procedure Attributes dialog box to set control attributes, such as property descriptions and their categories, which can be viewed in the Object Browser. You can supply similar information in Visual Basic .NET by using the attributes provided by the System.ComponentModel namespace.
48
49
Topic Objective
Lead-in
In this demonstration, you will learn how to create a control based on the Windows Forms TextBox control.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a Windows Forms user control based on the existing TextBox.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
50
Lead-in
This lesson examines how to create Web Forms user controls in Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In Visual Basic .NET, you can create controls for use within ASP.NET Web Forms. After completing this lesson, you will be able to: Create a Web Forms user control based on other controls in the System.Web.UI.UserControl class. Use a Web Forms user control within a Web Form.
51
1. Add a Web user control to an ASP.NET Web project 2. Use the Toolbox to drag existing controls to the Web user control designer 3. Add properties and methods 4. Save the .ascx file 5. Drag the .ascx file from Solution Explorer to the Web Forms Designer 6. Create Web Form code as usual
Lead-in
You can create your own Web user controls by extending the existing Web server controls provided by ASP.NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Creating your own Web user control allows you to extend the controls provided with ASP.NET. You can extend a single control with added features or create a new control that is a combination of existing controls. To create your own Web user control 1. Add a Web user control to your ASP.NET Web project. 2. Use the Toolbox to drag-and-drop existing Web server controls to the Web user control designer. 3. Add properties and methods in the code-behind file. 4. Save the .ascx Web user control file. To use your Web user control 1. Open your Web Form. 2. Drag the .ascx file from Solution Explorer to the Web Forms Designer. 3. Create any Web Form code that accesses the Web user control, as you would for existing Web server controls. 4. Test your control by running your application and displaying the Web Form.
52
Topic Objective
Lead-in
The code for creating a Web user control is very similar to that of a Web Form.
<%@ <%@ Control Control Language="vb" Language="vb" AutoEventWireup="false" AutoEventWireup="false" Codebehind="SimpleControl.ascx.vb" Codebehind="SimpleControl.ascx.vb" Inherits="MyApp.SimpleControl"%> Inherits="MyApp.SimpleControl"%> <asp:TextBox <asp:TextBox id="TextBox1" id="TextBox1" runat="server"></asp:TextBox> runat="server"></asp:TextBox> Public Public MustInherit MustInherit Class Class SimpleControl SimpleControl Inherits Inherits System.Web.UI.UserControl System.Web.UI.UserControl Protected Protected WithEvents WithEvents TextBox1 TextBox1 As As System.Web.UI.WebControls.TextBox System.Web.UI.WebControls.TextBox Public Property TextValue( ) As Public Property TextValue( ) As String String Get Get Return Return TextBox1.Text TextBox1.Text End End Get Get Set(ByVal Set(ByVal Value Value As As String) String) TextBox1.Text TextBox1.Text = = Value Value End End Set Set End End Property Property End End Class Class
*****************************ILLEGAL FOR NON-TRAINER USE****************************** To create a Web user control, you need to create: 1. The graphical layout of the controls in the .ascx file. 2. The code that executes in the.ascx.vb code-behind file. The following example shows how to create a Web user control based on the existing TextBox control while inheriting from the UserControl class. It also provides a custom property for setting the TextBox1.Text value. The following code is located in the Web user control .ascx file:
<%@ Control Language="vb" AutoEventWireup="false" Codebehind="SimpleControl.ascx.vb" Inherits="MyApp.SimpleControl" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
The example code shows the similarity between Web Forms and Web user control code, the main difference being the @ Control directive and the lack of any <html>, <body>, or <form> tags.
53
The SimpleControl class is similar to most classes in that it allows public access to private members of the class. However, note that it is through inheriting the UserControl class that the Web user control functionality is provided.
54
Topic Objective
Lead-in
This demonstration shows how to create a simple Web Forms user control that uses a Label and a TextBox as its constituent controls.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to create a simple Web Forms user control that contains a Label and a TextBox as its constituent controls.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
55
Objectives
After completing this lab, you will be able to: Create a Web Forms user control. Use a Web Forms user control on a Web Form.
Prerequisites
Before working on this lab, you must be familiar with creating Web Form applications, and have completed Lab 9.1.
Scenario
In this lab, you will create a Web Forms user control that requests logon information for a customer. The control will retrieve the customer information by means of the serviced component that you created in the previous lab. You will then use this control on a Web Form and test the control.
56
Display RequiredFieldValidator (ID) ErrorMessage ControlToValidate Display Label TextBox (ID) Text (ID) TextMode
57
58
To create the Web user control code 1. View the Code Editor for Logon.ascx. 2. Declare an event with the following signature:
Public Event SubmitPressed(ByVal Email As String, _ ByVal Password As String)
3. Create a Click event handler for the btnSubmit event. In this method, set the Visible property of the lblNotFound label to False, and raise the SubmitPressed event, passing the following parameters:
Parameter Email Password Value txtEmail.Text txtPassword.Text
4. Create a DisplayMessage subroutine that accepts a single string argument called Message. Within the subroutine, set the following values for the lblNotFound label.
Control property Text Visible Value Message True
59
60
To create the logon page 1. On the Project menu, click Add Web Form, and rename the file LogonPage.aspx. 2. Drag Logon.ascx from Solution Explorer to the LogonPage Web Forms Designer to create an instance of the control on the Web Form. 3. In the LogonPage code window, add an Imports CustomerComponent statement. 4. Add the following variable declaration after the Inherits System.Web.UI.Page statement:
Protected WithEvents Logon1 As Logon
5. Create an event handler procedure for the SubmitPressed event of Logon1, and add the following code:
Dim ds As DataSet, dr As DataRow Dim cust As ICustomer = New Customer( ) Try ds = cust.Logon(Email, Password) dr = ds.Tables(0).Rows(0) Session("FirstName") = dr("FirstName") Response.Redirect("Welcome.aspx") Catch ex As Exception Logon1.DisplayMessage _ ("No match was found. Please reenter your details.") End Try
6. Save the project. To test the application 1. In Solution Explorer, right-click LogonPage.aspx, and then click Set As Start Page. 2. On the Debug menu, click Start. 3. Click Submit without entering any values in the text boxes to test the validation controls. 4. Enter the following deliberately incorrect values in the text boxes, and then click Submit.
Control E-mail Password Value [email protected] john
5. Confirm that an error message is displayed by the user control. 6. Enter the same e-mail address as in step 4, but use the correct password of password, and then click Submit. Confirm that the welcome message is displayed and that the customer has been recognized. 7. Quit Microsoft Internet Explorer and Visual Studio .NET.
61
Threading
Topic Objective
To provide an overview of the topics covered in this lesson.
What Is a Thread? Advantages of Multithreading Creating Threads Using Threading When to Use Threading
Lead-in
Visual Basic .NET allows developers to use the power of threading in a way not previously available in Visual Basic.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Previous versions of Visual Basic have limited threading support. Visual Basic .NET allows developers to use the full power of threads when necessary. When you use threading correctly, you can enhance the performance of your application and make it more interactive. After you complete this lesson, you will be able to: Explain the basic concepts of threading. List the advantages of incorporating multithreading into your applications. Create and use threads by using the System.Threading namespace. Avoid some potential problems in your multithreaded applications. Warning Be aware that this section is an overview of how to use threading in Visual Basic .NET. This is a very complex subject, and you must be sure that you fully understand the implications before using these methods. For more information, see the .NET Framework SDK.
62
What Is a Thread?
To explain the basic concepts of threading.
Topic Objective
Lead-in
Before examining how Visual Basic .NET enables threading, it is important to understand the basic concepts of threading.
Process 1 Process 2
CPU
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip An application running on a computer is known as a process. Each process gets work done by using one or more threads. The thread is the unit of execution that is processed by the CPU of the computer.
The slide associated with this topic is an animated slide. Click the slide to reveal the following lessons, showing the iterative process of the thread scheduler: 1. Thread 1 2. Thread 2 3. Thread 3 4. Thread 1 5. Thread 2 6. Thread 3
Threading Process
A CPU can only execute a single thread at any one instant, so a thread scheduler allocates a certain amount of CPU time for each thread to get as much work done as possible before allowing another thread to access the CPU. This scheduling makes a computer appear to perform multiple tasks at once. In reality, the following is what happens: 1. Every thread contains its own call stack and storage for local variables. This information is kept with the thread and passed to the CPU whenever the thread is scheduled for processing. 2. When the time is up, the thread scheduler removes the thread from the CPU and stores the call stack and variable information. The more threads that are running on the system, the less frequently a thread is scheduled to run in the CPU. This is why a computer can appear to be running slowly when you have multiple applications open and functioning at the same time.
63
Threading Types
Different programming languages support different types of threading: Previous versions of Visual Basic support the apartment threading model. This model places some restrictions on the types of applications that these versions are best suited for creating. One of these restrictions is that an object is tied to the thread that it is created on, and cannot be used for object pooling in Component Services. However, this model makes development easy because you do not need to be involved with more complex issues such as synchronization. Visual Basic .NET supports the free threading model. This model allows you to use multithreading and features such as object pooling or to continue using single threads as you have in applications created with previous versions of Visual Basic.
64
Advantages of Multithreading
To explain the advantages of multithreading and free threading.
Topic Objective
Improved user interface responsiveness Example: a status bar No blocking Asynchronous communication No thread affinity Objects are not tied to one thread
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** A multithreaded application has several advantages over a single-threaded application.
No Blocking
Blocking occurs because a call to a single-threaded application must wait until any previous call by another client application has been fully satisfied before executing any other code. In server-based applications, blocking will occur if multiple clients make simultaneous requests of a process and only a single thread is available. Multithreaded applications are able to perform actions on different threads simultaneously (through thread scheduling) without waiting for other threads to finish their current execution. This allows multiple clients to be handled by different threads without any blocking in a server-based application.
65
Asynchronous Communication
Asynchronous communication is possible in a multithreaded application because one thread can make a request to another thread. The calling thread can continue with other processing because the request executes on a separate thread. An event can be raised when the second thread finishes executing the requested functionality, informing the first thread that it has completed its work.
No Thread Affinity
Visual Basic .NET uses the free threading model. This model does not restrict you to using an object only on the thread where it was initially created. You can create an object on one thread and then pass it to another thread without difficulty. This improves scalability when used in conjunction with Component Services and object pooling.
66
Creating Threads
Topic Objective
To explain how to create and use threads.
Lead-in
Use the System.Threading.Thread class Constructor specifies delegate method Methods provide control of thread processing Properties provide state and priority information Use a class if parameters are required Allow public access to class variables Raise an event when finished
The .NET Framework provides the System.Threading.Thread class, which allows you to create multiple threads.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The .NET Framework provides a simple way to create and work with multiple threads.
Use the Thread class to create multiple threads within a Visual Basic .NET based application.
67
Threading Methods
The Thread class also provides several methods to control the processing of a thread.
Method Start Abort Sleep Purpose Begins execution of the method delegate declared in the thread constructor. Explicitly terminates an executing thread. Pauses a thread. Specifies the number of milliseconds as the only parameter. If you pass zero as the parameter, the thread gives up the remainder of its current time slice. This is similar to DoEvents in previous versions of Visual Basic. Temporarily halts execution of a thread. Reactivates a suspended thread.
Suspend Resume
Threading Properties
The Thread class provides properties to retrieve information about the thread state and to manipulate the thread priority.
Property ThreadState Priority Purpose Use the ThreadState property to determine the current state of a thread, such as Running, Suspended, or Aborted. Modify the priority of a thread by setting its Priority property by using the ThreadPriority enumeration. The enumeration provides the following values: AboveNormal, BelowNormal, Highest, Lowest, and Normal.
Warning If you set thread priorities to a value of Highest, this may affect vital system processes by depriving them of CPU cycles. Use this setting with extreme caution.
68
Delivery Tip
You cannot specify a method delegate that accepts arguments in the thread constructor. If your procedure requires information to perform its required action, you can: Use classes to provide methods that perform operations on local data. Use public properties or variables to supply the local data. To use classes to supply parameters, you must create an instance of the class before calling the thread constructor. Use the AddressOf operator to pass a reference to the method of the class as the constructor parameter. You can then use the properties or public variables to supply any data required by the method. When the worker method finishes its execution, you can raise an event to inform the calling thread that the operation is completed.
69
Using Threading
Topic Objective
To explain a simple example of threading.
Class Class Calculate Calculate Public Public iValue iValue As As Integer Integer Public Public Event Event Complete(ByVal Complete(ByVal Result Result As As Integer) Integer) Public Public Sub Sub LongCalculation( LongCalculation( ) ) 'Perform 'Perform a a long long calculation calculation based based on on iValue iValue ... ... RaiseEvent Complete(iResult) 'Raise RaiseEvent Complete(iResult) 'Raise event event to to signal signal finish finish End End Sub Sub End End Class Class Sub Sub Test( Test( ) ) Dim Dim calc calc As As New New Calculate( Calculate( ) ) Dim th As Dim th As New New Threading.Thread(AddressOf Threading.Thread(AddressOf calc.LongCalculation) calc.LongCalculation) calc.iValue calc.iValue = = 10 10 AddHandler AddHandler calc.Complete, calc.Complete, AddressOf AddressOf CalcResult CalcResult th.Start( th.Start( ) ) End End Sub Sub Sub Sub CalcResult(ByVal CalcResult(ByVal Result Result As As Integer) Integer) ... ... End End Sub Sub
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** This topic shows how to prepare a class for threading, create a thread, start the thread, and perform calculations on the new thread.
When examining the previous code, note the following: The class provides a LongCalculation worker function, which will be executed on a separate thread. The worker function uses information stored in the public iValue integer variable to calculate its result. The Calculate class provides a Complete event to notify the calling thread that the calculation is finished.
70
When examining this code, note the following: The Test subroutine instantiates a Calculate object and specifies the LongCalculation delegate in the Thread constructor. A value is assigned to the iValue variable for use by the worker function. An event handler is created to detect completion of the calculation. The Start method is called on the separate thread to begin the processing of the calculation.
71
Topic Objective
Use threads carefully Using more threads requires more system resources Synchronize access to shared resources Prevent two threads from accessing shared data simultaneously Use SyncLock statement to block sections of code
Sub Sub Worker( Worker( ) ) SyncLock(theData) 'Lock SyncLock(theData) 'Lock this this object object variable variable theData.id theData.id = = iValue iValue 'Perform 'Perform some some lengthy lengthy action action iValue iValue = = theData.id theData.id End 'Unlock End SyncLock SyncLock 'Unlock the the object object variable variable End End Sub Sub
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip Using multiple threads is a useful programming concept in enterprise development; however, improper use of threads can cause performance problems, create inconsistent data, and cause other errors.
Point out that incorrect use of threads can have serious consequences.
System Resources
Threads consume memory and other valuable resources, such as CPU processing time. If your application creates multiple threads, it may do so at the expense of other applications or other threads within your own process. The more threads you create, the longer the delay between CPU time slices for each thread. If all applications created an excessive number of threads and used them constantly, the system would spend most of its time swapping threads in and out of the CPU, since the thread scheduler itself requires the CPU to perform the swapping logic.
72
Shared Resources
If multiple threads need to access the same information at the same time, a concurrency problem may arise. Two threads accessing a shared global resource may get inconsistent results back from the resource if other threads have altered the data. The following is an example of a situation in which this can occur: Thread A updates a value on a shared resource such as an integer, setting the value to 10 before performing some lengthy action. Thread B updates the same integer value to 15 during the delay of thread As lengthy action. When this action is completed, thread A may read the integer value back from the resource whose value is now 15.
73
74
Topic Objective
Lead-in
This demonstration shows how to use the SyncLock statement to synchronize a shared resource.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the SyncLock statement when using multiple threads in an application created in Visual Basic .NET.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
Be aware that the threads in this demonstration may not necessarily run in the order that they were launched, so your output may not be strictly as expected.
75
Review
To reinforce module objectives by reviewing key points.
Topic Objective
Components Overview Creating Serviced Components Creating Component Classes Creating Windows Forms Controls Creating Web Forms User Controls Threading
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. An unmanaged client application uses a class created in Visual Basic .NET but cannot access any methods of the class. What is the likely cause of this problem, and how would you fix it? The class may have public methods defined without using an interface or any class-level attributes. To solve this problem, create and implement methods in interfaces rather than classes, use the ClassInterface attribute, or use the COMClass attribute.
76
2. Modify the following code to use auto completion of transactions rather than the explicit SetAbort and SetComplete methods.
<Transaction(TransactionOption.Required)> _ Public Class TestClass Public Sub MySub( ) Try 'Perform action ContextUtil.SetComplete( ) Catch ex As Exception ContextUtil.SetAbort( ) Throw ex End Try End Sub End Class <Transaction(TransactionOption.Required)> _ Public Class TestClass <AutoComplete( )>Public Sub MySub( ) 'Perform action End Sub End Class
3. Create assembly attributes so Component Services can automatically create an application named TestComponents that runs as server activation. <Assembly: ApplicationName("TestComponents")> <Assembly: ApplicationActivation(ActivationOption.Server )>
4. Why would you use the IComponent interface? The interface enables component classes to site other components and enables the component class to be sited on other components.
77
5. The following code causes a compilation error. Explain what is causing the error and how it could be fixed.
Sub Main( ) Dim t As New Thread(AddressOf MySub) t.Start(10) End Sub Sub MySub(ByVal x As Integer) ... End Sub
The MySub procedure cannot be called directly because it expects an argument and the Start method of a Thread cannot accept parameters. To fix this error, you could create the following code:
Sub Main( ) Dim obj As New ThreadObj( ) Dim t As New Thread(AddressOf obj.MySub) obj.x = 10 t.Start( ) End Sub
Class ThreadObj Public x As Integer Sub MySub( ) ... End Sub End Class
78
Course Evaluation
To direct students to a Web site to complete a course evaluation.
Topic Objective
Lead-in
Between now and the end of the course, you can go to the Web site listed on this page to complete a course evaluation.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Your evaluation of this course will help Microsoft understand the quality of your learning experience. At a convenient time between now and the end of the course, please complete a course evaluation, which is available at http://www.metricsthatmatter.com/survey. Microsoft will keep your evaluation strictly confidential and will use your responses to improve your future learning experience.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 75 Minutes Labs: 45 Minutes This module provides students with the skills necessary to deploy Microsoft Visual Basic .NET applications. They will learn what deployment choices are available to them and how to use the various deployment project templates to successfully deploy any type of application After completing this module, students will be able to: Describe an assembly. List the different types of application deployment. Deploy a component assembly. Deploy an application based on Microsoft Windows. Deploy a Web-based application.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_10.ppt Module 10, Deploying Applications Lab 10.1, Packaging a Component Assembly Lab 10.2, Deploying a Windows-Based Application
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstration. Complete the labs.
iv
Demonstration
This section provides demonstration procedures that do not fit in the margin notes or are not appropriate for the student notes.
To specify launch conditions 1. On the Solution Explorer toolbar, click Launch Conditions Editor. Explain the existing conditions that verify that Internet Information Server (IIS) is present on the target server. 2. Right-click Search Target Machine, click Add File Search, and rename this Check for Cargo Database. 3. Change the properties of this search by using the information in the following table.
Property Property Folder FileName Depth Setting CARGOCHECK [ProgramsFilesFolder] Cargo.mdf 3
4. In the Launch Conditions Editor, right-click Launch Conditions, click Add Launch Condition, and then rename this Cargo Condition. 5. Change the properties of this condition by using the information in the following table.
Property Condition Message Setting CARGOCHECK Cargo database is not installed
6. On the Build menu, click Build WebSetup1. To deploy and test the application 1. On the Project menu, click Install. Follow the setup program, accepting the default options, wait for the deployment to finish, and then click Close. 2. Open Internet Information Services, and check that a new application called Demo10 has been installed. 3. Open Internet Explorer, and browse to http://localhost/Demo10/DefaultPage.aspx. Show the students that this application works as expected.
vi
Module Strategy
Use the following strategy to present this module: Describing Assemblies In this lesson, explain what assemblies are, how to create strong names, and how to version assemblies. You have discussed assemblies at various points throughout this course. Use this lesson to clarify any questions that have been raised throughout the previous modules. Students will have an opportunity to create a strong-named assembly in Lab10.1 later in this module. Selecting a Deployment Strategy In this lesson, explain to students the advantages gained by deploying applications in Visual Studio .NET. You will review the methods of deployment, from using XCOPY to creating a Windows Installer application. Be sure to stress that while XCOPY can simplify deployment, it cannot be used when registration of components is necessary. The Windows Installer is the best choice when deploying complex applications. Deploying Applications This lesson covers how to deploy both Windows-based and Web-based applications. Although these two types are quite disparate, the steps for deployment are actually very similar. You will review how to use the editor windows to customize your deployment, and you will show students how to use both the File System and Launch Conditions editors in the demonstration. Both of the labs for this module occur during this lesson. In the first one, students will package a component within a merge module, and in the second, they will include that in a setup project for a Windows-based application. You will also show the students how to deploy a Web-based application in the demonstration.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Lead-in
In this module, you will learn about the options available to you when deploying Visual Basic .NETbased applications.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you create and test an application, you will want to distribute it for use on other computers. The users may be end users running a Web application or an application based on Microsoft Windows, or other developers using a code library. In this module, you will learn how to deploy assemblies for use by client applications, how to decide what type of distribution strategy to implement, and how to deploy Windows-based and Web-based applications. After completing this module, you will be able to: Describe an assembly. List the different types of application deployment. Deploy a component assembly. Deploy an application based on Windows. Deploy a Web-based application.
Describing Assemblies
Topic Objective
To provide an overview of the topics covered in this lesson.
Assemblies Overview Benefits of Strong-Named Assemblies Creating Strong-Named Assemblies Versioning Strong-Named Assemblies Using the Global Assembly Cache
Lead-in
This lesson examines assemblies and the specific requirements for creating components.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In this lesson, you will learn about the role of assemblies in Microsoft Visual Basic .NET version 7.0. You will learn about the benefits of strongnamed assemblies and how to create them. Finally, you will learn how to version assemblies. After completing this lesson, you will be able to: Describe the benefits of using strong-named assemblies. Create strong-named assemblies. Version assemblies.
Assemblies Overview
To explain the function of assemblies.
Topic Objective
Lead-in
Contains code, resources, and metadata Provides security, type, and reference scope Forms a deployment unit Versionable Side-by-side execution allows multiple installed versions Global assembly cache allows assembly sharing
*****************************ILLEGAL FOR NON-TRAINER USE****************************** An assembly is the building block of a Microsoft .NET-compatible application. It is a built, versioned, and deployed unit of functionality that can contain one or more files. An application can be composed of one or more assemblies. You can think of an assembly as a collection of types and resources that form a logical unit of functionality and are built to work together. Using existing assemblies to add extra functionality to your application is similar to the way that you use Microsoft ActiveX libraries in previous versions of Visual Basic. You also can create your own assemblies for other applications to use. What makes assemblies different from .exe or .dll files in earlier versions of Windows is that they contain all the information you would find in a type library, in addition to information about everything else necessary to use the application or component. Delivery Tip
Point out that all applications will also use the .NET Framework assemblies.
The assembly manifest contains assembly metadata. It provides information about the assembly title, description, version information, and so on. It also provides information about linking to the other files in the assembly. This enables the assembly to be self describing, which allows you to distribute it using the XCOPY command. The information in the manifest is used at run time to resolve references and validate loaded assemblies. The assembly manifest can be stored in a separate file but is usually compiled as part of one of the PE files.
Topic Objective
Lead-in
Guaranteed uniqueness No two strong names can be the same Protected version lineage Only legitimate assembly versions can be loaded Enforced assembly integrity Assemblies are tested for unauthorized modification before loading
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use strong-named assemblies to ensure safe use of the components contained within the assembly. A strong-named assembly is a requirement for serviced components because only a single instance of the assembly is loaded regardless of the number of client applications. Delivery Tip
Guaranteed Uniqueness
Strong names guarantee that an assembly name is unique and cannot be used by anyone else. You generate strong names through the use of public and private key pairs when the assembly is compiled.
Topic Objective
Lead-in
Requires identity, public key, and digital signature Generating the public-private key pair Create a .snk file Modify AssemblyInfo.vb
<Assembly: <Assembly: AssemblyKeyFile("KeyFile.snk")> AssemblyKeyFile("KeyFile.snk")>
Strong-named assemblies are created by linking a strong name key file to the assembly.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The.NET Framework can create a strong-named assembly by combining the assembly identity (its name, version, and culture information), a public key, and a digital signature. You must generate the strong name key file (.snk extension) that contains the public-private key pair before you build the assembly. You can do this manually by using the Strong Name tool (sn.exe) utility. In AssemblyInfo.vb, you can use the AssemblyKeyFile attribute to link the key file to the component. The public key is inserted into the assembly manifest at compile time, and the private key is used to sign the assembly.
Lead-in
When a client makes a binding request, the runtime checks: The original binding information inside the assembly Configuration files for version policy instructions Use a publisher policy file to redirect the binding request
<bindingRedirect <bindingRedirect oldVersion="1.0.0.0" oldVersion="1.0.0.0" newVersion="1.0.1.0"/> newVersion="1.0.1.0"/>
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Often, you will want to update a component without redeploying the client application that is using it. However, by default, an application only functions with the original component that it was compiled with. To overcome this behavior, you must ensure that your components have strong names, which enables you to version them at a later date. When a client application makes a binding request, the runtime performs the following tasks: Checks the original assembly reference for the version to be bound Checks the configuration files for version policy instructions
You can use a publisher policy file to redirect a binding request to a newer instance of a component. The following example shows a publisher policy file. Note the publicKeyToken attribute, a hexadecimal value, which is used to identify the strong name of the assembly. This value can be obtained by using sn.exe with the T switch, or from the Assembly Cache listing in the .NET Framework Configuration snap-in in the Microsoft Management Console.
<configuration> <runtime> <assemblyBinding> <dependentAssembly> <assemblyIdentity name="myasm" publicKeyToken="e9b4c4996039ede8" culture="en-us"/> <bindingRedirect oldVersion="1.0.0.0" newVersion="1.0.1.0"/> <codeBase version="1.0.1.0" href="http://www.Microsoft.com/Test.dll"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
You can compile this XML file into a publisher policy assembly, to be shipped with the new component, using the Assembly Generation tool (Al.exe). This signs the assembly with the strong name originally used.
10
Topic Objective
Performance Quicker binding Only one instance ever loaded Shared location Can use machine configuration file to redirect bindings File security Only administrators can delete files Side-by-side versioning Can install multiple copies using different version information
Lead-in
The global assembly cache offers many advantages for the administration and usage of your components.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can store your shared components inside the global assembly cache. To do this, you must create a strong name for the assembly, and when deploying the component, you must specify that it is stored in the global assembly cache, as opposed to the common files folder for the client application. Using the global assembly cache has the following benefits.
Performance
If the component is stored in the cache, the strong name does not need to be verified each time the component is loaded. This method also guarantees that only one instance of the component is loaded in memory, reducing the overhead on the target computer.
Shared Location
You can use the computer configuration file to redirect all bindings to the global assembly cache, providing simpler administration of assemblies.
File Security
Only users with administrative privileges can delete files from the cache.
Side-by-Side Versioning
You can install multiple copies of the same component, with different version information, into the cache.
11
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** There are a variety of options available when deploying Visual Basic.NET based applications. Choosing what option to use depends on the type of application that you are deploying and the version of Windows you are deploying it to. Before you can begin the distribution process, you must understand the differences in the various strategies available to you. Some of these simply involve copying the application to an appropriate place, some involve creating a deployment project to copy the application and register any components, and some involve creating a complete setup application for use by the end user. After completing this lesson, you will be able to: Describe the deployment options available to you. Match deployment options with specific scenarios.
12
Deployment Overview
Topic Objective
To discuss the advantages that Visual Studio .NET deployment offers over deployment in earlier versions.
No-impact applications Private components Side-by-side versioning XCOPY deployment On-the-fly updates Global assembly cache
Lead-in
The new deployment options in Visual Studio .NET offer distinct advantages over the options in the Package and Deployment Wizard in Visual Basic 6.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Application developers have traditionally faced many issues when deploying their applications. Use of the deployment features in Microsoft Visual Studio .NET alleviates some of these issues. The following table lists some of the advantages of using Visual Studio .NET deployment.
Feature No-impact applications Private components Description All applications are isolated, which results in fewer .dll conflicts. By default, components are installed into the application directory. Therefore, you can only use it in that application. You can have more than one copy of a component on a computer, which can prevent versioning problems. Self-describing components can just be copied to the target computer. .dlls are not locked when in use and can be updated by an administrator without stopping the application. You can share assemblies between applications by installing them into the global assembly cache. This can also increase performance because only one copy of the assembly is loaded.
13
Copying Projects
Topic Objective
To discuss the simplest method of distributing an application.
Copying a project There is an extra menu command for Web applications You can copy a project directly to a Web server Using the XCOPY command Use the DOS command You can use it for any type of application
Lead-in
Distributing applications can be as simple as using the MS-DOS XCOPY command. However, this method does have certain restrictions.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Deploying simple applications with no dependencies can be as easy as copying the application to the target computer. Using this method can be quick, although it does not take advantage of the all the new features available in Visual Studio .NET deployment.
Copying a Project
When you are working with a Web application, you have an extra menu item available, Copy Project, which allows you to copy the project directly to a Web server. You can specify the access method, for example with Microsoft FrontPage Server extensions, and whether to copy just the necessary application files, the entire project, or all files in the project directory. Consider the following facts when using the Copy Project command: Assemblies are not registered for unmanaged client access. The locations of assemblies are not verified.
14
Deploying Projects
To provide an overview of the deployment options available.
Topic Objective
Windows Installer Is used for Windows-based and Web-based deployment Copies all required files and registers components Configures IIS for Web-based applications Merge modules Are used for reusable components Are included in an .msi file
Lead-in
The Windows Installer contains many features that enhance the deployment of your applications.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In general, you will create applications that have dependencies on other assemblies or components. In this situation, you must create a deployment package to ensure that the external references are correctly registered and located.
Windows Installer
You can use the Windows Installer to package all your data and installation instructions in one file, an .msi file, for easy distribution. Using the Windows Installer provides the following advantages: Support for the Zero Administration initiative for Windows This helps overcome the problems of overwriting shared components. Safe uninstall options Windows Installer provides an uninstall program that detects shared components and does not remove them. Rollback If the install fails before it is complete, for example, if the connection to the network share containing the source files is lost, then the Windows Installer will return the computer to its original state. You can use the Windows Installer to package both Windows-based and Webbased applications.
15
Merge Modules
You can use merge module projects to package shared components that will be used by more than one application on the target computer. You can then incorporate these modules into .msi packages whenever that component is used in a solution. Using merge modules has the following advantages: Eliminates versioning problems Captures the dependencies of the component Creates reusable setup code
16
Cab Project for downloading from Web server Merge Module Project for shared components Setup Project for Windows-based applications Setup Wizard to walk through deployment project creation Web Setup Project for Web-based applications
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** There are five options available to you when creating a deployment project in Visual Studio .NET. The following table lists the types of projects and their uses.
Project type Cab Project Merge Module Project Setup Project Setup Wizard Use Use this to create compressed CAB files for downloading from a Web server. Use this to create a setup for a shared component. Use this to create a setup for a Windows-based application. Use this to initiate the Setup Wizard that leads you through the steps of creating one of the four main deployment projects. Use this to create a setup for a Web-based application.
17
To create a new deployment project, click Setup and Deployment Projects in the New Project dialog box, as shown below:
18
Deploying Applications
Topic Objective
To provide an overview of the topics covered in this lesson.
Creating a Merge Module Project Creating a Setup Project Using the Editors Creating Installation Components Deploying the Application
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** To deploy applications, you need to create a setup project with all your installation preferences and build the project for distribution. After completing this lesson, you will be able to: Describe the two types of setup projects used for Windows-based and Webbased applications. Configure your installation process by using the Visual Studio .NET editors.
19
Never installed directly included in client application deployment project Contains DLL Any dependencies and resources Information for the Windows Installer Store one component only in one merge module If component changes, create a new merge module
Lead-in
After you create the strongnamed assembly, you need to package it within a merge module for further deployment with the client application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you create the strong-named assembly, you need to package it within a merge module for it to be included in the deployment project for a client application. The merge module provides you with a standard way of distributing components and ensuring that the correct version is installed. The merge module is never installed directly, but it is distributed within a Windows Installer project. It includes the .dll file, any dependencies, any resources, and any setup logic. This method of deployment ensures that whenever this shared component is used, it is installed on the target computer in the same way. It also contains information that the Windows Installer database uses to determine when you can safely remove a component during application removal. To package a component assembly, complete the following steps: 1. Create your component and build the .dll. 2. Add a merge module project to your solution. 3. Add the component to the Common Files folder or the global assembly cache. 4. Build the merge module project. 5. Add the merge module project to a Windows-based or Web-based setup project.
20
Objectives
After completing this lab, you will be able to create a merge module project.
Prerequisites
Before working on this lab, you must have: Knowledge of the merge module project template. Knowledge of the deployment editors. Knowledge of the setup project template for Windows-based applications.
Scenario
In this lab, you will create a merge module project to package a component assembly.
21
4. Close the Command Prompt window. To attach the key pair to the assembly 1. Open Microsoft Visual Studio .NET. 2. On the File menu, point to Open, and then click Project. 3. Browse to the install folder\Labs\Lab101\Starter\Component folder, click Component.sln, and then click Open. 4. In Solution Explorer, click Show All Files. 5. Right-click Component.snk, and then click Include In Project. 6. Open AssemblyInfo.vb. 7. Add the following assembly attribute:
<Assembly: AssemblyKeyFile("Component.snk")>
8. Build the component. To create the merge module project 1. In Visual Studio .NET, on the File menu, point to Add Project, and then click New Project. 2. In the Project Types pane, click Setup and Deployment Projects. 3. In the Templates pane, click Merge Module Project. Set the location to install folder\Labs\Lab101\Starter, and then click OK. 4. In the left pane of the File System Editor, right-click the Common Files Folder, point to Add, and then click Project Output. 5. In the Add Project Output Group dialog box, select Primary output and Content Files, and then click OK. 6. On the Build menu, click Build MergeModule1. 7. Close Visual Studio .NET.
22
To verify that the package has been created Open Windows Explorer, browse to the install folder\Labs\ Lab101\Starter\MergeModule1\Debug folder, and verify that MergeModule1.msm has been created.
23
Lead-in
You can use the New Project dialog box to select a project template for your setup project.
Creates a blank setup project with relevant folders in File System Editor Windows-based application Application Folder Users Desktop Users Programs Menu Web-based application Web Application Folder
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the Setup Project and Web Setup Project templates to create Windows Installer packages for Windows-based and Web-based applications, respectively. You specify which of these project types you want to use when you create a new project in Visual Studio .NET. You can also use the Setup Wizard to lead you through the process of gathering the necessary information resulting in the required project type.
24
Both project types start in the File System Editor window, which you use to specify where to install the included files on the target computer. You can allocate files, folders, shortcuts, and components to these folders. For example, you can include a ReadMe.htm or a merge module project containing a shared component in these folders. In addition to using the default folders, you can also use a predetermined set of special folders (for example the Windows folder), and you can also create your own subfolders.
Users Desktop
25
Topic Objective
Lead-in
In addition to the File System Editor, there are other editors that allow you to further customize the setup of your application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** In addition to the File System Editor, you can use a range of other editors to further define your setting for the installation process. You can access these editors by using the toolbar buttons in Solution Explorer, as shown below.
Registry
This gives you access to the commonly used registry hives and keys, such as HKEY_CURRENT_USER\Software and HKEY_LOCAL_MACHINE\ Software. These vary according to whether your application is a Windowsbased or Web-based application. In this editor, you can define your own keys and write their default values during the installation process.
26
File Types
This editor allows you to define new file types to be configured on the target computer and the actions associated with those types.
User Interface
This editor lists the windows in the Installation Wizard that the user sees and allows you to customize the messages and images displayed in them. You can customize both the standard and administrative installation programs. You can also add extra dialog boxes to the installation process. For example, you can request user preferences with text boxes and option buttons, request user information for registration purposes, or display license agreements.
Custom Actions
This allows you to include custom actions within your main setup program. These can be actions performed at install, commit, rollback or uninstall time. They can include running any executable file, .dll, or script file; adding users to or removing users from a database; or adding a support contact to the address book in Microsoft Outlook.
Launch Conditions
This editor allows you to define conditions for installing the application or performing custom actions. For example, if a database is not present on the server, you will not want to add users to it and may not want to install the application. You can check for files, registry keys, and Windows Installer installations. You can also customize the message given to the user if the condition is not satisfied.
27
Lead-in
You may also need to include Windows resources within your setup
*****************************ILLEGAL FOR NON-TRAINER USE****************************** When you are developing an application, you often use Windows resources such as event logs and message queues. These types of objects are available to you on the Components tab of the Visual Basic .NET toolbox.
28
The Visual Studio .NET installation process allows you to create these components on the target computer as part of your application installation process. You accomplish this by using installation components. You can set the properties of any component. These properties include elements such as the name of an existing message queue or name of the log. When you want to deploy your application, you can create ProjectInstaller files that copy all the settings for your component and re-create it on the target computer at installation time.
29
Topic Objective
Windows-based setup project Copies all files Registers components Performs other installation tasks Web setup project Copies all files Registers components Creates a Web application
Lead-in
After you configure your setup using the editors, you are ready to compile your setup project and deploy the application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** After you configure settings using the editors in Visual Studio .NET for your custom setup program, you can build the project ready for deployment. Because this is a standard Visual Studio .NET project, you can build or deploy the project in the usual ways, although building a Visual Basic solution will not build any setup projects included in it. Building the project creates an .msi file that you distribute to users so that they can run the setup program for your application. To install the application, you can run the .msi file on the target computer or click Install on the Project menu.
30
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will learn how to use the Setup Wizard to create a deployment project for a Web-based application. You will also learn how to use the Launch Conditions Editor to verify that a database is present on the target computer before installing the application.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
Delivery Tip
Ensure that students understand that this is a simple application created for demonstration purposes. It is the solution to Lab 7.1 of Course 2373B, Programming with Microsoft Visual Basic .NET.
31
Objectives
After completing this lab, you will be able to: Create a Windows Installer project. Deploy a Windows-based application.
Prerequisites
Before working on this lab, you must have: Completed Lab 10.1. Knowledge of the deployment editors. Knowledge of the setup project template for Windows-based applications.
Scenario
In this lab, you will deploy a Windows-based application. You will begin by creating a Windows Installer package that includes the merge module that you created in the previous lab and the client application. Then, you will deploy the application and ensure that it installs all sections successfully.
32
33
To customize the installation 1. In the File System Editor, open the Users Desktop folder. Right-click in the right pane and click Create New Shortcut. 2. In the Select Item in Project dialog box, open the Application Folder, click Customers.exe, and then click OK. 3. In the Properties window, change the name of the shortcut to Customers. 4. Use the same method to create a shortcut to Customers.exe in the Users Programs Menu. 5. Right-click the Application Folder, point to Add, and then click File. 6. Browse to the install folder\Labs\Lab102\Starter folder, click ReadMe.rtf, and then click Open. 7. On the Solution Explorer toolbar, click User Interface Editor. 8. Under Install, right-click Start, and then click Add Dialog. 9. In the Add Dialog dialog box, click Read Me, and then click OK. 10. Select the new Read Me dialog box in the editor. 11. In the Properties window, in the ReadmeFile property drop-down, click (Browse). In the Select Item in Project dialog box, open the Application Folder, click ReadMe.rtf, and then click OK. To build the project 1. On the File menu, click Save All. 2. On the Build menu, click Build Setup1. 3. When the project is successfully built, quit Visual Studio .NET.
34
35
Review
To reinforce module objectives by reviewing key points.
Topic Objective
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. Name the four ways of distributing a Visual Studio .NET project and describe what each is used for. XCOPY deployment for simple stand-alone applications Copy Project deploymentfor copying a Web project directly to the Web server Windows Installerfor deploying Windows-based and Web-based applications Merge Modulefor packaging reusable, shared components
2. How do you create a strong-named assembly? Use sn.exe to create a public-private key pair and apply it to the assembly by adding the AssemblyKeyFile attribute to the AssemblyInfo.vb file.
3. Describe the use of the Launch Conditions Editor. The Launch Conditions Editor allows you to define certain conditions under which the installation of an application fails, for example, the absence of a required database on a server.
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. 2002 Microsoft Corporation. All rights reserved. Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript, Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners.
iii
Instructor Notes
Presentation: 60 Minutes Lab: 00 Minutes This module provides students with the knowledge needed to decide whether to upgrade existing Microsoft Visual Basic 6.0based applications and describes the options that are available for upgrading. Students will receive recommendations for which types of applications to upgrade and which to leave alone. Finally, they will learn the tasks that are necessary before and after using the Visual Basic Upgrade Wizard and view a demonstration of the wizard. After completing this module, students will be able to: Make an informed decision about whether to upgrade an application. Describe the various upgrade options available. Use the Upgrade Wizard.
Required Materials
To teach this module, you need the following materials: Microsoft PowerPoint file 2373B_11.ppt Module 11, Upgrading to Visual Basic .NET
Preparation Tasks
To prepare for this module, you should: Read all of the materials for this module. Read the instructor notes and the margin notes for the module. Practice the demonstration.
iv
Demonstration
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes.
To review the upgraded application Run the application, demonstrating that the code is now functioning as expected. To review the issues identified by the Upgrade Wizard 1. Review the comments added to each of the classes in the Invoices project. Note the hyperlinks to Help topics. 2. If time allows, go through and make appropriate changes to the code, using the hyperlinks for further information about the issues. To discuss further modifications If time allows, discuss the other options available for further enhancements. These are mentioned in the student notes and can lead to a class discussion.
vi
Module Strategy
Use the following strategy to present this module: Deciding Whether to Upgrade In this lesson, you will discuss the advantages and disadvantages of upgrading an application created in Visual Basic 6.0 to Visual Basic .NET. You will talk about the advantagessuch as enhanced scalability, improved performance, and ease of deploymentand compare these to the disadvantages of time and money. This is obviously a subjective issue because no two projects will ever have the same advantages and costs, but the goal of the lesson is to make students aware of the factors that they need to consider. Options for Upgrading This lesson describes the three options for upgrading: full upgrade, partial upgrade, and full rewrite. Recommendations This is a single slide that outlines Microsofts recommendations for the upgrading of different types of applications. Performing the Upgrade This lesson covers the details of the actual upgrade process. It begins by discussing what you need to do to the Visual Basic 6.0based application to prepare it for the upgrade. These changes ensure that the Upgrade Wizard can maximize its output. You will then discuss how to use the Upgrade Wizard and what the resulting code and project will look like. Remember that you have spent the whole course discussing Visual Basic .NET and that the goal of this topic is to point out the upgrade-specific issues, not the general Visual Basic .NET code. You will also discuss the lists of problematic pieces of code that the wizard creates, including the Upgrade Report and Task List. Finally, you will demonstrate the Upgrade Wizard. If time allows, this demonstration can lead into a class discussion about further possible ways to enhance the project.
Overview
Topic Objective
To provide an overview of the module topics and objectives.
Deciding Whether to Upgrade Options for Upgrading Recommendations Performing the Upgrade
Lead-in
In this module, you will learn about upgrading applications created in Visual Basic 6.0 to Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** As you have seen throughout this course, there are some fundamental changes in Microsoft Visual Basic .NET version 7.0. These changes are necessary because Visual Basic .NET is a significant upgrade that takes full advantage of the Microsoft .NET Framework. Because of these changes, you will find that upgrading applications to Visual Basic .NET might take time and effort, but it does allow you to take advantage of the new features in the .NET Framework. The Visual Basic Upgrade Wizard has been provided as a step in the upgrade process to help you upgrade, but there are tasks that you should complete both before and after its use. In this module, you will learn the factors you must consider when deciding whether to upgrade an existing application, the options you have for upgrading, and how to use the Upgrade Wizard. After completing this module, you will be able to: Make an informed decision about whether to upgrade an application. Describe the various upgrade options available to you. Use the Upgrade Wizard.
Lead-in
Upgrading an application is not a necessity; you must examine the advantages and disadvantages of doing so before deciding to upgrade.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You must consider various factors when deciding whether to upgrade an application. In some situations, the advantages gained from porting the application to the .NET Framework will greatly outweigh the costs involved. In other situations, you might decide that the advantages are not worth the investment. Upgrading is not a necessity, and you should carefully examine the advantages and disadvantages before starting the process. After completing this lesson, you will be able to: Evaluate the advantages and disadvantages of the upgrade process. Identify how to decide when to upgrade your applications to Visual Basic .NET.
Advantages Gained
To discuss the advantages that can be gained from upgrading Visual Basic 6.0 based applications to Visual Basic .NET.
Topic Objective
Scalability Performance Deployment Access to rich set of base classes Better debugging Solves DLL conflicts Maintenance
Lead-in
Upgrading your Visual Basic 6.0based applications to Visual Basic .NET may result in improved performance and scalability.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip The .NET Framework provides many benefits to the application developer that may enhance applications created in Visual Basic version 6.0.
Remind students that there are many advantages to using the .NET Framework, but here we are considering the main advantages to upgrading an existing application.
Advantages
Three major advantages upgrading your application to Visual Basic .NET provides are: Scalability ADO.NET enhances scalability by means of the disconnected data architecture, which reduces the number of concurrent database connections necessary, thereby reducing the overhead needed to run the application. The ASP.NET state management system improves upon that of Active Server Pages (ASP). Session state can be shared among many servers in a Web farm, allowing for greater scalability. Performance ADO.NET is a simplified version of Microsoft ActiveX Data Objects (ADO). It is designed around Extensible Markup Language (XML) to work seamlessly with disconnected data. The DataReader object is designed for speed and greatly increases the performance of data intensive applications. ASP.NET has improved performance over ASP and other Web development technologies. ASP.NET is a compiled .NET-based environment, which will run faster than existing applications, and allows you to use early binding throughout your applications.
Deployment Deployment is greatly simplified in the .NET Framework. Depending on the complexity of your application, deployment can entail running an application directly from a server, using XCOPY to copy the application to a workstation or Web server, or installing by using Microsoft Windows Installer. Other advantages include: Maintenance Access to Rich Set of Base Classes Better Debugging Solves DLL Conflicts
Cost Incurred
To discuss the potential costs of upgrading an application to Visual Basic .NET.
Topic Objective
Time to upgrade may trade-off against future maintenance time May require redesign, as well as upgrading and recoding Financial costs can be spread by upgrading an application section by section
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The costs you may incur in upgrading an application can be measured in terms of time, effort, and ultimately finance. It will take you time to upgrade your applications from Visual Basic 6.0 to Visual Basic .NET; however, that time may actually recoup itself in the reduced maintenance time associated with the upgraded application or be outweighed by the benefits obtained by the upgrade. Visual Basic .NETbased applications can require less maintenance because of the improvements associated with the .NET Framework. XCOPY deployment ends DLL conflicts. Some applications will gain little benefit from simply upgrading the existing application to Visual Basic .NET. These include applications that may have been upgraded through various versions of Visual Basic and never redesigned to take full advantage of the current systems architecture. The costs of redesigning an application will greatly increase the overall cost, and may be a deciding factor in your choice. Some application architectures lend themselves to a gradual upgrade process over a period of time. For example, an application using a number of classes that contain data access code can be upgraded in a number of steps. First you can upgrade the user interface, then you can upgrade the middle-tier components, and then you can recode the existing ADO code to ADO.NET in the data tier.
Ease of Upgrade
Topic Objective
To discuss the factors that affect the ease of upgrading.
Lead-in
The ease with which an application can be upgraded is affected by various factors, including the structure of the code, the project types involved, and the language features used.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** There are a variety of factors that will affect how easy it is to upgrade an application. These include the original application architecture, the modularity of the code in the application, the types of projects and controls used in application, and the language constructs used.
Modularity of Code
Because Visual Basic .NET supports object-oriented features not available in Visual Basic 6.0, it is easier to upgrade modular code than non-modular code. If an application has been designed in a modular fashion, changes to one component should not adversely affect another, and this results in a simpler upgrade path.
Project Types
Visual Basic .NET does not support some of the Visual Basic 6.0 project types, such as dynamic HTML (DHTML) applications and ActiveX Documents. These applications cannot be upgraded and should be left in Visual Basic 6.0 or rewritten in Visual Basic .NET by using Web Forms.
Control Types
Some Visual Basic 6.0 controls are not supported in Visual Basic .NET and will upgrade to substitute controls. For example, the Shape, Line, and OLE Container controls are all unsupported and will upgrade to Label controls in Visual Basic .NET. If your application makes extensive use of these types of control, it may require more work to upgrade the application to a working solution.
Language Constructs
Some Visual Basic 6.0 keywords are not supported in Visual Basic .NET. For example, Option Base, LSet, and GoSub are not supported. Extensive use of these keywords in your projects will require manual work after the upgrade process.
Lead-in
Once you have decided to migrate your application to Visual Basic .NET, you will then need to determine the upgrade path to follow.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip There are three options available if you decide to upgrade an existing application: You can completely rewrite the application, gaining all the benefits of the .NET Framework. You can use the Upgrade Wizard on all sections of the application, gaining some of the benefits. Finally, you can do a partial upgrade, leaving legacy sections in Visual Basic 6.0. After completing this lesson, you will be able to: Identify the three upgrade options. Describe the advantages and disadvantages of each upgrade approach.
Remind students that the advantages and disadvantages listed here are general guidelines, and that each project must be assessed individually.
Complete Rewrite
Topic Objective
To discuss the advantages and disadvantages of a complete rewrite of an existing application.
Lead-in
Completely rewriting an application is not the easiest way to convert an application to Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** A complete rewrite of the application is the best way to gain all of the benefits of the .NET Framework, but this can also be the most costly solution. It is most commonly used when the application contains sections that are not upgradeable but that need to take advantage of the .NET Framework.
Advantages
Performance can be improved through the use of new technologies such as ASP.NET and ADO.NET. Scalability is increased when using ASP.NET rather than ASP or other Visual Basic 6.0 Web project types. If you rewrite your application from the very beginning, you will have the chance to redesign it to take advantage of the object-oriented features of Visual Basic .NET. Your code base will be reduced due to some of the new features in Visual Basic .NET; for example, resizing code can be replaced by using the Anchor properties of a control.
Disadvantages
Rewriting an application can be labor intensive, as it will potentially involve software analysts as well as developers. Learning Visual Basic .NET by rewriting an application can be very difficult for those involved. Any existing code that has been written will not be reused, and this results in wasted investment of the existing code.
Complete Upgrade
Topic Objective
To discuss the advantages and disadvantages of a complete upgrade of an existing application.
Lead-in
A complete upgrade is generally easiest, but it is the least likely of all the scenarios.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You will probably find that this is the easiest option for upgrading, but it will not be a common occurrence. Even if the application is completely upgradeable, it may not result in the most efficient code, so you are likely to need to revisit sections anyway.
Advantages
You will gain performance and scalability from the upgraded sections of the code. You will preserve the earlier investment made in the existing code by reusing the code.
Disadvantages
Some sections of the application may not be upgradeable (for example, ADO code), so this will not take advantage of .NET. Some upgraded sections may use COM interoperability to communicate with the .NET components, resulting in lower performance. Other sections may use the Visual Basic compatibility library, again introducing overhead into the system.
10
Partial Upgrade
Topic Objective
To discuss the advantages and disadvantages of a partial upgrade of an existing application.
Most likely option COM interoperability is only a problem if large number of client server calls
Advantages Improved performance Improved scalability Preserves investment in existing code Quick upgrade, and retain non-upgradeable code Disadvantages Use of COM interoperability adds overhead Difficult to maintain Difficult to deploy
Lead-in
A partial upgrade is the most likely option for migrating your application to Visual Basic .NET.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** A partial upgrade is the most likely option for migrating your application to Visual Basic .NET. This allows you to upgrade the sections of your code that will make the most benefit of using the .NET Framework while continuing to use the ones that will be difficult to upgrade. Sometimes you will use this method as a progressive upgrade option, allowing you to focus the upgrade process on small sections of the application at a time.
Advantages
Performing a partial upgrade can allow you to take advantage of the particular performance and scalability enhancements in the .NET Framework that are appropriate to your application. It preserves the investment made in your existing code, and allows reuse of as much or as little as you want.
Disadvantages
A partial upgrade may result in using COM interoperability to communicate between COM and .NET components. This may degrade performance. Applications that mix Visual Basic 6.0 and Visual Basic .NET are harder to deploy and maintain than single-language applications.
11
Recommendations
To provide some general guidelines about which type of upgrade to apply to various types of applications.
Topic Objective
Web client server Complete upgrade ASP to ASP .NET and Web Forms, COM components to .NET components, and ADO to ADO .NET Traditional N-tier applications Partial upgrade Leave client in Visual Basic 6.0 Enterprise legacy applications Complete rewrite Encapsulate legacy system in Web Service Stand-alone Windows-based applications Little benefit to upgrading
Lead-in
You have seen the upgrade options available. Now lets look at applying these to different application architectures.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You have seen that the various upgrade options will lend themselves to particular application architectures. The following recommendations can be used as general guidelines to help you decide on the best upgrade process for your particular needs.
12
13
Preparing for the Upgrade Using the Upgrade Wizard Results of the Upgrade Wizard Completing the Upgrade
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** You can use the Upgrade Wizard to assist you in upgrading your Visual Basic 6.0based applications to Visual Basic .NET. Opening a Visual Basic 6.0based application in Visual Basic .NET will create a new application and leave the existing application as it is. Delivery Tip Because of the differences between the two products, the Upgrade Wizard cannot perform the entire process, but it can simplify some of the tasks involved. After completing this lesson, you will be able to: Identify tasks you need to perform before, during, and after using the Upgrade Wizard. Note The Upgrade Wizard should only be used to upgrade applications created in Visual Basic 6.0. If you want to upgrade projects created in earlier versions of Visual Basic, open and compile them in Visual Basic 6.0 before using the wizard.
Mention GIGO garbage in, garbage out. Modifying Visual Basic 6.0 code will optimize the output of the wizard. Unmodified code will result in potentially more complex post-wizard tasks.
14
Lead-in
There are certain changes you can make to your Visual Basic 6.0 code to maximize the usefulness of the output of the Upgrade Wizard.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** There are certain tasks that you can perform before using the Upgrade Wizard to maximize the usefulness of its output. These are tasks that make the wizard able to upgrade what would otherwise be ambiguous code. It is easier to modify your Visual Basic 6.0 code and allow the wizard to upgrade it than to need to address the issues after the upgrading has occurred. You can identify these issues by upgrading your application, reading the comments added by the wizard, and then modifying your Visual Basic 6.0 based project before beginning the upgrade process again.
Early Binding
Late-bound objects can cause problems during the upgrade process when default properties are resolved, and when calls to updated properties, methods, and events are upgraded.
Example
In the following example, a Label object is declared as type Object, meaning that the Upgrade Wizard is unable to upgrade the Caption property to the Visual Basic .NET equivalent of the Text property:
Dim objLabel as Object Set objLabel = Form1.Label1 objLabel.Caption = "Enter your password" 'Cannot be upgraded
To avoid this, you should declare all of your variables as the explicit type.
Dim objLabel as Label Set objLabel = Form1.Label1 objLabel.Caption = "Enter your password" 'Can be upgraded
15
Null Propagation
Null propagation is the behavior in Visual Basic 6.0 that dictates that if you add Null to another data type, the result will always be Null.
Example
a = Null b = 5 c = a + b
Using the concatenation operator (&) in Visual Basic 6.0 does not result in Null propagation.
In Visual Basic 6.0, the above code will result in variable c evaluating to Null. In Visual Basic .NET, this code will return an invalid cast exception. To avoid this error, you should always check the contents of a variable that could potentially be Null prior to performing operations on it. The following code shows how to write your Visual Basic 6.0 code to ensure compatibility with Visual Basic .NET:
a = Null b = 5 If IsNull (a) Then ' Take appropriate action Else c = a + b End If
Note The Upgrade Wizard will upgrade the Visual Basic 6.0 Null constant to System.DBNull.Value and the IsNull function used in Visual Basic 6.0 to IsDbNull.
Date Variables
In Visual Basic 6.0, dates are stored internally as Double, so you can declare them as either Date or Double, and implicit type conversion will occur. In Visual Basic .NET, dates are not stored internally as Double, so they need to be declared as explicit Date types. Because there is no way for the Upgrade Wizard to determine which Doubles were intended as Dates, it cannot upgrade dates declared as Doubles. To avoid this problem when upgrading, declare all dates explicitly in Visual Basic 6.0 as the Date data type.
16
Constants
Some of the underlying values of intrinsic Visual Basic constants have changed. If your Visual Basic 6.0 code uses the constants, the Upgrade Wizard will automatically upgrade them to the new constants storing the new underlying values; however, if you have used explicit values in your code, the Upgrade Wizard will leave these unaltered, and errors may occur. The following example shows how to correctly use Visual Basic constants in your Visual Basic 6.0 code:
Example
'Incorrect use of underlying values Response = MsgBox("Do you want to continue?", 4) If Response = 6 Then 'Do something End If 'Correct use of predefined constants Response = MsgBox("Do you want to continue?", vbYesNo) If Response = vbYes Then 'Do something End If
Data Access
The only forms of supported data binding in Visual Basic .NET are ADO and ADO.NET. For this reason, it is recommended that you upgrade all Data Access Object (DAO) or Remote Data Objects (RDO) data binding to ADO in your Visual Basic 6.0 applications before upgrading to Visual Basic .NET. DAO, RDO, ADO, and ADO.NET code are all supported in Visual Basic .NET, so you do not need to change these before upgrading. However, you may decide to take advantage of the disconnected ADO.NET architecture and upgrade your code to ADO.NET after the upgrade process has been completed.
17
Topic Objective
Lead-in
The Upgrade Wizard will gather the information necessary to upgrade your application.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Once you have prepared your application for upgrade, use the Upgrade Wizard to perform the process. It is recommended that you begin by upgrading the user interface tier of your application, and work back through the other tiers. You can launch the Upgrade Wizard by opening a Visual Basic 6.0based application in Visual Basic .NET. This will gather the information necessary to upgrade your application. The Upgrade Wizard will not modify your original application; it will create an upgraded copy at the location you specify.
18
Lead-in
Language changes Code upgraded to be syntactically correct in Visual Basic .NET Form changes Most controls will upgrade Other changes Other functionality will be upgraded to similar objects
The Upgrade Wizard does not change the basic structure of your projects.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** When you have upgraded your application, the resulting project will still be very similar to the original. Delivery Tip Anything that can be upgraded is upgraded, and anything that cannot be upgraded, or anything that is ambiguous, will be marked with comments and entered in the Upgrade Report. Links are created to relevant topics in the documentation files to help you resolve any outstanding issues. Some Visual Basic 6.0 functions do not have equivalents in Visual Basic .NET, and these will be retained through use of compatibility functions.
Remember that the Upgrade Wizard creates a new project and leaves the original project alone.
Language Changes
The Upgrade Wizard modifies the code where possible to take into account the syntax changes in Visual Basic .NET. This includes: Resolving parameterless default properties. Adding the ByRef keyword to procedure parameters. Changing property procedures to the new syntax. Adding parentheses to all function calls. Changing all data types to their new equivalents.
19
Form Changes
Visual Basic forms will be upgraded to Windows Forms, although a few controls cannot be upgraded because they have no counterpart in Visual Basic .NET. These include the following, which all upgrade to Visual Studio .NET Label controls: OLE Container control Shape controls Line controls
Other Changes
Other functionality in applications created in Visual Basic 6.0 may not have a direct counterpart in Visual Basic .NET but will be left as is or upgraded to similar objects. For example: Resource files will upgrade to .resx files that can store any .NET data type. Web classes will not upgrade. ADO data environments will not upgrade. ADO code and ADO data binding will remain unchanged. Property pages are no longer used in Visual Basic .NET.
20
Topic Objective
Upgrade Report Upgrade comments Task List entries Testing Other tasks
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** The Upgrade Wizard also identifies any potential issues in the upgraded project. It creates an Upgrade Report that lists all potential problems, and adds tasks to the Task List for changes you need to make. These changes are also marked with comments in the code.
Upgrade Report
The Upgrade Report lists all upgrade errors and warnings, grouped by the file in which they occur. It contains details of the issue, the location, and the Help topic associated with the issue. This Help topic will explain why there is a problem with the code and what you should do to correct the code.
Upgrade Comments
The Upgrade Wizard adds fours types of comments to your code: UPGRADE_ISSUE These mark any lines of code that will prevent your code from compiling. UPGRADE_TODO These mark any code that will compile but that will still cause a run-time error. UPGRADE_WARNING These mark code that will compile but that may cause run-time errors. UPGRADE_NOTE These mark code that will compile and run but for which the changes in Visual Basic .NET may cause unwanted side effects. The comments also include a hyperlink to the Help topic associated with the issue.
21
Testing
You must ensure that you complete a full test cycle after the upgrade process, to check that the application is still functioning as you would expect.
Other Tasks
There are a number of other modifications that you can make to your code to improve it. The first of these should be done immediately; the rest can be done in the next phase of the upgrade. Replace compatibility functions and controls with .NET code. These are only provided for convenience during the upgrade process and should not be used in deployed applications. Upgrade ADO code to ADO.NET. This will take advantage of the benefits of ADO.NET. Replace COM components with NET components. This will reduce the number of managed to unmanaged calls, which will improve the performance of your application. Replace error handling code. You should replace any existing Visual Basic 6.0 error handling code with Visual Basic .NET exception handling using Try..Catch blocks to ensure a more structured approach to your error handling.
22
Topic Objective
Lead-in
Now that you have learned how to upgrade an application, lets watch the process as it happens.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Delivery Tip In this demonstration, you will see how to upgrade a Visual Basic 6.0 application to Visual Basic .NET. You will see the original Visual Basic 6.0 application, how to use the Upgrade Wizard, and some of the tasks that could be completed afterwards. This application is a simple invoice viewing system for the Cargo system. It is currently running as a Visual Basic 6.0 form-based application, interacting with class modules providing the data access code. You will see the projects being upgraded by the Upgrade Wizard and review the issues identified in the comments and Upgrade Report. Once the critical issues have been solved, there are other considerations for the project. All the data access code is ADO and could be upgraded to ADO.NET to take advantage of the disconnected architecture.
The step-by-step instructions for this demonstration are in the instructor notes for this module.
Delivery Tip
Ensure that students understand that this is a simple application created for demonstration purposes. Be sure to discuss with them the options that are available to further enhance an application after they have used the Upgrade Wizard and addressed the major issues.
23
Review
To reinforce module objectives by reviewing key points.
Topic Objective
Deciding Whether to Upgrade Options for Upgrading Recommendations Performing the Upgrade
Lead-in
The review questions cover some of the key concepts taught in the module.
*****************************ILLEGAL FOR NON-TRAINER USE****************************** 1. List two benefits of upgrading an application and how those benefits are gained. Scalability can be gained through the use of ASP.NET. Performance can be improved through the use of ASP.NET and ADO.NET.
2. What is the most commonly followed upgrade path? Why? Partial upgrade, because a complete rewrite is generally too expensive and a complete upgrade too impractical.
3. Which upgrade comments are not listed in the Task List? Why? UPGRADE_NOTE comments are not listed because they only highlight potential problems, and the code will run without any modifications.
24
Course Evaluation
To direct students to a Web site to complete a course evaluation.
Topic Objective
Lead-in
*****************************ILLEGAL FOR NON-TRAINER USE****************************** Your evaluation of this course will help Microsoft understand the quality of your learning experience. To complete a course evaluation, go to http://www.metricsthatmatter.com/survey. Microsoft will keep your evaluation strictly confidential and will use your responses to improve your future learning experience.