Transcript .NET Migration - Maheshwari Samaj
VB.NET Migration Moving from Visual Basic 6 to Visual Basic .NET
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
2
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 Your code Framework Class Libraries Common Language Runtime (CLR) Operating System Hardware Server Computer Your code Framework Class Libraries Common Language Runtime (CLR) Operating System Hardware Desktop Computer Your code Framework Class Libraries Compact Framework (CF) Operating System Hardware Handheld device CF-compatible device Windows XP Professional Windows .NET Server 2003 3
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
4
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
5
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
Web Application client HTML over HTTP ASP.NET
IIS Web Service client XML/SOAP over HTTP CLR Windows 2000 or Windows .NET Server 2003 6
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
WWW Worker Process 1 ASP.NET
App #1 ASP.NET
App #2 ASP.NET
App #3 WWW Worker Process 2 ASP.NET
App #4 ASP.NET
App #5 ASP App #1 HTTP.SYS (kernel mode) 7
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 Com;piler Assembly
MyApp1.exe
C# Compiler Assembly
MyApp2.exe
COBOL Compiler Assembly
MyApp3.exe
8
Assemblies
• • •
Each assembly contains a manifest An assembly contains type information Assemblies contain executable code that has been compiled into intermediate language (IL)
Class1 metadata
Assembly Manifest
assembly-specific metadata
Type Information
Class2 metadata Module1 metadata Interface1 metadata Class1 instructions
Intermediate language
Class2 instructions Module1 instructions
MyLibrary.dll
9
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
MyApp.exe
x86 machine code
MyLibrary.dll
x86 machine code
JIT compiler assembly loader MyApp.exe
assembly #1
MyLibrary.dll
assembly #2
10
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
mscorlib System System.Data
System.DirectoryServices
System.Drawing
System.EnterpriseServices
System.Management
System.Messaging
System.Security
System.Web
System.Web.Services
System.Windows.Forms
System.XML
Assembly file
mscorlib.dll
System.dll
System.Data.dll
System.DirectoryServices.dll
System.Drawing.dll
System.EnterpriseServices.dll
System.Management.dll
System.Messaging.dll
System.Security.dll
System.Web.dll
System.Web.Services.dll
System.Windows.Forms.dll
System.XML.dll
Purpose
Core system types CLR-specific system types ADO.NET
Active Directory Windows graphics functionality Services formerly known as COM+ 1.0
Windows computer management MSMQ messaging services Programmatic security ASP.NET
Additional web service support for ASP.NET
The Windows Forms framework Support for programming XML
11
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 12
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…
13
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
14
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)
15
"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 '*** source file: MyApp.vb
'*** build target: MyApp.exe
'*** references: MyLibrary.dll
Class MyApp Shared Sub Main() Dim Dim obj msg End Sub As New Human() obj.Name = "Bob" As String = obj.Speak
System.Console.WriteLine(msg) End Class
a component library DLL a console-based application
16
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
17
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 Dim obj msg End Sub End Class As New AcmeCorp.Human() obj.Name = "Bob" As String = obj.Speak
System.Console.WriteLine(msg) Namespace AcmeCorp Public Class Human Public Name As String Function Speak() As String Return End Function End Class End Namespace "Hi, my name is " & Name Imports AcmeCorp Imports System Class MyApp2 Shared Sub Main() Dim Dim obj msg End Sub End Class As New Human() obj.Name = "Bob" As String = obj.Speak
Console.WriteLine(msg)
18
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)
19
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
MyApp.exe
custom application
MyLibrary.dll
custom component library
Microsoft.VisualBasic.dll
Visual Basic-specific assembly
System.Data.dll
ADO.NET
System.dll
non-core system types
System.XML.dll
XML parser
mscorlib.dll
core system types
MSCOREE.DLL
20
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 Imports System Microsoft.VisualBasic
Module MyApp Sub Main() Dim IntRate As Double = 0.06, Years As Integer = 30, LoanValue As Double = 250000 ' call Microsoft.VisualBasic.Financial.Pmt
Dim Dim Payment display End Sub End Module As Double Payment = Pmt(IntRate / 12, Years * 12, LoanValue, 0, DueDate.BegOfPeriod) ' use constant Microsoft.VisualBasic.ControlChars.CrLf
As String MsgBox(display) = "Loan payment:" & ControlChars.CrLf
' call Microsoft.VisualBasic.Strings.FormatCurrency
display &= FormatCurrency(Payment) ' call Microsoft.VisualBasic.Interaction.MsgBox
21
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
22
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
23
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
24
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
25
VB.NET language improvements (part 1)
•
Variables can be declared and initialized in same line
Dim i As Integer = 100 •
As New syntax does not result in lazy instantiation
Dim obj As New Human '*** object created here •
Return statement can be used in functions
Public Class Public Name Function Human As String = "John Doe" Speak() As String Return "Hi, my name is " & Name End Function End Class
26
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 = p2 = End Sub New New Human() MySub 10, 20.1
Human() MySub(10, 20.1) Causes compile-time errors Correct syntax Sub MySub( ByVal x As Integer , y As Double ) '*** definition End Sub defined with
ByVal
semantics End Module
27
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 Try block Sub ProccessNumbers( Catch ex As ByVal x As Integer Dim temp As Integer Try temp = x * y '*** operation could result in overflow ArithmeticException , ByVal y As Integer ) Catch block #1 Catch block #2 '*** 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
28
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
29
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
30
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 End Function End Class "ID: " & ID & " - Name: " & Name
application-specific class definition client-side code
Module MyApp Sub Main() Dim customer1 As New customer1.ID = 714 Customer() customer1.Name = "Ryan Brandell" MsgBox(customer1.GetInfo()) End Sub End Module
31
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 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 Class Class1 '*** instance members Public Field1 As Integer Public Sub '*** implementation End Sub Method1() '*** shared members Public Shared Field2 As Integer Public Shared Sub '*** implementation End Sub End Class Method2()
32
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 '*** initialize shared fields Class2() Public Shared Public Shared End Class Field3 As String Field4 As New = "Rosebud" Class2()
33
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 IL
changing 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 ReadOnly BirthDate = 3.141592
As Date = Date .Today
End Class
34
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
Set block Get block
Public Class '*** private field Private Customer 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 '*** client-side code Dim s As String Dim obj As New Customer() obj.Name = "Bob" '*** triggers Set block s = obj.Name '*** triggers Get block
35
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 ' implementation ID As Integer ) As String End Function Function GetCustomerInfo( ByVal ' implementation End Function End Class Dim Name As String info1, info2 ) '*** client-side code As String As String Dim mgr As New CustomerManager() '*** call GetCustomerInfo(Integer) info1 = mgr.GetCustomerInfo(23) '*** call GetCustomerInfo(String) info2 = mgr.GetCustomerInfo("Bob")
36
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 m_Name = Name m_Phone = Phone End Sub End Class Dim c1 As Phone Customer As String ) c1 = New Customer("Wendy", "432-4636") Dim c2 As New Customer("Bob", "555-1212")
37
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 Class2 Sub New ( ByVal s As String ) '*** implementation End Sub End Class Class Class3 Sub New ( ByVal s As String ) '*** implementation End Sub Sub New End Sub () '*** implementation End Class Dim Dim Dim obj1 As New obj2 As New obj3 As New Class1() Class2() Class3() Calls default constructor Illegal : no default constructor Calls default constructor
38
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
Manager Programmer SeniorManager ManagerTrainee 39
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 Component System.ComponentModel
namespace
System.Windows.Forms
namespace
Control ScrollableControl ContainerControl Form ButtonBase Button CheckBox TextBoxBase TextBox RichTextBox Form1
Your custom form classes inherit implementation details from many different classes up the inheritance hierarchy
40
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 End Function End Class "Hi, I'm a human named " & Name Public Class Manager Inherits Human '*** Manager-specific members go here End Class Public Class End Class Programmer : Inherits Human '*** Programmer-specific members go here use line break between class name and Inherits keyword simulate line break using colon
41
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 Protected Human 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 End Class Programmer : Inherits Human '*** this class definition will not compile '*** base class has no accessible default constructor
42
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 Protected Human 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 Sub New ( ByVal Name As String ) Human MyBase End Sub .New(Name) '*** call to base class constructor '*** Programmer-specific initialization goes here End Class
43
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 Dim Dim ref1 As ref2 As Programmer = New Programmer() Class Human Overridable Sub '*** implementation End Sub End Class Speak() '*** use base class reference ref2.Speak() '*** calls Programmer.Speak
'*** use derived class reference ref1.Speak() '*** calls Programmer.Speak
Class Programmer Inherits Human Overrides Sub Speak() '*** implementation End Sub End Class
44
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 '*** implementation End Sub Speak() End Class Class Programmer : Inherits Overrides Sub Speak() '*** do stuff before Human MyBase End Sub End Class .Speak() '*** chain to base class implementation '*** do stuff after
45
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 '*** method semantics: adds customer to collection and returns new ID Function ICustomerManager AddCustomer( ByVal Name As String ) As Integer '*** method semantics: retrieves customer name associated with ID Function Function GetCustomerName( ByVal ID As Integer ) As String '*** method semantics: returns all customer names as a string array GetCustomerNames() End Interface As String ()
46
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 Function AddCustomer( ByVal Name As String ) As Integer 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
47
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 Next Customer In CustomerList Console.WriteLine(Customer) End Sub Sub Main() Dim obj1, obj2 obj1 = New As ICustomerManager HashtableCustomerManager() obj2 = End Sub New SqlServerCustomerManager() MyUtilityMethod(obj1) MyUtilityMethod(obj2)
48
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 '*** implementation omitted End Class Interface1
using colon
Interface Interface1 '*** members omitted End Interface Interface Interface2 '*** members omitted End Interface Class Class2 : End Class Implements Interface1 '*** implementation omitted
implement multiple interfaces using comma-delimited list
Class Class3 Implements '*** implementation omitted End Class Interface1, Interface2
49
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 End Interface i As Integer ) As String Class Class1 : Implements Public Sub Method1() Interface1 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
line continuation character can be used to improve readability
_
50
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 references
CLR 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
51
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 End Sub .Finalize() '*** last-chance clean up code here End Class
52
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 End Sub .Finalize() '*** last-chance clean up code here 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.WaitForPendingFinalizers()
53
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 End Sub End Class Dispose() Implements IDisposable.Dispose
'*** time-critical clean up code here Dim spot As New Dog() '*** have fun with the dog spot.Fetch() spot.RollOver() '*** dispose dog when done spot.Dispose()
54
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 Public Sub Dog : Implements IDisposable '**** Turn of finalization and call Cleanup 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 '*** cleanup code without finalization restrictions Else '*** cleanup code with finalization restrictions End If End Sub End Class Then
55
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
56
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
57
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
58
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() End Function As String '*** implementation Sub Method2( ByRef data() As Byte ) '*** implementation End Sub Sub Method3( Optional ByVal '*** implementation End Sub x As Double = 20.1) Sub Method4( ByVal v As Object ) '*** implementation End Sub
Type library
interface coclass _Class1 Class1
executable x86 instructions BobsLibrary.dll
59
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
Assembly Manifest dependent assembly list
mscorlib Microsoft.VisualBasic
Interop.BobsLibrary
Type library
interface coclass _Class1 Class1
executable x86 instructions TLBIMP.EXE
Assembly Manifest Managed Type Information
interface class _Class1 Class1 class Class1Class
MyApp.exe
BobsLibrary.dll
Interop.BobsLibrary.dll
60
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
61
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 Module BobsLibrary 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
62
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
63
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
64
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
65
Upgrade Report
66
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
67
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
68
.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 SqlClient provider architecture SQL Server DBMS
SqlCommand object SqlConnection object TDS Layer
managed code your data •
The OLE DB provider
– System.Data.OleDb is provider for OLE DB providers – OLE DB provider runs lots of code in unmanaged mode OLE DB provider architecture OLE DB-supported DBMS
OleDbCommand object OleDbConnection object OLEDB Provider
unmanaged code your data
69
Opening connections
•
With the SqlClient provider
Dim ConnectString = "server=localhost;database=Market;uid=sa;pwd=" Dim ConnectString conn As New As String System.Data.SqlClient.SqlConnection(ConnectString) conn.Open() '*** use connection conn.Close() •
With the OleDb provider
Dim ConnectString As String ConnectString = "Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=c:\MyDataFiles\Northwind4.mdb" Dim conn As New System.Data.OleDb.OleDbConnection(ConnectString) conn.Open() '*** use connection conn.Close()
70
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 = "server=localhost;database=Market;uid=sa;pwd=" Dim 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
71
Commands
•
Most DBMS interaction requires dealing directly with commands
– SQL statements must be submitted with a command object Shared Sub Dim Add(Product As String , Price As Decimal , Quantity As Decimal ConnectString = "server=localhost;database=Market;uid=sa;pwd=" ) Dim conn As New SqlConnection(ConnectString) Dim SQL cmd As String As New = "INSERT INTO Products" & _ " VALUES('" & Product & "', " & _ Price & ", " & _ Quantity & ")" SqlCommand(sSQL, conn) Dim Try conn.Open() cmd.ExecuteNonQuery() Catch ex As SqlException '*** deal with error reported from SQL Server Catch ex Finally As Exception '*** deal with generic exception '*** if connection is open, close it End Try End Sub
72
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 = "server=localhost;database=Market;uid=sa;pwd=" Dim Dim conn SQL As New SqlConnection(ConnectString) '*** generate SQL to determine how many dogs are in inventory 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()
73
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.StoredProcedure
'*** create parameters and add to them parameters collection '*** execute stored procedure '*** fetch output parameters Create Procedure GetCustomerInfo( @Customer varchar(30), @CreditLimit money OUTPUT, @AccountBalance money OUTPUT) As SELECT @CreditLimit = CreditLimit, @AccountBalance = AccountBalance FROM Customers WHERE Customer = @Customer RETURN(1)
74
Executing a stored procedure
'*** create command object Dim Dim cmd As New cmd.CommandType = CommandType.StoredProcedure
'*** create parameter objects p1, p2, p3 SqlCommand("GetCustomerInfo", conn) As SqlParameter p1 = New SqlParameter("@Customer", SqlDbType.VarChar) p1.Direction = ParameterDirection.Input
p1.Value = "Bob" p2 = New SqlParameter("@CreditLimit", SqlDbType.Money) p2.Direction = ParameterDirection.Output
p3 = New SqlParameter("@AccountBalance", SqlDbType.Money) p3.Direction = ParameterDirection.Output
'*** add parameter objects to command's Parameters collection cmd.Parameters.Add(p1) cmd.Parameters.Add(p2) cmd.Parameters.Add(p3) '*** execute stored procedure conn.Open() cmd.ExecuteNonQuery() conn.Close() Console.WriteLine(P2.Value) '*** retrieve output parameters Dim CreditLimit As Decimal = CDec (cmd.Parameters("@CreditLimit").Value) Dim AccountBalance As Decimal = CDec (cmd.Parameters("@AccountBalance").Value)
75
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 Do While As IDataReader = cmd.ExecuteReader() '*** enumerate through records 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
76
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 Dim Dim SQL As String = "SELECT Product FROM Products;" & _ cmd As New reader As "SELECT Customer FROM Customers" SqlCommand(SQL, conn) IDataReader = cmd.ExecuteReader() '*** get data from result set #1 Console.WriteLine("Product list:") Do While Loop reader.Read() Console.WriteLine(reader.GetString(0)) '*** 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 Console.WriteLine(reader.GetString(0)) Loop End If reader.Read()
77
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
Product
Ant Bird Cat Dog
Price
$ 0.49 $ 4.49 $29.95 $79.95
Quantity
5000 500 100 20
Customer
Bob Mary Sue Leonard SQL Server DBMS your data Dataset DataTables
78
Populating a Dataset
•
DataAdapter typically used to populate a Dataset
– Call to Fill adds one or more DataTables to DataSet Dim Dim conn As New SqlConnection(ConnectString) SQL As String = "SELECT * FROM Products" Dim Dim Dim cmd As New SqlCommand(SQL, conn) adapter As New SqlDataAdapter(cmd) dataset1 As New '*** fetch data conn.Open() DataSet() adapter.Fill(dataset1, "ProductsTable") conn.Close() DataAdapter Command Connection
Product
Ant Bird Cat Dog
Price
$ 0.49 $ 4.49 $29.95 $79.95
ProductsTable Quantity
5000 500 100 20 your data
79
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
Cat Dog
Price
$29.95 $79.95
DataView1 Quantity
100 20
RowFilter="Price > 20" Product
Ant Bird Cat Dog
Price
$ 0.49 $ 4.49 $29.95 $79.95
ProductsTable Quantity
5000 500 100 20
Product
Dog Cat Bird Ant
Price
$79.95 $29.95
$ 4.49 $ 0.49
DataView2 Quantity
20 100 500 5000
Sort="Price DESC" 80
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
81
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
82
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
– Jason’s site
http://www.subliminalsystem.com
– Ted’s site
http://www.aggelos.com
– Doug’s site
83