Saturday, May 21, 2011

The Prisoner’s Dilemma – An Exercise in Inheritance

The prisoner's dilemma is a fundamental problem in game theory that demonstrates why two people might not cooperate even if it is in both their best interests to do so. It was originally framed by Merrill Flood and Melvin Dresher working at RAND in 1950. Albert W. Tucker formalized the game with prison sentence payoffs and gave it the "prisoner's dilemma" name (Poundstone, 1992).

A classic example of the prisoner's dilemma (PD) is presented as follows:

Two suspects are arrested by the police. The police have insufficient evidence for a conviction, and, having separated the prisoners, visit each of them to offer the same deal. If one testifies for the prosecution against the other (defects) and the other remains silent (cooperates), the defector goes free and the silent accomplice receives the full one-year sentence. If both remain silent, both prisoners are sentenced to only one month in jail for a minor charge. If each betrays the other, each receives a three-month sentence. Each prisoner must choose to betray the other or to remain silent. Each one is assured that the other would not know about the betrayal before the end of the investigation. How should the prisoners act?

If we assume that each player cares only about minimizing his or her own time in jail, then the prisoner's dilemma forms a non-zero-sum game in which two players may each either cooperate with or defect from (betray) the other player. In this game, as in most game theory, the only concern of each individual player (prisoner) is maximizing his or her own payoff, without any concern for the other player's payoff. The unique equilibrium for this game is a Pareto-suboptimal solution, that is, rational choice leads the two players to both play defect, even though each player's individual reward would be greater if they both played cooperatively.

In the classic form of this game, cooperating is strictly dominated by defecting, so that the only possible equilibrium for the game is for all players to defect. No matter what the other player does, one player will always gain a greater payoff by playing defect. Since in any situation playing defect is more beneficial than cooperating, all rational players will play defect, all things being equal.

In the iterated prisoner's dilemma, the game is played repeatedly. Thus each player has an opportunity to punish the other player for previous non-cooperative play. If the number of steps is known by both players in advance, economic theory says that the two players should defect again and again, no matter how many times the game is played. However, this analysis fails to predict the behavior of human players in a real iterated prisoners dilemma situation, and it also fails to predict the optimum algorithm when computer programs play in a tournament. Only when the players play an indefinite or random number of times can cooperation be an equilibrium, technically a subgame perfect equilibrium meaning that both players defecting always remains an equilibrium and there are many other equilibrium outcomes. In this case, the incentive to defect can be overcome by the threat of punishment.

In casual usage, the label "prisoner's dilemma" may be applied to situations not strictly matching the formal criteria of the classic or iterative games, for instance, those in which two entities could gain important benefits from cooperating or suffer from the failure to do so, but find it merely difficult or expensive, not necessarily impossible, to coordinate their activities to achieve cooperation.

Strategy for the classic prisoner's dilemma





In "win-lose" terminology the table looks like this:



Imagine you are player A. If player B decides to stay silent about committing the crime then you are better off confessing, because then you will get off free. Similarly, if player B confesses then you will be better off confessing, since then you get a sentence of 3 months rather than a sentence of 1 year. From this point of view, regardless of what player B does, as player A you are better off confessing. One says that confessing (defecting) is the dominant strategy.

As Prisoner A, you can accurately say, "No matter what Prisoner B does, I personally am better off confessing than staying silent. Therefore, for my own sake, I should confess." However, if the other player acts similarly then you both confess and both get a worse sentence than you would have gotten by both staying silent. That is, the seemingly rational self-interested decisions lead to worse sentences—hence the seeming dilemma. In game theory, this demonstrates that in a non-zero-sum game a Nash equilibrium need not be a Pareto optimum.

Although they are not permitted to communicate, if the prisoners trust each other then they can both rationally choose to remain silent, lessening the penalty for both of them.



Sumber:
Book: Billy Hollis, 1999, Visual Basic 6: Design, Specification and Objects, Prentice-Hall Series on Microsoft Technologies
http://en.wikipedia.org/wiki/Prisoner's_dilemma
http://www.iterated-prisoners-dilemma.net/
http://www.lifl.fr/IPD/ipd.html.en

Wednesday, May 4, 2011

Controls Collection in VB6

The Controls Collection is a built-in collection belonging to a form and is maintained by Visual Basic. The Controls Collection contains references to all the controls on that form. Each member of the collection points to a different object on that form—for example, a TextBox, ComboBox, ListView, and so on.

Each form in a project has its own Controls Collection that you can use to navigate through the different controls on a form. You can refer to each control within the collection as follows:

Form.Controls(index)

where Form is the form name, and Index is an integer value referring to the desired control. Since the Controls Collection is zero-based, Index values range from 0 up through a number that is one less than the total number of controls on the form. If you have 10 controls on a form, the Index values for the Controls Collection would range from 0 through 9.

You will usually use in a Controls Collection when you need to process all the controls or the majority of the controls on a given form. You can loop through a Controls Collection either with a For Next loop, as in Prog 1, or with a For Each loop, as inProg 2.

Prog 1
LOOPING THROUGH A CONTROLS COLLECTION WITH A FOR NEXT LOOP
For I = 0 To Form1.Controls.Count - 1
' process Form1.Controls(I)
Next

Prog 2
LOOPING THROUGH A CONTROLS COLLECTION WITH A
FOR EACH LOOP
For Each obj In Form1. Controls
' process obj
Next

