Visual Basic.NET Taking the Most Successful Language One Step Further.
-
Upload
laura-garrison -
Category
Documents
-
view
218 -
download
0
Transcript of Visual Basic.NET Taking the Most Successful Language One Step Further.
Objectives
Introduction to Microsoft Visual Basic.NET New concepts Changes
Integration into .NET
Tools
Contents
Section 1: Overview
Section 2: Language Features
Section 3: Integration into .NET
Section 4: Putting It All Together
Summary
Section 1: Overview
Make the language even easier to use ...at least easier to learn
Get rid of some design flaws
Add full set of object-oriented programming features
Make it a first-class citizen of the .NET world
...but don't reinvent the language
First-Class Object Orientation
Concept of classes and interfaces Inheritance Overloading Shared members Constructors and initializers
Sub New()
anObject = New Class(“Data”, data)
Object-oriented event system
Inheritance Concepts
Concept of Reuse Composition (Has-A)
MyForm Has-A Control
Inheritance (Is-A) MyForm Is-A EntryForm
Building Type Hierarchies
Versioning
Polymorphism
MyForm Control
Form
EntryForm
MyForm
MyNewForm
Section 2: Language Features
Type System
Classes and Inheritance
Exception Handling
Event Concept
Changes
Type System
Uses the .NET common type system No need for marshalling between languages
Every type is either a value or a reference type Value types:
Primitives, enumerations, structures
Reference Types: Classes, modules, interfaces, arrays, delegates, and strings
Object can contain both Everything implicitly inherits from System.Object
Primitive Types Integral Types
Byte (8 bits), Short (16 bits) Integer (32 bits), Long (64 bits)
Floating-Point Types Single (4 bytes), Double (8 bytes)
Exact Numeric Type Decimal (28 digits) (replaces Currency)
Boolean, Date, Char
String (Reference Type!)
Signed bytes and unsigned integers not supported
Enumerations
Symbolic name for a set of values
Strongly typed
Based on integral type Byte, Short, Integer, or Long Integer is default
Example: Enum Color As Byteredyellowgreen
End Enum
Arrays
Built on .NET System.Array class
Defined with type and shape
Declaration only syntax
Lower bound index is always zero
Fixed size no longer supported
Rank cannot be changed
Dim anArray() As IntegerReDim anArray(10)
Dim OneDimension(10) As IntegerDim TwoDimensions(20,intVal) As Integer
Interfaces
Declare semantic contracts between parties Enable component orientation
Define structure and semantics for specific purpose
Abstract definitions of methods and properties
Support (multiple) inheritance
Example: Interface IPersonAge
Property YearOfBirth() As Integer
Function GetAgeToday() As Integer
End Interface
Classes Concept for objects: data and code
Classes contain members: Data members: variables, constants Properties: values accessed through get/set
methods Methods: functionality for object or class
Subs and Functions
Specials: events, delegates, constructor
Concept of Overloading Method Overloads another
With same name, but different parameters
Accessibility
Each member can have its own accessibility Private
Restricted to context of declaration
Protected (class members only) Additional access by derived classes
Friend Access from same assembly
Protected Friend Union of Protected and Friend access
Public No restrictions
Properties Not a storage location—can be computed
Usage like data members
Can be ReadOnly or WriteOnly
Public Class Sample Private m_val as Integer Public Property val() as Integer Get return m_val End Get Set m_val = value End Set End PropertyEnd Class
intVal = Sample.val
Sample Class DefinitionPublic Class CustomerImplements ICustomer
Private CustomerNo As String
Public Property Customer() As String Get Return CustomerNo End Get Set CustomerNo = Customer End SetEnd Property
Public Overloads Sub New()End Sub
Public Overloads Sub New(ByVal par as Integer) MyBase.New(par)End Sub
Public Sub DoAny(ByVal c as Char) Implements ICustomer.DoAnyEnd Sub
End Class
Inheritance 1/2
Single base class, but multiple base interfaces
Abstract base classes
Non-inheritable classes
Public Class DerivedClassInherits BaseClassImplements IBase1, IBase2...
End Class
Public MustInherit Class AbstractBase ...End Class
Public NotInheritable Class FinalClass...End Class
Inheritance 2/2
Overrides Method overrides another with same signature
NotOverridable (default) Cannot be overridden
MustOverride Must be overridden – empty method body
Qualified access MyClass, MyBase
Structures User-defined types—replace Type
Lightweight “Classes“ Consists of the same members Is value types, Classes are reference types Can implement Interfaces Can not be inherited
Public Structure CustomerImplements ICustomer
Public CustomerNo, Name As String
Public Sub New()End Sub
Public Sub Do(ByVal c as Char) Implements ICustomer.DoEnd Sub
End Structure
Exception Handling
Exceptions are not necessarily errors
Two styles: structured (SEH) and unstructured (UEH)
Only one style allowed in a method
UEH supported for backward compatibility On Error, Resume, Error Microsoft.VisualBasic.Information.Err
Structured Exception Handling Exceptions are system concepts
Propagated between components
Syntactical form of handling:
Can define custom exceptions Derived from System.Exception
Exceptions can be user-defined and thrown explicitly Throw
Try <something risky>Catch e As Exception <recover from the exception>Finally <execute this regardless>End Try
Delegates Object-oriented function pointers
Can point to a specific method of a specific instance
Delegate Function CmpFunc(x As Integer, y As Integer) As Boolean
Public Function Cmp(x As Integer, y As Integer) As Boolean... (This function implemented in some class)End Function
Sub Sort(Sort As CmpFunc, ByRef IntArray() As Integer) ... If Sort.Invoke(IntArray(i), Value) Then ... Exchange values End If ...End Sub
Call Sort( new CmpFunc( AddressOf aObj.Cmp), AnArray)
Events
Traditional WithEvents style still supported
New event system based on .NET Framework Implemented on top of delegates
Multicast events
Dynamic hookup of method as handler
AddHandler, RemoveHandler
Many events can be routed to same method
Private WithEvents mW As Widget
Public Sub mW_MouseHover(...) Handles mW.MouseHover
Simpler, More Consistent
Boolean operators And, Or, Xor, and Not are still bitwise AndAlso and OrElse added for short-circuiting
More obvious declarations Visual Basic 6: Dim i,j as Integer
i is Variant, j is Integer Visual Basic.NET: Dim i,j as Integer
i and j are Integer
Variables declared in a block have block scope
No implicit object creation—must use New
More Robust
Strict type checking
Implicit and explicit type conversions
Option Strict
Option Explicit
Optional parameters must have default values
Sub Calculate(Optional ByVal param As Boolean = False)
Dim Base as CBaseDim Derived as CDerived = new CDerived()
Base = Derived
Better Performance
Supports free threading More responsiveness
Short-circuit evaluation X = A AndAlso B AndAlso (C OrElse D)
Reference assignment for arrays
Some Other Changes
Parentheses around nonempty parameter lists Always required for function and procedure calls
Default parameter passing method is now ByVal
Properties as reference parameters Changes are now reflected back
Gosub/Return no longer supported
Default data types no longer supported
Arithmetic operator shortcuts: x += 7
Late binding
Deterministic Finalization
An object used to be destroyed automatically Just at the moment it is no longer needed
No longer available with Visual Basic.NET: No automatic reference counting behind the scenes Objects are destroyed at garbage collector’s choice Resources may stay locked virtually forever
One possible solution: Provide your own reference counting and disposal scheme
Make your objects stateless
Section 3: Integration into .NET
Common Language Runtime
Concepts of Namespaces, Assemblies, Modules
Free Threading
Reflection
Attributes
Windows Forms
Tools
The Common Language Runtime
Access to .NET platform services
Cross-language interoperation That includes inheritance
Interoperation w/ COM and Platform Invocation Services COM-Interop PInvoke Calling unmanaged code has its implications
Namespaces Organizational concept
May and should be nested System.Reflection MyLib.Helpers.Controls.Inputs
Multiple namespaces declared in program
Namespaces can span multiple programs
Importing namespaces Allows unqualified access to types Placed at file or project level
Global namespace without a name Globally declared members have program scope
Namespace MyLib
...
End Namespace
Assemblies
Result of compiling is still a .dll or .exe file Single-file or multiple-file assembly
File contains metadata (manifest) Description of the assembly itself Description of implemented types External references Version information Enforce security And more ...
Modules
Smallest unit that can be compiled
Contains one or more classes or interfaces Sub Main() usually has module scope
More than one module can share an assembly which is an multifile assembly then
Example: Imports System Public Module MainMod Sub Main() Console.WriteLine("Hello World!") End Sub End Module
Free Threading
Run multiple tasks independently Objects can be shared by threads
Use AddressOf operator on Sub to declare
Sub cannot have arguments or return value
Synchronization needed
Dim myThread As New Threading.thread(AddressOf MySub)
myThread.Start()
myThread.Join()
Threading Sample
Dim Writer As Thread = new Thread(AddressOf AnObj.ThreadSub)
Dim Reader As Thread = new Thread(AddressOf AnObj.ThreadSub)
...
Writer.Start()
Reader.Start()
Writer.Join()
Reader.Join()
...
Public Sub ThreadSub
Monitor.Enter(Me) 'Enter Synchronization block
...
Monitor.Exit(Me)
End Sub
Reflection
Mechanism for obtaining run-time information Assemblies Types: classes, interfaces, methods
Provides explicit late-bound method invocation
May even construct types at run time System.Reflection.Emit
Attributes Additional declarative information on program item
May define custom attribute classes
Can be retrieved at run time
Enhance program functionality Giving hints to the system runtime
Use as meta elements
Public Class PersonFirstName Inherits AttributeEnd Class
<PersonFirstName()> Dim Vorname As String<PersonFirstName()> Dim NamaDepan As String
<WebMethod()> Public Function Hello As String ...
Windows® Forms
New forms library based on .NET Framework
Can be used for desktop applications
Local user interface for three-tier applications
Windows Client Web Service
DatabaseForm1.vb Business Object GetOrder
Dataset
orders.xsdDataset
orders.xsdDataset Command
orderCommand
HTTP
XML
OLE DB
Command-Line Compiler
Compiles Visual Basic source into MSIL
Can have a multitude of options
Can be called from arbitrary environment
Uses fewer system resources than Visual Studio
Can be used with nmake Useful for multi-language projects
Vbc /target:exe /out:myprogram.exe *.vb
Visual Studio.NET
Built around the .NET Framework SDK
Improved integration and functionality Multiple-language projects One integrated IDE for all languages and tasks Integrated tools: Visual Modeler, database management Perfect help integration: Dynamic Help, IntelliSense®
Highest productivity for all: Rapid application development Large-scale projects
From Visual Basic 6 to Visual Basic.NET
Visual Basic.NET is a true successor of Visual Basic 6 ...but some things make a difference
Compatibility classes help with the transition Microsoft.VisualBasic imported by default Classes that deliver the functionality of...
Collections
Date/time functions
More
Prepare for porting!
Visual Basic Upgrade Wizard
Applies changes automatically
Generates solution Type conversions
Variant to Object
Integer to Short, Long to Integer
Type to Structure
Currency to Decimal
Zero-bound arrays .NET Windows Forms replace Visual Basic 6 Forms
Recommendations for upgrading
Section 4: Putting It All Together
Sample Walkthrough Exploring Visual Basic.NET Features in Duwamish Books
Demo: Duwamish Books
Enterprise Sample application
"Best practice" multiple-tier design
Included with Visual Studio.NET
Great start to learn about Visual Basic.NET ASP.NET ADO.NET
Summary
Major touchup to take advantage of the .NET Framework
Modernized and consistent language
Legacy features finally dropped
Your Visual Basic.NET code can be reused
Supported migration path
Installing the Sample 1/2
Install the "Enterprise Samples" with Visual Studio.NET
Location of the Visual Basic Version Directory .\EnterpriseSamples\DuwamishOnline VB
Installation Tasks Check the prerequisites
Microsoft Windows 2000 Server; Microsoft SQL Server™ 2000 with English Query optional and supported
Read the Readme.htm
Run Installer Duwamish.msi (double-click it)
Installing the Sample 2/2
The installation wizard will guide you
Defaults should be OK for almost everybody.
Setup will install database, Web site, and code
After installation is complete: File/Open Solution with the Duwamish.sln file Can build the sample with Build/Build Solution
User / Browser
IIS
Duwamish Architecture Overview
DataAccess
Database
Com
mon.D
ata
BusinessRules
BusinessFacade
System
Fram
ework
Web
ASP.NET
ADO.NET
Common Components Duwamish7.Common
Contains systems configuration options Contains common data definitions (classes)
subnamespace Duwamish.Common.Data
"Internal" data representation for Book, Category, Customer, OrderData
Duwamish7.SystemFramework Diagnostics utilities Pre and post condition checking classes Dynamic configuration In short:
Everything that's pure tech and not business code
Duwamish7.DataAccess
Contains all database-related code
Uses ADO.NET architecture Using SQL Server managed provider Shows DataSet, DataSetCommand usage
Optimized for performance by using stored procs
Duwamish7.BusinessRules
Implements all business rules Validation of business objects (for examle,
Customer EMail) Updating business objects Calculations (Shipping Cost, Taxes)
All data access performed through DataAccess
Duwamish7.BusinessFacade
Implements logical business subsystems CustomerSystem: Profile management OrderSystem: Order management ProductSystem: Catalog management
Reads data through DataAccess
Data validated and updated using BusinessRules
BusinessFacade encapsulates all business-related functionality
Duwamish7.Web
Implements the user interface for Web access
Uses ASP.NET architecture Employs Web Forms model Uses code behind forms Manages state Uses custom Web controls
All functionality accessed through BusinessFacade
Legal Notices
Unpublished work. 2001 Microsoft Corporation. All rights reserved.
Microsoft, IntelliSense, Visual Basic, Visual Studio, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their respective owners.