migrating vba/vb6 arcobjects applications to · 2009-04-02 · schedule todayypgpp we will cover...

46
Migrating VBA/VB6 ArcObjects Applications to .NET Migrating VBA/VB6 ArcObjects Applications to .NET Don Kemlage, Jianxia Song and Jeremy Wright Don Kemlage, Jianxia Song and Jeremy Wright

Upload: others

Post on 20-Mar-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Migrating VBA/VB6 ArcObjects Applications to .NETMigrating VBA/VB6 ArcObjects Applications to .NET

Don Kemlage, Jianxia Song and Jeremy WrightDon Kemlage, Jianxia Song and Jeremy Wright

Page 2: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

ScheduleSchedule

Today we will cover providing practical experience in Today we will cover providing practical experience in y p g p py p g p pmigrating ArcObjects code from VBA/VB6 to .NETmigrating ArcObjects code from VBA/VB6 to .NET

– Why Migrate– Key Concepts– Language DifferencesLanguage Differences– Visual Studio Migration Features– Bringing It All Together

Additi l R– Additional Resources

Page 3: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Why Migrate

It depends on your situation– If it ain’t broke don’t fix it– Stay competitive

It will be a challengeIt will be a challenge– Costly– 7,000 – 10,000 lines of code converted per week– 2 to 3 weeks understanding all migration issues2 to 3 weeks understanding all migration issues– Understand the .NET Framework capabilities

Page 4: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Why Migrate - VBA/VB6 disadvantages

Falling behind the technology curve

Not a ‘true’ object oriented language

Have to call Win32 API to access system internalsHave to call Win32 API to access system internals

IDE issues– Debugging problematic for COM objects– VB magic

DLL hell

Page 5: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Why Migrate - The Facts

VBA–– As of July 1, 2007 Microsoft discontinued new VBA distribution As of July 1, 2007 Microsoft discontinued new VBA distribution

licenseslicenses–– ESRI VBA SDK’s are in maintenance modeESRI VBA SDK’s are in maintenance mode–– Note: ArcGIS 9.3 is using VBA version 6.5Note: ArcGIS 9.3 is using VBA version 6.5

VB6–– Microsoft will end support at the end of 2008Microsoft will end support at the end of 2008pppp–– ESRI VB6 SDK’s are being deprecated in 9.3 (no VB6 in 9.4)ESRI VB6 SDK’s are being deprecated in 9.3 (no VB6 in 9.4)

Page 6: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Why Migrate - .NET Advantages

True Object Oriented language– Supports Inheritance, function overloading, structured exception

handling, multithreading, garbage collection

.NET Framework – Common Language Runtime (CLR)

• Virtual machine, MSIL– The .NET Framework class library

Visual Studio IDE– One IDE for all .NET projectsO e o a p ojects– Option to choose from Multiple Programming Languages – ESRI’s Visual Studio Integration tools– Easier Debugging ArcObjects applicationEasier Debugging ArcObjects application

Page 7: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Why Migrate - .NET Advantages (continued)

Easy Deployments– No more .dll hell– XCOPY .NET Assemblies to target machine – Recompile not necessary to target different Operating Systems

Improved maintenance and scalability

Page 8: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Key Concepts

COM API– Expose type information using type libraries

.NET API– Use metadata as a source of type information yp– Interop Assemblies to map .NET and COM identities– Managed code vs. Unmanaged code

• COM Interop APIp• http://msdn2.microsoft.com/en-us/library/sd10k43k.aspx

Page 9: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Key Concepts - The LanguagesThe Languages

VBAVBA–– The builtThe built--in customization language of ArcGIS Desktop in customization language of ArcGIS Desktop –– Create User Interface (UI) Controls and MacrosCreate User Interface (UI) Controls and Macros

VB6 / .NETVB6 / .NET–– Create Active X (COM) .dlls for ArcGIS Desktop and ArcGIS Engine Create Active X (COM) .dlls for ArcGIS Desktop and ArcGIS Engine

applications (.exe)applications (.exe)–– Can extend ArcGIS System in many areasCan extend ArcGIS System in many areas