A common use of the Controls Collection is to clear all the controls on a form. If the user wants to reset all the fields on a data entry form, you can code a Clear button with code such as that found in Prog 3

Prog 3
CODE TO RESET ALL FIELDS ON A DATA ENTRY FORM

Private Sub cmdClear_Click()
Dim objControl As Control
Dim sTemp As String
For Each objControl In Me.Controls
If TypeOf objControl Is TextBox Then
' clear the text
objControl.Text = ""
ElseIf TypeOf objControl Is ComboBox Then
' reset the listindex
objControl.ListIndex = -1
ElseIf TypeOf objControl Is Label Then
' leave labels as is
ElseIf TypeOf objControl Is CommandButton Then
' leave commandbuttons as is
ElseIf TypeOf objControl Is MaskEdBox Then
' clear the masked edit control
sTemp = objControl.Mask
objControl.Mask = ""
objControl.Text = ""
objControl.Mask = sTemp
Else
' leave any other control alone
End If
Next
End Sub

This code in the Listing loops through all the controls on a form and clears each control based on its type. To clear a TextBox control, for example, you would set the Text property to a 0-length string. To clear a CheckBox, you would set the value property to vbUnchecked.

Notice that the code in the Listing uses an If statement to determine the type of control being cleared. You must make sure you know the type of control you reference to avoid runtime errors. Errors occur if you try to reference a property of a control that is not a valid property. If the first control on a form is a TextBox, you can clear that control by using:

Me.Controls(0).Text = ""

If, on the other hand, the first control is a CheckBox that does not have a Text property, with the same code, you will get a runtime error from Visual Basic. The Clear button code example avoids this problem by checking for specific control types within the Controls Collection. The syntax for the If statement is as follows:

If TypeOf objectname Is objecttype Then
' code
EndIf

where objectname is the object or control (that is TextBox, ComboBox, and so forth) on which you are working and objecttype is the class of the object. Using this If structure before you reference a control through the Controls Collection will help you avoid runtime errors.

Forms Collection pada VB6

This section discusses the use of VB's Forms Collection. Topics covered include:
  • using methods and properties of the collection,
  • using specific items within the Forms Collection (referencing individual forms),
  • looping through the collection,
  • verifying loaded forms,
  • unloading forms from the collection.
In Visual Basic, a collection is just a group of objects. If you have more than one form in a project, you would have a Forms Collection that you can use to easily manipulate all forms or just one specific form.The Forms Collection is a built-in or intrinsic collection of VB. Another example of a collection built into VB is the Controls Collection that will return all the controls contained on the specified form.

The Forms Collection contains the loaded forms of all VB form types. MDI Parent forms, MDI Child forms, and non-MDI forms are all included in the collection, along with any forms created at runtime.

The Forms Collection only contains the forms that are currently loaded in memory. If a project contains multiple forms and only the Startup form has been loaded, the collection will only have one item. To be included in the Forms Collection, all forms must be loaded. They do not have to be shown onscreen, only loaded.

If a form is the unloaded from memory, that form is no longer part of the Forms Collection. The collection will reduce its count by one, and that form will no longer be available in the collection.


Methods and Properties of the Forms Collection

Most VB collections have various methods or properties that will return information regarding the collection of objects. The Forms Collection has only one property, Count. This property gives the total number of forms currently loaded by the application. To find the total number of forms in the project, just use code such as the following:

iFormCount = Forms.Count

To test the Forms.Count property in VB, use a single form and place one command button on the form. Open the code window for the command button and type the code shown in Listing 4.14.

PROGRAMMING WITH FORMS.COUNT PROPERTY

Sub Command1_Click()
Msgbox "The Forms Collection has " & _
Forms.Count & _
" forms currently", _
vbInformation, "Forms Count"
End Sub

This code will show a message box with a string that contains the number of forms in the collection. Remember that only loaded forms are in the collection. Any form that has not been loaded or that has been unloaded will not be part of the collection.

Using specific items within the Forms Collection

Each object in the collection can also be referred to by its specific ordinal number. This is an item number automatically assigned as the new items are added to the collection.

When referring to the ordinal number of a form, you must always remember that the Forms Collection is 0-based. The first item in the collection will always have the ordinal value of 0. The following lines demonstrate using the item value:

Forms(0).Caption
Forms(1).Name
Forms(2).Width

This code assumes that a VB project has three forms and that all forms have been loaded into memory. The first line will return the Caption of the very first item (item 0) in the collection. The second line will return the Name property of Form(1). The third line will return the value of the last form's width.

These code examples show how easy referencing specific items in the collection can be. This can be an alternative method to using the specific form names in a given project. With the Forms Collection, you also do not have to know the name of a given form to control it. This will assist in manipulating forms generated at runtime.

Looping Through the Forms Collection

Another way to use the Forms Collection is with various looping techniques. By using For...Next, For...Each, or Do...While statements, the programmer can loop through the collection to affect all the forms, search for specific forms, and search for specific properties or even values. This will assist in searching for information without having to program every form name individually.

A simple example would be to retrieve each form's Caption, as shown below.

LOOPING THROUGH THE FORMS COLLECTION WITH FOR...NEXT

Dim iLoop as Integer
For iLoop = 0 to Forms.Count - 1
MsgBox Forms(iLoop).Caption
Next iLoop

