VB.NET Migration Moving from Visual Basic 6 to Visual Basic .NET PowerPoint PPT Presentation

presentation player overlay
1 / 83
About This Presentation
Transcript and Presenter's Notes

Title: VB.NET Migration Moving from Visual Basic 6 to Visual Basic .NET


1
VB.NET MigrationMoving from Visual Basic 6to
Visual Basic .NET
2
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

3
The .NET Framework is a development platform
  • .NET framework based on a standard execution
    engine (EE)
  • Common Language Runtime (CLR) provides EE for
    Windows
  • Compact Framework provides EE for lightweight
    devices
  • .NET programming based on Framework Class
    Libraries (FCL)

Your code
CF-compatible device
Windows XP Professional
Windows .NET Server 2003
4
Windows support for the .NET Framework
  • Client-side Windows platforms
  • Windows XP
  • Windows 2000
  • Windows NT
  • Windows 98
  • Server-side Windows platforms
  • Windows .NET Server 2003
  • Windows 2000 Server

5
Distributed applications with .NET
  • .NET architected to address shortcomings of DCOM
  • communications cannot be limited to a LAN
    environment
  • communications must be able to pass through
    firewalls
  • communications may have to address non-Windows
    clients
  • application must be able to scale to Internet
  • Creating distributed applications in the .NET era
  • server-side applications created using ASP.NET
  • server-side applications created using .NET
    Remoting

6
ASP.NET a platform on a platform
  • ASP.NET is a framework building server-side
    applications
  • ASP.NET effectively replaces the original ASP
    framework
  • communications based on HTTP, HTML, XML and SOAP
  • can be used to communicate with non-Windows
    platforms
  • ASP.NET supports building two styles of
    applications
  • HTML-based Web applications
  • XML-based Web services

ASP.NET
IIS
Web Application client
HTML over HTTP
Web Service client
XML/SOAP over HTTP
CLR
Windows 2000 or Windows .NET Server 2003
7
Windows .NET Server 2003 With IIS6
  • IIS6 provides several Web server advancements
  • better integration with ASP.NET
  • new process model with kernel-mode web-driver
    (HTTP.SYS)
  • better performance than previous versions of IIS
  • powerful new application-pooling support

HTTP.SYS (kernel mode)
8
What is managed code?
  • Managed code is code written to target .NET
    Framework
  • managed language requires special compiler
  • compilers exist for VB.NET, C, Managed C, IL,
    COBOL, etc.
  • Managed code compiled into assemblies
  • assembly is unit for distribution, deployment,
    reuse and revision
  • assembly contains code that is platform
    independent

VB.NET Source Code
C Source Code
COBOL Source Code
VB.NET Compiler
COBOL Compiler
C Compiler
Assembly MyApp1.exe
Assembly MyApp3.exe
Assembly MyApp2.exe
9
Assemblies
  • Each assembly contains a manifest
  • An assembly contains type information
  • Assemblies contain executable code that has been
    compiled into intermediate language (IL)

MyLibrary.dll
Assembly Manifest
assembly-specific metadata
Type Information
Module1 metadata
Interface1 metadata
Class1 metadata
Class2 metadata
Intermediate language
Class1 instructions
Class2 instructions
Module1 instructions
10
Just-in-time (JIT) Compilation
  • Execution engine performs JIT compilation on IL
  • JIT compilation transforms IL to
    platform-specific machine code
  • JIT compilation occurs on a method-by-method
    basis
  • JIT compilation allows for verification of safe,
    reliable code

hosting process
CLR execution environment MSCOREE.DLL
MyLibrary.dll x86 machine code
MyApp.exe x86 machine code
JIT compiler
assembly loader
MyApp.exe assembly 1
MyLibrary.dll assembly 2
11
Framework Class Libraries (FCL)
  • FCL represents native API for .NET Framework
  • all .NET Framework implementations support base
    class libraries
  • Windows implementation of FCL provides richest
    support