Page 10: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Key Concepts -- Entry Points for ArcGIS CustomizationsEntry Points for ArcGIS Customizations

VBA VBA –– Use ‘ThisDocument’ and ‘Application’ variables as the gatewayUse ‘ThisDocument’ and ‘Application’ variables as the gatewaypp g ypp g y

VB6 and .NETVB6 and .NET–– Use ‘hook’ object passed into the OnCreate method to reference theUse ‘hook’ object passed into the OnCreate method to reference theUse hook object passed into the OnCreate method to reference the Use hook object passed into the OnCreate method to reference the

applications (ArcMap, ArcCatalog)applications (ArcMap, ArcCatalog)–– Use ‘HookHelper’ object when the command is to support a variety of Use ‘HookHelper’ object when the command is to support a variety of

hook objectshook objects

Page 11: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Data Type DifferencesData Type Differences

VBA/VB6 VB.NET C# CLRVariant/Object Object object System.Object

String String String System StringString String String System.StringBoolean Boolean bool System.Boolean(n/a) Char char System.CharSingle Single float System.Singleg g y gDouble Double double System.DoubleCurrency Decimal decimal System.DecimalDate Date (n/a) System.DateTime(n/a) (n/a) sbyte System.SByteByte Byte byte System.ByteInteger Short short System.Int16(n/a) (n/a) ushort System.UInt16Long Integer int System.Int32(n/a) (n/a) uint System.UInt32( / ) L l S t I t64(n/a) Long long System.Int64(n/a) (n/a) ulong System.UInt64

Page 12: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Inheritance and PolymorphismInheritance and Polymorphism

Use existing code to create new behavior

VBA/VB6 uses only Implements (Polymorphism)VBA/VB6 uses only Implements (Polymorphism)VBA/VB6 uses only Implements (Polymorphism)VBA/VB6 uses only Implements (Polymorphism)–– http://msdn2.microsoft.com/enhttp://msdn2.microsoft.com/en--us/library/7z6hzchx(VS.80).aspxus/library/7z6hzchx(VS.80).aspx

.NET uses both Implements and Inherits (Inheritance).NET uses both Implements and Inherits (Inheritance).NET uses both Implements and Inherits (Inheritance).NET uses both Implements and Inherits (Inheritance)–– http://msdn2.microsoft.com/enhttp://msdn2.microsoft.com/en--us/library/1yk8s7sk(VS.80).aspxus/library/1yk8s7sk(VS.80).aspx

Implements (Polymorphism)Implements (Polymorphism)Implements (Polymorphism)Implements (Polymorphism)–– Must implement all the members declared in the interfaceMust implement all the members declared in the interface–– Can Implement multiple interfacesCan Implement multiple interfaces

Inherits (Inheritance)Inherits (Inheritance)–– Take advantage of functionality of base classesTake advantage of functionality of base classes–– Can only Inherit one ClassCan only Inherit one Class–– ESRI.ArcGIS.ADF AssemblyESRI.ArcGIS.ADF Assembly

Page 13: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Error HandlingError Handling

VBA/VB6VBA/VB6–– On Error GoTo / On Error Resume NextOn Error GoTo / On Error Resume Next–– http://www.cpearson.com/excel/ErrorHandling.htmhttp://www.cpearson.com/excel/ErrorHandling.htm

On Error GoTo ErrorHandlerOn Error GoTo ErrorHandler......Exit SubExit SubErrorHandler:ErrorHandler:

On Error GoTo ErrorHandlerOn Error GoTo ErrorHandler......Exit SubExit SubErrorHandler:ErrorHandler:ErrorHandler:ErrorHandler:MsgBox CStr(Err.Number) & " " & MsgBox CStr(Err.Number) & " " & Err.DescriptionErr.Description

ErrorHandler:ErrorHandler:MsgBox CStr(Err.Number) & " " & MsgBox CStr(Err.Number) & " " & Err.DescriptionErr.Description

Page 14: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Error Handling (continued)Error Handling (continued)

.NET.NET–– Try Catch Finally / Throw an ExceptionTry Catch Finally / Throw an Exception–– http://support.microsoft.com/kb/315965http://support.microsoft.com/kb/315965

