Professional Documents
Culture Documents
1
Agenda
2
Intro to the CLR and VB.NET
3
The .NET framework as a development platform
4
Code which targets the CLR can be run on several platforms
MyApp.exe
MyLibrary.dll
?
available 2001-2002
available 2002-2004
5
Common Language Runtime (CLR)
• In the CLR, code is always loaded and run under strict control of
the system
– Code written to target the CLR is known as managed code
– Managed code must be written in a language designed for
the CLR
– Managed code is distributed and reused in terms of
assemblies
– Managed code is compiled into intermediate language (IL)
– Code in IL form undergoes JIT compilation at load time
6
Code in the form of IL must undergo JIT compilation
CLR
MSCOREE.DLL
Hosting Process
32-bit Windows
7
CLR Architecture
My Application
MyApp.exe
My Component
MyLibrary.dll
Hosting Process
8
A sampling of the Base Class Libraries (BCL)
9
A Universal Type System
10
Component Metadata and Reflection
11
VB.NET code with custom attributes applied
Imports System
Imports System.Reflection
Imports System.EnterpriseServices
<Assembly: AssemblyCulture("en-US")>
<Assembly: AssemblyKeyFile("MyKey.snk")>
<Assembly: AssemblyVersion("2.0.12.0")>
<Transaction(TransactionOption.Required)> _
Class Class2 : Inherits ServicedComponent
Sub <AutoComplete> Method1()
'*** implementation
End Sub
End Class
12
Compiling and testing code
13
A VB.NET application, a component library and a MAKEFILE
'*** MyApp.vb
'*** MyLibrary.vb
Imports System
Imports AcmeCorp Namespace AcmeCorp
Public Class Class1
Module MyApp Function Foo() As String
Sub Main() Return "Hi from a VB.NET DLL"
Dim obj As New Class1 End Function
Console.WriteLine(obj.Foo()) End Class
End Sub End Namespace
End Module
MyLibrary.dll : MyLibrary.vb
vbc /t:library MyLibrary.vb
14
Migrating from VB6 to VB.NET
15
VB.NET includes many new conveniences
End Function
16
VB.NET removes inconsistencies that were allowed in VB6
Sub Foo()
' Set no longer required/allowed on assignment statements
Dim obj As Class1
obj = New Class1 ' compiles
Set obj = New Class1 ' doesn't compile
' Argument lists in all calls must be enclosed in parentheses
Bar(3) ' compiles
Bar 4 ' doesn't compile
End Sub
17
ASP.NET: a platform on a platform
18
Hello, World using VB.NET in an ASP.NET page
<html>
<body>
</body>
</html>
19
A component library that's accessible to ASP.NET pages
'*** WebUtilities.vb
'*** WebUtilities.dll placed in \bin directory
Imports System
Imports System.Collections
Namespace AcmeCorp.WebUtilities
End Namespace
20
An ASP.NET page that uses component libraries
<html>
<body>
<h3>Customer list</h3>
<%
'*** ASP.NET automatically references DLLs in \bin directory
Dim MyDataObject As New MyDataClass
Dim Customer As String
For Each Customer in MyDataObject.GetCustomerList()
Response.Write("<li>" & s & "</li>")
Next
%>
</body>
</html>
21
ASP.NET code can be partitioned using code-behind features
Namespace AcmeCorp
Public Class ContentGenerator
Function GetContent() As String
Return "This text was generated by MyUtilityCode.vb"
End Function
End Class
End Namespace
22
An example of a Web form and server-side controls
<html>
<body>
<form runat="server">
<p><ASP:Textbox id="txtValue1" runat="server" /></p>
<p><ASP:Textbox id="txtValue2" runat="server" /></p>
<p><ASP:Button text="Add Numbers"
runat="server" OnClick="cmdAdd_OnClick" /> </p>
<p><ASP:Textbox id="txtValue3" runat="server" /></p>
</form>
</body>
</html>
<script runat="server">
Sub cmdAdd_OnClick(sender As Object , e As System.EventArgs)
Dim x, y As Integer
x = CInt(txtValue1.Text)
y = CInt(txtValue2.Text)
txtValue3.Text = CStr(x + y)
End Sub
</script>
23
Adjusting to a new type system
24
Managed types
25
Core CLR types in the System namespace
Object
Byte Single
Int64 DateTime
26
Using some of the built-in managed types
27
Namespaces and nested classes help to avoid naming conflicts
Namespace DevelopMentor
End Namespace
28
Compile-time type checking
29
Strongly-typed binding versus late binding
Module MyApp
Sub Main
End Sub
End Module
31
CLS-compliant primitive types
N/A TimeSpan 00:00:00 64-bit long integer in IEEE time span format
N/A Guid (all zeros) 128-bit integer vlaue (often used as unique ID)
32
Strings
33
Creating instances of the System.String type
34
Comparing strings
35
Using functions from the System.String class
36
Using ToString
37
Using the class System.Text.StringBuilder
Imports System
Imports System.Text
Imports Microsoft.VisualBasic
Module MyApp
Const LB As String = ControlChars.CrLf
Sub Main()
‘*** employ StringBuilder to parse together large string
Dim sb As New StringBuilder(512)
sb.Append("How have you been doing?")
sb.Append(LB)
sb.Append("I haven't seen you in a while.")
sb.Insert(0, "Hi John," & LB)
‘*** extract string from StringBuilder object
Dim s As String = sb.ToString()
Console.WriteLine(s)
End Sub
End Module
38
System.Object
39
Instance of all types are assignable to variables of type Object
40
Parameters of type Object are flexible yet not type-safe
Sub Main()
Dim x As Class1
ProcessCheeseburger(x) '*** x Is Nothing
End Sub
42
Implicit narrowing conversions are prohibited
43
Explicit casts are required when converting from System.Object
44
Logical comparisons versus bitwise operations
45
Performing bitwise operations
Dim x As Integer = 3
Dim y As Integer = 6
47
Designing classes
48
Classes provide the basic building blocks for writing software
49
Possible levels of member accessibility
50
Shared members versus instance members
51
Memory is allocated differently for instance and shared fields
Module MyApp
Sub Main() obj2
Class1 instance
Dim obj1 As New Class1() Field1 12
obj1.Field1 = 9
Class1.Field2 = 15 Class1
shared fields
52
Accessing shared methods from the Math and Console classes
Imports System
Module MyApp
Sub Main()
Dim result1, result2, result3 As Double
result1 = Math.Sqrt(225)
result2 = Math.Pow(15, 2)
result3 = Math.Log(225)
Console.WriteLine("r1={0}, r2={1}, r3={2}", _
result1, result2, result3 )
End Sub
End Module
53
A class can contain instance members and shared members
Class Class1
End Class
54
Fields
55
An object graph is a set of object which reference one another
56
Methods
57
Methods can take several different forms of parameters
Class Class1
End Class
58
Properties
59
A VB.NET property definition
End Property
End Class
61
Properties can be defined with parameters
62
Overloading methods and properties
63
Method overloading
Class CustomerManager
End Class
64
Method overloading can simulate optional parameters
Class Class1
End Class
65
Constructors
66
Designing class with instance constructors
67
Overloading constructors
68
Shared constructors
69
Interfaces and inheritance
70
What is an interface?
71
An interface defines a contract of behavior without implementation
72
'*** client-side code using ICustomerManager interface
mgr.AddCustomer("Bob")
mgr.AddCustomer("Shannon")
mgr.AddCustomer("Jose")
End Sub
Sub Main
Dim obj1, obj2 As ICustomerManager
obj1 = New HashtableCustomerManager
obj2 = New SqlServerCustomerManager
MyUtilityMethod(obj1)
MyUtilityMethod(obj2)
End Sub
73
Interface syntax
74
Using the Implements keyword
Interface Interface1
'*** contains no members
End Interface
Class Class1
Implements Interface1
'*** implementation omitted
End Class
75
The Programmer class implements the IPerson interface
Interface IPerson
Property Name() As String
Sub Speak()
End Interface
End Class
76
Implements clauses map interface members to implementations
Interface Interface1
Sub Foo()
End Interface
Interface Interface2
Sub Bar()
End Interface
77
Interface members can be renamed or hidden within public member list for a class
Interface Interface1
Sub Foo()
Module MyApp
Sub Bar()
Sub Main()
End Interface
Dim refA As New Class1
Dim refB As Interface1 = refA
Class Class1 : Implements Interface1
'*** legal
'*** method renamed
refA.Bob
Sub Bob() Implements Interface1.Foo
refB.Foo
'*** impl
refB.Bar
End Sub
'*** illegal
'*** method hidden
refA.Foo
Private Sub BarImpl() _
refA.Bar
Implements Interface2.Bar
End Sub
'*** impl
End Module
End Sub
End Class
78
Interfaces and inheritance
79
Two variations on implementing a derived interface
Interface IAnimal
Sub Breathe()
End Interface
Module MyApp
Sub Main()
Dim obj1 As IHuman = New Manager
ProcessAnimal(obj1)
ProcessHuman(obj1)
Dim obj2 As IHuman = New Programmer
ProcessAnimal(obj2)
ProcessHuman(obj2)
End Sub
End Module
81
Interface conversion and discovery
82
Option Strict forces explicit casting between non-compatible types
83
Converting between interfaces and testing for interface support
End Sub
84
Base classes and inheritance
85
Specifying a base class
87
Base/derived relationship
88
Private, Protected and Public members
'*** client
Module MyApp
Sub Main()
Dim obj As New Class2
obj.x = 10 '*** illegal
obj.y = 20 '*** illegal
obj.z = 30 '*** legal
End Sub
End Module
89
Interface IPerson
Property Name() As String
Sub Speak()
End Interface
Module MyApp
Sub Main()
'*** Programmer instance is compatible with IPerson and Person type
Dim obj1 As New Programmer
obj1.Name = "Bob"
Foo(obj1)
Bar(obj1)
'*** Manager instance is compatible with IPerson and Person type
Dim obj2 As New Manager
obj2.Name = "Lucy"
Foo(obj2)
Bar(obj2)
End Sub
End Module
91
Base types and constructors
92
Base classes and constructors
End Class
End Class
93
Static binding and member shadowing
94
Field and method shadowing
Module MyApp
Sub Main()
'*** access object through Class2 ref
Dim refA As Class2 = New Class2
Dim i As Integer = refA.x '*** accesses Class2.x
refA.Foo() '*** executes Class2.Foo
'*** access same object through Class1 ref
Dim refB As Class1 = refA
Dim j As Integer = refB.x '*** accesses Class1.x
refB.Foo() '*** executes Class1.Foo
End Sub
End Module 95
Dynamic binding and virtual methods
96
Virtual function tables
97
Virtual method dispatching in action
Module MyApp
Sub Main()
'*** access object through Class2 ref
Dim refA As Class2 = New Class2
refA.Foo() '*** executes most derived impl (Class2.Foo)
Dim s1 As String = refA.ToString() '*** calls Class1.ToString
'*** access same object through Class1 ref
refB.Foo() '*** executes most derived impl (Class2.Foo)
Dim s2 As String = refB.ToString() '*** calls Class1.ToString
End Sub
End Module 98
Chaining a call to the base class
99
Abstract classes
100
Base classes and design
101
Refactoring common functionality
Public Class Manager : Implements IPerson Public Class Programmer : Implements IPerson
Private m_Name As String Private m_Name As String
Property Name() As String _ Property Name() As String _
Implements IPerson.Name Implements IPerson.Name
'*** implementation '*** implementation
End Property End Property
Sub Speak() Implements IPerson.Speak Sub Speak() Implements IPerson.Speak
'*** implementation '*** implementation
End Sub End Sub
End Class End Class
Before Refactoring
After Refactoring
Public Class Person : Implements IPerson
Private m_Name As String
Property Name() As String Implements IPerson.Name
'*** implementation
End Property
Overridable Sub Speak() Implements IPerson.Speak
'*** implementation
End Sub
End Class
Public Class Manager : Inherits Person Public Class Programmer : Inherits Person
Overrides Sub Speak() Overrides Sub Speak()
'*** custom implementation '*** custom implementation
End Sub End Sub
End Class End Class
102
Structured exception handling
103
Error handling
104
Exceptions defined
105
Exceptions and the CLR type system
Object
Exception
ApplicationException
SystemException
Your Exception
InvalidCast NullReference
TypeLoadException
Exception Exception
ArithmeticException ArgumentException
106
System.Exception
Namespace System
Public Class Exception
'*** constructors
Overloads Public Sub New()
Overloads Public Sub New(message As String)
String (message As String, inner As Exception)
' members
Overridable ReadOnly Property InnerException As Exception
ReadOnly Property Message As String
ReadOnly Property TargetSite As MethodBase
MethodBase StackTrace As String
Overridable Property Source As String
Overridable ReadOnly Property HelpLink As String
Overridable Function SetHelpLink(url As String) As Exception
Overridable Function GetBaseException() As Exception
Protected HResult As Integer
End Class
End Namespace
107
Raising exceptions
108
Catching exceptions
109
Try-Catch statement
110
Try-Catch statement with declarations
111
Termination handlers
112
Try-Finally statement
113
Try-Catch-Finally statement revisited
114
User-defined exception
Sub Withdraw()
‘*** throw custom exception if business rule is violated
Throw New AccountException(“You don’t have enough money)
End Sub
End Class
End Class
115
Objects and values
116
Classes, reference variables and objects
117
Figure 6.2: Objects and object references
Module MyApp
Sub Main
Dim don As Person ' don is a reference
don.HealThyself() ' runtime exception - null reference
don = New Person() ' don now refers to an object
don.HealThyself() ' legal - valid reference
don = Nothing ' don no longer references the object
don.HealThyself() ' runtime exception - null reference
End Sub
End Module
118
Reference types vs. value types
119
The CLR type system
Object
Primitive types
Enum Structure1
Boolean Char
Byte Single
Int16 Double
Enum1
Int32 Decimal user-defined
value types
Int64 DateTime
120
User-defined value types
121
Value types and memory
122
Using value and reference types
Sub Main
Dim var1 As Size ' var1 is an instance of Size
var1.Height = 100 ' legal
Dim var2 As CSize ' var2 is a reference
var2.Height = 100 ' illegal, var2 = Nothing
var2 = New CSize() ' var2 refers to an instance of CSize
var2.Height = 100 ' legal, var2 <> Nothing
End Sub
123
Cloning
124
Implementing System.ICloneable
Namespace System
Public Interface ICloneable
Function Clone() As Object
End Interface
End Namespace
Imports System
End Class
125
Implementing Clone with a deep copy
126
Object lifecycle and finalization
127
References and finalization
Finalize
128
Programmer hygiene
129
Value types and boxing
130
Boxing in action
Sub Main()
Dim var1 As Structure1
Foo(var1) – boxing occurs
End Sub
131
Delegates and events
132
Delegates defined
133
Delegate signatures
134
Figure 9.3: Using a delegate type
Module Module1
Sub FireDelegate(del As Delegate1)
del("Here we go")
End Sub
End Module
135
Delegate constructors
136
Creating a delegate
Class Class1
Sub JoeBobsHandler(s As String)
Console.WriteLine("Joe Bob's handler: " & s)
End Sub
End Class
Module MyApp
Sub Main
Dim handler As New Class1
Dim del1, del2 As Delegate1
' longhand syntax for creating and using a delegate
del1 = New Delegate1(AddressOf handler.JoeBobsHandler)
del1.Invoke("Test message 1")
' shorthand syntax for creating and using a delegate
del2 = AddressOf handler.JoeBobsHandler
del2("Test message 2")
End Sub
End Module
137
Binding a delegate to a shared method
Class Class2
Shared Sub JimBobsHandler(s As String)
Console.WriteLine("Jim Bob's handler: " & s)
End Sub
End Class
Module MyApp
Sub Main
Dim del As Delegate1
del = AddressOf Class2.JimBobsHandler
del("Test message")
End Sub
End Module
138
System.Delegate
139
Delegates revealed
140
System.MulticastDelegate
141
Using multicast delegates
Class Class1
Shared Sub JoeBobsHandler(s As String)
Console.WriteLine("Joe Bob's handler: " & s)
End Sub
End Class
Class Class2
Shared Sub JimBobsHandler(s As String)
Console.WriteLine("Jim Bob's handler: " & s)
End Sub
End Class
Module MyApp
Sub Main
Dim d1, d2, d3 As Delegate1
d1 = AddressOf Class1.JoeBobsHandler
d2 = AddressOf Class2.JimBobsHandler
' create d3 which is a mutlicast of d1 and d2
d3 = CType(System.Delegate.Combine(d1, d2), Delegate1)
d3("Here we go!")
Console.ReadLine()
End Sub
End Module
142
Asynchronous invocation
143
Synthesized synchronous/asynchronous delegate methods
'*** pseudo-VB.NET/IL
public class FooDelegate : Inherits MulticastDelegate
'*** synchronous invocation
Function Invoke() As String
'*** issue asynchronous invocation
Function BeginInvoke(cb As AsyncCallback, _
asyncState As Object) As IAsyncResult
'*** harvest asynchronous invocation results
Function EndInvoke(result As IAsyncResult) As String
End Class
144
Asynchronous invocation with polling
Module MyApp
Sub Main()
Dim d1 As New FooDelegate(AddressOf FooImpl)
Dim ar As IAsyncResult = d1.BeginInvoke(Nothing, Nothing)
'*** poll until call is complete
Do Until ar.IsCompleted
System.Threading.Thread.Sleep(0)
Loop
'*** harvest ref/out parameters
Dim s As String = d1.EndInvoke(ar)
End Sub
End Module
145
Asynchronous invocation with callback
Module MyApp
Sub Main()
Dim d1 As New FooDelegate(AddressOf FooImpl)
Dim cb As New AsyncCallback(AddressOf CallbackMethod1)
'*** issue asynchronous call and register callback method
Dim ar As IAsyncResult = d1.BeginInvoke(cb, d1)
End Sub
End Module
146
Asynchronous invocation
IClonable target
ISerializable method
FooImpl
Delegate
User-defined Target
e Delegate
I n vok
gin Type
Be
IAsyncResult
Call
Object Invo
ke
IClonable target
ISerializable method
Delegate Completed
System. Completion
Async Target
Callback
147
Events
148
Declaring an event
149
Firing an event
150
Public Class EventClass1
Private MyData As String
Event OnDataChanged(NewValue As String)
Public Sub UpdateData(s As String)
RaiseEvent OnDataChanged(s)
End Sub
End Class
Class ListenerClass1
Private WithEvents Source As EventClass1
Public Sub New(ByVal s As EventClass1)
Source = s
End Sub
Private Sub BobsHandler(NewValue As String) _
Handles Source.OnDataChanged
System.Console.WriteLine("Handler data update: " & NewValue)
End Sub
End Class
Module MyApp
Public Sub Main()
Dim ec As New EventClass1
Dim listener1 As New ListenerClass1(ec)
ec.UpdateData("some new value")
Console.ReadLine()
End Sub
End Module 151
Agenda
152