visual basic essentials - training materials for it ... · pdf filevisual basic essentials...

55
Object Innovations Course 4202 Student Guide Revision 4.5 Visual Basic Essentials Evaluation Copy

Upload: lebao

Post on 26-Mar-2018

215 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Object Innovations Course 4202

Student Guide Revision 4.5

Visual Basic Essentials Evaluation Copy

Page 2: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC ii All Rights Reserved

Visual Basic Essentials Rev. 4.5 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

™ is a trademark of Object Innovations. Authors: Robert J. Oberg and Dana Wyatt Copyright ©2013 Object Innovations Enterprises, LLC All rights reserved.. Object Innovations 877-558-7246 www.objectinnovations.com Printed in the United States of America.

Evaluation Copy

Page 3: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 .NET: What You Need to Know Chapter 2 Visual Basic for the Sophisticated Programmer Chapter 3 Object-Oriented Programming in Visual Basic Chapter 4 Visual Basic and the .NET Framework Chapter 5 Delegates and Events Chapter 6 Introduction to Windows Forms Chapter 7 Newer Features in Visual Basic Appendix A Using Visual Studio 2012 Appendix B Learning Resources

Evaluation Copy

Page 4: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• The course software installs to the root directory C:\OIC\VbEss.

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

− Example programs for Appendix A are in the directory AppA.

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

− The CaseStudy directory contains a case study in multiple steps.

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

Evaluation Copy

Page 5: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed)

Chapter 1 .NET: What You Need to Know .............................................................. 1 Getting Started ................................................................................................................ 3 .NET: What Is Really Happening ................................................................................... 4 .NET Programming in a Nutshell ................................................................................... 5 .NET Program Example.................................................................................................. 6 Viewing the Assembly.................................................................................................... 7 Viewing Intermediate Language..................................................................................... 8 Understanding .NET ....................................................................................................... 9 Visual Studio 2012........................................................................................................ 10 Creating a Console Application .................................................................................... 11 Visual Studio Solutions................................................................................................. 12 Starter Code .................................................................................................................. 13 Using the Visual Studio Text Editor............................................................................. 14 IntelliSense.................................................................................................................... 15 Build and Run the Project ............................................................................................. 16 Pausing the Output........................................................................................................ 17 Visual Basic and GUI Programs ................................................................................... 18 .NET Documentation .................................................................................................... 19 Summary ....................................................................................................................... 20

Chapter 2 Visual Basic for the Sophisticated Programmer .................................. 21 Visual Basic .................................................................................................................. 23 Hello, World ................................................................................................................. 24 Compiling, Running (Command Line) ......................................................................... 25 Program Structure ......................................................................................................... 26 Namespaces................................................................................................................... 28 Project Imports.............................................................................................................. 29 Startup Object ............................................................................................................... 30 Variables ....................................................................................................................... 32 Literals and Constants................................................................................................... 33 Operators....................................................................................................................... 34 Short-Circuit Operators................................................................................................. 35 More Operators ............................................................................................................. 36 Operator Precedence ..................................................................................................... 38 Control Structures ......................................................................................................... 39 Conditionals .................................................................................................................. 40 Looping Constructs....................................................................................................... 42 Types in Visual Basic ................................................................................................... 45 Object............................................................................................................................ 46 Simple Data Types........................................................................................................ 47 Floating Point Data Types ............................................................................................ 48 Implicit Conversions..................................................................................................... 49 Explicit Conversions..................................................................................................... 50

Evaluation Copy

Page 6: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC vi All Rights Reserved

Boolean Data Type ....................................................................................................... 51 Structure........................................................................................................................ 52 Enumeration Types ....................................................................................................... 53 Reference Types............................................................................................................ 54 Class Types ................................................................................................................... 55 Object............................................................................................................................ 56 String Data Type ........................................................................................................... 57 Copying Strings ............................................................................................................ 58 StringBuilder Class ....................................................................................................... 59 Classes and Structures................................................................................................... 61 Arrays............................................................................................................................ 62 One Dimensional Arrays............................................................................................... 63 System.Array ................................................................................................................ 64 InputWrapper Class ...................................................................................................... 65 Input Wrapper Implementation..................................................................................... 66 Jagged Arrays................................................................................................................ 67 Rectangular Arrays ....................................................................................................... 68 For Each for Arrays ...................................................................................................... 69 Boxing and Unboxing ................................................................................................... 70 Output in Visual Basic .................................................................................................. 71 Formatting..................................................................................................................... 72 Formatting Example...................................................................................................... 73 Modules......................................................................................................................... 74 Subroutines and Functions............................................................................................ 75 Default Parameters........................................................................................................ 78 Exceptions..................................................................................................................... 79 Exceptions – Example Program.................................................................................... 80 System.Exception.......................................................................................................... 82 Implicit Line Continuation............................................................................................ 83 Lab 2 ............................................................................................................................. 84 Summary ....................................................................................................................... 85