This code declares an integer variable for looping and then sets up the For...Next statement. Notice iLoop = 0. You must start at 0 because collections are 0-based. Because you will not always know the amount of forms in the collection, you can take the Forms.Count and subtract 1 from the total. You must remove 1 because the Count starts at 1 and the Collection starts at 0. When this sample code is
run, a message box displays with the Caption property of every form in the collection.

An alternative to the For... Next loop would be the For...Each loop, which does not depend on an integer counter (see Listing 4.16).

LOOPING THROUGH THE FORMS COLLECTION WITH FOR...EACH

Dim frmCurr as Form
For each frmCurr in Forms
MsgBox FrmCurr.Caption
Next frmCurr

This is probably preferable to the For...Next loop because you don't have to keep track of position in the collection.

Using the Forms Collection to Verify Whether a Form Is Loaded

When a form is referenced in code, it automatically loads the form into memory. An advantage of the Forms Collection is that it contains only forms that have been loaded into memory. This enables the programmer to test for a specific form by looping through the collection and testing the Name property of every item in the collection.

An example of this code is found in Listing program below.

VERIFYING WHETHER A PARTICULAR FORM IS LOADED

Sub Command1_Click()
Dim frmCurr as Form
For each frmCurr in Forms
If frmCurr.Name = "Form3" Then
MsgBox "Form3 has been loaded"
End If
Next frmCurr
End Sub

This code declares a form variable for looping and then sets up the For...Each statement. Inside the For...Each statement is an If test. With this code you are looking through each item in the collection and testing the property frmCurr.Name. This allows frmCurr to represent every form that is loaded in the collection. If the Name property is equal to Form3, a message box displays informing us that Form3 has been loaded into memory.

This code sample requires a project with at least three forms. The default form names are expected, and the Form_Load event is responsible for loading all forms into memory. Remember that if the forms are not loaded at the moment the code runs, they will not be included in the collection.

Using the Forms Collection to Unload All Forms

Another common use of the Forms Collection is to unload all forms. Although the End statement would provide a faster, simpler way to terminate the application, it can have unwanted effects because a call to End will immediately terminate the application without allowing any further events (such as Unload events) to run. Looping through the Forms Collection to unload all members might seem like a more complicated way to do the task, but it allows normal processing of Unload and other events.

The code of Listing 4.18 shows one way to control the loop. First, you must determine the total number of elements in the collection then reduce that number by one to accommodate for that fact that the collection is 0-based. The loop unloads collection members in reverse order from the highest-numbered member to the lowest. This is due to the fact that, after each unload of a collection member, the number of members in the collection decreases by one.

UNLOADING ALL FORMS WITH A DESCENDING FOR...NEXT LOOP

Sub cmdClose_Click()
Dim iLoop As Integer
Dim iHighestForm as integer
iHighestForm = Forms.Count — 1
For iLoop = iHighestForm To 0 Step — 1
Unload Forms(iLoop)
Next iLoop
End Sub

A more elegant way to unload all forms would be with a For...Each loop, as in the example of Listing program below.

UNLOADING ALL FORMS WITH A FOR...EACH LOOP

Sub cmdClose_Click()
Dim frmCurr as Form
For each frmCurr in Forms
Unload frmCurr
Next frmCurr
End Sub

Both of the above methods assume that at least one form has been loaded in the collection and that a command button named cmdClose is on one of the loaded forms. After run, all forms should be unloaded, and the project will terminate if no other forms are in memory.

Friday, March 18, 2011

Understanding Properties, Method, Event in VB

Understanding Properties, Methods, and Events

All objects in the Visual Basic language, including forms and controls, have their own properties, methods, and events. Properties can be thought of as an object's attributes, methods as its actions, and events as its responses.
An everyday object such as a helium balloon also has properties, methods, and events. A balloon's properties include visible attributes such as its height, diameter, and color. Other properties describe its state (inflated or deflated), or attributes that are not visible, such as its age. All balloons have these properties, although the values of these properties may differ from one balloon to another.
A balloon also has known methods or actions that it can perform. It has an inflate method (filling it with helium), a deflate method (expelling its contents), and a rise method (letting go of it). Again, all balloons are capable of these methods.
Balloons also have responses to certain external events. For example, a balloon responds to the event of being punctured by deflating, or to the event of being released by rising.



A balloon has properties (Color, Height, and Diameter), responds to events (Puncture), and can perform methods (Deflate, MakeNoise).

Properties

If you could program a balloon, the Visual Basic code might resemble the following "code," which sets a balloon's properties.

Balloon.Color = Red
Balloon.Diameter = 10
Balloon.Inflated = True

Notice the order of the code—the object (Balloon), followed by the property (Color), followed by the assignment of the value (= Red). You could change the balloon's color by substituting a different value.

Methods

A balloon's methods are called like this.

Balloon.Inflate
Balloon.Deflate
Balloon.Rise(5)

The order is similar to that of a property—the object (a noun), followed by the method (a verb). In the third method, there is an additional item, called an argument, which specifies the distance the balloon will rise. Some methods will have one or more arguments to further describe the action to be performed.

Events

The balloon might respond to an event as follows:

Sub Balloon_Puncture()
Balloon.MakeNoise("Bang")
Balloon.Deflate
Balloon.Inflated = False
End Sub

In this case, the code describes the balloon's behavior when a Puncture event occurs: call the MakeNoise method with an argument of "Bang" (the type of noise to make), then call the Deflate method. Since the balloon is no longer inflated, the Inflated property is set to False.