Try'Code that may raise an error

Try'Code that may raise an errorCode that may raise an errorIf x = 0 Then

Throw New System.DivideByZeroExceptionEnd If

Catch ex As Exception

Code that may raise an errorIf x = 0 Then

Throw New System.DivideByZeroExceptionEnd If

Catch ex As ExceptionCatch ex As Exception'Code to handle the errorMessageBox.Show(ex.InnerException.ToString)

Finally'Code to do any final clean up

Catch ex As Exception'Code to handle the errorMessageBox.Show(ex.InnerException.ToString)

Finally'Code to do any final clean upCode to do any final clean up'This sections always executes

End Try

Code to do any final clean up'This sections always executes

End Try

Page 15: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Variable declaration and InstantiationVariable declaration and Instantiation

VBA/VB6– Use Dim to declare a variable– Use Set to assign an object instance to a variableUse Set to assign an object instance to a variable

‘VB6Dim pPolygon as IPolygonSet pPolygon = New Polygon

‘VB6Dim pPolygon as IPolygonSet pPolygon = New Polygon

VB.NET

Set pPolygon = New PolygonSet pPolygon = New Polygon

– Set keyword is gone– Can perform the declaration & instantiation on one line

‘VB NET T li i‘VB NET T li i‘VB.NET Two line versionDim aPoint as IPointaPoint = New PointClass

‘VB NET O li i

‘VB.NET Two line versionDim aPoint as IPointaPoint = New PointClass

‘VB NET O li i‘VB.NET One line versionDim aPolygon as IPolygon = new PolygonClass‘VB.NET One line versionDim aPolygon as IPolygon = new PolygonClass

Page 16: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Traversing COM InterfacesTraversing COM Interfaces

Switching between interfaces ona Class is central to traversinga Class is central to traversingArcObjects

In VBA/VB6 this is call Query Interface (QI)

In .NET this is call Casting

Page 17: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Traversing COM Interfaces (cont.)Traversing COM Interfaces (cont.)

VBA/VB6 (Query Interface):

Dim areaPolygon as IArea Dim areaPolygon as IArea Set areaPolygon = New PolygonDim geometry as IGeometry

If TypeOf geometry is IArea Then

Set areaPolygon = New PolygonDim geometry as IGeometry

If TypeOf geometry is IArea Then

'Query InterfaceSet geometry = areaPolygon'Query InterfaceSet geometry = areaPolygon

End IfEnd If

Page 18: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Traversing COM Interfaces (cont.)Traversing COM Interfaces (cont.)

VB.NET (Casting – There are 4 options):

Dim areaPolygon as IArea = New PolygonClassDim areaPolygon as IArea = New PolygonClassyg yg

‘ Analogous to QI in VB6 – Throws InvalidCastException on errorDim geometryPolygon1 as IGeometry = areaPolygon

yg yg

‘ Analogous to QI in VB6 – Throws InvalidCastException on errorDim geometryPolygon1 as IGeometry = areaPolygon

‘ Throws InvalidCastException on errorDim geometryPolygon2 as IGeometry = CType(areaPolygon,IGeometry)

‘ Throws InvalidCastException on error

‘ Throws InvalidCastException on errorDim geometryPolygon2 as IGeometry = CType(areaPolygon,IGeometry)

‘ Throws InvalidCastException on errorpDim geometryPolygon3 as IGeometry = DirectCast(areaPolygon, IGeometry)

‘ Returns Nothing on error

pDim geometryPolygon3 as IGeometry = DirectCast(areaPolygon, IGeometry)

‘ Returns Nothing on errorgDim geometryPolygon4 as IGeometry = TryCast(areaPolygon, IGeometry)

gDim geometryPolygon4 as IGeometry = TryCast(areaPolygon, IGeometry)

Page 19: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Traversing COM Interfaces (cont.)Traversing COM Interfaces (cont.)

A .NET alternative to eliminate Casting (or QI) altogether for g ( ) gcreatable classes