Chapter 3 Object-Oriented Programming in Visual Basic....................................... 89 Visual Basic as an Object-Oriented Programming Language ...................................... 91 Classes vs. Objects........................................................................................................ 92 Creating a Class ............................................................................................................ 93 Creating and Referencing Objects ................................................................................ 94 Bank Example............................................................................................................... 95 Account Class ............................................................................................................... 96 Shared Members ........................................................................................................... 98 Auto-Implemented Properties..................................................................................... 100 Auto-Implemented Property Example ........................................................................ 101 Classes and Modules................................................................................................... 102 Self-Generating IDs .................................................................................................... 103 Methods vs. Properties................................................................................................ 105 Defining Member Variables ....................................................................................... 106 Adding Methods.......................................................................................................... 107

Evaluation Copy

Page 7: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC vii All Rights Reserved

Adding Properties ....................................................................................................... 108 Overloading Methods.................................................................................................. 110 Object Lifecycle.......................................................................................................... 112 Classes vs. Structures.................................................................................................. 116 Inheritance................................................................................................................... 118 Inheritance and Scope ................................................................................................. 120 Invoking the Base Class.............................................................................................. 122 Shadowing Base Class Methods ................................................................................. 123 Polymorphism............................................................................................................. 124 Overriding Base Class Methods.................................................................................. 125 Heterogeneous Collections ......................................................................................... 127 Abstract Classes .......................................................................................................... 128 Abstract Methods ........................................................................................................ 129 User Defined Exception Classes................................................................................. 130 Operator Overloading ................................................................................................. 133 Lab 3 ........................................................................................................................... 135 Summary ..................................................................................................................... 136

Chapter 4 Visual Basic and the .NET Framework .............................................. 139 Components and OO in Visual Basic ......................................................................... 141 Interfaces..................................................................................................................... 142 Interfaces in Visual Basic ........................................................................................... 144 Implementing an Interface .......................................................................................... 145 Using an Interface ....................................................................................................... 146 Multiple Interfaces ...................................................................................................... 147 Using Multiple Interfaces ........................................................................................... 150 TypeOf ... Is and Dynamic Interfaces ......................................................................... 152 Interfaces in Visual Basic and COM .......................................................................... 154 Resolving Ambiguity in Interfaces ............................................................................. 155 System.Object ............................................................................................................. 158 Collections .................................................................................................................. 160 ArrayList ..................................................................................................................... 161 ArrayList Methods ...................................................................................................... 162 Example: StringList ................................................................................................... 163 IEnumerable and IEnumerator.................................................................................... 164 Using Enumerators...................................................................................................... 165 Collections of User-Defined Objects .......................................................................... 166 Account Class ............................................................................................................. 167 Collection Interfaces ................................................................................................... 168 ICollection................................................................................................................... 169 IList ............................................................................................................................. 170 Default Properties ....................................................................................................... 171 Using the Item Property .............................................................................................. 172 Copy Semantics in Visual Basic ................................................................................. 173 Arrays.......................................................................................................................... 174 Shallow Copy and Deep Copy.................................................................................... 175 CopyDemo Example Program .................................................................................... 176

Evaluation Copy

Page 8: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC viii All Rights Reserved

Reference Copy........................................................................................................... 178 Memberwise Clone ..................................................................................................... 179 Using ICloneable ........................................................................................................ 180 Lab 4A ........................................................................................................................ 181 Writing Generic Code ................................................................................................. 182 Using a Class of Object............................................................................................... 183 Generic Types ............................................................................................................. 184 Generic Example......................................................................................................... 185 Generic Client Code.................................................................................................... 186 System.Collections.Generic........................................................................................ 187 Lab 4B......................................................................................................................... 188 Summary ..................................................................................................................... 189

Chapter 5 Delegates and Events ............................................................................ 195 Overview of Delegates and Events ............................................................................. 197 Callbacks and Delegates ............................................................................................. 198 Usage of Delegates ..................................................................................................... 199 Declaring a Delegate................................................................................................... 200 Defining a Method ...................................................................................................... 201 Creating a Delegate Object ......................................................................................... 202 Calling a Delegate....................................................................................................... 203 Random Number Generation ...................................................................................... 204 A Random Array......................................................................................................... 205 Combining Delegate Objects ...................................................................................... 206 Account.vb .................................................................................................................. 207 DelegateAccount.vb.................................................................................................... 208 Events.......................................................................................................................... 209 Static and Dynamic Event Handling........................................................................... 210 Dynamic Event Handling............................................................................................ 211 Chat Room Example ................................................................................................... 212 Static Event Handling ................................................................................................. 214 Lab 5 ........................................................................................................................... 216 Summary ..................................................................................................................... 217

Chapter 6 Introduction to Windows Forms ......................................................... 221 Creating a Windows Forms App................................................................................. 223 IDE Generated Code in VB 2012 ............................................................................... 227 Partial Classes ............................................................................................................. 228 Windows Forms Event Handling................................................................................ 229 Add Events for a Control ............................................................................................ 230 Events Documentation................................................................................................ 231 Closing a Form............................................................................................................ 232 ListBox Control .......................................................................................................... 233 ListBox Example ........................................................................................................ 234 My............................................................................................................................... 235 Command Line Arguments......................................................................................... 236 Lab 6 ........................................................................................................................... 237 Summary ..................................................................................................................... 238