While you can't actually program a balloon, you can program a Visual Basic form or control. As the programmer, you are in charge. You decide which properties should be changed, which methods should be invoked, or which events should be responded to in order to achieve the desired appearance and behavior.

Object Oriented Programming dalam VB

What is Object Oriented Programming?

Object Oriented Programming allows developers to mimic real world items and concepts. In an OOP world, each object knows what information describes itself and what actions it can perform with that information. OOP allows developers to create reusable objects that interact with each other to form complex entities.

Definition of Classes
A "Class" is a template which defines the attributes (properties in VB) and the actions or methods which can be performed upon those attributes for a given type of entity. The class definition is used to create "Instances" of the class, which are the actual objects used within your application.

A Class is generally considered to be a "Black Box". That is, you can use the object created from a Class without knowing how the internal code works. All the developer needs to know is which methods to call to perform certain functions. How those functions perform their tasks is hidden.

Programmers generally create a Class for each separate entity used within their application. Classes allow developers to write modifiable, readable, reusable code.

Objects = Attributes + Actions
An object is an "Instance" of a Class. In Visual Basic you can create any number of "Object Variables" from a single Class Definition. Each object knows what data describes it and how to manipluate that data.

Each data item is called an "Attribute" in OOP. Visual Basic implements these attributes as "Properties". Properties are exposed through the Public Interface of an object. Each object can have internal variables, not seen by users, which are used to store information the object requires to perform its task(s).

Example of An Object Which Exposes Public Properties

VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsPerson"
Attribute VB_Creatable = False
Attribute VB_Exposed = False

'Internal Member Variables
Private mFirstName as String

'Public Properties

Public Property Let FirstName ( Value as String)
'assign Value to internal variable from the outside world

mFirstName = Value

End Property

Public Property Get FirstName ( ) as String
'retreive internal variable and expose to outside world

FirstName = mFirstName

End Property

Objects not only contain their own data but they know how to perform tasks on that data. Tasks are performed by various functions and procedures defined in the Class Definition.These functions and procedures are called Methods in OOP. Once again only those Methods exposed by the Public Interface are available to outside users.

Example of An Object Which Exposes Public Methods

VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsPerson"
Attribute VB_Creatable = False
Attribute VB_Exposed = False

'Internal Member Variables
Private mFirstName as String
Private mLastName as String

'Public Properties

Public Property Let FirstName ( Value as String)
'assign Value to internal variable from the outside world

mFirstName = Value

End Property

Public Property Get FirstName ( ) as String
'retreive internal variable and expose to outside world

FirstName = mFirstName

End Property

Public Property Let LastName ( Value as String)
'assign Value to internal variable from the outside world

mLastName = Value

End Property

Public Property Get LastName ( ) as String
'retreive internal variable and expose to outside world

LastName = mLastName

End Property

'Public Methods

Public Function FullName ( ) as String
'retreives the persons full name

FullName = mFirstName & " " & mLastName

End Function

Encapsulation

One of the fundamental concepts of OOP is the method with which objects store and manipulate data known as Encapsulation.

Each object consists of internal variables which, when exposed to outside world, become its' attributes. That is, the data that is input and output from the object. VB defines these exposed attributes as Properties.

In addition to knowing what data to deal with, each object knows how to manipulate that data. Functions and Procedures that perform tasks are called Methods. A Method can be used internally or exposed to the programmer. If a Method is declared as Private then it can only be used inside the object. The outside world does not see it.

The developer communicates and controls the object via the Public Interface, a set of Public Properties and Methods which the object exposes to the outside. How an object performs its tasks is of no concern to the developer using the object. It is essentially a "Black Box".

Inheritance

In the pure world of OOP, objects can be created from other objects. Any properties and methods from one class are then automatically available as properties and methods of the new class. This is called Inheritance.

Visual Basic provides a modified version of Inheritance commonly termed Containment. A class can still expose its childrens' properties and methods but the developer of the class must explicitly reference the child in any calls made to those properties or methods. A comparison is the best way of explaining this concept.

C++ directly uses Person.Name when Student.Name is called





VB must explicitly call Person.Name when Student.Name is called

Let's look at how you would code this :

'Class : clsStudent
' Contains a reference to a Person Object

'private member variables
Private oPerson as clsPerson
Private iGrade as Integer

Public Sub Create ( )
'load this object and create the person object

Set oPerson = New clsPerson

End Sub

Public Property Let Name ( sNewName as String)
'set the person objects Name Property

oPerson.Name = sNewName

End Property

Public Property Get Name ( ) as String
'retreive the person objects Name Property

Name = oPerson.Name

End Property


Polymorphism

Objects can be as complex as you desire to make them. Some objects provide the functionality of several different objects with similar behaviours. This is Polymorphism, the ability to change the behaviour of a class based upon certain criteria.

Lets look at an example :

Two geographic areas have different methods to calculate Sales Tax.

Region A calculates Sales Tax at a flat 5% of the Sales Total.

Region B calculates Sales Tax on a prorated basis - 6% up to $200, 4% for all sales over $200.

We can create an object class which performs the calculation for Region A, and another class for Region B. Then create a class which references both the previous objects. When you wish to calculate taxes just tell your Wrapper Class which region to use and the proper calculations are performed.

Here's the code for this example :


'Class : clsTaxRegionA

Const iTaxRate = .05

Public function CalcTaxes ( curTaxableValue as Currency) as Currency

CalcTaxes = iTaxRate * curTaxableValue