Dim aPolygon as New PolygonClassDim aPolygon as New PolygonClassDim aPolygon as New PolygonClassDim aPolygon as New PolygonClass

This will show all availableThis will show all availableProperties and Eventsavailable in IntelliSense

Page 20: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences - Events

Events let you know when something has occurred

You can add code to respond to an event

For example, a command button has a Click event. – The code performs some action when the user clicks a control

VBA/VB6 uses the WithEvents keyword to wire up an event– Only supports one outbound interface per coclassOnly supports one outbound interface per coclass– Uses dummy coclass to access other outbound interfaces

VB.NET uses AddHandler and AddressOf keywords to wire up an event– Dummy coclass not needed for outbound interfaces– Can unwire events too (can’t do in VB6/VBA)– Uses Delegate to communicate – Event interfaces have an Event suffixEvent interfaces have an _Event suffix– Note: Can still use VBA/VB6 sytle WithEvents if desired

Page 21: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Event in Event in VBA/VB6

Step 1: Use WithEvents keyword to declare a variableStep 2: Hookup the sink and the event source

Private WithEvents m_pActiveViewEvents As Map

Private Sub ICommand_OnCreate(ByVal hook As Object)

'Set the hook object

Private WithEvents m_pActiveViewEvents As Map

Private Sub ICommand_OnCreate(ByVal hook As Object)

'Set the hook object'Set the hook objectDim pApp As IApplicationpApp = hook

'Cast to an IMxDocument

'Set the hook objectDim pApp As IApplicationpApp = hook

'Cast to an IMxDocumentDim pMxDoc As IMxDocumentpMxDoc = pApp.Document

'Wire up the event handlerm pActiveViewEvents = pMxDoc FocusMap

Dim pMxDoc As IMxDocumentpMxDoc = pApp.Document

'Wire up the event handlerm pActiveViewEvents = pMxDoc FocusMapm_pActiveViewEvents = pMxDoc.FocusMap

End Sub

Private Sub m_pActiveViewEvents_SelectionChanged()

m_pActiveViewEvents = pMxDoc.FocusMap

End Sub

Private Sub m_pActiveViewEvents_SelectionChanged()'FIRES WHENEVER THE SelectionChanged EVENT OCCURS

End Sub'FIRES WHENEVER THE SelectionChanged EVENT OCCURS

End Sub

Page 22: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Events in VBEvents in VB.NET

Step 1: Cast the event interface Step 2: Register the event handler method Step 3: Implement the event handler methodStep 3: Implement the event handler method

Private m_map_Events As IActiveViewEvents_Event

Public Overrides Sub OnCreate(ByVal hook As Object)

Private m_map_Events As IActiveViewEvents_Event

Public Overrides Sub OnCreate(ByVal hook As Object)

'Set the hook objectDim m_application As IApplication = CType(hook, IApplication)

'Get the ArcMap documentDim document As IDocument = m_application.Document

'Set the hook objectDim m_application As IApplication = CType(hook, IApplication)

'Get the ArcMap documentDim document As IDocument = m_application.Document_

'Cast to an IMxDocumentDim mxDocument As IMxDocument = CType(document, IMxDocument)

'Wire up the map's event handlerE t CT ( F M IA ti Vi E t E t)

_

'Cast to an IMxDocumentDim mxDocument As IMxDocument = CType(document, IMxDocument)

'Wire up the map's event handlerE t CT ( F M IA ti Vi E t E t)m_map_Events = CType(map.FocusMap,IActiveViewEvents_Event)

'Create an instance of the delegate, add it to SelectionChangedAddHandler m_map_Events.SelectionChanged, AddressOf OnActiveViewEventsSelectionChanged

End Sub

m_map_Events = CType(map.FocusMap,IActiveViewEvents_Event)

'Create an instance of the delegate, add it to SelectionChangedAddHandler m_map_Events.SelectionChanged, AddressOf OnActiveViewEventsSelectionChanged

End SubEnd Sub

Private Sub OnActiveViewEventsSelectionChanged()'FIRES WHENEVER THE SelectionChanged EVENT OCCURS

End Sub

End Sub

