enhancing visual basic .net applications far beyond the scope of visual basic 6.0

454
“How to do the things that you used to do under VB6 even better under VB.NET, and how to make your VB.NET applications accomplish so very much more.” Written and Edited by David Ross Goben Copyright © 2010-2014 by David Ross Goben All rights reserved. (Last updated February 14, 2015) (The above two logos are registered trademarks of Microsoft Corporation) This title was originally published as “Visual Basic .NET Compared to Visual Basic 6.0” in July, 2010. NOTE: If you have trouble downloading a PDF copy of this document, go to Google Docs and download it freely: https://docs.google.com/file/d/0B_Dj_dKazINlMmUwOGFjZTktNTI1ZS00NDgzLWIwNWUtYTMzNzc0Yjk2NWIx/edit?usp=sharing

Upload: david-g

Post on 06-May-2015

9.064 views

Category:

Technology


13 download

DESCRIPTION

Taking what one learned under VB6 and turbo charge it with VB.NET savvy. This document reviews the fundamental differences between VB6 and VB.NET, and how to deal with and exploit those changes. A plethora of solution examples are featured. Numerous articles are also included, demonstrating often simple coding techniques to accomplish amazing feats for what many online have claimed was impossible.

TRANSCRIPT

  • 1.How to do the things that you used to do under VB6 even better under VB.NET, and how to make your VB.NET applications accomplish so very much more. Written and Edited by David Ross Goben Copyright 2010-2014 by David Ross Goben All rights reserved. (Last updated February 14, 2015) (The above two logos are registered trademarks of Microsoft Corporation) This title was originally published as Visual Basic .NET Compared to Visual Basic 6.0 in July, 2010. NOTE: If you have trouble downloading a PDF copy of this document, go to Google Docs and download it freely: https://docs.google.com/file/d/0B_Dj_dKazINlMmUwOGFjZTktNTI1ZS00NDgzLWIwNWUtYTMzNzc0Yjk2NWIx/edit?usp=sharing

2. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 2 Table of Contents Introduction...........................................................................................................................................8 Why Is VB.NET Not 100% Compatible with VB6?.......................................................................................9 Why .NET?..................................................................................................................................................10 What is .NET?...................................................................................................................................................... 11 What is the .NET Framework? .............................................................................................................................. 11 What is a Namespace?......................................................................................................................................... 12 What is an Application Domain?............................................................................................................................ 13 What is a Solution/Assembly?............................................................................................................................... 13 What is a Project? ................................................................................................................................................ 14 Object Oriented Programming....................................................................................................................14 Classes and Objects............................................................................................................................................. 15 Fields, Properties, Methods, and Events ............................................................................................................... 16 Encapsulation, Inheritance, and Polymorphism...................................................................................................... 17 Overloading, Overriding, and Shadowing............................................................................................................... 17 Scoping Rules...................................................................................................................................................... 18 My Basic Guidelines for VB.NET Development .........................................................................................19 Conclusion to the Introduction....................................................................................................................19 Noteworthy VB.NET Features That Differ from, or are New to VB6.................................................21 Notes Regarding the VB6 Compatibility Library.........................................................................................21 Notes Regarding All String Variables in VB.NET Now Being Reference Types........................................22 Notes Regarding Sending Structures to P/Invokes....................................................................................23 Notes Regarding Fixed-Length Strings ......................................................................................................23 A Note Regarding Passing Parameters ByVal...........................................................................................25 A Note Regarding Returning Value Data via the Return Command from Functions.................................25 A Note Regarding Multi-Variable Declaration.............................................................................................25 Notes Regarding Collections Now Storing Objects, Not Simple Strings....................................................26 A Note Regarding VB.NET Default Properties That Cannot Be Parameterless........................................27 A Note Regarding VB.NET Having Dropped the Let Keyword.................................................................27 A Note Regarding New and Wider Variable Definitions.............................................................................28 A Note Regarding Edit and Continue .........................................................................................................28 Notes Regarding the VB.NET GET/SET Property Format.........................................................................28 A Note Regarding the Support of UsingEnd Using.................................................................................29 A Note Regarding the New IsNot Keyword...............................................................................................29 A Note Regarding the New AndAlso Keyword..........................................................................................29 A Note Regarding the New OrElse Keyword............................................................................................29 A Note Regarding Overloading, and Why We Should Welcome It ............................................................29 A Note Regarding New Variable Types SByte, UShort, UInteger, ULong, and UIntPtr ............................30 A Note Regarding Partial Classes and Structures .....................................................................................30 A Note Regarding Form-Linked Controls ...................................................................................................30 A Note Regarding Better IntelliSense.........................................................................................................31 A Note Regarding Accessing Common or All Options in IntelliSense Popups..........................................31 A Note Regarding Snippets........................................................................................................................31 A Note Regarding the Exception Assistant ................................................................................................31 A Note Regarding the Immediate Window .................................................................................................31 A Note Regarding Debug Trace Enhancements........................................................................................31 A Note Regarding the Continue Statement................................................................................................31 A Note Regarding Data Source Binding.....................................................................................................31 A Note Regarding the Conditional Operator...............................................................................................31 A Note Regarding Structured Exception Handling.....................................................................................32 A Note Regarding Type Inference..............................................................................................................32 A Note Regarding Anonymous Typing.......................................................................................................32 A Note Regarding Enumerators .................................................................................................................32 A Note Regarding Optional Event Parameters...........................................................................................32 Notes Regarding the MY Namespace........................................................................................................33 Notes Regarding Class Construction and Destruction...............................................................................33 Notes Regarding New Style P/Invoke Signatures......................................................................................36 3. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 3 A Note Regarding the VB.NET Event Firing Sequence .............................................................................40 Notes Regarding Form Command Changes..............................................................................................40 Notes Regarding MouseMove Event Parameters......................................................................................43 A Note Regarding Type Object as the New Universal Data Type .............................................................45 A Note Regarding the Instance Handle......................................................................................................45 A Note Regarding Checking For a Previous Application Instance.............................................................46 A Note Regarding Getting the App Title.....................................................................................................46 A Note Regarding Getting the App Path and the App EXE Name..................................................................46 A Note Regarding Reviving the VB6 App Command.................................................................................47 Notes Regarding Registry I/O.....................................................................................................................49 A Note Regarding Collections Enhancements ...........................................................................................49 A Note Regarding Literal Type Characters ................................................................................................50 A Note Regarding Adjusting Form Opacity (Transparency).......................................................................50 Notes Regarding Loading Images..............................................................................................................50 Notes Regarding Loading Icons .................................................................................................................51 Notes Regarding Embedding Classes........................................................................................................52 Notes Regarding Accessing Private Class Members from a Sister Object ...............................................52 Featured Articles 54 VB.NET Generics Collection Classes................................................................................................55 How to Perform Easy Font Manipulation at Runtime under VB.NET...............................................58 Easily Change Font Sizes at Runtime...........................................................................................................58 Easily Change Font Styles at Runtime (Bold, Italic, Underline, and Strikethrough) ........................................58 Easily Change Font Names at Runtime ........................................................................................................59 Building a Suite of Runtime Font Modification Tools......................................................................................60 Drawing Labels with Transparent Backgrounds over Images.........................................................62 Easily Placing Labels with Transparent Backgrounds over Controls..............................................................62 Painting Text Directly onto Controls with Ease..............................................................................................64 Emulating VB6 Image Control Features in VB.NET..........................................................................65 Painting Images on a Form...........................................................................................................................65 Image Rendering over Multiple Form Objects ...............................................................................................72 Emulating What VB6 Image Controls Do Using a Borderless Form...............................................................74 Room for Improvement....................................................................................................................................... 76 Emulating What VB6 Image Controls Do Using a PictureBox........................................................................81 Emulating What VB6 Image Controls Do Using a Resource Icon ..................................................................82 Super-Fast No-Holds-Barred VB6 Image Emulation......................................................................................84 Emulating Mouse Interaction on Drawn Images............................................................................................84 Conclusion ...................................................................................................................................................85 Implementing Unions in VB.NET .......................................................................................................86 Understanding VB.NET Imports.........................................................................................................90 Namespaces, Modules, and Non-Inheritable Local Classes: Siblings by Different Names..............90 Using Imports Aliases .....................................................................................................................90 Referencing Class Data without Importing or Instantiation..............................................................91 Understanding VB.NET Delegates.....................................................................................................92 Delegates in Events .....................................................................................................................................92 Delegates and AddressOf.............................................................................................................................93 Delegates and Callbacks..............................................................................................................................94 Invoking Methods through Delegates............................................................................................................95 Using a Delegate to Perform Super-Fast Shell-Metzner Sorts on Any 1D Array.............................................96 VB.NET Structures Compared to VB6 User-Defined Types...........................................................101 Releasing COM Objects from Memory in VB.NET..........................................................................104 Changed Behavior of VB6 Functions in VB.NET............................................................................105 Array Function...........................................................................................................................................105 Dir Function ...............................................................................................................................................105 Get#, Put# Functions.................................................................................................................................105 IsObject Function ......................................................................................................................................105 Mod Operator ............................................................................................................................................106 4. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 4 Return Statement ......................................................................................................................................106 SavePicture Statement..............................................................................................................................106 Str Function ...............................................................................................................................................106 TypeName Function ..................................................................................................................................106 TypeOf Function........................................................................................................................................107 VarType Function ......................................................................................................................................107 Upgrading Win32 Data Types for VB.NET P/Invokes .....................................................................108 Fix-Length Strings......................................................................................................................................108 Strings Used in Interfaces...........................................................................................................................109 Strings Used in Platform Invoke..................................................................................................................109 Strings Used in Structures..........................................................................................................................110 Fixed-Length String Buffers........................................................................................................................111 Dealing with As Any in P/Invoke Signatures .............................................................................................111 Using the AsAny Marshalling Parameter.....................................................................................................112 Thread Creation, Queue Hooking, and Other Special P/Invoke Features ....................................................113 String Formats Changes between VB6 and VB.NET ......................................................................114 Marshaling Memory and Passing Strings to P/Invokes in VB.NET................................................116 Upgrading Administrative Rights Checks.......................................................................................120 Running applications that require Administrative Privileges.........................................................................120 Check for the User having Administrative Rights.........................................................................................121 Running Applications Requiring Administrative Rights without Being Prompted ..........................................121 Disabling User Account Control through your User Account Settings ..................................................................................122 Disabling User Account Control through the Control Panel..................................................................................................122 Disabling User Account Control through MSCONFIG ..........................................................................................................122 Disabling User Account Control through Editing the Registry...............................................................................................122 Adding Run-Time Custom Menus to VB.NET .................................................................................123 Understanding Menus by Converting a MenuStrip to a MainMenu ..............................................................123 Optimizing MainMenu Design Code............................................................................................................127 Building ContextMenuStrip PopUp Menus on the Fly..................................................................................130 Cloning MenuStrip Items with a Custom CloneMenuStripItem Method ........................................................131 Using CloneMenuStripItem to Create a New MergeMenuStrip Method........................................................132 Simplifying the Construction of Custom Code for the CloneMenuStrip Method............................................133 Conclusion .................................................................................................................................................135 Adding Window and File Lists to VB.NET Menus.......................................................................... 136 Maintaining an Active Child Windows List............................................................................................... 136 Adding an Open Window List to a VB.NET MenuStrip menu................................................................................ 137 Adding a MainMenu and ContextMenu control to your VB.NET Toolbox............................................................... 137 Maintaining a Most Recently Used File List ............................................................................................ 138 MRU File Support under VB6.............................................................................................................................. 138 MRU File Support under VB.NET........................................................................................................................ 142 Flicker-Free VB.NET Form Resizing ................................................................................................147 The Minimalist Solution for Form Resizing Flicker...................................................................................148 Adding a Little Pizzazz to the Minimalist Solution....................................................................................149 Adding More Pizzazz to Build a More Stable Solution.............................................................................149 Adding Alotta Pizzazz: Professional Results by Intercepting the Windows Message Queue .................150 Form Resize Subclassing under VB6............................................................................................................... 151 Form Resize Subclassing under VB.NET......................................................................................................... 153 Easy Ways to Draw Lines and Shapes, and to Paint in VB.NET....................................................157 First, News of Free VB.NET Line and Shape Controls ............................................................................157 Drawing Lines from the Paint Event .........................................................................................................157 Drawing Rectangles from the Paint Event................................................................................................159 Drawing Ellipses (Circular Shapes) from the Paint Event........................................................................160 Painting Backgrounds with Patterns.........................................................................................................161 Painting the Background of Odd Shapes Using a Flood Fill....................................................................163 GDI-Based FloodFill.......................................................................................................................................... 163 GDI+ FloodFill................................................................................................................................................... 165 Drawing Other Shapes from the Paint Event ...........................................................................................169 Drawing Super-Fast Rounded Rectangles from the Paint Event.............................................................169 Drawing Shapes Outside of the Paint Event ............................................................................................174 5. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 5 Conclusion ................................................................................................................................................174 Adding Icons to ListBoxes and ComboBoxes with Ease under VB.NET......................................175 Principle features of an Owner-Drawn ListBox (and ComboBox)............................................................175 Using A Generic List Collection and an ImageListControl .......................................................................176 Using A Flag at the Start of the List Item Text..........................................................................................177 Using a Custom Class as a List Item to Index Graphics..........................................................................178 Centering a Message Box on a Form under VB.NET......................................................................179 The Simple Explanation of Centering a Message Box on a Form ...........................................................179 Some Background Information .................................................................................................................179 A More Detailed Explanation of Centering a Message Box on a Form....................................................180 The Detailed Explanation of Centering a Message Box on a Form .........................................................180 Putting It All Together ...............................................................................................................................184 Restoring Raster Graphics and Rubber Bands to .NET................................................................ 186 Getting an Image Graphics Object Without Going Through the Paint() Event........................................ 187 Restoring Raster Operations to .NET...................................................................................................... 187 Getting Ones Hands Dirty................................................................................................................................... 188 The GDI32 Class ................................................................................................................................................ 190 Emulating a Selection Rubber Band under GDI...................................................................................... 196 Emulating a Selection Rubber Band under GDI+.................................................................................... 197 Using the GDI+ DrawReversibleFrame() Method.................................................................................................. 197 Using the GDI+ DrawRectangle() Method and a Translucent Brush...................................................................... 199 Extending VB.NET Controls Functionality..................................................................................... 201 Demonstrating Control Extension Using the VB.NET ComboBox (and ListBox).................................... 201 Win32 ComboBox Messages............................................................................................................................... 202 The CB_DIR Message (and how to make it work under VB.NET) ......................................................................... 203 The CB_SETTOPINDEX and CB_GETTOPINDEX Messages.............................................................................. 206 The CB_SETEXTENDEDUI and CB_GETEXTENDEDUI Messages..................................................................... 207 The CB_SETCURSEL Message.......................................................................................................................... 208 Adding a CheckBox to the Edit Field of a ComboBox ........................................................................................... 209 Sizing the ComboBox DropDown List Width......................................................................................................... 210 Sizing the ComboBox DropDown List Height........................................................................................................ 212 Adding the DriveListBox, DirListBox, and FileListBox Controls to VB.NET ............................................ 213 Send (SMTP) and Retrieve (POP3) Email with Ease under VB.NET ............................................. 215 Adding the VB6 MAPISession and MAPIMessage Controls to VB.NET................................................. 215 PART ONE ----------------------------------------------------------------------------------------------------------------------------------- Sending Email under VB.NET using Native Methods ....................................................................... 216 Quick and Dirty Email Senders .................................................................................................................... 216 TCP Ports, SSL Authentication, and Creating Credentials............................................................................. 218 An Email Sender with a Lot of Muscle .......................................................................................................... 219 Sending Email Messages as HTML ........................................................................................................................... 221 Sending Alternate Message Views.............................................................................................................................. 223 Sending Alternate Message Views with Different Context Types and Transfer Encoding ........................................... 226 Typical Email Server Specifications ..................................................................................................................230 PART TWO ---------------------------------------------------------------------------------------------------------------------------------- Encoding and Decoding Email Data.................................................................................................. 231 Allowing Users to Specify Content-Type and Content-Transfer-Encoding Options ......................................... 232 Determining if Text can be Encoded As Quoted-Printable, Base64, or 7Bit.................................................... 234 Converting 8-Bit HTML Data to 7-Bit without Loss of Integrity........................................................................ 234 Converting 8-Bit Text Data to 7-Bit without Data Loss................................................................................... 235 Decoding Quoted-Printable Text .................................................................................................................. 236 Translating Base64 Data Back to Its Original Format.................................................................................... 236 Translating BinHex Data Back to its Original Format..................................................................................... 239 PART THREE ------------------------------------------------------------------------------------------------------------------------------- Receiving Email under VB.NET using Native Methods..................................................................... 240 Connecting to a POP3 Server...................................................................................................................... 243 Checking for a POP3 Server Response........................................................................................................ 244 Checking for Being Connected to a POP3 Server......................................................................................... 244 Getting a Response from the POP3 Server .................................................................................................. 244 Submitting a Request to the POP3 Server.................................................................................................... 246 Disconnecting from the POP3 Server........................................................................................................... 246 6. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 6 Getting Email Statistics from the POP3 Server ............................................................................................. 247 Getting an Email Reference List from the POP3 Server ................................................................................ 247 Get an Email Header from the POP3 Server................................................................................................. 248 Retrieve an Email from the POP3 Server ..................................................................................................... 249 Deleting an Email from the POP3 Server...................................................................................................... 249 Reset (Undo) All Deletes from the POP3 Server........................................................................................... 250 Send a Keep-Alive NOOP Command to the POP3 Server........................................................................... 250 Disposing of Resources............................................................................................................................... 250 Using the Completed POP3 Class ............................................................................................................... 251 PART FOUR -------------------------------------------------------------------------------------------------------------------------------- Email Data Blocks Made Easy .......................................................................................................... 252 Easily Extracting the Component Parts from an Email File............................................................................. 255 Compiling Everything into an Email Class Library ............................................................................ 257 Building the VBNetMail Class Library............................................................................................................ 259 Accessing your New VBNetEmail Class Library DLL from another Project...................................................... 259 The Complete SMTP.VB File ............................................................................................................ 260 The Complete POP3.VB File............................................................................................................. 260 The Complete Utilities.VB File........................................................................................................... 267 Conclusion.............................................................................................................................................. 274 Useful References 275 Comparing Visual Basic System I/O Commands......................................................................276 REALLY Looking under the Hood of Visual Basic .NET ..........................................................278 VB6 Changed Commands In VB.NET ........................................................................................280 VB6 Aficionado Complaint Department (116 VB6 User Complaints against VB.NET Answered) .........................................................................................................................................292 Additional "Black Book" Tips 319 Black Book Tip # 1: Bypassing Click Events when a Context Menus is Not Displayed on a Right-Click .....320 Bonus Tip.........................................................................................................................................321 Black Book Tip # 2: Creating an Association between a File Extension and Your Application....................322 Black Book Tip # 3: Get the Linked File Path from a Shortcut File.............................................................325 Bonus Tip.........................................................................................................................................326 Black Book Tip # 4: Create a Shortcut File within Your Code ....................................................................327 Bonus Tip.........................................................................................................................................328 Black Book Tip # 5: Adding a File to the Recent Documents Folder..........................................................329 Black Book Tip # 6: Sorting Any Column in a ListView Control in Ascending or Descending Order............330 Black Book Tip # 7: Sizing a Label or TextBox to Fully Contain a String for Display ..................................333 Black Book Tip # 8: Set a New SelectedIndex for a ListBox or a ComboBox without Firing its Click Event.336 Black Book Tip # 9: Display TextBox Text Format-Justified at Runtime.....................................................338 Bonus Tip 1......................................................................................................................................343 Bonus Tip 2......................................................................................................................................343 Black Book Tip # 10: Get The ListIndex of a ListBox Row that is Under the Mouse Cursor........................344 Black Book Tip # 11: Open Windows Explorer with a Target File Selected................................................345 Black Book Tip # 12: Determining if an array is Dimensioned....................................................................346 Black Book Tip # 13: Customizing the Display of TabControl Tabs ...........................................................347 Bonus Tip.........................................................................................................................................351 Black Book Tip # 14: Detecting a TabControl Tab on a Right MouseDown Event......................................352 Black Book Tip # 15: Prevent the User from Selecting a TabControl Tab ..................................................353 Black Book Tip # 16: Hiding Tab Pages without Destroying the Tab Pages or their Resources .................354 Black Book Tip # 17: Passing a Parameter ByVal when the Invoking Function Specifies a ByRef Parameter...357 Black Book Tip # 18: Show and Hide Additional Information at the Bottom of the Form.............................358 Black Book Tip # 19: Easily Recovering Crashed Menus and Toolbars under VB.NET..............................361 Black Book Tip # 20: Tracking ComboBox Items under the Mouse ...........................................................367 Black Book Tip # 21: Greatly Simplifying P/Invoke Definitions of POINTAPI and RECT Structures............370 Black Book Tip # 22: Easily Sorting Strongly-Typed Generics Collection Lists ..........................................376 Black Book Tip # 23: Dithering a Forms Background.........................................................................380 Black Book Tip # 24: Designing Intelligent Context Menus for TextBox and RichTextBox Controls ..........383 7. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 7 Black Book Tip # 25: Setting Context Menu Icon Image Transparency at Runtime....................................387 Bonus Tip # 1...................................................................................................................................389 Bonus Tip # 2...................................................................................................................................390 Black Book Tip # 26: Adding Background Transparency to Images on Toolstrips and Menus..................391 Black Book Tip # 27: Easily Do a Redim Preserve with Leftward Bounds of Multi-dimensioned Arrays....394 Black Book Tip # 28: Implementing a C-Style Bit Field Class in VB.NET ..............................................398 Black Book Tip # 29: Taking Advantage of, and Extending Application Events......................................409 Black Book Tip # 30: Enable Built-In Justify-Alignment in a RichTextBox from VB.NET.............................412 Black Book Tip # 31: Easily Replace Power Pack Shape Controls with Paint() Event code .......................416 Black Book Tip # 32: Dealing with the Form Cursor not displaying over Form Controls .............................425 Black Book Tip # 33: Passing Scalar Values and Strings to and from a Byte Array....................................427 Black Book Tip # 34: Display Buttons Labels wider than the button normally allows..................................437 Black Book Tip # 35: Performing Selections or inserting RichText Data Off-screen without Scrolling.........439 Black Book Tip # 36: Opening an Associated Application without a File....................................................442 Black Book Tip # 37: Comparing Color Values..........................................................................................446 Closing Remarks ..............................................................................................................................447 About the Author ..............................................................................................................................449 Free Online PDF Documents Available by David Ross Goben.....................................................................450 Open Letters Sent to Advocates for the Electric Universe and Expansion Tectonics Theories.....................450 Navigating Your Way through Visual Basic 6.0 to Visual Basic .NET Application Upgrades ........................451 Enhancing Visual Basic .NET Applications Far Beyond the Scope of Visual Basic 6.0................................452 Doom 3 Walkthrough and Strategy Guide ..................................................................................................453 Also Available from the Author......................................................................................................................454 A Gnostic Cycle: Exploring the Origin of Christianity ...................................................................................454 NOTE: This manual was first written when VB2008 was still a new product. Presently VB2013 is the current contender, but the contents of this manual are still fully applicable to the VB2010, 2012, and VB2013 environments. Further, the Upgrade Wizard referenced herein was last available in VB2008, which is still available in its free Microsoft Visual Basic 2008 Express edition. Also, it is my feeling that VB2008 has so far actually been their very best effort, where Microsoft finally fully realizing their Dot NET philosophy in Visual Basic (though, having said that, VB2010 is my new absolute favorite). Although VB2005 was a decent start, I have always looked at it as more of a Release Candidate for Visual Basic .NET, because translating between VB6 and VB2005 was still sometimes a rather tricky and often frustratingly complicated effort, almost always never worth all the effort. VB2002 and VB2003 were extremely poor implementations that were filled with too often convoluted, complicated trash that should have never been found or accepted within the Dot NET environment. It is my feeling that they should have never bothered releasing any of that code for sale, except to those who wanted to freely download and Beta test it, and to report bugs and enhancement suggestions (though we must recognize that they had to recoupe their development costs, somehow). It is my strongest feeling that VB6 should have been fully and aggressively supported through the release cycle of VB2008, not the marginalized nodding support that it received through the release of VB2008. Until that time, Microsoft should have more assertively supported extensions to forms and the ability to access Dot NET forms, workspaces, and code until that time (as it was, they did in fact do this, but no one in the VB6 community ever seemed to be aware of it), easing the VB6 transition from its procedural code platform roots to the more powerful Object Oriented world of Dot NET. Unlike the claims made by many critics from the VB6 field, everything that can be done in VB6 can be easily accomplished using Dot NET as of VB2008, no longer requiring convoluted alternative solutions or intense, deep research to find a compatible alternative for a simple feature. However, many developers do not have for, or may never have a need for object-based programming, and VB6 still fills that procedural language niche for VB. 8. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 8 Introduction Transitioning from Microsoft Visual Basic 6.0 (VB6) to Microsoft Visual Basic .NET (VB.NET1 ), at first glance, may look to be an intimidating endeavor. After all, you have likely heard or read through copious magazines and blogs that there are huge differences between these two developmental platforms. Though some of those differences are real, most of them are simply imagined, engendered by nothing more than unapprised conjecture. Of the real platform deviations, most are simply due to them having to be expressed differently; plainly because VB.NET strictly follows a stringent pattern of uniform language syntax, which is something VB6 was not always good at. Hence, a programming language feature may have to be implemented under VB.NET using a radically different access conduit than the way it may have been realized under VB6. Other disparities, some seen as much more profound, actually end up being VB6 features that VB.NET does in fact support, but, again, due to tight .NET platform architectural specifications, VB.NET cannot support them in an identical manner, but may by necessity have to utilize non-VB6-style invocation rules. Nevertheless, by employing some simple user- defined helper functions, such as will be demonstrated throughout this document, you can easily emulate lost VB6 commands, or, in most cases, make their functionality more accessible through simpler syntax. Regardless, you will find that, overall, VB.NET supports all these many differences, both major and minor, in but different forms, and in all it also implements much more robust2 techniques to apply their functionality. Many of the major differences bemoaned by many VB6 purists3 no longer exist; having existed only in Beta releases of VB.NET, but being addressed by the time of the initial product launch, or, in more complex cases, in later releases. See the article, VB6 Aficionado Complaint Department (116 VB6 User Complaints against VB.NET Answered), on page 292 to examine these numerous charges many VB6 devotees hold against VB.NET, and how all but a pittance of them are groundless. And of those few that are not groundless, they are actually quite easily resolved, rendering as petty the remainder of those complaints. Instead of simply adding some nifty .NET features to VB6 and calling it VB.NET (they actually did do it with their Microsoft Interop Forms Toolkit 2.0 (http://msdn.microsoft.com/en-us/vstudio/aa701257.aspx), allowing a step- wise transition of VB6 apps to VB.NET), after long debate Microsoft chose the far more laborious task of reengineering VB from the ground up, making it fully .NET compliant. Considering the monumental work involved to accomplish such a task, this could not have been a very easy decision. For example, VB.NET sports two powerful forms packages called Windows Forms and Web Forms; a new and more powerful version of ADO to easily access disconnected data sources; a much more logical, much more powerful and feature-rich structured language that also removes or replaces many legacy or hacked commands that no longer had meaning or had a complicated or convoluted structure; greatly improved type safety; exposing low-level data that advanced developers need to access; and made it easier to write distributed applications. This bounty of new VB.NET features opened an abundance of doors that were previously inaccessible to VB6 developers. With Web Forms and ADO.NET, one can quickly develop scalable Web sites. With inheritance, the language now fully supports object-oriented programming. Windows Forms fully support accessibility and visual inheritance; and deploying applications is now as simple as copying your executables and components from directory to directory, often referred to as XCOPY deployment, so you no longer need to worry about DLL versioning issues. With VB.NET, this versioning danger and the resulting intense aggravation (often referred to as DLL Hell4 ) is a thing of the past. 1 VB.NET is pronounced V-B-Dot-Net; just as .NET is pronounced Dot-Net, and VB6 is pronounced V-B-Six. I have also heard them pronounced Vib-Net and Vib-Six. 2 Robust: Bullet-proof; bug-proof. This usually implies sturdy code that is written to avoid errors, using strong types and error-trapping. 3 I find the term VB6 Purists to be humorous, because VB6 is not a pure language by any measure, but rather a mongrel mix of really cool features and concepts, added to by a hodge-podge of hacks and fixes, starting with VB1, chiseled together with brilliance, tricks, hacks and work-arounds to provide a GUI and windows forms to what was otherwise DOS-level QuickBasic. Even so, VB6 was for years my personal favorite. But the point remains that its language is structurally convoluted, often clumsy, and its program structure precluded much more modern programming concepts. 4 DLL Hell: When an older version of a DLL overwrites a newer DLL, and suddenly previously working applications start blowing up because they cannot find entry points in the DLL that had previously existed in the newer version of that DLL.This also includes newer DLLs that dropped older entry points, which clearly should be a developmental no-no in professional-grade applications. 9. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 9 As importantly, VB.NET now fully integrates with the other Microsoft Visual Studio .NET languages. You can even develop application components in different programming languages, and your classes can now inherit from classes written in other languages using cross-language inheritance. With a unified debugger, you can now debug multiple language applications, irrespective of whether they are running locally or on remote computers. Whatever .NET language you use, the .NET Framework provides a rich set of Application Programming Interfaces (APIs) for Microsoft Windows and the Internet, that are now, in the .NET world, commonly referred to as P/Invokes or Pinvokes; meaning Platform Invokes5 or Processor Invocations. Why Is VB.NET Not 100% Compatible with VB6? Why does VB.NET not fully support VB6 code, as written, just as all VB6 and previous editions were able to read and execute previous generations of code? Because many of the things that VB6 supported were not supportive of OOP (Object Oriented Programming). Many of the features VB6 users bemoan the loss of in VB.NET are features that: 1) can be dangerous to the operating environment, but can in fact be implemented by safer means under .NET, 2) are not applicable to the OOP paradigm6 , so .NET- compliant implementations were introduced, or 3) invited the development of less than robust code. VB1-6 used a procedural programming language featuring event-triggered execution. VB.NET, however, is a fully Object Oriented Programming Language (OOPL). These paradigms, procedural and object oriented, are vastly different. To me, it is truly amazing that VB.NET can actually use as much VB6 code, especially unchanged, as it does. Previous to VB.NET, an object oriented language often required colossal program readjustments in order to upgrade a procedural version of its language. A case in point is the structured, though procedural language C, versus the object oriented language C++. Granted, you could compile and execute straight C code, for the most part, using a C++ compiler and successfully execute it, but it would still run as a procedural program. To convert it to use objects as VB.NET requires, entailing forms, controls and such, necessitates exceptional feats of code translation. But the VB.NET Upgrade Wizard (available through VB2008, but sadly missing in later editions, though you can still install VB2008 Express to take advantage of it) does a dazzling job. See my free companion document, Navigating Your Way Through Visual Basic 6.0 to Visual Basic .NET Application Upgrades (www.slideshare.net/davidrossgoben), to learn how to address most every upgraded VB6 program code issue. There were two options that Microsoft had to consider when designing VB .NET: they could simply retrofit the existing code base to run on top of the .NET Framework, but it would still be stuck with being a procedural language, even though it would be able to run VB6 code right off the bat, or they could rebuild VB from the ground up, not taking any shortcuts, not sacrificing even one .NET feature, and in the process take complete advantage of a fully functional object oriented platform. To deliver the features that were most requested by their customers, such as inheritance and threading, to provide full and uninhibited access to the platform and to other platform languages, and to ensure that VB moved forward into the next generation of Web applications, the right, though more burdensome decision was to rebuild VB from the ground up on the .NET platform (and no, it is not a modified version of C#). For example, many, but not all of the new features found in the Windows Forms package could have been added to the existing VB6 code base as new controls or as more properties. However, this would have been to tremendous cost to all the other great features inherent to Windows Forms, such as security and visual inheritance, not to mention that VB.NET would have lost the powerful Web Forms package entirely, which allows your users to access and run code behind your forms directly from your web page without having to install driver code onto their own machines first, as with VB6. See also ASP.NET. 5 P/Invoke or Pinvoke terms are used for two reasons: 1) because API is common to the reference API Calls, and 2) it refers to invoking the processor, which implies something outside of the managed space, which is exactly what it is. Further, these invocation processes are likewise referred to as Signatures, replacing the API Declaration term; tying in with Method Delgates or Method Signatures, which are like C/C++ Prototype Declarations. 6 Paradigm: Organized method of performing a task. 10. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 10 Once on this tract, one of Microsofts principal goals was to ensure that VB.NET code could fully interoperate with methods and classes written in other languages, such as Microsoft Visual C# or Microsoft Visual C++ (and visa versa), without caveats or being forced to implement hidden helper code. Another goal was to enable the VB.NET developer to harness the full power of the .NET Framework simply and with absolutely no impediments, and all without having to resort to internal support workarounds, which were traditionally required just to make Windows P/Invokes work with VB6. An example of such a hack was the code used to work around the inability of VB6 to employ method overloading (also known as function overloading), by introducing the messy and potentially dangerous As Any feature to API Declaration templates. Method overloading, an essential feature common to Object Oriented Programming, allows different methods to employ the very same method name, but each would utilize different parameter counts and/or parameter types. As a result, when you invoke the method name, the compiler will take a look at your parameter list and determine from them which of the like-named methods to actually invoke. This eliminates entirely the need to use an As Any cheat. Method overloading will be demonstrated in several examples later in this document. VB.NET now has the same variable types, arrays, user-defined types, enumerations, classes, and interfaces as does Visual C++ and any other language that targets the .NET CLR (Common Language Runtime). As a result, they also had to remove features that did not play well with the .NET paradigm, such as fixed-length strings and non-zero-based arrays from the VB language, even though this document will show you with detailed examples how to still implement them (both of these features can be easily emulated using super-quick coding techniques, or by very simple user-defined classes). Why .NET? Though the .NET Common Language Runtime operates only on Microsoft Windows and Linux platforms, this will change. As of this writing, development of support for other platforms such as UNIX (which Linux is modeled after) and iMac7 are either in the works, or are being conceptualized (considering that .NETs F# runs on the Mac, it may already have a working CLR). The result of this will be that you can write code in .NET and run that code on various platforms and CPUs without changing the code or even needing to recompile. This is the core purpose behind .NET; to be a multi- platform development environment that can compile on one platform, but execute on many. This sounds almost like the much slower Java scripting platform and its philosophy of write once, run anywhere. Unlike previous versions of Visual Studio, .NET compiles its code into an MIL (Machine Independent Language also referred to as Microsoft Intermediate Language or just as IL). This MIL was carefully developed around advanced CPU (Central Processing Unit) architecture, designed to be as close as possible to the instruction sets for most 32- and 64-bit CPUs (this MIL is technically an actual machine language, yet one for a hypothetical, though ideal CPU, but which can almost instantly be translated to native code with its built-in Just-In-Time Compiler). Soon you may be able to write an application on one platform and then execute it on another without change. This MIL is instantly compiled into native machine code on the target platform by the CLRs just-in-time compiler. Hence, as long as a platform has a Microsoft .NET CLR, your code can run on that platform. Granted, to many this may almost appear to perhaps be an interpreted or a tokenized p-code8 language; it most definitely is not, because its code is not being interpreted at all. It is even rumored that such institutions as Intel and AMD may even be playing with the idea of developing a CPU or an add-on hardware device that will be able to execute MIL code directly, without just-in-time compiling. 7 The iMacs OsX is a Unix-based operating system modeled after Carnegie Mellon Universitys Mach microkernel, which was in turn an upgrade/replacement for BSDs FreeBSD and NETBSD implementations of UNIX. BSD is presently devoting heavily into research and development in the .NET direction. 8 P-code: Pseudo-code. This is an intermediate, tokenized version of a program, popular with many in-house development languages, which, though still interpreted on many platforms, it also runs much faster than interpreting text source code because the code is already in an intermediate state between the source code and the CPU machine code. 11. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 11 What is .NET? The .NET environment is filled with terminology, such as the above, which might be unfamiliar to most VB6 programmers. Understanding this terminology and what they imply in the scheme of things will go a long way toward making sense of it, and turn people out there into .NET developers. Rest assured that you do not have to fully understand most of it when you first get started, and you can most probably get along by knowing virtually nothing about it, to start. The great thing about it is that you can get started developing code without having to understand every little stinking thing before you can write anything. Obviously, a fuller understanding of it is immensely helpful, but you can safely relegate such comprehension to periods when you have time to do so (picking this stuff up will also present you with some really cool tricks that you can use to spiff up your code). But trying to absorb everything all at once will only result in you forgetting most of it, and causing you anxiety due to information over-load. Basically, the entire .NET environment is wrapped within by a thing called the .NET Framework. This framework must, like any new technology, be installed on a system before one can use it. Before some start to complain, this approach is no different though nowhere nearly as complicated as requiring someone to install a Windows Operating System prior to them being able to run applications designed for a particular Windows environment. If you have been using computers long enough, you can probably remember saving your pennies to get the Level II BASIC upgrade for the TRS-80 Model I computer so that you could write real programs beyond its primitive Level I Tiny BASIC. Presently, all recent versions of Windows have come with the .NET Framework pre-installed (or can download them free of charge), just as it is standard for computers to come with an Operating System installed. What is the .NET Framework? In a nutshell, the .NET Framework is a logical tree-structure filled with classes. At the very root of this structure is a single class called Object. From this primitive class all other classes in .NET are derived. Each more complex class object normally uses (inherits) a simpler base class as its foundation. This progression goes ever on, until you have truly complex classes the bear little resemblance to that ancestral root class, but none-the-less shares, as a part of its bag of tricks, the basic interfaces of that root class. On the surface, however, constructing them is just like constructing VB6 classes and modules. You may have caught on that the framework is filled with classes. Indeed, it is filled with nothing but classes. This is the first thing that you should remember everything in the .NET environment, even a form or a module, is actually a class or an instance of one (an object). And normal variables? They are also class objects, albeit a variation called abstract classes, but nonetheless can feature properties and methods. Even your regular VB Module files are actually classes, where all exposed (Public/Friend) members are internally treated as Shared Friend, and the module is automatically imported internally so that you do not need to fully qualify a methods or propertys name by using the module class name in order to access it (though you can if you want to). Still sound strange or confusing? No worries; we will clarify these points soon enough. NOTE: The most important differences between Concrete and Abstract classes are these: Concrete classes must be instantiated using the New keyword, and during basic copying they will simply pass a reference to themselves. Abstract classes do not have to be instantiated and also automatically clone themselves (make new copies) when assigned to a different variable. This makes them a bit messy because they can copy themselves all over the place, but they do clean up quite easily when they go out of scope. I said the structure of the .NET Framework was like a tree. This implies branches and leaves. Indeed, it is formatted much like the directory structure of a disc drive, where each branching node (which is defined as a special non-inheritable class) is referred to as a Namespace, which envelopes a collection of related classes, where these classes are the nodes, being child classes embedded within their parent namespace class. This is on top of the fact that classes within this framework can also be design to be a branching tree. Indeed, .NET Namespaces simply organize classes into groups of subclasses that are usually expected to work together. The structure of the .NET Framework is composed of terms such as Namespaces, Application Domains, Assemblies, Solutions, and Projects. Let's take a quick look as these from the outside, in. 12. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 12 What is a Namespace? Everything within the .NET Framework, to include every program that you develop, are each wrapped inside a thing called a namespace (wrapper class), though most new .NET developers may not even be aware of it. When you create a new project, one of the properties of the project is a Namespace. By default, the name given the namespace is the same as the firstand usually the onlyproject. However, if you have multiple classes defined in separate solutions that are related to each other, you may wish to change the default namespace for each such project to be identical if these projects will be working closely with each other. A namespace is actually a non-inheritable class wrapper than envelops a project. When you import another namespace into a project, that namespace class is auto-instantiated, and all of its non-private members, which may be classes, enumerations, properties, or methods, are treated as Shared Friend by the other members of the source file, which can be accessed by the whole application, or, if you wish, just by selected source files if the namespace had been specifically imported into them. However, it is inaccessible from outside applications, if, for example, your project is a DLL. Again, a namespace is non-inheritable; you are prevented from instantiating a namespace to an object (this would be pointless, anyway). In much simpler terms, adding a namespace is exactly like adding an invisible VB Module file to your application. Namespaces do not follow any stringent organizational rules regarding the classes that can be defined within them. It is simply a convenience for the developer that related classes can be declared within them, just like with a disc folder sure, you can put anything into them, but it makes more sense to place things that have something to do with each other, or is considered a part of a suite of solutions for something. Hence, grouping of classes within a namespace is a bit of an esoteric art. But keeping related classes together is just common sense. It is like defining properties and methods for a class; you normally define only properties and methods for a class that actually have something to do with that class. Anything else is useless and poor design. Likewise, a namespace would hold classes that have something to do with each other. For example, there is a namespace named Microsoft.VisualBasic. The VisualBasic namespace is a child namespace of the Microsoft namespace (there are basically two root namespaces System and Microsoft and everything else, as far as the .NET Framework goes, branches from them as sub-classes). The VisualBasic namespace holds classes relating to VB.NET. For examples, the Constants and ControlChars enumerations are children of the VisualBasic namespace. Within the VisualBasic namespace you will find most classes, methods, enumerations, constants, and properties relating to VB.NET (you therefore will of course not find language- specific syntax keywords there, such as If, Then, Else, etc.). You can bring up the Object Browser from the View menu and explore these namespaces and classes for yourself. A great hint for VB2008 users is to have the Dynamic Help tab open and in view (found in the VB2008 Help menu, but sadly gone as of VB2010), so as you click items in the Object Browser, you can use the Dynamic Help to explore them in exhaustive detail. Dynamic Help should be one of your new best friends, and will help you find answers to anything that you find of interest. Unlike Visual Studio 6, the .NET Help System is not mostly directed at C++, but is directed at all CLR languages (of which VB.NET is a full member), featuring VB examples for all related features. A cool trick here, even if you are writing code in C# or C++, is that you can actually access the Visual Basic classes and invoke their functionality. This is really handy when there is a VB-only method that you want to take advantage of from non-VB language code. Conversely, if your VB.NET code needs to use something like pointer manipulation, where you would change data through pointers (pointers are often used to target actual memory locations), then you can write such code in C# or C++ and invoke it from VB.NET, even though you can in fact do such from VB.NET by using deeper .NET features and processor invocations, as will also be demonstrated later within this document. We will briefly discuss how to access namespaces (referencing and importing) when we take a look at the structure of code. Suffice it to say for now that there are four types of objects that can be created at the namespace level: Classes, Modules, Structures, and Enumerations. Also, each can be defined with a scope of Private, Public, Friend, or Protected. Private members will be visible only to within the structure or code block they are declared within. Public members can be accessed from outside the class, to include by other 13. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 13 applications that can access its parent, such as a DLL. Friend members are treated by the application as if Public, but as Private to all outside applications that could otherwise access its parent. Protected specifies that the item is accessible only from within its own class or from a derived class. Enumerations should already be familiar, but a much-welcomed enhancement in .NET is the ability to declare them with a storage class (storage type). Instead of their values being generic, slow, Variant- type expressions, you can declare the values of an Enum to contain Singles, Doubles, Integers, and such. Structures, unlike the very primitive User-Defined Types of VB6, can also include methods and properties. For certain, structures are classes, except that they are what is called a value-type object (an abstract class, in Object Oriented lingo), as opposed to reference-type objects (a concrete class) that most classes resolve to. We will be looking deeper into these two types a little later. Modules, by appearance, are treated just like VB6 Modules. However, there is an important internal difference that perhaps you need not worry yourself about, but is a very cool bit of trivia: VB.NET modules are actually classes. The key distinction of a module is that it, unlike a typical class, cannot be instantiated as an object simply because a module is auto-imported into a project, being treated just like a non-inheritable namespace. As such, non-private methods and variables in the module are handled within the application as Shared Friend. These treatments were done so that VB6 developers migrating over to .NET would not suffer a grand mal siezure because they no longer had Modules available. I have heard a number of C# developers complaining that they cannot likewise define C# modules. Well, technically they can. All they have to do is to declare a class as non-inheritable, declare all of the variables and methods that they want to be accessible to the application as Shared Friend, and to import this class so that they do not have to declare the module name when they wish to access a variable or method within the module, though this would not hurt in-as-far as self-documentation is concerned. What is an Application Domain? An Application Domain is a solution or group of solutions that work together, sharing memory, but are completely separated from each other in managed memory by the CLR. This process separation, which is a great feature of .NET, guarantees that components cannot interfere with each other, which had previously been a nightmare for those who had multiple executables that shared data space. Granted, most of you will never have to worry about this, focusing instead on single executable applications, but those who do write such complex programs, the headaches have been removed, especially the pain of trying to quash circular references in released objects that somehow kept resurrecting themselves, as had been the case with VB6. Again, this is a concept that, in the end, is quite helpful, though you really do not have to bother your head with even knowing that it exists. The fact is that most of you could have gone through the rest of your careers without thinking about it even once. What is a Solution/Assembly? Solutions and Assemblies are classed together. Why? Because for all practical purposes they are the same thing, and the terms are basically interchangeable. Why are there two terms for the same thing? It is simply a matter of perspective, though their differences for most people might appear a bit gray. Instead of pulling out charts and diagrams and opening thick tomes to differentiate these two things, suffice it to say that when someone is talking about a Solution or an Assembly, they are talking about the same thing. Basically, a Solution is the final result; the wrapper that can hold one or more projects, such as an EXE and supporting DLL files. An Assembly describes that Solution, defining the Solution's fingerprint, such as the auto- generated Globally Unique Identification number (GUID) and the version number. Note that currently VB.NET Solutions can only hold one EXE, and the other optional projects must produce non-EXE files, such as DLLs (granted, the command-line compiler can compile solutions with more than one EXE, though there is very seldom much need to require you doing this). By default, the name of the solution will be the same as the name that you provide for the first (and usually the only) project you created. 14. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 14 Frankly, the only time you need to be concerned with an Assembly is when you want to edit the application description, version number, title, and such. In this case you can simply open the AssmeblyInfo.vb file, if you see it in the Solution Explorer, or open the project properties and select the Assembly Information button to edit this file through a much safer dialog interface, and modify the entries (if you do not understand what I mean, simply access it and look for yourself it will then become quite obvious). Personally, I think of the whole thing as a Solution, and I associate the idea of an Assembly as this single AssemblyInfo file, and forget about their real technical descriptions. What is a Project? Most of you already know the answer to this one. It is the executable/control/DLL that you are developing. Think of it as your Program. Each project can contain only one compiled object, whether it is an EXE, a DLL, or some other control object. When you create a new stand-alone project in VB.NET, it also creates a thing that wraps around the Project called a Solution, giving it the same name as the initial or only project (a Solution is simply an organizing wrapper around a project or group of projects See below), as well as a Namespace that can wrap itself around one or more Solutions (also see below) with the same name as the initial or only project. Indeed, when you go about creating a new application, .NET will in fact be prompting you for a new project (though you can in fact create blank solutions from the File/New menu), which will concurrently create the like-named solution and namespace in the background. You should change these at the time of creation in the creation dialog if you in fact will require them to be different from the default, but you can just as easily change them afterward. Although it would at first seem logical to first create a namespace, then to create the solution(s) within it, and within the solution(s) to finally create the project(s), most applications do not need to work this way, and this latter approach would therefore be nothing more than a peevish bother than a help in most development projects. This somewhat cut-to-the-chase approach is a well-received feature for most developers. Beside, the solution and namespace can be redefined very simply afterward. Object Oriented Programming VB.NET, as opposed to VB6, is a full-fledged Object Oriented Programming Language. Everything in VB.NET, to include simple variables, is derived from class definitions. Although people new to OOP design might not imagine much practical use for OOP, preferring instead linear, procedural languages, such as VB6, even a basic introduction will clarify the tremendous advantages it has over conventional programming that had spawned the development of maddeningly confusing spaghetti code and half-cocked programming. The introduction of structured programming by languages such as Pascal, ADA, Algol, and C, for example, tried to straighten this problem out, but failed miserably in that it was too easy to work around. Objects, on the other hand, promote and almost force structured design, where each object is a self-contained building block that is plugged into and links to other code. Because these objects are like black boxes9 , the need for developing a design paradigm is critical to application development. Anyone who has ever been involved in a large and complex project realizes (the unlucky ones realized it after the fact) that breaking a project down into smaller self-contained modules is highly beneficial, and also lends itself greatly to a development team environment, where each member of the team can work on a separate module, test it and debug it individually, before it is plugged into the main application. The typical flow of an OOP project is to break each task or class down into more primitive classes, which, when grouped together, will define the complex outer class. Each sub-class has a particular set of tasks to perform. Each module can be further broken down into simpler separate classes that in turn perform even smaller tasks. Again, these smaller classes are self-contained and can be separately tested. 9 Black Boxes: Predictable widgets, though their inner workings may be unseen or not known except by its developer. However, when known data is input, predictable known output results are guaranteed, allowing their working content to be ignored by all, except for those whose job it is to develop, provide, and service those widgets. 15. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 15 The VB2008 edition of VB.NET works around most incompatibilities between an OOPL like VB.NET and a procedural language like VB6, to include making the new Integrated Development Environment (IDE) reasonably familiar and compatible to that of VB6. A great example of this, as discussed earlier, is VB Modules, which are files whose public contents were accessible from other files as though that code was within the invokers file. In VB.NET, VB modules are actually classes that are automatically imported into the IDE (see the Imports command), which allows developers to use these convenient module classes just the as they did under VB6. Another development in VB.NET are control and form containers, allowing developers to access these containers like collections, just as they were used to doing under VB6. If new to object-oriented programming, the following terms and concepts will help you get a head start in gaining a basic understanding of the Object Oriented paradigm. Just keep reminding yourself that it is a whole lot easier to do than it is to explain. Classes and Objects It is critically important that you fully comprehend the idea of objects, the classes that describe them, and how they are incorporated in .NET. If you have written a lot of classes, most of this is old news to you, but I keep running into many very advanced developers who have authored only a few, if any, classes, or were not exactly sure how classes were actually handled internally. A full understanding of Objects is critical to mastering .NET. First, lets clarify something for those who have little or no experience with classes and objects. A Class is the code that simply describes an Object, such as a form; defining the fields, properties, methods, and events by which the personality of the object is established. Thus, a Class is the code you write to support an Object. An Object therefore is an instance of a Class; the tangible manifestation of something that the Class describes that is accessible from code external to it, such as the portion of your application that will use it. Truth is, most of this gobblety-gook will be invisible to you as you write code just like you did under VB6. The OOP concept of wrapping relatedmethods and properties together is called encapsulation. An Object that contains the methods that manipulate the data it contains is also easier to debug. Objects and their Class definitions are therefore developer-friendly. Ultimately, an object is something that contains data and should always protect that data. The properties, methods, and events that it can contain are there solely to support that data and be a controlling conduit to the users of that data. Too many new people to OOP cannot seem to make sense of objects being the encapsulation of data that includes methods to support that data. How do you make a program out of a bunch of that stuff? But in simpler terms, an Object is also the Form that comprises the user-interface of a simple program. Its Data is simply the procedure-level variables defined within them. Other aspects of the program, like classes, modules, and even outside references that support the application comprise other objects (things). An Object is a structure containing data (storage fields and properties) and methods (functions, subroutines, and events) that can manipulate the data. Everything in VB.NET associates with objects. An Object is just about anything that you can think of. We work with physical objects all the time: televisions, cars, customers, reports, phones, light bulbs anything. In computer terms, an object is a tangible representation of an abstract concept that we want to manipulate in our application, such as a Form. What is important here is that an object does not contain just data (properties, which an OOP calls attributes). It also contains the programmed intelligence to produce actions related to it, such as a bill object being able to print itself if it has a print method (subroutine) that can be invoked (called). An Object is an instance of a Class, causing the program code of the class is be brought out from concept into manipulative tangibility, allowing its data to consume space in the applications memory reserved for object instantiation (often referred to as the Heap), with one copy of the actual program code of the class being shared by all object instances of that class, and each object instance of the class storing its private data in each instances separate and unique allocated storage space on the Heap. 16. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 16 Classes are important to object-oriented programming because they allow you to group related items as a single unit, and they enable you to fully control their visibility and accessibility to other procedures or objects. Classes can also inherit and reuse code defined in other classes (excepting, of course, imported classes, or if they are specifically declared to be non-inheritable meaning they can only be imported). In OOP, all objects are modeled upon a class definition. A class describes an object that has properties and/or methods. In .NET, everything is an instance of a class (either Abstract or Concrete; see below for details). Classes are quite clearly the very heart of Object-Oriented development. However, there are two different types of class objects in OOP, being Value Type and Reference Type. Value Type Objects: A numeric variable, such as an Integer, is an example of a Value Type Object. When you define a variable as a new Integer, you do not define it as a new instantiation of an integer as you would with a user-defined class (you do not need to use the New keyword to create it). Value types are typically called structures, because their makeup is just like a simple VB.NET Structure (a User-Defined Type in VB6). In OOP, such structures are called Abstract Classes, meaning that, although they are constructed very much like classical classes, the data and code assigned to them are not simply pointed to by them, but instead they are self-contained structures that actually encapsulate their data. They also do not create classical objects, which are stored in a separate memory pool, known as the Heap, and therefore they do not have to be released to the Garbage Collector. Also unlike classical objects, their data is automatically released when they go out of scope (visibility/accessibility). Even though they can be very messy, leaving copies of themselves everywhere they go, they also clean up very easily and very quickly by their simply going out of scope. Though Structures in VB.NET are similar to VB6 Type blocks, they differ in that, under .NET, they follow object oriented programming rules, and being Abstract Classes, they are like regular classes in that they can also contain properties and methods. They can in fact be initialized using the New keyword (this is used to concurrently initialize the fields of the structure during its creation, not to instantiate it as a classical object). More on this will be discussed later, which should relieve any confusion you may still be feeling right now. Reference Type Objects: These are considered regular, classical, or typical classes, and are also called Concrete Classes. These types must always be instantiated using the New keyword. Variables assigned to these types of objects do not contain the data of the object, as abstract classes do, but are instead just a simple reference pointer to the actual encapsulated object that is stored in a protected memory pool called the Heap. Fields, Properties, Methods, and Events Classes consist of fields, properties, methods, and events, and often referred to as Members of the class. Fields are data the object contains. Fields are like variables because they can be read or set directly, and are in fact declared exactly like VB variables. For example, if you have an object named "Car", you could store its color in a public field named "Color" (for example, Public carColor As Color). Normally, one would store fields as Private, and actually access this private data through Public Properties. Properties are methods that access and set information about an object as though they were fields or variables, and implemented through property Get and Set accessors attributes. These accessors provide greater validation control over how field values are stored or returned (though they are transparent to you under VB.NET). This layer of indirection between the value being stored and the procedures that use this value helps isolate your data and lets you validate values before they are assigned or retrieved. To the consumer (user) of the object, accessing a property member of the object acts just like one was directly accessing a publicly declared field or variable. Methods come in two flavors; subroutines (subs) and functions. You may have referred to executing these as calling them in VB6 (and Microsoft still does), but it is preferred in OOP to say that they are being invoked10 . The reason behind this is that to invoke something is to imply that it is something called out from within something else. Methods are essential, because, after all, most objects, such as a form, needs to do something. Methods therefore represent actions that an object can perform on or with its data. For example, a "Car" object could have "StartEngine," "Drive," and "Stop" methods. You define methods by adding subroutines or functions to your class. 10 Invoked: Summoned out of something else, such as from an object. 17. Enhancing Visual Basic .NET Beyond the Scope of Visual Basic 6.0 David Ross Goben Page 17 Events are notifications an object receives from, or transmits to other objects or applications. Events enable objects to perform actions whenever a specific incident occurs. An example of an event for the "Car" class would be a "Check_Engine" event. Because Microsoft Windows is an event-driven operating system, events can come from other objects, applications, or from an input device, such as a mouse, a keyboard, or from a joystick. Like under VB6, clicking a form button executes code defined within a Click event method. Encapsulation, Inheritance, and Polymorphism Fields (variables declared within a cl