End Function
'Class : clsTaxRegionB

Const iTaxRate1 = .06
Const iTaxRate2 = .04

Public function CalcTaxes ( curTaxableValue as Currency) as Currency

If curTaxValue < 200 then

CalcTaxes = iTaxRate1 * curTaxableValue

else

CalcTaxes = iTaxRate2 * curTaxableValue

end if

End Function
'Class : clsSalesTax

'private member variables
Private sRegion as String
Private oRegionA as clsTaxRegionA
Private oRegionB as clsTaxRegionB

Public Property Let Region ( sRegionFlag as String )

sRegion = sRegionFlag

End Property

Public Sub Create ( )

Set oRegionA = New clsTaxRegionA
Set oRegionB = New clsTaxRegionB

End Sub

Public function CalcTaxes ( curTaxableValue as Currency) as Currency
'calculate taxes based on region

if sRegion = "A" then

CalcTaxes = oRegionA.CalcTaxes (curTaxableValue)

else

CalcTaxes = oRegionB.CalcTaxes (curTaxableValue)

end if

End Function



Thursday, February 24, 2011

Getting Started with Visual Basic 6.0

Visual Basic 6 Integrated Development Environment

Visual Basic is initiated by using the Programs option > Microsoft Visual Basic 6.0 > Visual Basic 6.0. Clicking the Visual Basic icon, we can view a copyright screen enlisting the details of the license holder of the copy of Visual Basic 6.0. Then it opens in to a new screen as shown in figure 1 below, with the interface elements Such as MenuBar, ToolBar, The New Project dialog box. These elements permit the user to buid different types of Visual Basic applications

One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment (IDE). IDE is a term commonly used in the programming world to describe the interface and environment that we use to create our applications. It is called integrated because we can access virtually all of the development tools that we need from one screen called an interface. The IDE is also commonly referred to as the design environment, or the program.





Tha Visual Basic IDE is made up of a number of components

* Menu Bar
* Tool Bar
* Project Explorer
* Properties window
* Form Layout Window
* Toolbox
* Form Designer
* Code Window
* Object Browser, etc.

In previous versions of Visual Basic, the IDE was designed as a Single Document Interface (SDI). In a Single Document Interface, each window is a free-floating window that is contained within a main window and can move anywhere on the screen as long as Visual Basic is the current application. But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI) format. In this format, the windows associated with the project will stay within a single container known as the parent. Code and form-based windows will stay within the main container form.

Visual Basic startup dialog box



Menu Bar

This Menu Bar displays the commands that are required to build an application. The main menu items have sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access to the commonly used commands and a button in the toolbar is clicked once to carry out the action represented by it.

Toolbox

The Toolbox contains a set of controls that are used to place on a Form at design time thereby creating the user interface area. Additional controls can be included in the toolbox by using the Components menu item on the Project menu. A Toolbox is represented in figure 2 shown below.

Toolbox window with its controls available commonly:



Control
Description
Pointer Provides a way to move and resize the controls form
PictureBox Displays icons/bitmaps and metafiles. It displays text or acts as a visual container for other controls.
TextBox Used to display message and enter text.
Frame Serves as a visual and functional container for controls
CommandButton Used to carry out the specified action when the user chooses it.
CheckBox Displays a True/False or Yes/No option.
OptionButton OptionButton control which is a part of an option group allows the user to select only one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
ComboBox Contains a TextBox and a ListBox. This allows the user to select an ietm from the dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and VScrollBar These controls allow the user to select a value within the specified range of values
Timer Executes the timer events at specified intervals of time
DriveListBox Displays the valid disk drives and allows the user to select one of them.
DirListBox Allows the user to select the directories and paths, which are displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Shape Used to add shape (rectangle, square or circle) to a Form
Line Used to draw straight line to the Form
Image used to display images such as icons, bitmaps and metafiles. But less capability than the PictureBox
Data Enables the use to connect to an existing database and display information from it.
OLE Used to link or embed an object, display and manipulate data from other windows based applications.
Label Displays a text that the user cannot modify or interact with.


Project Explorer window

Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The Project Explorer as shown in in figure servres as a quick reference to the various elements of a project namely form, classes and modules. All of the object that make up the application are packed in a project. A simple project will typically contain one form, which is a window that is designed as part of a program's interface. It is possible to develop any number of forms for use in a program, although a program may consist of a single form. In addition to forms, the Project Explorer window also lists code modules and classes.

Properties Window

The Properties Window is docked under the Project Explorer window. The Properties Window exposes the various characteristics of selected objects. Each and every form in an application is considered an object. Now, each object in Visual Basic has characteristics such as color and size. Other characteristics affect not just the appearance of the object but the way it behaves too. All these characteristics of an object are called its properties. Thus, a form has properties and any controls placed on it will have propeties too. All of these properties are displayed in the Properties Window.

Object Browser

The Object Browser allows us to browse through the various properties, events and methods that are made available to us. It is accessed by selecting Object Browser from the View menu or pressing the key F2. The left column of the Object Browser lists the objects and classes that are available in the projects that are opened and the controls that have been referenced in them. It is possible for us to scroll through the list and select the object or class that we wish to inspect. After an object is picked up from the Classes list, we can see its members (properties, methods and events) in the right column.

A property is represented by a small icon that has a hand holding a piece of paper. Methods are denoted by little green blocks, while events are denoted by yellow lightning bolt icon.

Object naming conversions of controls (prefix)

Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar -vsb