Private Sub OnActiveViewEventsSelectionChanged()'FIRES WHENEVER THE SelectionChanged EVENT OCCURS

End Sub

Page 23: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences - Replace Win32 API calls with .NETFramework libraries

Windows API calls are not .NET managed code

Replace Win32 API calls with .NET Framework libraries.NET Framework libraries

There are thousands of .NET equivalents to Win32 API functions

http://msdn2 microsoft com/en-us/library/aa302340 aspxhttp://msdn2.microsoft.com/en us/library/aa302340.aspx

Page 24: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences –– I/O functionsI/O functions

File I/O functions resides in System.IO assembly

Win32 function .NET Framework API

CopyFile System.IO.File.Copy

CreateDirectory System.IO.Directory.CreateDirectory

GetCurrentDirectory System.IO.Directory.GetCurrentDirectory

ReadFile System.IO.FileStream.Read

SearchPath System.IO.File.ExistsSearchPath System.IO.File.Exists

Page 25: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Printer-related functions

Printer-related functions reside in System.Drawing.Printing

Win32 function NET Framework APIWin32 function .NET Framework API EnumForms System.Drawing.Printing.PrinterSettings.PaperSizes

EnumPrinters System.Drawing.Printing.PrinterSettings.InstalledPrintersy g g g

GetDefaultPrinter System.Drawing.Printing.PrinterSettings constructorSystem.Drawing.Printing.PrinterSettings.PrinterName

G tF S t D i P i ti P i t S tti P SiGetForm System.Drawing.Printing.PrinterSettings.PaperSizes

GetPrinter System.Drawing.Printing.PrinterSettings.PrinterName System.Drawing.Printing.PrinterSettings properties

SetPrinter System.Drawing.Printing.PrinterSettings.PrinterName System.Drawing.Printing.PrinterSettings properties

DeviceCapabilities System.Drawing.Printing.PrinterSettings propertiesp y g g g p p

Page 26: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- GDI+ drawing functions

All GDI+ drawing code resides in System.Drawing.DLL

Win32 function .NET Framework API

BitBlt System.Drawing.Graphics.DrawImage

CreateBitmap System.Drawing.Bitmap constructor

CreatePen System.Drawing.Pen constructor

GetDC System.Drawing.Graphics.GetHdc

ReleaseDC System.Drawing.Graphics.ReleaseHdc

GetDeviceCaps System.Drawing.Graphics propertiesSystem.Drawing.Printing.Printersettings

Rectangle System.Drawing.Graphics.DrawRectangle

Page 27: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Windows Forms and embedded Controls

IToolControl, ComboBox, EditBox, ImageList, ImageCombo

VB6– Can access Windows Forms directly– Form Load event automatically executed

.NET– Must create an instance of the Windows Form

Page 28: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Windows Forms and embedded Controls cont.

VB6

Private Sub ICommand_OnCreate(ByVal hook As Object)frmEvents.Application = hook

End Sub

Private Sub ICommand OnClick()

Private Sub ICommand_OnCreate(ByVal hook As Object)frmEvents.Application = hook

End Sub

Private Sub ICommand OnClick()Private Sub ICommand_OnClick()frmEvents.Show

End Sub

Private Sub ICommand_OnClick()frmEvents.Show

End Sub

Public Overrides Sub OnClick()Public Overrides Sub OnClick()

VB.NET

'Launch the Windows form set the Application PropertyDim frmEvents As New frmEventsfrmEvents.Application = m_applicationfrmEvents.Show()

'Launch the Windows form set the Application PropertyDim frmEvents As New frmEventsfrmEvents.Application = m_applicationfrmEvents.Show()

End SubEnd Sub

Page 29: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences Language Differences -- Bitmap Property for Commands and Tools

VB6– Returned type as an esriSystem.OLE_Handle

.NET– Returned type as an IntegerReturned type as an Integer– For Polymorphic classes, use Bitmap.GetHbitmap function and clean

up with gdi32.dll DeleteObject function– For Inheritance classes, set the m bitmap property, _ p p p y

Page 30: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences – Bitmap Property VB6 & VB.NETVB6 (Polymorphic)