Evaluation Copy

Page 9: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC ix All Rights Reserved

Chapter 7 Newer Features in Visual Basic ........................................................... 243 Local Type Inference .................................................................................................. 245 Local Type Inference – Example................................................................................ 246 Object Initializers........................................................................................................ 247 Array Initializers ......................................................................................................... 248 Anonymous Types ...................................................................................................... 249 Partial Methods ........................................................................................................... 250 Partial Method Definition ........................................................................................... 251 Partial Method Implementation .................................................................................. 252 Test Program............................................................................................................... 253 Running the Example.................................................................................................. 254 Extension Methods...................................................................................................... 255 Extension Methods Example ...................................................................................... 256 Collection Initializers.................................................................................................. 257 Variance in Generic Interfaces.................................................................................... 258 Covariance Example ................................................................................................... 259 Variance with IComparer(Of T) ................................................................................. 260 Interfaces with Variance Support................................................................................ 261 Contravariance Example............................................................................................. 262 Language-Integrated Query (LINQ) ........................................................................... 263 LINQ Example............................................................................................................ 264 Using IEnumerable(OfT> ........................................................................................... 265 Iterators ....................................................................................................................... 266 Yield Keyword............................................................................................................ 267 Iterator Examples ........................................................................................................ 268 Asynchronous Programs in VB 2012 ......................................................................... 269 Task and Task(Of TResult)......................................................................................... 270 Aysnc Methods ........................................................................................................... 271 Async Example ........................................................................................................... 272 Synchronous Call ........................................................................................................ 273 Async Call................................................................................................................... 274 Threading .................................................................................................................... 275 Summary ..................................................................................................................... 276

Appendix A Using Visual Studio 2012...................................................................... 279 A Visual Studio Solution ............................................................................................ 281 Toolbars ...................................................................................................................... 283 Customizing a Toolbar................................................................................................ 284 Creating a Console Application .................................................................................. 286 Using the Visual Studio Text Editor........................................................................... 287 Build and Run the Bytes Project................................................................................. 288 Running the Bytes Project .......................................................................................... 289 Executable File Location ............................................................................................ 290 Managing Configurations ........................................................................................... 291 Project Configurations ................................................................................................ 292 Debugging................................................................................................................... 293 Just-in-Time Debugging Demo................................................................................... 294

Evaluation Copy

Page 10: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC x All Rights Reserved

Breakpoints ................................................................................................................. 297 Watch Variables.......................................................................................................... 298 Debug Toolbar ............................................................................................................ 299 Stepping with the Debugger........................................................................................ 300 Demo: Stepping with the Debugger........................................................................... 301 Call Stack and Call Hierarchy..................................................................................... 302 Multiple-Project Solution Demo................................................................................. 303 Adding a Reference..................................................................................................... 304 Project Dependencies.................................................................................................. 305 Startup Project............................................................................................................. 306 Hidden Files ................................................................................................................ 307 Summary ..................................................................................................................... 308

Appendix B Learning Resources ............................................................................... 309

Evaluation Copy

Page 11: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

.NET: What You Need to Know

Evaluation Copy

Page 12: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 2 All Rights Reserved

.NET: What You Need to Know

Objectives

After completing this unit you will be able to:

• Describe the essentials of creating and running a program in the .NET environment.

• Build and run a simple Visual Basic program in the .NET environment.

• Use the ILDASM tool to view intermediate language.

• Use Visual Studio 2012 as an effective environment for creating Visual Basic programs.

• Use the .NET Framework SDK documentation.

Evaluation Copy

Page 13: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 3 All Rights Reserved

Getting Started

• From a programmer’s perspective, a beautiful thing about .NET is that you scarcely need to know anything about it to start writing programs for the .NET environment.

− You write a program in a high-level language (such as Visual Basic), a compiler creates an executable .EXE file (called an assembly), and you run that .EXE file.

• Even very simple programs, if they are designed to do something interesting, such as perform output, will require that the program employ the services of library code.

− A large library, called the .NET Framework Class Library, comes with .NET, and you can use all of the services of this library in your programs.

Evaluation Copy

Page 14: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 4 All Rights Reserved

.NET: What Is Really Happening

• The assembly that is created does not contain executable code, but, rather, code in Intermediate Language, or IL (sometimes called Microsoft Intermediate Language, or MSIL).

− In the Windows environment, this IL code is packaged up in a standard portable executable (PE) file format, so you will see the familiar .EXE extension (or, if you are building a component, the .DLL extension).

− You can view an assembly using the ILDASM tool.

• When you run the .EXE, a special runtime environment (the Common Language Runtime, or CLR) is launched and the IL instructions are executed by the CLR.

− Unlike some runtimes, where the IL would be interpreted each time it is executed, the CLR comes with a just-in-time (JIT) compiler, which translates the IL to native machine code the first time it is encountered.

− On subsequent calls, the code segment runs as native code.

Evaluation Copy

Page 15: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 5 All Rights Reserved

.NET Programming in a Nutshell

1. Write your program in a high-level .NET language, such as Visual Basic.

2. Compile your program into IL.

3. Run your IL program, which will launch the CLR to execute your IL, using its JIT to translate your program to native code as it executes.

• We will look at a simple example of a Visual Basic program, and run it under .NET.

− Don’t worry about the syntax of Visual Basic, which we will start discussing in the next chapter.

Evaluation Copy

Page 16: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 6 All Rights Reserved

.NET Program Example

• See SimpleCalc in the Chap01 folder.

1. Enter the program in a text editor.

' SimpleCalc.vb ' ' This program does a simple calculation: calculate ' area of a rectangle Module SimpleCalc Sub Main () Dim base As Integer = 20 Dim height As Integer = 5 Dim area As Integer area = base * height System.Console.WriteLine("Area = {0}", area) End Sub End Module 2. Compile the program at the command line. Start the console

window via Start | All Programs | Microsoft Visual Studio 2012 | Visual Studio Tools | Developer Command Prompt for VS2012. Navigate to the Chap01\SimpleCalc folder.

>vbc SimpleCalc.vb 3. Run your IL program SimpleCalc.exe

>SimpleCalc area = 100

Evaluation Copy

Page 17: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 7 All Rights Reserved

Viewing the Assembly

• You can view the assembly using the ILDASM tool1. >ildasm SimpleCalc.exe

1 You can change the font size from the View menu.

Evaluation Copy

Page 18: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 8 All Rights Reserved

Viewing Intermediate Language

• Double-click on Main:void()

Evaluation Copy

Page 19: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 9 All Rights Reserved

Understanding .NET

• The nice thing about a high-level programming language is that you usually do not need to be concerned with the platform on which the program executes.

• You can work with the abstractions provided by the language and with functions provided by libraries.

• Your appreciation of the Visual Basic programming language and its potential for creating great applications will be richer if you have a general understanding of .NET.

• After this course, we suggest you next study:

− .NET Framework Using Visual Basic

Evaluation Copy

Page 20: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 10 All Rights Reserved

Visual Studio 2012

• While it is possible to write Visual Basic programs using any text editor, and compile them with the command-line compiler, it is very tedious to program that way.

• An IDE makes the process of writing software much easier.

− An IDE provides convenience items, such as a syntax-highlighting editor.

− An IDE reduces the tedium of keeping track of configurations, environment settings and file organizations.

• You may use Visual Studio 2012 throughout this course to create and compile your VB programs.

• Visual Studio 2012 is discussed in more detail in Appendix A.

Evaluation Copy

Page 21: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 11 All Rights Reserved

Creating a Console Application

• We will now create a simple console application.

− Our program is the same simple calculator we created earlier that was compiled at the command line.

1. From the Visual Studio main menu, choose File | New Project.... This will bring up the New Project dialog.

2. Choose “Console Application.”

3. Leave .NET Framework 4.5 as the target framework. Leave checked “Create directory for solution”. 2

4. In the Name field, type SimpleCalcVs and for Location browse to C:\OIC\VbEss\Demos. Click OK.

2 Examples in later chapters frequently do not have a directory for solution.

Evaluation Copy

Page 22: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 12 All Rights Reserved

Visual Studio Solutions

• In Visual Studio 2012, project information is organized by solutions and projects.

− A solution, specified by a .sln file, consists of one or more projects, specified by .vbproj files in the case of Visual Basic.

• Notice Solution Explorer in the top-right.

Evaluation Copy

Page 23: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 13 All Rights Reserved

Starter Code

• We see that a Visual Studio solution has been created with one project.

• The project contains two elements.

− The folder MyProject contains a number of files that we normally will not need to touch.

− Module1.vb contains skeleton code that we will edit.

− We’ve closed a few windows that we don’t need at this point.

Evaluation Copy

Page 24: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 14 All Rights Reserved

Using the Visual Studio Text Editor

• In Solution Explorer, change the name of the file Module1.vb to SimpleCalc.vb.

• Other changes will be made for you automatically, such as changing the name of the module to SimpleCalc.

• Make the following edits, using the Visual Studio text editor.

Module SimpleCalc Sub Main() Dim base As Integer = 20 Dim height As Integer = 5 Dim area As Integer area = base * height System.Console.WriteLine("Area = {0}", area) End Sub End Module

− Notice that the Visual Studio text editor highlights syntax, indents automatically, and so on.

− In Visual Basic, as opposed to Visual C#, the editor does other things for you too, such as supply matching End keywords, adjust capitalization of keywords, and so on.

Evaluation Copy

Page 25: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 15 All Rights Reserved

IntelliSense

• A powerful feature of Visual Studio is IntelliSense.

− IntelliSense will automatically pop up a list box allowing you to easily insert language elements directly into your code.

Evaluation Copy

Page 26: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 16 All Rights Reserved

Build and Run the Project

• Building a project means compiling the individual source files and linking them together with any library files to create an IL executable .EXE file.

• You can build the project by using one of the following:

− Menu Build | Build Solution or toolbar button or keyboard shortcut Ctrl+Shift+B.

− Menu Build | Build SimpleCalcVs or toolbar button (this just builds the project SimpleCalcVs)3.

• You can run the program without the debugger by using one of the following:

− Toolbar (This toolbar button is not provided by default; see Appendix A for how to add it to your Build toolbar.)

− Keyboard shortcut Ctrl + F5

• You can run the program in the debugger by using one of the following:

− Menu Debug | Start Debugging

− Toolbar

− Keyboard shortcut F5

• Try it!

3 The two are the same in this case, because the solution has only one project, but some solutions have multiple projects, and then there is a difference.

Evaluation Copy

Page 27: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 17 All Rights Reserved

Pausing the Output

• If you run the program in the debugger from Visual Studio, you will notice that the output window automatically closes on program termination.

• To keep the window open, you may prompt the user for some input.

Module SimpleCalc Sub Main() Dim base As Integer = 20 Dim height As Integer = 5 Dim area As Integer area = base * height System.Console.WriteLine("Area = {0}", area) System.Console.WriteLine( _ "Prese Enter to exit") System.Console.ReadLine() End Sub End Module

• This version of the program is saved as a Visual Studio 2012 project in Chap01\SimpleCalcVs.

• Remember that you can always make the console window stay open by running without the debugger via Control + F5.

Evaluation Copy

Page 28: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 18 All Rights Reserved

Visual Basic and GUI Programs

• Microsoft’s Visual Basic language works very effectively in a GUI environment.

− Using Windows Forms, it is easy to create Windows GUI programs in Visual Basic.

Example: See Chap01\SimpleCalcGui

• We will discuss GUI programming using Visual Basic in Chapter 6.

Evaluation Copy

Page 29: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 19 All Rights Reserved

.NET Documentation

• MSDN documentation for the .NET Framework is included with Visual Studio 2012.

− Use the menu Help | View Help. Other menu choices let you add and remove content and to set a preference for launching in Browser or Help Viewer.

Evaluation Copy

Page 30: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 1

Rev.4.5 Copyright © 2013 Object Innovations Enterprises, LLC 20 All Rights Reserved

Summary

• As in other environments, with .NET you write a program in a high-level language, compile to an executable (.EXE file), and run that .EXE file.

• The .EXE file, called an assembly, contains Intermediate Language instructions.

• You can view an assembly through the ILDASM tool.

• Visual Studio 2012 is a powerful IDE that makes it easy to develop Visual Basic programs.

• With Visual Studio, it is easy to create GUI programs using Visual Basic.

• You can access extensive .NET Framework documentation through the Visual Studio help system.

Evaluation Copy

Page 31: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 195 All Rights Reserved

Chapter 5

Delegates and Events

Evaluation Copy

Page 32: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 196 All Rights Reserved

Delegates and Events

Objectives

After completing this unit you will be able to:

• Use delegate objects to implement callbacks.

• Use the Random class to generate random test data.

• Use aggregations of delegate objects.

• Use delegate objects to implement and handle event notifications.

Evaluation Copy

Page 33: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 197 All Rights Reserved

Overview of Delegates and Events

• In the previous chapters we examined interfaces in some detail.

• One feature of interfaces is that they facilitate writing code in such a way that your program is called into by some other code.

• This style of programming has been available for a long time, under the guise of “callback” functions.

• In this chapter, we examine delegates in Visual Basic, which can be thought of as type-safe and object-oriented callback functions.

• Delegates are the foundation for a more elaborate callback protocol, known as events.

• Events are a cornerstone of COM, the predecessor of .NET, and are widely used in Windows programming.

• We will study events and look at several example programs that illustrate delegates and events.

Evaluation Copy

Page 34: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 198 All Rights Reserved

Callbacks and Delegates

• A callback function is one that your program specifies and registers in some way. This function is then called by another program.

− In C and C++, callback functions are implemented using function pointers.

• In Visual Basic, you can encapsulate a reference to a method inside a delegate object.

• A delegate can refer to either a shared method or an instance method.

• When a delegate refers to an instance method, it stores both an object instance and an entry point to the instance method.

− The instance method can then be called through this object instance.

− When a delegate object refers to a shared method, it stores just the entry point of this shared method.

Evaluation Copy

Page 35: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 199 All Rights Reserved

Usage of Delegates

• You can then pass this delegate object to other code, which can then call your method.

− The code that calls your delegate method does not have to know at compile time which method is being called; it only has to know the exact signature.

• In Visual Basic, a delegate is considered a reference type that is similar to a class type.

− A new delegate instance is created just like any other class instance, using the New operator.

− Visual Basic delegates are implemented by the .NET Framework class library as a class, derived ultimately from System.Delegate.

• Delegates are object-oriented and type-safe, and they enjoy the safety of the managed code execution environment.

Evaluation Copy

Page 36: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 200 All Rights Reserved

Declaring a Delegate

• You declare a delegate in Visual Basic using a special notation with the keyword Delegate and the signature of the encapsulated method.

Private Delegate Function Compare( _ ByVal x As Integer, ByVal y As Integer) As Boolean

− The Compare delegate in this example can contain a reference to any function with the return type Boolean and two parameters of type Integer.

• An example program illustrates sorting an array in both ascending and descending order.

− The choice is made according to what Compare delegate instance is used

− See the example program DelegateDemo.

Evaluation Copy

Page 37: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 201 All Rights Reserved

Defining a Method

• When you instantiate a delegate, you will need to specify a method, which must match the signature in the delegate declaration.

• The method may be either a shared method or an instance method.

− Recalled that all methods of a module are automatically shared.

• Here are some examples of methods that can be hooked to the Compare delegate:

Private Function LessThan(ByVal x As Integer, _ ByVal y As Integer) As Boolean If x < y Then Return True Else Return False End If End Function Private Function GreaterThan(ByVal x As Integer, _ ByVal y As Integer) As Boolean If x > y Then Return True Else Return False End If End Function

Evaluation Copy

Page 38: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 202 All Rights Reserved

Creating a Delegate Object

• You instantiate a delegate object with the New operator, just as you would with any other class.

− The following code illustrates creating a delegate object that is hooked to a shared method.

Private Sub Ascending() Dim array As Integer() = GetArray() ' Instantiate delegate for ascending sort Dim comp As New Compare(AddressOf GreaterThan) BubbleSort(array, comp) ShowArray(array) End Sub

Evaluation Copy

Page 39: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 203 All Rights Reserved

Calling a Delegate

• You call a delegate just as you would a method.

− The delegate object is not a method, but it has an encapsulated method.

− The delegate object “delegates” the call to this encapsulated method, hence the name “delegate.”

• In the following code, the delegate object comp is called is called to perform a comparison of two elements while performing a sort.

Private Sub BubbleSort(ByVal array As Integer(), _ ByVal comp As Compare) For i As Integer = array.Length - 1 To 0 Step -1 Dim j As Integer = 0 Do While j < i If comp(array(j), array(j + 1)) Then Dim temp As Integer = array(j) array(j) = array(j + 1) array(j + 1) = temp End If j += 1 Loop Next i End Sub

Evaluation Copy

Page 40: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 204 All Rights Reserved

Random Number Generation

• The .NET Framework provides a useful class Random, in the System namespace, which can be used for generating psuedo-random numbers for simulations.

• There are two constructors: Public Sub New() ' uses default seed Public Sub New(ByVal Seed As Integer) ' seed is specified

− The default seed is based on the current date and time, resulting in a different stream of random numbers each time.

− By specifying a seed, you can produce a deterministic stream.

• Overloaded Next methods produce a random integer. Dim volume As Integer = rangen.Next(1, 10) * 100

− This code produces a random volume between 100 and 1000, in multiples of 100.

• The NextDouble method produces a random double between 0 and 1.

Dim r as Double = rangen.NextDouble();

− The value r is in the range:

0 <= r < 1

Evaluation Copy

Page 41: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 205 All Rights Reserved

A Random Array

• Our program DelegateDemo generates a random array of integer test data.

Module DelegateDemo Private array As Integer() Public Sub Main() InitArray() ShowArray(GetArray()) Ascending() Descending() End Sub Private Sub InitArray() Dim rand As Random = New Random() ' Random size between 5 and 10 Dim size As Integer = rand.Next(5, 10) array = New Integer(size - 1) {} Dim i As Integer = 0 Do While i < size ' Random integers between 1 and 100 array(i) = rand.Next(1, 100) i += 1 Loop End Sub ...

Evaluation Copy

Page 42: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 206 All Rights Reserved

Combining Delegate Objects

• A powerful feature of delegates is that you can combine them, implementing an invocation list of methods.

− When such a delegate is called, all of the methods on the invocation list will be called in turn.

− The System.Delegate.Combine method can be used to combine the invocation methods of two delegate objects and the System.Delegate.Remove method removes them.

• The program DelegateAccount illustrates using delegates in our bank account scenario.

− The file Account.vb declares the delegate Notify. The Account class has an encapsulated delegate object.

− The file DelegateAccount.vb contains methods matching the signature of the delegate.

− The Main method instantiates delegate objects and adds and removes them from the encapsulated delegate object in the Account class.

− The Account class uses its encapsulated delegate object to invoke suitable notifications when the account is overdrawn.

• The Account class does not know or care which notification methods will be invoked in the case of an overdraft.

− It simply calls the delegate, which in turn calls all the methods on its invocation list.

Evaluation Copy

Page 43: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 207 All Rights Reserved

Account.vb

Public Delegate Sub Notify(ByVal balance As _ Decimal) Public Class Account Private balance As Decimal Public notifyDlg As Notify Public Sub New(ByVal bal As Decimal) balance = bal End Sub Public Sub Deposit(ByVal amount As Decimal) balance += amount End Sub Public Sub Withdraw(ByVal amount As Decimal) balance -= amount If balance < 0 Then notifyDlg(balance) End If End Sub End Class

Evaluation Copy

Page 44: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 208 All Rights Reserved

DelegateAccount.vb

Module DelegateAccount Public Sub Main() Dim acc As New Account(100) Dim custDlg As _ New Notify(AddressOf NotifyCustomer) Dim bankDlg As _ New Notify(AddressOf NotifyBank) ' Notify customer of an overdraft acc.notifyDlg = _ System.Delegate.Combine(acc.notifyDlg, custDlg) acc.Withdraw(125) ' Also notify bank of an overdraft acc.notifyDlg = _ System.Delegate.Combine(acc.notifyDlg, bankDlg) acc.Withdraw(50) ' Remove bank notification acc.notifyDlg = System.Delegate.Remove(acc.notifyDlg, bankDlg) acc.Withdraw(50) End Sub Private Sub NotifyCustomer( _ ByVal balance As Decimal) Console.WriteLine("Dear customer,") Console.WriteLine( _ " Account overdrawn, balance = {0}", balance) End Sub Private Sub NotifyBank(ByVal balance As Decimal) Console.WriteLine("Dear bank,") Console.WriteLine( _ " Account overdrawn, balance = {0}", balance) End Sub End Module

Evaluation Copy

Page 45: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 209 All Rights Reserved

Events

• Delegates are the foundation for a more elaborate callback protocol known as events.

• Conceptually, servers implement incoming interfaces, which are called by clients.

− In a diagram, such an interface may be shown with a small bubble (a notation used in COM).

• Sometimes a client may wish to receive notifications from a server when certain events occur.

• The server may then specify an outgoing interface.

− The server defines the interface and the client implements it.

− In a diagram, such an interface may be shown with an arrow (again, a notation used in COM).

ServerClient

Evaluation Copy

Page 46: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 210 All Rights Reserved

Static and Dynamic Event Handling

• Visual Basic can support static event handling via the WithEvents keyword in a manner similar to VB6.

• Visual Basic also supports dynamic event handling, where event handlers can be added or removed at runtime.

• We will look at dynamic event handling first, because it is tied closely to the underlying delegate mechanism that we have studied.

• We will then discuss static event handling.

Evaluation Copy

Page 47: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 211 All Rights Reserved

Dynamic Event Handling

• The .NET Framework provides an easy-to-use implementation of the event paradigm built on delegates.

− Visual Basic simplifies working with .NET events by providing the keyword Event and the AddHandler and RemoveHandler keywords to hook up event handlers to events and to remove them.

− The Framework also defines a base class EventArgs to be used for passing arguments to event handlers.

− A number of derived classes, such as MouseEventArgs, define data members to hold appropriate argument information for specific events.

• An event handler is a delegate with a specific signature:

Public Delegate Sub EventHandler( _ ByVal sender As Object, ByVal e As EventArgs)

− The name EventHandler is arbitrary. The first argument represents the source of the event, and the second argument contains data associated with the event.

Evaluation Copy

Page 48: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 212 All Rights Reserved

Chat Room Example

• The chat room example in EventDemo\Step2 illustrates the complete architecture on both the server and client sides.

• The server declares delegates: Public Delegate Sub JoinHandler( _ ByVal sender As Object, ByVal e As ChatEventArg) Public Delegate Sub QuitHandler( _ ByVal sender As Object, ByVal e As ChatEventArg)

• The ChatServer class declares events based on these delegates:

Public Class ChatServer Private m_members As ArrayList = New ArrayList() Public Event Join As JoinHandler Public Event Quit As QuitHandler

• Whenever a new member joins or quits, the server sends a notification to the client.

Public Sub JoinChat(ByVal name As String) m_members.Add(name) ' fire the Join event RaiseEvent Join(Me, New ChatEventArg(name)) End Sub Public Sub QuitChat(ByVal name As String) m_members.Remove(name) ' fire the Quit event RaiseEvent Quit(Me, New ChatEventArg(name)) End Sub

Evaluation Copy

Page 49: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 213 All Rights Reserved

Chat Room Example (Cont’d)

• The client program defines event handlers, which print out an appropriate message.

Public Sub OnJoinChat(ByVal sender As Object, _ ByVal e As ChatEventArg) Console.WriteLine( _ "sender = {0}, {1} has joined the chat", _ sender, e.m_name) End Sub

• The Main procedure registers the event handlers. Sub Main() Dim chat As ChatServer = New ChatServer() ' Register to receive event notifications AddHandler chat.Join, AddressOf OnJoinChat AddHandler chat.Quit, AddressOf OnQuitChat ' Call methods on the server chat.JoinChat("Michael") chat.JoinChat("Bob") chat.JoinChat("Sam") chat.ShowMembers("After 3 have joined") chat.QuitChat("Bob") chat.ShowMembers("After 1 has quit") End Sub

Evaluation Copy

Page 50: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 214 All Rights Reserved

Static Event Handling

• Static event handling in Visual Basic is simpler but less flexible.

− If a class implements events, you may declare an object reference to that class using the WithEvents keyword.

− The Visual Basic compiler will then look for matching procedures with the Handles keyword and, under the hood, instantiate delegates and add handlers.

• As an example, consider EventDemo\Step3.

− The server program is unchanged. The client program now uses static event handling.

' ChatClient.vb ' Step3 - Static Event Handling Imports System Module ChatClient Dim WithEvents chat As ChatServer Public Sub OnJoinChat( _ ByVal sender As Object, _ ByVal e As ChatEventArg) Handles chat.Join Console.WriteLine( _ "sender = {0}, {1} has joined the chat", _ sender, e.m_name) End Sub

Evaluation Copy

Page 51: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 215 All Rights Reserved

Static Event Handling (Cont’d)

Public Sub OnQuitChat( _ ByVal sender As Object, _ ByVal e As ChatEventArg) Handles chat.Quit Console.WriteLine( _ "sender = {0}, {1} has quit the chat", _ sender, e.m_name) End Sub Sub Main() chat = New ChatServer("OI Chat Room") ' Don't need these AddHandler calls ' AddHandler chat.Join, AddressOf OnJoinChat ' AddHandler chat.Quit, AddressOf OnQuitChat ' Call methods on the server chat.JoinChat("Michael") chat.JoinChat("Bob") chat.JoinChat("Sam") chat.ShowMembers("After 3 have joined") chat.QuitChat("Bob") chat.ShowMembers("After 1 has quit") End Sub End Module

• Here is the output (both versions): sender = OI Chat Room, Michael has joined the chat sender = OI Chat Room, Bob has joined the chat sender = OI Chat Room, Sam has joined the chat --- After 3 have joined--- Michael Bob Sam sender = OI Chat Room, Bob has quit the chat --- After 1 has quit--- Michael Sam

Evaluation Copy

Page 52: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 216 All Rights Reserved

Lab 5

Implementing Events

In this lab, you will study the chat room server and add code to the chat room client in order to provide event handlers and hook them to the event. You will also add code to the server in order to provide better information about the sender of the event.

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

Suggested time: 30 minutes

Evaluation Copy

Page 53: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 217 All Rights Reserved

Summary

• Delegates can be thought of as type-safe and object-oriented callback functions.

• In Visual Basic, you can encapsulate a reference to a method inside a delegate object.

• You can then pass this delegate object to other code, which can call your method.

• The code that calls your delegate method does not have to know at compile time which method is being called.

• Delegates can be combined, creating an invocation list of methods.

• The Random class, in the System namespace, provides an easy means for generating random numbers.

• Delegates are the foundation for a more elaborate callback protocol, known as events.

Evaluation Copy

Page 54: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 218 All Rights Reserved

Lab 5

Implementing Events

Introduction In this lab, you will study the chat room server and add code to the chat room client to provide event handlers and hook them to the event. You will also add code to the server to provide better information about the sender of the event. Suggested Time: 30 minutes Root Directory: OIC\VbEss Directories: Labs\Lab5\EventDemo (do your work here) Chap05\EventDemo\Step0 (backup copy of starter files) Chap05\EventDemo\Step1 (answer to first part) Chap05\EventDemo\Step2 (answer to second part) Chap05\EventDemo\Step3 (static event handling) Instructions 1. Build and run the starter project. You will see a printout showing chat room

membership after three people have joined and again after one person has quit. Study the code in both the server and client. The server is fully provided with event functionality. No events are fired, because no client has hooked into any of the events.

2. In the client, add event handlers OnJoinChat and OnQuitChat with the proper signature for event handlers. They should print out the sender and also a brief message indicating who has joined or quit the chat.

3. In the Main method, add code to register these event handlers with the appropriate server events.

4. Build and run the program. You should now see that your event handlers are called every time someone joins or quits the chat. But the information about the sender is not very descriptive – just the name of the class of the sender is displayed. (Step 1)

5. To get more descriptive information, add a field chatName to the ChatServer class that is initialized in the constructor. Add code in the client to provide a chat name when instantiating a ChatServer object.

6. Now add code to the server so that the chat name will be displayed, rather than the class name, when the client prints out the sender. How do you do this?

Evaluation Copy

Page 55: Visual Basic Essentials - Training Materials for IT ... · PDF fileVisual Basic Essentials Evaluation Copy. ... Chapter 1 .NET: What You Need to Know ... .NET Programming in a Nutshell

VbEss Chapter 5

Rev. 4.5 Copyright © 2013 Object Innovations Enterprises, LLC 219 All Rights Reserved

7. You do it by overriding the ToString() method. Build and run. (Step 2)

8. If you have time, modify the client to use static event handling (WithEvents keyword) in place of dynamic event handling. (Step 3)

Evaluation Copy