What is Visual Basic?
A programming language and environment developed by Microsoft. Based on the BASIC language, Visual Basic was one of the first products to provide a graphical programming environment and a paint metaphor for developing user interfaces. Instead of worrying about syntax details, the Visual Basic programmer can add a substantial amount of code simply by dragging and dropping control, such as buttons and dialog boxes , and then defining their appearance and behavior.
Although not a true object-oriented programming language in the strictest sense, Visual Basic nevertheless has an object-oriented philosophy. It is sometimes called an event-driven language because each object can react to different events such as a mouse click.
Since its launch in 1990, the Visual Basic approach has become the norm for programming languages. Visual Basic is sometimes called a Rapid Application Development (RAD) system because it enables programmers to quickly build prototype applications.
Ensure smooth parameter passage from ASP into VB components
When you create an ASP application, a VB DLL offers an excellent way to build n-tier, business components into the mix. When you call a VB component's methods in ASP, however, keep in mind that ASP is a loosely typed language. In essence, this means that all ASP variables are variants. As a result, if you've created a VB method that accepts arguments of a specific type, you'll need to convert any ASP variables that you pass into the function into the proper type.
For instance, suppose your VB component contains the following function:
Public Function MyTest( str As String, lng As Long)
It's not much of a function, but it serves our purposes. Now suppose you wanted to use this method in an ASP page. If you supply the arguments directly, like so: <%
Dim myCom, result
Set myCom = Server.CreateObject("myVBDLL.MyCom")
result = myCom.MyTest("StringTest", 2)
" & result & "
Set myCom = Nothing
ASP automatically casts the arguments into the proper data type. However, if your code assigns the values to variables before passing them, as in:
Dim myCom, result
Dim myStr, myNum
myStr = "StringTest"
myNum = 2
Set myCom = Server.CreateObject("myVBDLL.MyCom")
result = myCom.MyTest(myStr, myNum)
" & result & "
Set myCom = Nothing
VB will balk under these circumstances, because the variables are really variants.
To correctly pass in these variables, we could use the CStr and CLng functions respectively, like so:
result = myCom.MyTest(CStr(myStr), CStr(myNum))
Get rid of dead code
Dead code means unnecessary, inoperative code that can be removed. Dead code includes functions and sub-programs that are never called, properties that are never read or written, constants and enums that are never referenced. Dead variables are ones that are never read - even if they've been given a value. User-defined types can also be dead, and there may be a lot of extra API declarations.
Even whole files can sometimes be completely unnecessary. Dead code leads to excessive memory use, slower execution, larger .exe files, higher maintenance effort and errors. That's why it's important to clean your projects by removal of dead code.
Avoid fixed-length Strings
Fixed-length strings generally occupy more memory than variable-length ones. The problem is worse if you have to reserve lots of space for long strings in your fixed-length string variables. If you're planning to migrate to VB.NET, then you have one more reason why not to use fixed-length strings. VB.NET doesn't support them natively. You get better performance with variable-length strings.
Void Static Variables
Static variables are those that reside in the memory for the whole execution time. The opposite of static variables is dynamic variables. Dynamic variables are procedure-level variables that are created when the procedure is entered, and destroyed when the procedure ends.
Local are those variables and arrays that are declared inside a procedure. So why should you avoid static local variables? Static variables are slower and consume memory. It is better to use normal, dynamic local variables.
If you really need a static local variable, use a private module-level variable instead. There is a drawback with this, though. You should keep other procedures from using the same variable to avoid unwanted side effects.
Reclaim memory after use
If you are using static variables, it's important to reclaim the memory they occupied when you don't need the variables any more. With dynamic variables memory isn't so much of a problem, because they are destroyed when the procedure ends.
The below table shows how you can reclaim the memory occupied by different variable types. Arrays are discussed below the table.
Type of variable Code to reclaim occupied space Variable-length String MyString = "" Variant MyVariant = Empty Form Unload MyForm Object Set MyObjectVariable = Nothing
Reclaim memory from arrays
Arrays are often memory-hungry. This applies especially to static arrays, whose size is fixed for the lifetime of the program. Dynamic arrays are better for memory optimizations, because they can be resized. However, some memory optimization can be applied to both array types.
One way to reclaim space occupied by an array is to clear all its elements one by one as shown above. Another way is to use Erase orReDim.
- Erase frees the memory used by dynamic arrays. With static arrays, however, the effect is somewhat limited. Doing Erase for a static array is the same as clearing all its elements separately.
- ReDim can be used only for dynamic arrays. You can ReDim a dynamic array to a smaller size. If you just want to reduce the array and still pre serve some data in it, you can use ReDim Preserve, like this: ReDim Preserve MyArray(SmallerSize)
Type your variables
VB's default data type is Variant. All variables that don't have any other type are implicit Variants.
Avoid variants when possible. They are slow, and they consume memory. If you use variant instead of, say, integer you waste 14 bytes of memory. This can be significant in a large project. Integers are much faster than variants. This is true particularly in For... Next loops.
Use Option Explicit to force declaration of your variables. This helps you to get rid of unnecessary variants.
Aivosto Project Analyzer can help you to ensure properly typed variables. It can list the implicit Variants and missing Option Explicit statements for you. Typing your variables is a very good habit and a sign of professional development.
Memory optimizations with graphics
Graphics may use a lot of memory and also slow your program down. Here are some easy tips to avoid that.
- Reclaim graphics memory with LoadPicture() and Cls. You can also set the Picture property to Nothing (VB 4.0 and later).
- Use Image controls instead of PictureBoxes.
- Use RLE, GIF, JPG, and WMF picture formats instead of BMPs. If possible, try to reduce the number of colors in your pictures.
- Load a picture only once. If you need to display one picture in several places, you can just assign it from one control to another with this code:
MyGraph.Picture = OldGraph.Picture
Doing this will save the picture only once in your executable file, but you may use it on many controls.
- Set AutoRedraw = False. If it's True, VB will create an AutoRedraw image that consumes memory.
Optimize for speed
Users are often complaining about slow programs. They may have slightly old computers, but usually it is the developer to blame. How to make apps faster?
Some memory optimizations described in the previous chapter contribute to speed optimization too. These are getting rid of dead code and using appropriate variable types instead of Variants. On many occasions, when you minimize memory usage you will also minimize execution time. In some cases, however, the two goals may be contradictory.
Aivosto VB Watch Profiler is a performance measurement tool that can help you squeeze the most out of your code. It measures the time your code takes to execute - line by line, procedure by procedure. You can make before-after comparisons and check which algorithm is the best one to use. You can also find the bottleneck areas in your project - the areas where you can achieve maximal performance boost with minimal effort.
Cache properties in variables
If you are going to need the value of a property more than once, assign it to a variable. Variables are generally 10 to 20 times faster than properties of the same type.
Use For Each..Next
Collections allow you to iterate through them using an integer For(index)..Next loop. However, For Each..Next is often faster. Besides, it's easier to read too!
Check for loops
Normally, loops are those parts of a program that take the most time to execute. The worst thing is several loops nested. You can use Aivosto Project Analyzer to find out where the deepest loops are in your code.
You may have heard of mathematical complexity measures like O(n) and O(n2). O(n) means that the execution time of a procedure is proportional to the input size n. O(n2) means it's proportional to the square of the input size. In other words, O(n) is much faster than O(n2), if n is large.
What is n, the input size? It can be anything, including the number of lines in a text file, the dimensions of an array, or the size of binary data. It all depends on what you're programming. The worst case is denoted by O(2n). This means those execution time rises exponentially when n increases. On the other hand, if execution time rises only logarithmically, like O(log n), you have a fast procedure even for large sets of data.
Mathematical complexity (and the time to execute) is mostly due to the number of nested loops. With a recursive procedure (procedure that calls itself), the problem isn't that simple, but most of VB procedures are not recursive
Working with objects
Minimize the dots. Each dot consumes some time, and makes the code more difficult to read. You can refer to an object's default property just with the name of the object (without the name of the property!). You can also assign an object to an object variable, like this:
Dim X As SomeObject
Now you can refer to X instead of the long alternative.
You can use With..End With for the same effect, but beware! There is a caveat. With..End With takes some time to execute, so it's not effective to use it to replace just one or two references to an object's properties. Experiment.
Early and late binding
If you know what type an object will be, use that type! Avoid variables declared As Object or As Variant.
This is called early binding - VB knows what type to expect at compile time. The opposite is late binding - the type is known only at run-time. Late binding is much slower. Remember to declare your objects properly!
Optimize display speed
Often it's important how fast your application appears to run, even if the actual speed isn't that high. Some ways to speed up display speed:
- 1. Set ClipControls property to False.
- Use Image instead of PictureBox, and Label instead of TextBox, if possible.
- Hide controls when setting properties. This prohibits multiple repaints.
- Keep a form hidden but loaded if you need to display it fast. The drawback of this method is that it consumes some memory.
- Use background processing for longer runs. You can achieve background processing with appropriately placed DoEvents. A good place to put DoEvents is inside time-consuming loops. This needs some consideration, because the user might click some buttons, for example, and your program must know what the user is allowed to do when the background process is running. Set flags like Processing=True and check them in appropriate places.
- Use progress indicators.
- Pre-load data you will need later. For example, you can load the contents of a database table into an array for faster access.
- Use Show in Form_Load event.
- Simplify your startup form, or use a splash screen
How to write understandable code
Do you like spaghetti? No matter if you do or not, you probably don't like spaghetti code.
It is very common to find poorly designed code that is difficult to understand. But that would also be easy to avoid. After all, it is so easy to make understandable code. It doesn't really take a lot of time -but it will save a lot in the future.
Start writing decent code now!
Making non-spaghetti code is not about writing a few docs after the program is ready. It is a continuous process that starts at the same time you write the first line of code. Think about the reader that will read the code next year. Will he or she understand the code that has no indentation, meaningless variable names, jumps from place to place, and no comments? Besides, that person might be you! Aivosto VB Friend is a tool that beautifies your code while you write it. It adds proper indentation and white space, and splits complex structures to multiple lines. You can customize it to fits your own personal coding style.
Split complex procedures
Overly long and complex procedures are hard to understand. They are error-prone. One particular sign of a complex procedure is the amount of nested conditionals (if, do..loop, select case).
You probably already guessed that Aivosto Project Analyzer can help you with both finding procedures to split, and also the dreaded GoTo's and GoSub's. It might not come as a surprise that the utility also helps with the next tip, avoiding unintended passing of parameters by reference.
Whenever possible, use the keyword Private. This will make your procedures and variables accessible inside the same module only. The advantage is increased modularity in your code.
Private MyVariable As Integer
Knowing which thing should be Private and which one Public is difficult, especially if that wasn't taken care of when the original code was written. Ifthing is Public when it shouldn't, it's called the excess scope problem. Fortunately, this problem is easy for an automated code analysis to solve.
Use proper error handling
VB apps crash easily, with messages like "Invalid function call" and "Overflow".
A quick and dirty way to prevent crashes is to use On Error Resume Next. Put it in every procedure, and your app completely ignores most errors. The user never knows what went wrong if she never sees one error message.
A more sophisticated solution is to build real error handlers. If an error occurs, display a meaningful error message and give the user the ability to ignore the error, retry, or abort the program. For your own purposes, build and show enough information so that the user may report any bugs to you to fix. Put this in every procedure, and you have a robust program.
Reuse, reuse, and reuse!
Reusability is the magic word of programming today. In VB, you can reuse procedures, code modules, or class modules. Reuse greatly reduces the time to develop a program.
You can achieve reusability if you program in an object-oriented language creating reusable classes. Although VB isn't a strictly object oriented language, it has a class mechanism called class modules (.cls). VB can also create ActiveX controls - quite a powerful mechanism for reuse.
It is usually not enough that an application runs on your own computer, or your colleague's one. It must run on the customers' computers too.
Debugging is tough when you have to debug executable files - and that's the way to do it if you have to debug on someone else's computer. That may also be the case when you use ocx or dll files. VB doesn't have anything to help with this. Fortunately, Aivosto VB Watch Debugger has. It gives you the ability to see inside compiled VB programs, libraries and modules. You can see call stacks, procedure parameters, initialized objects, and call trace - even line-by-line if required.
Dynamically add a VB control to a Frame at runtime
For large VB applications with expansive GUI's not only is real estate at a premium, but so are system resources. As a result, you may often need to generate controls at runtime. To do so, you're probably familiar with VB's Controls collection. This collection consists of the controls on are form.
Typically, you use this collection like so:
Controls.Add "VB.TextBox", "txtBox999"
The first parameter takes the progID of the control you want to add. You can determine a control name by searching for it in VB's Object Browser. The second parameter takes the name of the new control. The above statement would add a textbox named txtBox999 to the current form.
However, you may not be aware that you can also use this command to add a control to any other type of container object, such as Frames and PictureBoxes. To do so, you pass a reference to this container object as the Add method's third parameter like so:
Controls.Add "VB.TextBox", "txtBox999", Frame1
Be aware that when you add a control with this method, by default VB makes it invisible. You'll need to set it visible in your procedure, presumably after sizing and positioning it.
To see how this command works in a VB project, launch a standard VB project. Drop a Command Button and a Frame onto the default form. Next, right-click on the form and select View Code from the shortcut menu. In the Code window, enter the following procedure:
Private Sub Command1_Click()
Now press [F5] and click the button on the form. When you do, VB automatically adds a textbox to the frame and positions it accordingly.
An easy way to test a user's Internet connection with the API
As more and more of your applications become distributed across the Internet, you'll no doubt want to build in a way to determine if the current user is actually connected to the Web. Fortunately, the Windows API offers a quick and easy way to do so with the InternetGetConnectedState() function.
This function uses the declaration syntax seen here:
Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef dwflags As Long, _
The function returns 1 if a connection exists and 0 if not. You can easily convert these values to their Boolean equivalents in VB. After the test, the dwflags parameter will indicate what type of connection the user has. You use bitwise comparisons to test for specific values. The dwflags constants are as follows:
Private Const CONNECT_LAN As Long = &H2
You can ignore the dwReserved parameter.
To see how this function works, launch a new VB project, and drop a Command Button onto the default form. Right-click on the form and select View Code from the shortcut menu. When the IDE opens the Code window, enter the InternetGetConnectedState() function and constant declarations as shown above. Then, enter the following procedures:
Public Function IsWebConnected(Optional ByRef ConnType As String) As Boolean
When you run this program and click the form's command button, the message box tells you if you're connected to the Internet and by what type of connection.
Capture SQL Server stored procedure output values with ADO
As you may know, T-SQL, as used by SQL Server, lets you define output parameters in a stored procedure. These parameters let T-SQL pass values back out to the code executing the stored procedure. In general, output parameters are more efficient than recordsets for returning single values because they don't require the additional resources of a cursor, etc.
To retrieve an output parameter via ADO in VB, you first create a Parameter object, indicating that it's an output parameter (or an output/input parameter). You then append this parameter to a Command object, just like you would when passing in an input parameter. After your code executes the Command, SQL Server and ADO fill the Parameter object with the appropriate value.
To see how this works, consider the following T-SQL stored procedure:
CREATE PROCEDURE [sp_BookList]
Normally, this procedure might return the total dollar amount in inventory for a specific book. To keep things simple, we hard-coded the return value. To retrieve this parameter in VB, you'd use code like this:
Private Sub Form_Load()
Notice that in the Execute method, we specified adExecuteNoRecords. Doing so tells ADO not to bother building and populating a recordset just to hold the return value.
Once executed, your code can retrieve the output parameter value one of two ways: either by accessing the Parameters collection, or by using the Parameter object directly. The following code illustrates both methods and concludes the previous code procedure.
MsgBox FormatCurrency(param2.Value, 2)
Identify VB controls with the TypeOf keyword
Often in your code procedures, you may need to determine what typeof control your code has accessed. For instance, you may want to alter the text on every command button on a form. Or you may want to change the properties for several different controls. In such instances, you have several ways to test for a control type. The most efficient and fastest method is the TypeOf operator.
Unlike other methods of determining a control's type, such as theTypeName property, the TypeOf keyword doesn't need several roundtrips to the Registry to obtain the information it needs. As a result, it reduces the processing drag necessary for your code.
This keyword must appear in an If...Then statement, like so:
If TypeOf ctl Is CommandButton Then
The following code shows an example of how to use this keyword in a procedure.
Private Sub Command1_Click()
When to supply the @ in SQL Server parameter names
As you may know, ADO provides two ways to supply a stored procedure with parameter values. In the first method, you refer to the parameter name directly and simply assign a value. In the second, you build a Parameter object from scratch and add it to the Command object's Parameters collection.
Be aware, though, that when using named parameters, you must supply the @ character, which precedes every SQL Server parameter name, like so:
cmd.Parameters("@someParam") = 250
On the other hand, when you build the Parameter object from scratch, you don't need to supply the @ character, as seen here:
Set param = cmd.CreateParameter("someParam", adBigInt, adParamInput, 2, 250)
An alternate way to let VB determine odd and even numbers
In a previous tip, we suggested that you use the MOD arithmetic operator to determine if a number is odd or even. As many of you pointed out, however, the technique we presented wasn't the most efficient method; because MOD actually performs a division behind the scenes. As a result, multiple calls to this operator could bog down the processor.
As an alternative, you can perform a simple bitwise comparison against the number you want to test, such as
myNumber And 1
When you do, Visual Basic returns either a 0 or 1--1 for odd numbers, and 0 for even numbers. You can then use these results in your code.
For a simple example, launch a standard Visual Basic project and add a textbox and command button to the default form. N ext, in the command button's Click() event, add the following code:
Dim blnIsOdd As Boolean
Press [F5] to run the project. Enter a number in the textbox and click the command button. When you do, Visual Basic tells you whether the number is odd or not.
Deciphering MP3 Tag information with Visual Basic
The Windows Media Player provides an easy, quick way to drop MP3 capability into a Visual Basic application. However, once you have an MP3, you may have wondered how to read information about the song, such as the song title and artist's name. If the MP3 file uses the most popular tag encryption, ID3, then you're in luck. This standard stores the Tag information in the last 128 bytes of the file (Tag:3, Title:30, Artist:30, Album:30, Year:4, Comment:30, Genre:1)
To read this information, first open the MP3 file and grab the last 128 bytes. With ID3, the first three slots hold the string TAG if the file actually contains information. If the file does contain Tag information, store the last 128 bytes in a custom variable. After that, cycle through the MP3 file, extracting information as you go. The following procedure shows the code that extracts this information as well as creates several important variables to use later on:
Notice that the code has to handle the genre character a little differently. That's because ID3 stores this data as a single ASCII character. To match up the actual number with its corresponding description--say contained in a combo box--the procedure converts the ASCII to a number, and then looks up that number in the combo box.