Private Property Get ICommand_Bitmap() As esriSystem.OLE_HANDLEICommand_Bitmap = frmResources.ImageList1.ListImages(1).Picture.Handle

End Property

Private Property Get ICommand_Bitmap() As esriSystem.OLE_HANDLEICommand_Bitmap = frmResources.ImageList1.ListImages(1).Picture.Handle

End Property

VB6 (Polymorphic)

p yp y

Private ReadOnly Property ICommand Bitmap() As Int32 Implements ICommand.BitmapPrivate ReadOnly Property ICommand Bitmap() As Int32 Implements ICommand.Bitmap

VB.NET (Polymorphic)y p y _ p() p p

GetDim bitmap As Bitmap = m_frmResources.ImageList1.Images.Item(0)bitmap.MakeTransparent(bitmap.GetPixel(0, 0))m_hBitmap = bitmap.GetHbitmap()Return CInt(m_hBitmap)

y p y _ p() p pGet

Dim bitmap As Bitmap = m_frmResources.ImageList1.Images.Item(0)bitmap.MakeTransparent(bitmap.GetPixel(0, 0))m_hBitmap = bitmap.GetHbitmap()Return CInt(m_hBitmap)

End GetEnd Property

'Define the Windows gdi32.dll API call<Runtime.InteropServices.DllImport("gdi32.dll")> _Private Shared Function DeleteObject(ByVal hObject As IntPtr) As Boolean

End GetEnd Property

'Define the Windows gdi32.dll API call<Runtime.InteropServices.DllImport("gdi32.dll")> _Private Shared Function DeleteObject(ByVal hObject As IntPtr) As BooleanPrivate Shared Function DeleteObject(ByVal hObject As IntPtr) As BooleanEnd Function

'Release the memory for the bitmap associated with the Command.Protected Overrides Sub Finalize()

If (m hBitmap.ToInt32() <> 0) Then

Private Shared Function DeleteObject(ByVal hObject As IntPtr) As BooleanEnd Function

'Release the memory for the bitmap associated with the Command.Protected Overrides Sub Finalize()

If (m hBitmap.ToInt32() <> 0) Then( _ p () )DeleteObject(m_hBitmap)

End IfMyBase.Finalize()

End Sub

( _ p () )DeleteObject(m_hBitmap)

End IfMyBase.Finalize()

End Sub

Page 31: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Language Differences – Bitmap Property VB.NET Alternate

Using ESRI Base Command Class (Inheritance)– The Bitmap is an Embedded Resource in the Project

Public Sub New()MyBase.New()

Public Sub New()MyBase.New()

...

Try

...

Try'TODO: change bitmap name if necessaryDim bitmapResourceName As String = Me.GetType().Name + ".bmp"MyBase.m_bitmap = New Bitmap(Me.GetType(), bitmapResourceName)

Catch ex As Exception

'TODO: change bitmap name if necessaryDim bitmapResourceName As String = Me.GetType().Name + ".bmp"MyBase.m_bitmap = New Bitmap(Me.GetType(), bitmapResourceName)

Catch ex As ExceptionSystem.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap")

End Try

End Sub

System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap")End Try

End Sub

Page 32: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Visual Studio Migration Features

Microsoft– Visual Basic Upgrade Wizard

ESRI– ArcGIS Code ConverterArcGIS Code Converter– ArcGIS Project Wizard Templates (choosing the right one)– Item Templates

Page 33: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Visual Studio Migration Features - Visual Basic Upgrade Wizard

Converts VB6 projects toVB NET j tVB.NET projects

There are several limitations– Common dialogs– MsgBox– Win32API– .etc...

Page 34: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Visual Studio Migration Features - ArcGIS Code Converter

Converts ArcGIS 8.3 to ArcGIS 9.x namespaces in the code– Dim pPoly As ESRI.ArcObjects.Core.IPolygon ‘8.3 namespace– Dim pPoly As ESRI.ArcGIS.Geometry.IPolygon ‘9.x namespacep y y yg p

Appropriate project references will be updated– ESRI ArcGIS Utility assembly is replaced with ESRI ArcGIS ADFESRI.ArcGIS.Utility assembly is replaced with ESRI.ArcGIS.ADF