Monday, February 21, 2011

Characteristics of VB Programming Language

Visual Basic (VB) is the third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its COM programming model. Visual Basic is relatively easy to learn and use.

Visual Basic was derived from BASIC and enables the rapid application development (RAD) of graphical user interface (GUI) applications, access to databases using Data Access Objects, Remote Data Objects, or ActiveX Data Objects, and creation of ActiveX controls and objects. Scripting languages such as VBA and VBScript are syntactically similar to Visual Basic, but perform differently.

A programmer can put together an application using the components provided with Visual Basic itself. Programs written in Visual Basic can also use the Windows API, but doing so requires external function declarations.

The final release was version 6 in 1998. Microsoft's extended support ended in March 2008 and the designated successor was Visual Basic .NET (now known simply as Visual Basic).

Like the BASIC programming language, Visual Basic was designed to be easily learned and used by beginner programmers. The language not only allows programmers to create simple GUI applications, but can also develop complex applications. Programming in VB is a combination of visually arranging components or controls on a form, specifying attributes and actions of those components, and writing additional lines of code for more functionality. Since default attributes and actions are defined for the components, a simple program can be created without the programmer having to write many lines of code. Performance problems were experienced by earlier versions, but with faster computers and native code compilation this has become less of an issue.

Although programs can be compiled into native code executables from version 5 onwards, they still require the presence of runtime libraries of approximately 1 MB in size. This runtime is included by default in Windows 2000 and later, but for earlier versions of Windows like 95/98/NT it must be distributed together with the executable.

Forms are created using drag-and-drop techniques. A tool is used to place controls (e.g., text boxes, buttons, etc.) on the form (window). Controls have attributes and event handlers associated with them. Default values are provided when the control is created, but may be changed by the programmer. Many attribute values can be modified during run time based on user actions or changes in the environment, providing a dynamic application. For example, code can be inserted into the form resize event handler to reposition a control so that it remains centered on the form, expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text box, the program can automatically translate the case of the text being entered, or even prevent certain characters from being inserted.

Visual Basic can create executables (EXE files), ActiveX controls, or DLL files, but is primarily used to develop Windows applications and to interface database systems. Dialog boxes with less functionality can be used to provide pop-up capabilities. Controls provide the basic functionality of the application, while programmers can insert additional logic within the appropriate event handlers. For example, a drop-down combination box will automatically display its list and allow the user to select any element. An event handler is called when an item is selected, which can then execute additional code created by the programmer to perform some action based on which element was selected, such as populating a related list.

Alternatively, a Visual Basic component can have no user interface, and instead provide ActiveX objects to other programs via Component Object Model (COM). This allows for server-side processing or an add-in module.

The language is garbage collected using reference counting, has a large library of utility objects, and has basic object oriented support. Since the more common components are included in the default project template, the programmer seldom needs to specify additional libraries. Unlike many other programming languages, Visual Basic is generally not case sensitive, although it will transform keywords into a standard case configuration and force the case of variable names to conform to the case of the entry within the symbol table. String comparisons are case sensitive by default, but can be made case insensitive if so desired.

The Visual Basic compiler is shared with other Visual Studio languages (C, C++), but restrictions in the IDE do not allow the creation of some targets (Windows model DLLs) and threading models.

