Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic.NET Taking the Most Successful Language One Step Further.

Similar presentations

Presentation on theme: "Visual Basic.NET Taking the Most Successful Language One Step Further."— Presentation transcript:

1 Visual Basic.NET Taking the Most Successful Language One Step Further

2 Objectives Introduction to Microsoft Visual Basic.NET New concepts Changes Integration into.NET Tools

3 Contents Section 1: Overview Section 2: Language Features Section 3: Integration into.NET Section 4: Putting It All Together Summary

4 Section 1: Overview Make the language even easier to 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

5 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

6 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

7 Section 2: Language Features Type System Classes and Inheritance Exception Handling Event Concept Changes

8 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

9 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

10 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 Byte red yellow green End Enum

11 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 Integer ReDim anArray(10) Dim OneDimension(10) As Integer Dim TwoDimensions(20,intVal) As Integer

12 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

13 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

14 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

15 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 Property End Class intVal = Sample.val

16 Sample Class Definition Public Class Customer Implements ICustomer Private CustomerNo As String Public Property Customer() As String Get Return CustomerNo End Get Set CustomerNo = Customer End Set End 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.DoAny End Sub End Class

17 Inheritance 1/2 Single base class, but multiple base interfaces Abstract base classes Non-inheritable classes Public Class DerivedClass Inherits BaseClass Implements IBase1, IBase2... End Class Public MustInherit Class AbstractBase... End Class Public NotInheritable Class FinalClass... End Class

18 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

19 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 Customer Implements ICustomer Public CustomerNo, Name As String Public Sub New() End Sub Public Sub Do(ByVal c as Char) Implements ICustomer.Do End Sub End Structure

20 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

21 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 Catch e As Exception Finally End Try

22 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)

23 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

24 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

25 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 CBase Dim Derived as CDerived = new CDerived() Base = Derived

26 Better Performance Supports free threading More responsiveness Short-circuit evaluation X = A AndAlso B AndAlso (C OrElse D) Reference assignment for arrays

27 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

28 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

29 Section 3: Integration into.NET Common Language Runtime Concepts of Namespaces, Assemblies, Modules Free Threading Reflection Attributes Windows Forms Tools

30 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

31 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

32 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...

33 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

34 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()

35 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

36 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

37 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 Attribute End Class Dim Vorname As String Dim NamaDepan As String Public Function Hello As String...

38 Windows® Forms New forms library based on.NET Framework Can be used for desktop applications Local user interface for three-tier applications Windows ClientWeb Service Database Form1.vb Business Object GetOrder Dataset orders.xsd Dataset orders.xsd Dataset Command orderCommand HTTP XML OLE DB

39 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

40 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

41 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!

42 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

43 Section 4: Putting It All Together Sample Walkthrough Exploring Visual Basic.NET Features in Duwamish Books

44 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

45 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

46 Questions?

47 Duwamish Books A Sample Application for Microsoft.NET

48 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)

49 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

50 User / Browser IIS Duwamish Architecture Overview DataAccess Database Common.Data BusinessRules BusinessFacade SystemFramework Web ASP.NET ADO.NE T

51 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

52 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

53 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

54 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

55 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

56 Shop at Duwamish Online.NET Demo: Duwamish in Action

57 Exploring Duwamish VB Exploring Visual Basic.NET Features in Duwamish

58 Extending Duwamish VB

59 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.

Download ppt "Visual Basic.NET Taking the Most Successful Language One Step Further."

Similar presentations

Ads by Google