Page 35: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Visual Studio Migration Features - ArcGIS Project Wizard

They are Templates (choose the right one)

Fi t d id th t f l ti dFirst, decide on the type of solution you need

Then, choose the appropriate ArcGIS Project Template feature of the Visual Studio Integration Framework to use

In-Process (.dll)Out-Of-Process (.exe)ArcGIS Engine Windows ApplicationArcGIS Engine Console Application

( )ArcGIS Desktop Class Library GeneralArcGIS Desktop Class Library ArcGlobeArcGIS Desktop Class Library ArcSceneArcGIS Desktop Class Library ArcCatalogArcGIS Desktop Class Library ArcMapArcGIS Desktop Class Library ArcMapArcGIS Engine Class Library

Page 36: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Visual Studio Migration Features - Item Templates

Default code templates for adding ArcGIS customizations– Component category registration– Implemented interface stubs and common members

Accessed by– Context Menu:

Right click project name in the Solution Explorer > Add > New Item

– Menus: Project > Add New Item

Page 37: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Bringing It All Together - The upgrade process

Plan

Prepare

Upgrade

Test

Deployp y

Advance

Page 38: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Bringing It All Together - PreparePrepare

Verify unused library referencesVerify unused library references

M d l i d h iblM d l i d h iblModularize code as much as possible Modularize code as much as possible –– Separate the business logic of the application from the EventsSeparate the business logic of the application from the Events–– Parameterize functions where possibleParameterize functions where possible

Minimize the use of global variablesMinimize the use of global variables–– Minimize the use of global variablesMinimize the use of global variables

“Option Strict” on, Option ExplicitU lU l b d d t t h k th i bl t if t iblb d d t t h k th i bl t if t ibl–– Use earlyUse early--bound data type, check the variable types if not possiblebound data type, check the variable types if not possible

Others:Others:–– ZeroZero--bound arrays, avoid default propertiesbound arrays, avoid default properties

Page 39: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Bringing It All Together - UpgradeUpgrade

Create a autoCreate a auto--translated VB.NET code projecttranslated VB.NET code project–– Use the Visual Studio code converter to import the VB6 project to .NETUse the Visual Studio code converter to import the VB6 project to .NET–– If the ArcObjects code is in 8.x, use the ArcGIS .NET Code ConverterIf the ArcObjects code is in 8.x, use the ArcGIS .NET Code Converter

Create a new VB.NET code project to hold the final codeCreate a new VB.NET code project to hold the final code–– Use ESRI’s Visual Studio IDE Integration features to create the Framework stubsUse ESRI’s Visual Studio IDE Integration features to create the Framework stubs–– Copy the business logic from the autoCopy the business logic from the auto--translated project translated project –– Edit the Framework stubs to use the business logicEdit the Framework stubs to use the business logic–– Fix the language specific constructs and GUI forms/controls that did not autoFix the language specific constructs and GUI forms/controls that did not auto--translate translate –– Delete autoDelete auto--translated commentstranslated comments

Page 40: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Bringing It All Together - Upgrade (continued)Upgrade (continued)

Common issues:Common issues:–– Compile Error/WarningCompile Error/Warning

–– Wizard creates both class and interface definitionsWizard creates both class and interface definitions for userfor user--defined interfaces defined interfaces

– Use OLE- automation-compliant interfaces (IGeometryBridge)– COM registration– Component category registration– Component category registration–– OLE_HANDLE valuesOLE_HANDLE values– Events

'<interface>__<member>' cannot implement '<member>’.

because there is no matching property on interface '<interface>'

Private ReadOnly Property ICommand_Bitmap() As Integer Implements ICommand.Bitmap

“Couldn't resolve default property of object <variable name>”

Page 41: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Bringing It All Together - Migrating a VBA application to .NETMigrating a VBA application to .NET

From the VBA Editor export the .bas, .cls, and .frm files to diskFrom the VBA Editor export the .bas, .cls, and .frm files to disk

Create a new VB6 project and add the exported code filesCreate a new VB6 project and add the exported code files