Assembly Name Assembly file Purpose
mscorlib mscorlib.dll Core system types
System System.dll CLR-specific system types
System.Data System.Data.dll ADO.NET
System.DirectoryServices System.DirectoryServices.dll Active Directory
System.Drawing System.Drawing.dll Windows graphics functionality
System.EnterpriseServices System.EnterpriseServices.dll Services formerly known as COM 1.0
System.Management System.Management.dll Windows computer management
System.Messaging System.Messaging.dll MSMQ messaging services
System.Security System.Security.dll Programmatic security
System.Web System.Web.dll ASP.NET
System.Web.Services System.Web.Services.dll Additional web service support for ASP.NET
System.Windows.Forms System.Windows.Forms.dll The Windows Forms framework
System.XML System.XML.dll Support for programming XML
12
Reasons to migrate to the .NET Framework
  • Keep pace with Microsoft (don't get left behind)
  • Better environment for developers
  • Take advantage of FCL
  • Better code distribution and deployment
  • Better security
  • Leverage ASP.NET
  • Build better distributed applications than
    possible with DCOM
  • Use Web services to integrate with other
    platforms
  • Use the Compact Framework to target light weight
    devices
  • interoperability layer allows you to move code
    incrementally

13
Challenges in migrating to .NET using VB.NET
  • Transition from COM to the CLR
  • new type system and programming model
  • new rules for deployment and versioning
  • Learning new programming concepts
  • strict type checking
  • shared members, method overloading, and
    constructors
  • interfaces, inheritance, and delegates
  • structured exception handling
  • attributes
  • reference types versus value types
  • Learning a completely new set of APIs
  • new Windows forms package
  • new data access API (who would have guessed)
  • lots of others

14
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

15
Using Visual Studio .NET
  • Visual Studio .NET provides
  • Project management via project files and solution
    files
  • A code editor with color coding and IntelliSense
  • An integrated compiler and a visual debugger
  • Various add-ins, wizards and code generators
  • Development in Visual Studio .NET is based on
    projects
  • In many cases, a project produces a single
    assembly
  • Projects contain references to other assemblies
    and projects
  • Visual Studio .NET project types
  • Class Library project
  • Console Application project
  • Windows Application project (based on Windows
    Forms)
  • Web Application Projects (based on ASP.NET)
  • Web Service Projects (based on ASP.NET)

16
"Hello World" with VB.NET
' source file MyLibrary.vb ' build target
MyLibrary.dll Public Class Human Public Name As
String Function Speak() As String Return
"Hi, my name is " Name End Function End Class
a component library DLL
' source file MyApp.vb ' build target
MyApp.exe ' references MyLibrary.dll Class
MyApp Shared Sub Main() Dim obj As New
Human() obj.Name "Bob" Dim msg As
String obj.Speak System.Console.WriteLine(ms
g) End Sub End Class
a console-based application
17
Projects and references
  • Each project maintains a list of referenced
    assemblies
  • VS.NET adds some common references automatically
  • You can add references to other assemblies
  • You can add also references to other VS.NET
    projects

18
Namespaces
  • Namespace is user-defined scope in which types
    are defined
  • Namespaces created using Namespace keyword
  • Namespaces imported using Imports keyword

Class MyApp1 Shared Sub Main() Dim obj As
New AcmeCorp.Human() obj.Name "Bob" Dim
msg As String obj.Speak System.Console.Write
Line(msg) End Sub End Class
Namespace AcmeCorp Public Class Human
Public Name As String Function Speak() As
String Return "Hi, my name is " Name
End Function End Class End Namespace
Imports AcmeCorp Imports System   Class MyApp2
Shared Sub Main() Dim obj As New Human()
obj.Name "Bob" Dim msg As String
obj.Speak Console.WriteLine(msg) End
Sub End Class
19
Projects and namespaces
  • Project properties dialog provides additional
    assistance with namespace management
  • Namespaces can be imported on a per-project basis
  • Root namespace serves as top-level namespace for
    project
  • All project types defined inside Root namespace
    (if one exists)

20
Assemblies used by a typical application
  • Assemblies are built with a list of dependent
    assemblies
  • mscorlib.dll automatically referenced
  • Microsoft.VisualBasic.dll automatically
    referenced
  • All other assemblies must be referenced
    explicitly
  • Assembly manifest contains list of dependant
    assemblies

21
The Microsoft.VisualBasic assembly
  • Visual Basic .NET has its own assembly
  • contains helper classes used behind the scenes by
    compiler
  • contains VB6-compatible methods (i.e. wrappers to
    CLR types)
  • VB-specific productivity functions
  • automatically referenced by the Visual Basic .NET
    compiler

Imports System Imports Microsoft.VisualBasic Modu
le MyApp Sub Main() Dim IntRate As Double
0.06, Years As Integer 30, LoanValue As Double
250000 ' call Microsoft.VisualBasic.Financia
l.Pmt Dim Payment As Double Payment
Pmt(IntRate / 12, Years 12, LoanValue, 0,
DueDate.BegOfPeriod) ' use constant
Microsoft.VisualBasic.ControlChars.CrLf Dim
display As String "Loan payment"
ControlChars.CrLf ' call Microsoft.VisualBasic
.Strings.FormatCurrency display
FormatCurrency(Payment) ' call
Microsoft.VisualBasic.Interaction.MsgBox
MsgBox(display) End Sub End Module
22
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

23
Creating forms-based applications
  • .NET introduces new forms package known as
    WinForms
  • Replaces Ruby forms package from previous
    versions of VB
  • WinForms development based on two GUI-based
    assemblies
  • System.Windows.Forms and System.Drawing

24
WinForms Primer
  • Using the Visual Studio .NET Forms Designer
  • Drag-and-drop controls onto a form
  • Change form and control properties via a property
    sheet
  • Write your code behind event procedures

WinForms designer very similar to building
forms-based applications with previous versions
of Visual Basic
25
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

26
VB.NET language improvements (part 1)
  • Variables can be declared and initialized in same
    line
  • As New syntax does not result in lazy
    instantiation
  • Return statement can be used in functions

Dim i As Integer 100
Dim obj As New Human ' object created here
Public Class Human Public Name As String
"John Doe" Function Speak() As String
Return "Hi, my name is " Name End
Function End Class
27
VB.NET language improvements (part 2)
  • Many inconsistencies and idiosyncrasies have been
    removed
  • Set statement not required/allowed on assignment
  • parameters always passed in parentheses
  • default parameter passing convention has changed
    to ByVal

Module MyApp Sub Main() Dim p1, p2 As
Human Set p1 New Human() MySub 10,
20.1 p2 New Human() MySub(10, 20.1)
End Sub Sub MySub(ByVal x As Integer, y As
Double) ' definition End Sub End Module
Causes compile-time errors
Correct syntax
defined with ByVal semantics
28
VB.NET language improvements (part 3)
  • Error reporting based on structure exception
    handling
  • Try statements replace On Error GoTo syntax
  • On Error GoTo syntax supported for backward
    compatibility
  • Try statement provides ability to catch
    exceptions
  • Try statement contains one Try block with guarded
    code
  • Try statement can contain one or more Catch
    blocks

Sub ProccessNumbers(ByVal x As Integer, ByVal y
As Integer) Dim temp As Integer Try temp
x y ' operation could result in overflow
Catch ex As ArithmeticException ' handle
math exceptions MsgBox("Math exception "
ex.Message) Catch ex As Exception '
handle all other exceptions
MsgBox("Unexpected system exception "
ex.Message) Finally code that always happens
End Try End Sub
Try block
Catch block 1
Catch block 2
29
VB.NET language improvements (part 4)
  • Strict type checking improve quality of your code
  • enable using Option Strict on
  • every variable and parameter must be defined with
    specific type
  • many implicit conversions are prohibited
  • you are required to write more conversions
    explicitly

Option Explicit On Option Strict On Module
MyApp Sub Main() ' my application code
End Sub End Module
30
Advancements in OOP support
  • Visual Basic .NET provides first-class OOP
    support
  • as powerful as C or Java
  • VB6 programmers must learn many new OOP concepts
  • New concepts in OOP
  • Interfaces
  • shared members
  • overloading methods
  • constructors
  • inheritance
  • overridable methods and polymorphism

31
Defining classes in Visual Basic .NET
  • Class definitions contain members
  • fields, constructors, methods, properties and
    events

Public Class Customer ' field definitions
Public ID As Integer Public Name As String
' method definition Public Function
GetInfo() As String Return "ID " ID " -
Name " Name End Function End Class
application-specific class definition
Module MyApp Sub Main() Dim customer1 As
New Customer() customer1.ID 714
customer1.Name "Ryan Brandell"
MsgBox(customer1.GetInfo()) End Sub End Module
client-side code
32
Shared members versus instance members
  • Each class member is either an instance or shared
    member
  • instance members defined at object scope
  • shared members defined at class scope

Class Class1 ' instance members Public
Field1 As Integer Public Sub Method1() '
implementation End Sub ' shared members
Public Shared Field2 As Integer Public Shared
Sub Method2() ' implementation End
Sub End Class
Module MyApp Sub Main() ' access
instance members Dim obj As New Class1()
obj.Field1 10 obj.Method1() ' access
shared member Class1.Field2 10
Class1.Method2() End Sub End Module
33
Field initialization
  • How do you initialize fields?
  • using in-line initializers
  • using constructors (more on this later this
    lecture)
  • Examples of using in-line initializers

Class Class1 ' initialize instance fields
Public Field1 As Integer 10 Public Field2 As
Class2 New Class2() ' initialize shared
fields Public Shared Field3 As String
"Rosebud" Public Shared Field4 As New
Class2() End Class
34
ReadOnly and Const fields
  • Fields can be defined as Const fields
  • Const field values must be known at compile time
  • Const fields are implicitly shared
  • Const field values are compiled into client-side
    ILchanging Const value requires recompiling
    clients
  • Fields can be defined as ReadOnly fields
  • ReadOnly field values can be calculated at run
    time
  • ReadOnly fields must be initialized during
    construction
  • ReadOnly fields cannot be modified after
    initialization

Class Class1 Const PI As Single 3.141592
ReadOnly BirthDate As Date Date.Today End Class
35
New property syntax
  • Properties require new syntax
  • each property is defined as either instance or
    shared member
  • each property must implement a Get block and/or a
    Set block
  • not possible to have property with public Get and
    private Set

Public Class Customer ' private field
Private m_Name As String ' property provides
controlled access to private field Public
Property Name() As String Set(ByVal Value As
String) ' perform validation here if
necessary m_Name Value End Set
Get ' perform calculations here if
necessary Return m_Name End Get End
Property End Class
Set block
Get block
' client-side code Dim s As String Dim obj As
New Customer() obj.Name "Bob" ' triggers Set
block s obj.Name ' triggers Get block
36
Overloading methods and properties
  • Two or more class members can be given the same
    name
  • you can overload a set of methods or a set of
    properties
  • Overloaded members must differ with their
    parameter lists
  • parameter lists must differ in size and/or in
    sequence of types
  • you cannot overload based on return type or
    parameter name

Class CustomerManager Function
GetCustomerInfo(ByVal ID As Integer) As String
' implementation End Function Function
GetCustomerInfo(ByVal Name As String) As String
' implementation End Function End Class
' client-side code Dim info1, info2 As
String Dim mgr As New CustomerManager() ' call
GetCustomerInfo(Integer) info1
mgr.GetCustomerInfo(23) ' call
GetCustomerInfo(String) info2
mgr.GetCustomerInfo("Bob")
37
Constructors
  • Constructors are special methods designed to
    initialize fields
  • CLR executes constructor whenever New is called
    on a class
  • creatable classes must have at least one
    constructor
  • constructors defined using sub procedures named
    New
  • constructors can be parameterized and overloaded
  • parameters passed by client after class name

Class Customer Private m_Name As String
Private m_Phone As String Sub New(ByVal Name As
String, ByVal Phone As String) m_Name Name
m_Phone Phone End Sub End Class
Dim c1 As Customer c1 New Customer("Wendy",
"432-4636") Dim c2 As New Customer("Bob",
"555-1212")
38
Default constructor
  • Non-parameterized constructor called "default
    constructor"
  • allows client to create object without passing
    parameters
  • VB.NET compiler automatically adds a default
    constructor to classes that have no explicit
    constructor
  • default constructor (if desired) must be
    explicitly added to classes that contain other
    constructors

Class Class1 ' no explicit constructors End
Class
Class Class3 Sub New(ByVal s As String)
' implementation End Sub Sub New()
' implementation End Sub End Class
Class Class2 Sub New(ByVal s As String)
' implementation End Sub End Class
Dim obj1 As New Class1() Dim obj2 As New
Class2() Dim obj3 As New Class3()
Calls default constructor
Illegal no default constructor
Calls default constructor
39
Implementation inheritance
  • An OOP technique to reuse code across classes
  • derived class inherits implementation from base
    class
  • inheritance relationships create inheritance
    hierarchies
  • Inheritance establishes "IS A" relationship
    between classes
  • two classes that cannot pass "IS A" test should
    not be related together through inheritance

Human
Manager "IS A" Human
Programmer "IS A" Human
Programmer
Manager
ManagerTrainee
SeniorManager
40
Example of a large inheritance hierarchy
  • Classes from the WinForms namespace have been
    designed to fit into a large inheritance hierarchy

Object
System namespace
MarshalByObjectRef
System.ComponentModel namespace
Component
System.Windows.Forms namespace
Control
ScrollableControl
TextBoxBase
ButtonBase
Button
TextBox
ContainerControl
CheckBox
RichTextBox
Form
Form1
Your custom form classes inherit implementation
details from many different classes up the
inheritance hierarchy
41
Inheriting from a base class
  • Class can explicitly inherit from a base class
  • class defines base class using Inherits keyword
  • class can only have one base class (no multiple
    inheritance)
  • Class without explicit base class inherits from
    System.Object

Public Class Human Public Name As String
Public Function Speak() As String Return "Hi,
I'm a human named " Name End Function End
Class Public Class Manager Inherits Human
' Manager-specific members go here End
Class Public Class Programmer Inherits Human
' Programmer-specific members go here End Class
use line break between class name and Inherits
keyword
simulate line break using colon
42
Base classes and constructors
  • Constructors and base types have "issues"
  • derived class contract doesn't include base class
    constructors
  • derived class must provide its own constructor(s)
  • derived class constructor must call a base class
    constructor
  • compiler can automatically generate call to
    accessible default constructor in base class
    constructor if one exists

Public Class Human Protected m_Name As String
Sub New(ByVal Name As String) ' implicit
call to System.Object.New() m_Name Name
End Sub End Class Public Class Programmer
Inherits Human ' this class definition will
not compile ' base class has no accessible
default constructor End Class
43
Calling base class constructor
  • Base class constructor called via MyBase.New
  • can only be called once
  • must be first executable line in derived class
    constructor

Public Class Human Protected m_Name As String
Sub New(ByVal Name As String) ' implicit
call to default constructor of Object m_Name
Name End Sub End Class Public Class
Programmer Inherits Human Sub New(ByVal Name
As String) MyBase.New(Name) ' call to base
class constructor ' Programmer-specific
initialization goes here End Sub End Class
44
Dynamic binding and overridable methods
  • Polymorphism is an important OOP concept
  • interchangeable objects designed to exhibit
    different behaviors
  • made possible by base class with overridable
    methods
  • overridable methods require dynamic binding
  • Dynamic binding is based on a key principle
  • target member definition determined at run time
    based on type of object regardless of reference
    variable type

Class Human Overridable Sub Speak() '
implementation End Sub End Class Class
Programmer Inherits Human Overrides Sub
Speak() ' implementation End Sub End
Class
Dim ref1 As Programmer New Programmer() Dim
ref2 As Human ref1 ' use base class
reference ref2.Speak() ' calls
Programmer.Speak ' use derived class
reference ref1.Speak() ' calls
Programmer.Speak
yyy
45
Chaining a call to an overridden method
  • Overriding method can leverage base class
    implementation
  • technique for extending base class method (not
    replacing)
  • base class implementation accessible via MyBase
    keyword
  • note that MyBase keyword always results in static
    binding

Class Human Overridable Sub Speak() '
implementation End Sub End Class Class
Programmer Inherits Human Overrides Sub
Speak() ' do stuff before
MyBase.Speak() ' chain to base class
implementation ' do stuff after End
Sub End Class
46
What is an interface?
  • Interface is an abstract type
  • it defines a contract of behavior without an
    implementation
  • it (usually) consists of method and/or property
    signatures
  • it also defines semantics for each interface
    member
  • it cannot be used to instantiate an object
  • concrete classes used provide implementation for
    interface

Public Interface ICustomerManager ' method
semantics adds customer to collection and
returns new ID Function AddCustomer(ByVal Name
As String) As Integer ' method semantics
retrieves customer name associated with ID
Function GetCustomerName(ByVal ID As Integer) As
String ' method semantics returns all
customer names as a string array Function
GetCustomerNames() As String() End Interface
47
Classes implement interface
  • Client-side code can be written against an
    interface
  • more flexible than writing code directly against
    class
  • interfaces decouple client-side code from
    specific classes

Public Interface ICustomerManager Function
AddCustomer(ByVal Name As String) As Integer
Function GetCustomerName(ByVal ID As Integer) As
String Function GetCustomerNames() As
String() End Interface
' uses hashtable to store data Public Class
HashtableCustomerManager Implements
ICustomerManager ' implementation omitted for
clarity End Class
' uses SQL Server to store data Public Class
SqlServerCustomerManager Implements
ICustomerManager ' implementation omitted for
clarity End Class
48
Polymorphism
  • Interfaces are the key to achieving polymorphism
  • client-side code can switch between
    plug-compatible classes

' method can be called with any
ICustomerManager-compatible object Sub
MyUtilityMethod(ByVal mgr As ICustomerManager)
mgr.AddCustomer("Bob") mgr.AddCustomer("Shannon"
) mgr.AddCustomer("Jose") Dim CustomerList As
String() mgr.GetCustomerNames() Dim Customer
As String For Each Customer In CustomerList
Console.WriteLine(Customer) Next End Sub Sub
Main() Dim obj1, obj2 As ICustomerManager
obj1 New HashtableCustomerManager() obj2
New SqlServerCustomerManager()
MyUtilityMethod(obj1) MyUtilityMethod(obj2) End
Sub
49
Interface syntax
  • VB.NET provides syntax for defining/implementing
    interfaces
  • interfaces are defined with the Interface
    construct
  • class declares support for interface with
    Implements keyword
  • class definition can declare support for multiple
    interfaces

use line break between class name and Implements
keyword
Class Class1 Implements Interface1 '
implementation omitted End Class Class
Class2 Implements Interface1 '
implementation omitted End Class Class
Class3 Implements Interface1, Interface2 '
implementation omitted End Class
simulate line break using colon
Interface Interface1 ' members omitted End
Interface Interface Interface2 ' members
omitted End Interface
implement multiple interfaces using
comma-delimited list
50
Implementing interface members
  • VB.NET provides syntax for defining/implementing
    interfaces
  • interfaces usually contain method and/or property
    signatures
  • all interface members are implicitly public
  • interface members must be mapped using Implements
    keyword

Interface Interface1 Sub Method1() Function
Method2(ByVal i As Integer) As String End
Interface
line continuation character can be used to
improve readability
Class Class1 Implements Interface1 Public Sub
Method1() Implements Interface1.Method1 '
method implementation End Sub Public Function
Method2(ByVal i As Integer) As String _
Implements Interface1.Method2 ' method
implementation End Function End Class
51
Garbage collection
  • Garbage collector (GC) reclaims memory for
    objects
  • GC collects objects it determines to be
    unreachable
  • GC can relocate "live" objects in memory to
    compact heap
  • GC typically triggered by memory usage thresholds
  • GC freezes program execution
  • CLR inspects well-known places for object
    referencesCLR looks at places such as the stack
    and shared fields
  • CLR follows object references to discover all
    live objects
  • objects that are not reachable are collected

52
Object lifecycle and finalization
  • Garbage collector calls well-known Finalize
    method if it exists
  • classes can optionally override Finalize
  • overridden version of Finalize should call base
    class Finalize
  • Two important things to note about Finalize
  • Finalize is not called in a timely fashion
  • adding a Finalize method to your class is
    expensive

Public Class Dog Protected Overrides Sub
Finalize() MyBase.Finalize() '
last-chance clean up code here End Sub End
Class
53
The System.GC class
  • You can access the garbage collector
    programmatically
  • done through shared methods of the System.GC
    class
  • triggering GC makes it possible to test and debug
    Finalize code
  • triggering GC unacceptable in high-performance
    applications

Public Class Dog Protected Overrides Sub
Finalize() MyBase.Finalize() '
last-chance clean up code here End Sub End Class
Dim spot As New Dog() ' exercise the dog '
release only rooted reference spot
Nothing ' trigger garbage collection
manually System.GC.Collect() System.GC.WaitForPend
ingFinalizers()
54
Dispose
  • CLR does not provide support for deterministic
    finalization
  • Finalize isn't actually called when you want it
    to be called
  • Finalize cannot clean up resources in
    time-critical fashion
  • Dispose method used to clean up time-critical
    resources
  • objects with Dispose method should implement
    IDisposable
  • Dispose method must be called by client

Public Class Dog Implements IDisposable '
other members omitted for clarity Public Sub
Dispose() Implements IDisposable.Dispose '
time-critical clean up code here End Sub End
Class
Dim spot As New Dog() ' have fun with the
dog spot.Fetch() spot.RollOver() ' dispose dog
when done spot.Dispose()
55
Using Dispose and Finalize together
  • Class can be written to support both Dispose and
    Finalize
  • By convention, both methods should forward to
    common method
  • Finalize should execute only when Dispose has not
    executed
  • Dispose should be written to suppress
    finalization notification

Public Class Dog Implements IDisposable '
Turn of finalization and call Cleanup Public
Sub Dispose() Implements IDisposable.Dispose
System.GC.SuppressFinalize(Me) Cleanup(True)
End Sub ' Call base class Finalize and call
Cleanup Protected Overrides Sub Finalize()
MyBase.Finalize() Cleanup(False) End Sub
' cleanup code goes here - this method
executes only once! Sub Cleanup(ByVal Disposing
As Boolean) If Disposing Then '
cleanup code without finalization restrictions
Else ' cleanup code with finalization
restrictions End If End Sub End Class
56
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

57
Motivation for interoperability
  • Not all code can run in managed mode
  • lots of code cannot and will not be written
  • Interoperability allows you to use unmanaged code
  • Win32 API
  • other standard Windows DLLs
  • MS-supplied COM components
  • COM components written with VB5 and VB6

58
Calling a COM DLL from VB.NET
  • CLR provides a CLR-to-COM interoperability layer
  • it allows .NET clients to access COM DLL
    component libraries
  • Motivation for using the CLR-to-COM
    interoperability layer
  • VB.NET clients can access COM APIs like ADO and
    MSXML
  • VB.NET clients can access DLLs written in VB5 and
    VB6

59
Creating a COM DLL with VB6
  • VB6 ActiveX DLL projects used to create COM DLLs
  • VB6 compiler publishes COM type info in type
    library in DLL
  • VB6 compiler automatically creates default
    interface for each class

VB6 compiler
' Class1 - a public Multiuse class in
VB6 Function Method1() As String '
implementation End Function Sub Method2(ByRef
data() As Byte) ' implementation End
Sub Sub Method3(Optional ByVal x As Double
20.1) ' implementation End Sub Sub
Method4(ByVal v As Object) '
implementation End Sub
60
Using a VB6 DLL from VB.NET
  • CLR-to-COM interaction made possible by interop
    assemblies
  • interop assembly is a managed shim DLL that wraps
    a COM DLL
  • .NET client programs against managed types in
    interop assembly
  • CLR uses interop assembly at runtime to
    create/call COM objects
  • How do you create an interop assembly?
  • using a .NET SDK Framework utility named
    TLBIMP.EXE
  • using Visual Studio .NET

MyApp.exe
Assembly Manifest
dependent assembly list
mscorlib Microsoft.VisualBasic Interop.BobsLibrary
Interop.BobsLibrary.dll
Assembly Manifest
Managed Type Information
TLBIMP.EXE
interface _Class1 class Class1 class Class1Class
61
Creating an interop assembly with VS.NET
  • Visual Studio .NET can build the interop assembly
    for you
  • use COM tab in project's Add Reference dialog
  • VS.NET cannot build an interop assembly with a
    strong name

62
Activating a COM object
  • VB.NET clients program against types in interop
    assembly
  • COM types appear as CTS types
  • COM objects are activated using New operator
  • CLR makes CoCreateInstance call on COM runtime
  • method invocation set up through vtable binding

Imports BobsLibrary Module MyApp Sub Main()
' use interface and coclass types Dim
obj1 As _Class1 obj1 New Class1()
obj1.Method1() obj1 nothing wait for GC
Marshal.ReleaseComObject(obj1) ' use
generated wrapper class Dim obj2 As New
Class1Class() obj2.Method1()
Marshal.ReleaseComObject(obj2) End Sub End
Module
63
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

64
Migrating VB6 projects to VB.NET
  • Upgrade Wizard utility
  • used to upgrade Visual Basic 6.0 projects to
    Visual Basic .NET
  • How does it work?
  • creates a new project
  • copies each file from the original project into
    the new project
  • modifies VB.NET files as necessary
  • generates report detailing what it did and what
    you still need to do
  • How do you use it?
  • Use Visual Studio .NET to open any Visual Basic
    6.0 project file

65
The Upgrade Wizard
  • What types of VB6 projects should be upgraded?
  • ActiveX DLL projects upgrade to Class Library
    projects
  • Standard EXE projects upgrade to Windows
    Application projects

66
Upgrade Report
67
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

68
ADO.NET and manager providers
  • ADO.NET is .NET infrastructure for accessing
    rectangular data
  • especially for accessing data in a DBMS
  • System.Data and nested namespaces encompass
    ADO.NET
  • implementation for ADO.NET lives in
    System.Data.dll
  • despite it's name, ADO.NET has nothing to do with
    ADO
  • ADO.NET architecture based on data providers
  • providers encapsulate DBMS-specific
    implementation details

69
.NET Framework ships with two data providers
  • The SQL Server provider
  • System.Data.SqlClient is provider for SQL Server
  • SqlClient provider runs almost exclusively in
    managed mode
  • The OLE DB provider
  • System.Data.OleDb is provider for OLE DB
    providers
  • OLE DB provider runs lots of code in unmanaged
    mode

SqlClient provider architecture
SQL Server DBMS
your data
TDS Layer managed code
OLE DB provider architecture
OLE DB-supported DBMS
OLEDB Provider unmanaged code
your data
70
Opening connections
  • With the SqlClient provider
  • With the OleDb provider

Dim ConnectString As String ConnectString
"serverlocalhostdatabaseMarketuidsapwd" Dim
conn As New System.Data.SqlClient.SqlConnection(C
onnectString) conn.Open() ' use
connection conn.Close()
Dim ConnectString As String ConnectString
"Microsoft.Jet.OLEDB.4.0" _
"Data Sourcec\MyDataFiles\Northwind4.mdb" Dim
conn As New System.Data.OleDb.OleDbConnection(Conn
ectString) conn.Open() ' use
connection conn.Close()
71
Managing connections
  • Interaction with DBMS is always vulnerable to
    exceptions
  • work should always be structured in Try
    statements
  • handle exceptions appropriately
  • make sure to close connection when done

Dim ConnectString As String ConnectString
"serverlocalhostdatabaseMarketuidsapwd" Di
m conn As New SqlConnection(ConnectString) Try
conn.Open() ' your work goes here Catch ex
As Exception ' handle exceptions as they
arise Finally If conn.State
ConnectionState.Open Then conn.Close() End
If End Try
72
Commands
  • Most DBMS interaction requires dealing directly
    with commands
  • SQL statements must be submitted with a command
    object

Shared Sub Add(Product As String, Price As
Decimal, Quantity As Decimal) Dim
ConnectString "serverlocalhostdatabaseMarket
uidsapwd" Dim conn As New
SqlConnection(ConnectString) Dim SQL As
String "INSERT INTO Products" _
" VALUES('" Product "', " _
Price ", " _
Quantity ")"
Dim cmd As New SqlCommand(sSQL, conn) Try
conn.Open() cmd.ExecuteNonQuery()
Catch ex As SqlException ' deal with
error reported from SQL Server Catch ex As
Exception ' deal with generic exception
Finally ' if connection is open,
close it End Try End Sub
73
Executing commands
  • There are three common ways to execute a command
  • ExecuteNonQuery called when statement returns no
    data
  • ExceuteScalar called when statement returns one
    row single field
  • ExecuteReader called when statement returns
    multiple rows/fields

Dim ConnectString As String "serverlocalhostda
tabaseMarketuidsapwd" Dim conn As New
SqlConnection(ConnectString) ' generate SQL to
determine how many dogs are in inventory Dim SQL
As String "SELECT Quantity FROM Products" _
" WHERE Product'Dog'" Dim cmd
As New SqlCommand(SQL, conn) conn.Open() '
return data from query with one row and one
field Dim quantity As Integer
CInt(cmd.ExecuteScalar()) conn.Close()
74
Commands and stored procedures
  • Command object is used to execute stored
    procedure
  • Command object has parameters collection
  • parameter objects must be created and added to
    collection
  • parameter objects must be create with proper type
    and direction
  • SqlClient uses only named parameters
  • OleDb uses positional parameters

Dim cmd As New SqlCommand("GetCustomerInfo",
conn) cmd.CommandType CommandType.StoredProcedur
e ' create parameters and add to them
parameters collection ' execute stored
procedure ' fetch output parameters
Create Procedure GetCustomerInfo( _at_Customer
varchar(30), _at_CreditLimit money OUTPUT,
_at_AccountBalance money OUTPUT) As SELECT
_at_CreditLimit CreditLimit, _at_AccountBalance
AccountBalance FROM Customers WHERE Customer
_at_Customer RETURN(1)
75
Executing a stored procedure
' create command object Dim cmd As New
SqlCommand("GetCustomerInfo", conn) cmd.CommandTyp
e CommandType.StoredProcedure ' create
parameter objects Dim p1, p2, p3 As
SqlParameter p1 New SqlParameter("_at_Customer",
SqlDbType.VarChar) p1.Direction
ParameterDirection.Input p1.Value "Bob" p2
New SqlParameter("_at_CreditLimit",
SqlDbType.Money) p2.Direction
ParameterDirection.Output p3 New
SqlParameter("_at_AccountBalance",
SqlDbType.Money) p3.Direction
ParameterDirection.Output ' add parameter
objects to command's Parameters
collection cmd.Parameters.Add(p1) cmd.Parameters.A
dd(p2) cmd.Parameters.Add(p3) ' execute stored
procedure conn.Open() cmd.ExecuteNonQuery() conn.C
lose() Console.WriteLine(P2.Value) ' retrieve
output parameters Dim CreditLimit As Decimal
CDec(cmd.Parameters("_at_CreditLimit").Value) Dim
AccountBalance As Decimal CDec(cmd.Parameters("_at_
AccountBalance").Value)
76
Retrieving data with a DataReader object
  • DataReader objects provide fastest technique for
    fetching rows
  • DataReader based on streaming I/O and
    forward-only cursors
  • DataReader objects implement IDataReader
    interface
  • Call to Connection.ExecuteReader returns
    DataReader object
  • DataReader object provides means to enumerate
    through rows

Dim conn As New SqlConnection(ConnectString) conn.
Open() ' create SELECT command and retrieve
DataReader object Dim SQL As String "SELECT
Product FROM Products" Dim cmd As New
SqlCommand(SQL, conn) Dim reader As IDataReader
cmd.ExecuteReader() ' enumerate through
records Do While reader.Read()
Console.WriteLine(CStr(reader("Product")))
Console.WriteLine(CStr(reader(0)))
Console.WriteLine(reader.GetString(0)) Loop '
close connection when done conn.Close()
retrieve field value by name
retrieve field value by zero-based ordinal
retrieve strongly-typed field value
77
Dealing with multiple resultsets
  • DataReader can deal with multiple result sets
  • submitting multiple SELECT statements reduces
    roundtrips
  • call NextResult to move to next result set

Dim SQL As String "SELECT Product FROM
Products" _ "SELECT
Customer FROM Customers" Dim cmd As New
SqlCommand(SQL, conn) Dim reader As IDataReader
cmd.ExecuteReader() ' get data from result
set 1 Console.WriteLine("Product list") Do
While reader.Read() Console.WriteLine(reader.Get
String(0)) Loop ' check to see if there's
another result set If reader.NextResult Then
' get data from result set 2
Console.WriteLine("Customer list") Do While
reader.Read() Console.WriteLine(reader.GetStri
ng(0)) Loop End If
78
DataSets
  • DataSet provides in-memory caching mechanism
  • DataSet used to cache rows of data on client-side
  • DataSet can store multiple relational result sets
  • DataAdapter object typically used to populate
    Dataset object
  • DataSet model based on DataTable, DataColumn and
    DataRow

your application's process
SQL Server DBMS
Product Price Quantity
Ant 0.49 5000
Bird 4.49 500
Cat 29.95 100
Dog 79.95 20
Customer
Bob
Mary
Sue
Leonard
your data
Dataset
DataTables
79
Populating a Dataset
  • DataAdapter typically used to populate a Dataset
  • Call to Fill adds one or more DataTables to
    DataSet

Dim conn As New SqlConnection(ConnectString) Dim
SQL As String "SELECT FROM Products" Dim cmd
As New SqlCommand(SQL, conn) Dim adapter As New
SqlDataAdapter(cmd) Dim dataset1 As New
DataSet() ' fetch data conn.Open() adapter.Fill
(dataset1, "ProductsTable") conn.Close()
DataAdapter
Command
Connection
your data
Product Price Quantity
Ant 0.49 5000
Bird 4.49 500
Cat 29.95 100
Dog 79.95 20
ProductsTable
80
DataViews
  • DataViews allow you to filter and sort rows from
    DataTables
  • DataView created on top of a DataTable
  • DataView can filter out rows from DataTable
  • DataView can resort rows from DataTable
  • DataView can also be used to search and/or update
    DataTables
  • DataView cannot be used to join together
    DataTables

Product Price Quantity
Cat 29.95 100
Dog 79.95 20
RowFilter"Price gt 20"
DataView1
Product Price Quantity
Ant 0.49 5000
Bird 4.49 500
Cat 29.95 100
Dog 79.95 20
Product Price Quantity
Dog 79.95 20
Cat 29.95 100
Bird 4.49 500
Ant 0.49 5000
Sort"Price DESC"
ProductsTable
DataView2
81
Call To Action
  • Learn how to use the .NET Framework
  • learn how to program using VB.NET and/or C
  • learn how the CLR works
  • learn how ASP.NET works
  • Migrate to Windows .NET Server 2003 and IIS6
  • best server-side platform for .NET Framework
  • better integration with ASP.NET

82
Agenda
  • The .NET Framework and the CLR
  • Introduction to Visual Studio .NET
  • Creating Windows Forms applications
  • Visual Basic .NET language improvements
  • Using VB.NET together with VB6
  • Porting VB6 projects to VB.NET
  • Writing data access code with ADO.NET

83
Useful URLs
  • http//portals.devx.com/SummitDays
  • valuable .NET resources including Ted's sample
    chapter
  • http//msdn.microsoft.com/nett
  • valuable .NET resources from Microsoft
  • http//www.develop.com
  • Information about instructor-led training from
    DevelopMentor
  • http//www.themastermans.com/isvtour
  • Jasons site
  • http//www.subliminalsystem.com
  • Teds site
  • http//www.aggelos.com
  • Dougs site
Write a Comment
User Comments (0)
About PowerShow.com