TechiWarehouse.Com

Programming Languages


Software Engineering Phases - Software Engineering PhasesThere are four fundamental phases in most, if not all, software engineering methodologies. These phases are analysis, design, implementation, and testing. These phases address what is to be built, how it will be built, building it, and making it high quality. . These steps together define the cradle-to-grave life cycle of the software project. Obviously, if an action is done many times, it needs to be done correctly and efficiently.
Divider Line

Computer Training Excuses - No ExcuseYou wouldn't go to a doctor who had never been to medical school, or hire a lawyer who never studied law. One side-effect of a world advancing as rapidly as ours is that fields are becoming more and more specialized and narrow. People can no longer get by on general knowledge in their careers, something I found out for myself not too long ago. I'd been out of high school for two years, scraping by on my own and picking up scraps of programming as I went. I saw all of the self-taught programmers breaking into the IT industry, and I hoped to do the same. After all, IT is one of the few industries out there where being creative and a quick learner is more important than a degree.
Divider Line

Which is the Easiest Programming Language? - Programming LanguagesIf you have some misconception in mind that the programming languages are easy or hard, I am afraid to say that you are mistaken. To tell you frankly about the programming languages, there is nothing such as easy or tough programming language. The only thing that you need to keep in mind while stepping into the world of programming languages is that which programming language would set your base by giving you in-depth knowledge of programming logics and the basics of programming techniques.
Divider Line

Entering into Programming World - Good Luck ProgrammingOnce you have learned some programming languages, you feel yourself completely prepared to enter into the programming world, and start working on the programming languages that you have learned. Many students also feel that they have learned extra things which might be helpful in their programming careers. The matter of fact is that the real world is entirely different from what you have been taught in the classrooms.
Divider Line

Basic Object-Oriented Concepts - Basic Object-Oriented Concepts There is an old story of how several blind men set out to understand what an elephant was by examining a live specimen. Each of them explored a different part of the elephant's body. One blind man, falling against the elephant's side, proclaimed that an elephant must be very much like a wall. Another, grasping the elephant's ear, decided that an elephant must closely resemble a leaf. One grabbed the elephant's tail and determined that elephants must resemble ropes.
Divider Line

Why Programmers Love the Night - Programming at night One famous saying says that programmers are machines that turn caffeine from coffee and Coca Cola into a programming code. And if you ask a programmer when does he like working the most and when is he most productive - he is probably going to say late at night or early in the morning, that is when he has the greatest energy and concentration to work.
Divider Line

How to be a Programmer - Programing training To be a good programmer is difficult and noble. The hardest part of making real a collective vision of a software project is dealing with one's coworkers and customers. Writing computer programs is important and takes great intelligence and skill. But it is really child's play compared to everything else that a good programmer must do to make a software system that succeeds for both the customer and myriad colleagues for whom she is partially responsible. In this essay I attempt to summarize as concisely as possible those things that I wish someone had explained to me when I was twenty-one.
Divider Line

TW Tech Glossary - Misplaced your bible? Well here it is - Tech Glosasary! This truly took a while to complete and should be used by all from beginners to advance techies.
Divider Line

Visual Basic Tutorial - Visual Basic Tutorial This Visual Basic tutorial is the very much requested by TechiWarehouse. It'll will be enough to get a beginner up and making VB codes and programs. Although, it will need some time and dedication as with any other tutorial. VISUAL BASIC is one of the easiest programming tool to master. With some basic guidance, anybody could come up with a nice little windows-based program within a short time, age is not the limit.
Divider Line

What Programming Language To Learn - Programming LanguagesOne of the most common questions we hear from individuals hoping to enter the IT industry is, "What programming languages do I need to know?" Obviously this is a complex question, and the answer will depend on what field the questioner is going into. Many programming languages are taught during courses used to obtain a computer information science degree. However, those already in IT know that the greatest skill you can have is to be a jack-of-all-trades. A well-prepared worker can switch between computer programming jobs with only minimal training, thanks to a wide knowledge of multiple programming languages.
Divider Line

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.