For each .frm create a matching .cls file and copy/paste code to itFor each .frm create a matching .cls file and copy/paste code to it–– The VBA forms (.frm) GUI will not translate to .NET, but you can The VBA forms (.frm) GUI will not translate to .NET, but you can

salvage the codesalvage the code

Add all of the ESRI References to the projectAdd all of the ESRI References to the project

Save the new VB6 projectSave the new VB6 project

Follow the ‘Migrating a VB6 application to .NET’ recommendations Follow the ‘Migrating a VB6 application to .NET’ recommendations

Page 42: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

A demo showing a VB6 to VB.NET project conversionA demo showing a VB6 to VB.NET project conversion

Plan

Prepare

Upgrade

T tTest

Deploy

Advance

Page 43: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Additional Resources - Resources for Migration

Microsoft’s patterns and practices book: Upgrading Visual Basic 6.0 Applications to Visual Basic .NET and Visual Basic 2005

– http://www.microsoft.com/downloads/details.aspx?FamilyId=7C3FE0A9-CBED-485F-BFD5-847FB68F785D&displaylang=en

ESRI’s EDN document series: Programming with .NET– http://edndoc.esri.com/arcobjects/9.3/NET/12BF6F08-1B25-4002-9640-

73D4EB0E6CED.htm

ESRI’s EDN document: Migrating and upgrading your code– http://edndoc.esri.com/arcobjects/9.3/NET/13ef8415-8314-4bc9-9b77-

4b03599c2c11.htm

Page 44: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Additional Resources - C# Advice

A good VB.NET to C# converter is available by Tangible Software Solutions (http://www.tangiblesoftwaresolutions.com/)

get and set ‘VB NET‘VB NETget_ and set_ VB.NETDim layer As ILayer = map.Layer(0)

//C#//ILayer layer = map.Layer(0);

VB.NETDim layer As ILayer = map.Layer(0)

//C#//ILayer layer = map.Layer(0);

Use System.Type.Missing to indicate optional and undefined parameters

ILayer layer = map.get_Layer(0);ILayer layer = map.get_Layer(0);

‘VB NET‘VB NETVB NETIAvtiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics)

//C#IActiveView.PartialRefresh (esriViewDrawPhase.esriViewGraphics, Type.Missing,

VB NETIAvtiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics)

//C#IActiveView.PartialRefresh (esriViewDrawPhase.esriViewGraphics, Type.Missing,

NamespacesMay need to manually add to code since not required VB NET

Type.Missing);Type.Missing);

– May need to manually add to code since not required VB .NET

Page 45: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Additional Resources - Deployment

Use regasm.exe to register .NET Assemblies

Component categories done automatically with .NET project– http://edndoc.esri.com/arcobjects/9.2/NET/33903846-919f-48b4-a4b1-

ef97680ddb7b.htm

Learn more about deploying ArcGIS Desktop and Engine .NET applicationsapplications

– Thursday 3/26/09 11:15am – 11:30am Mesquite C

Page 46: Migrating VBA/VB6 ArcObjects Applications to · 2009-04-02 · Schedule Todayypgpp we will cover providing practical experience in migrating ArcObjects code from VBA/VB6 to .NET –

Want to Learn More?Want to Learn More?ESRI Training and Education ResourcesESRI Training and Education Resources

•• InstructorInstructor--Led TrainingLed Training–– Developing Applications with ArcGIS Engine Using the Microsoft .NET FrameworkDeveloping Applications with ArcGIS Engine Using the Microsoft .NET Framework

http://www esri com/traininghttp://www esri com/training–– http://www.esri.com/traininghttp://www.esri.com/training

Additional ResourcesAdditional Resources

•• Tech Talk Tech Talk •• ESRI Resource CentersESRI Resource Centers

Questions, answers and information…Questions, answers and information…

–– Outside this room right now!Outside this room right now! –– PPTs, code and videoPPTs, code and video

resources.esri.comresources.esri.com

Session Attendees:Session Attendees:Please turn in your session evaluations.Please turn in your session evaluations.

. . . Thank you. . . Thank you