Visual Basic has the following traits which differ from C-derived languages:
  • Multiple assignment available in C language is not possible. A = B = C does not imply that the values of A, B and C are equal. The boolean result of "Is B = C?" is stored in A. The result stored in A would therefore be either false or true.
  • Boolean constant True has numeric value −1. This is because the Boolean data type is stored as a 16-bit signed integer. In this construct −1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the Boolean value False). This is apparent when performing a Not operation on a 16 bit signed integer value 0 which will return the integer value −1, in other words True = Not False. This inherent functionality becomes especially useful when performing logical operations on the individual bits of an integer such as And, Or, Xor and Not.[5] This definition of True is also consistent with BASIC since the early 1970s Microsoft BASIC implementation and is also related to the characteristics of CPU instructions at the time.
  • Logical and bitwise operators are unified. This is unlike some C-derived languages (such as Perl), which have separate logical and bitwise operators. This again is a traditional feature of BASIC.
  • Variable array base. Arrays are declared by specifying the upper and lower bounds in a way similar to Pascal and Fortran. It is also possible to use the Option Base statement to set the default lower bound. Use of the Option Base statement can lead to confusion when reading Visual Basic code and is best avoided by always explicitly specifying the lower bound of the array. This lower bound is not limited to 0 or 1, because it can also be set by declaration. In this way, both the lower and upper bounds are programmable. In more subscript-limited languages, the lower bound of the array is not variable. This uncommon trait does exist in Visual Basic .NET but not in VBScript. OPTION BASE was introduced by ANSI, with the standard for ANSI Minimal BASIC in the late 1970s.
  • Relatively strong integration with the Windows operating system and the Component Object Model. The native types for strings and arrays are the dedicated COM types, BSTR and SAFEARRAY.
  • Banker's rounding as the default behavior when converting real numbers to integers with the Round function. ? Round(2.5, 0) gives 2, ? Round(3.5, 0) gives 4.
  • Integers are automatically promoted to reals in expressions involving the normal division operator (/) so that division of one integer by another produces the intuitively correct result. There is a specific integer divide operator (\) which does truncate.
  • By default, if a variable has not been declared or if no type declaration character is specified, the variable is of type Variant. However this can be changed with Deftype statements such as DefInt, DefBool, DefVar, DefObj, DefStr. There are 12 Deftype statements in total offered by Visual Basic 6.0. The default type may be overridden for a specific declaration by using a special suffix character on the variable name (# for Double, ! for Single, & for Long, % for Integer, $ for String, and @ for Currency) or using the key phrase As (type). VB can also be set in a mode that only explicitly declared variables can be used with the command Option Explicit.

History of Visual Basic

VB 1.0 was introduced in 1991. The drag and drop design for creating the user interface is derived from a prototype form generator developed by Alan Cooper and his company called Tripod. Microsoft contracted with Cooper and his associates to develop Tripod into a programmable form system for Windows 3.0, under the code name Ruby (no relation to the Ruby programming language).

Tripod did not include a programming language at all. Microsoft decided to combine Ruby with the Basic language to create Visual Basic.

The Ruby interface generator provided the "visual" part of Visual Basic and this was combined with the "EB" Embedded BASIC engine designed for Microsoft's abandoned "Omega" database system. Ruby also provided the ability to load dynamic link libraries containing additional controls (then called "gizmos"), which later became the VBX interface.

Timeline

  • Project 'Thunder' was initiated
  • Visual Basic 1.0 (May 1991) was released for Windows at the Comdex/Windows World trade show in Atlanta, Georgia.
  • Visual Basic 1.0 for DOS was released in September 1992. The language itself was not quite compatible with Visual Basic for Windows, as it was actually the next version of Microsoft's DOS-based BASIC compilers, QuickBASIC and BASIC Professional Development System. The interface used a Text user interface, using extended ASCII characters to simulate the appearance of a GUI.
  • Visual Basic 2.0 was released in November 1992. The programming environment was easier to use, and its speed was improved. Notably, forms became instantiable objects, thus laying the foundational concepts of class modules as were later offered in VB4.
  • Visual Basic 3.0 was released in the summer of 1993 and came in Standard and Professional versions. VB3 included version 1.1 of the Microsoft Jet Database Engine that could read and write Jet (or Access) 1.x databases.
  • Visual Basic 4.0 (August 1995) was the first version that could create 32-bit as well as 16-bit Windows programs. It also introduced the ability to write non-GUI classes in Visual Basic. Incompatibilities between different releases of VB4 caused installation and operation problems. While previous versions of Visual Basic had used VBX controls, Visual Basic now used OLE controls (with files names ending in .OCX) instead. These were later to be named ActiveX controls.
  • With version 5.0 (February 1997), Microsoft released Visual Basic exclusively for 32-bit versions of Windows. Programmers who preferred to write 16-bit programs were able to import programs written in Visual Basic 4.0 to Visual Basic 5.0, and Visual Basic 5.0 programs can easily be converted with Visual Basic 4.0. Visual Basic 5.0 also introduced the ability to create custom user controls, as well as the ability to compile to native Windows executable code, speeding up calculation-intensive code execution. A free, downloadable Control Creation Edition was also released for creation of ActiveX controls. It was also used as an introductory form of Visual Basic: a regular .exe project could be created and run in the IDE, but not compiled.
  • Visual Basic 6.0 (Mid 1998) improved in a number of areas including the ability to create web-based applications. VB6 has entered Microsoft's "non-supported phase" as of March 2008. Although the Visual Basic 6.0 development environment is no longer supported, the runtime is supported on Windows Vista, Windows Server 2008 and Windows 7. Mainstream Support for Microsoft Visual Basic 6.0 ended on March 31, 2005. Extended support ended in March 2008. In response, the Visual Basic user community expressed its grave concern and lobbied users to sign a petition to keep the product alive. Microsoft has so far refused to change their position on the matter. Ironically, around this time (2005), it was exposed that Microsoft's new anti-spyware offering, Microsoft AntiSpyware (part of the GIANT Company Software purchase), was coded in Visual Basic 6.0. Its replacement, Windows Defender, was rewritten as C++ code.
  • Visual Basic .NET (VB 7), the original Visual Basic .NET was released alongside Visual C# and ASP.NET in 2002. Significant changes broke backward compatibility with older versions and caused a rift within the developer community.
  • Visual Basic .NET 2003 (VB 7.1) was released with version 1.1 of the .NET Framework. New features included support for the .NET Compact Framework and a better VB upgrade wizard. Improvements were also made to the performance and reliability of the .NET IDE (particularly the background compiler) and runtime. In addition, Visual Basic .NET 2003 was available in the Visual Studio .NET Academic Edition (VS03AE). VS03AE is distributed to a certain number of scholars from each country without cost.
  • Visual Basic 2005 (VB 8.0) is the name used to refer to the Visual Basic .NET, Microsoft having decided to drop the .NET portion of the title.
    Visual Basic 2005 introduced features meant to fill in the gaps between itself and other "more powerful" .NET languages, adding .NET 2.0 languages features.
  • Visual Basic 2008 (VB 9.0) was released together with the Microsoft .NET Framework 3.5 on 19 November 2007.
  • Visual Basic 2010 (VB 10.0) was release in April 2010. Microsoft had planned to use the Dynamic Language Runtime (DLR) for that release but shifted to a co-evolution strategy between Visual Basic and sister language C# to bring both languages into closer parity with one another. Visual Basic's innate ability to interact dynamically with CLR and COM objects has been enhanced to work with dynamic languages built on the DLR such as IronPython and IronRuby. The Visual Basic compiler was improved to infer line continuation in a set of common contexts, in many cases removing the need for the "_" line continuation character. Also, existing support of inline Functions was complemented with support for inline Subs as well as multi-line versions of both Sub and Function lambdas.

Visual Programming vs Non Visual Programming

a visual programming language (VPL) is any programming language that lets users create programs by manipulating program elements graphically rather than by specifying them textually. A VPL allows programming with visual expressions, spatial arrangements of text and graphic symbols, used either as elements of syntax or secondary notation. Many VPLs (known as dataflow or diagrammatic programming) are based on the idea of "boxes and arrows", where boxes or other screen objects are treated as entities, connected by arrows, lines or arcs which represent relations.

VPLs may be further classified, according to the type and extent of visual expression used, into icon-based languages, form-based languages, and diagram languages. Visual programming environments provide graphical or iconic elements which can be manipulated by users in an interactive way according to some specific spatial grammar for program construction.

Current developments try to integrate the visual programming approach with dataflow programming languages to either have immediate access to the program state resulting in online debugging or automatic program generation and documentation (i.e. visual paradigm). Dataflow languages also allow automatic parallelization, which is likely to become one of the greatest programming challenges of the future.

Note: Microsoft Visual Studio (Visual Basic, Visual C#, Visual J#, etc.) are commonly confused to be but are not visual programming languages. All of these languages are textual and not graphical. MS Visual Studio is a visual programming environment, but not a visual programming language, hence the confusion.

Windows Programming vs DOS Programming

A Windows program is quite different from its ancient relative, the MS-DOS program. A DOS program follows a relatively strict path from beginning to end. Although this does not necessarily limit the functionality of the program, it does limit the road the user has to take to get to it. A DOS program is like walking down a hallway; to get to the end you have to walk down the hallway, passing any obstacles that you may encounter. A DOS program would only let you open certain doors along your stroll.

Windows, on the other hand, opened up the world of event-driven programming. Events in this context include, for example, clicking a button, resizing a window, or changing an entry in a text box. The code that you write responds to these events. To go back to the hallway analogy: In a Windows program, to get to the end of the hall, you just click on the end of the hall. The hallway can be ignored. If you get to the end and realize that is not where you wanted to be, you can just set off for the new destination without returning to your starting point. The program reacts to your movements and takes the necessary actions to complete your desired tasks (Visual Basic .NET).

Another big advantage in a Windows program is the abstraction of the hardware; which means that Windows takes care of communicating with the hardware for you. You do not need to know the inner workings of every laser printer on the market just to create output. You do not need to study the schematics for graphics cards to write your game. Windows wraps up this functionality by providing generic routines that communicate with the drivers written by hardware manufacturers. This is probably the main reason that Windows has been so successful. The generic routines are referred to as the Windows Application Programming Interface (API).

Another big advantage in a Windows program is the abstraction of the hardware; which means that Windows takes care of communicating with the hardware for you. You do not need to know the inner workings of every laser printer on the market just to create output. You do not need to study the schematics for graphics cards to write your game. Windows wraps up this functionality by providing generic routines that communicate with the drivers written by hardware manufacturers. This is probably the main reason that Windows has been so successful. The generic routines are referred to as the Windows Application Programming Interface (API).

Visual Basic changed the face of Windows programming by removing the complex burden of writing code for the user interface (UI). By allowing programmers to draw their own UI, it freed them to concentrate on the business problems they were trying to solve. Once the UI is drawn, the programmer can then add the code to react to events.

Visual Basic has also been extensible from the very beginning. Third-party vendors quickly saw the market for reusable modules to aid developers. These modules, or controls, were originally referred to as VBXs (named after their file extension). Prior to Visual Basic 5.0, if you did not like the way a button behaved, you could either buy or create your own, but those controls had to be written in C or C++. Database access utilities were some of the first controls available. Version 5 of Visual Basic introduced the concept of ActiveX, which allowed developers to create their own ActiveX controls.

When Microsoft introduced Visual Basic 3.0, the programming world changed again. Now you could build database applications directly accessible to users (so-called front-end applications) completely with Visual Basic. There was no need to rely on third-party controls. Microsoft accomplished this task with the introduction of Data Access Objects (DAO), which allowed programmers to manipulate data with the same ease as manipulating the user interface.

Versions 4.0 and 5.0 extended the capabilities of Version 3.0 to allow developers to target the new Windows 95 platform. Crucially they also made it easier for developers to write code, which could then be manipulated to make it usable to other language developers. Version 6.0 provided a new way to access databases with the integration of ActiveX Data Objects (ADO). The ADO feature was developed by Microsoft to aid Web developers using Active Server Pages to access databases. All of the improvements to Visual Basic over the years have ensured its dominant place in the programming world. It helps developers write robust and maintainable applications in record time.

With the release of Visual Basic .NET in February 2002, most of the restrictions that used to exist have been obliterated. In the past, Visual Basic has been criticized and maligned as a “toy” language, as it did not provide all of the features of more sophisticated languages such as C++ and Java. Now, Microsoft has removed these restrictions and made Visual Basic .NET a very powerful development tool. This trend continues with Visual Basic .NET. Although not as drastic a change as from Visual Basic 6 to Visual Basic .NET, there are enough improvements in the language and integrated development environment that Visual Basic .NET is a welcome upgrade and is a great choice for programmers of all levels.