Tips

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)
MyTest = "String = " & str & ": Long = " & lng
End Function

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)
Response.Write("

" & 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)
Response.Write("

" & 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.

  1. Reclaim graphics memory with LoadPicture() and Cls. You can also set the Picture property to Nothing (VB 4.0 and later).
  2. Use Image controls instead of PictureBoxes.
  3. Use RLE, GIF, JPG, and WMF picture formats instead of BMPs. If possible, try to reduce the number of colors in your pictures.
  4. 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.

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

Mathematical complexity

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
Set X = SomeContainer.SomeObject(123)

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. 1. Set ClipControls property to False.
  2. Use Image instead of PictureBox, and Label instead of TextBox, if possible.
  3. Hide controls when setting properties. This prohibits multiple repaints.
  4. Keep a form hidden but loaded if you need to display it fast. The drawback of this method is that it consumes some memory.
  5. 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.
  6. Use progress indicators.
  7. Pre-load data you will need later. For example, you can load the contents of a database table into an array for faster access.
  8. Use Show in Form_Load event.
  9. 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.

Use Private

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
Private Sub MyProcedure()

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.

Debugging executables

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()
Dim txtBox As TextBox
Set txtBox = Controls.Add("VB.TextBox", "txtBox", Frame1)
With txtBox
.Move 150, 240, 1500
.Visible = True
End With
End Sub

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, _
ByVal dwReserved As Long) 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
Private Const CONNECT_MODEM As Long = &H1
Private Const CONNECT_PROXY As Long = &H4
Private Const CONNECT_OFFLINE As Long = &H20
Private Const CONNECT_CONFIGURED As Long = &H40

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
Dim dwflags As Long
Dim WebTest As Boolean
ConnType = ""
WebTest = InternetGetConnectedState(dwflags, 0&)
Select Case WebTest
Case dwflags And CONNECT_LAN: ConnType = "LAN"
n Case dwflags And CONNECT_MODEM: ConnType = "Modem"
Case dwflags And CONNECT_PROXY: ConnType = "Proxy"
Case dwflags And CONNECT_OFFLINE: ConnType = "Offline"
Case dwflags And CONNECT_CONFIGURED: ConnType = "Configured"
Case dwflags And CONNECT_RAS: ConnType = "Remote"
End Select
IsWebConnected = WebTest
End Function
Private Sub Command1_Click()
Dim msg As String
If IsWebConnected(msg) Then
msg = "You are connected to the Internet via: " & msg
Else
msg = "You are not connected to the Internet."
End If
MsgBox msg, vbOKOnly, "Internet Connection Status"
End Sub

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]
(@ISBN as varchar(30),
@TotalDollar as money OUTPUT)
AS
SELECT @TotalDollar = 404.32
GO

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()
Dim cmd As New ADODB.Command
Dim param1 As New ADODB.Parameter
Dim param2 As New ADODB.Parameter
With cmd
.CommandText = "sp_BookList"
.CommandType = adCmdStoredProc
.ActiveConnection = CONN_STRING
Set param1 = .CreateParameter("ISBN", adVarChar, adParamInput, 30, "90023433")
.Parameters.Append param1
Set param2 = .CreateParameter("TotalDollar", adCurrency, adParamOutput)
.Parameters.Append param2
.Execute Options:=adExecuteNoRecords
Set .ActiveConnection = Nothing
Set param1 = Nothing
End With

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)
MsgBox FormatCurrency(cmd.Parameters("TotalDollar"), 2)
Set param2 = Nothing
Set cmd = Nothing
End Sub

 

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
'Do something
End If

The following code shows an example of how to use this keyword in a procedure.
 

Private Sub Command1_Click()
Dim ctl As Control
Dim str As String
For Each ctl In Me.Controls
If TypeOf ctl Is CommandButton Then _
str = "CommandButton"
If TypeOf ctl Is TextBox Then str = "TextBox"
If TypeOf ctl Is OptionButton Then str = _
"OptionButton"
If TypeOf ctl Is DriveListBox Then str = _
"DriveListBox"
If TypeOf ctl Is DataCombo Then str = _
"DataCombo"
MsgBox str
Next ctl
End Sub

 

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)
cmd.Parameters.Append param

 

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
blnIsOdd = CLng(Text1.Text) And 1
MsgBox blnIsOdd

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:
 

Option Explicit
Private Type TagInfo
Tag As String * 3
Songname As String * 30
artist As String * 30
album As String * 30
year As String * 4
comment As String * 30
genre As String * 1
End Type
Dim FileName As String
Dim CurrentTag As TagInfo
Private Sub Form1_Load()
Dim temp As String
On Error Resume Next
FileName = App.Path & "\myMP3.mp3"
Open FileName For Binary As #1
With CurrentTag
Get #1, FileLen(FileName) - 127, .Tag
If Not .Tag = "TAG" Then
label8.Caption = "No tag"
Close #1
Exit Sub
End If
Get #1, , .Songname
Get #1, , .artist
Get #1, , album
Get #1, , .year
Get #1, , .comment
Get #1, , genre
Close #1
txtTitle = RTrim(.Songname)
txtArtist = RTrim(.artist)
txtAlbum = RTrim(.album)
txtYear = RTrim(.year)
txtComment = RTrim(.comment)
Temp = RTrim(.genre)
txtGenreCode = Asc(Temp)
Combo1.ListIndex = CInt(txtGenreCode) - 1
End With
End Sub

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.


Did You Know?

  • If someone knows Visual Basics like the back of his/her hand, then he/she can program almost anything from an online application to offline intranet database system.
    [I'm really getting good at these gender correct statements ;)]




Premium Tutorials & Screencasts



Partners Links
Kardi Teknomo - Programming lessons for beginners: learn how to program step by step using Visual Basic 6. Research, publications, resume.