• No results found

Visual Basic 6.0 Notes short

N/A
N/A
Protected

Academic year: 2021

Share "Visual Basic 6.0 Notes short"

Copied!
43
0
0

Loading.... (view fulltext now)

Full text

(1)

Introduction to Visual Basic 6.0

Visual basic is an ideal programming language for developing sophisticated professional applications for Microsoft windows. It makes use of graphical user interface for creating robust and powerful applications. Coding in GUI environment is easy and quicker as compare to traditional, linear programming languages.

Visual Basic was developed from BASIC programming language. It required at least Microsoft windows 95/NT 3.51, 486 processor and minimum of 16 M.B. of RAM and also 250 MB of hard disk to install complete enterprise edition.

Starting Visual Basic 6.0

Visual Basic is initiated by using the Program option -> Microsoft Visual Studio and Microsoft Visual Basic 6.0 from it. Then it opens into a screen as shown below (fig 1.1)

Fig .1.1

The integrated Development Environment

One of the most significant changes in visual basic 6.0 is the integrated Development Environment (IDE). IDE is the 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 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

• Object Browser

(2)

This is bar display the commands that are required to build an application. The main menu items have sub menu items that can be chosen when needed.

Tool Bar

The toolbar in the menu bar provide quick access to the commonly used commands.

Toolbox

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

Fig 1.2

• The pointer provides a way to move and resize the control and forms.

• Label display a text that the user cannot modify or interact with.

• Frame control serves as a visual and functional container for control.

• Checkbox display a True/False or yes/no option.

• Textbox is a control used to display message and enter text.

• The Listbox display a list of items from which a user can select one.

• ComboBox contains a textbox and Listbox. This allows the user to select an item from Dropdown Listbox, or to type in a selection in the textbox.

• HScrollBar and VScrollBar controls allow the user to select a value within the specified range of value.

• Timer control executes the timer events at specified intervals of time.

• Dirlistbox allows the user to select the directories and paths, which are displayed

• Shape control use to draw shape on form.

• Image control is used to display icons, bitmaps, metafiles etc Pointer Label Frame Checkbox Combobox HScrollBar Timer DirListBox Shape Image OLE VScrollBar DriveListBox FileListBox Line Data Picture Textbox CommandButton OptionButton Listbox

(3)

• OLE control is used to link or embed an object, display and manipulate data from other windows based applications.

• Picturebox displays icons/bmp/jpg and metafiles. It displays text or acts as a visual container for other controls.

• CommandButton control which is a part of an option group allows the user to select only one option even if it display multiple choices.

• The FileListBox display a set of files from which user can select the desired one.

• The DriveListBox display the valid disk drives and allows the user to select one of them.

• Line control to draw a line on form.

• Data control enables the user to connect to an existing database and display information from it.

Project Explorer

Docked on the right side of the screen, just under the toolbar, is the project Explorer window. It display objects of your project like forms, classes and modules. All the object that make up the application are packed in a project.

Fig 1.3 (project explorer )

Properties Window

The properties window is docked under the project explorer window. The properties windows exposes the various characteristics of selected objects.

Fig 1.4 ( Properties window )

Form Layout

The form layout window use to place the form starting position after you runs it.

Fig 1.5 (Form layout window)

Variables, Data Types and Modules

Variable are used for storing values temporarily. Declaring a variable tells Visual basic to reserve space in memory. It is not must that a variable should be declared before using it.

A defined naming strategy has to be followed while naming a variable.

(4)

2. It must be unique within the same scope.

3. It should not contain any special character like %,&, #, @ or $ Syntax

Dim variable [as type] For e.g

Dim str as string Dim I as integer

Scope of variables

A variable is scoped to a procedure-level(local) or module-level depending on how it is declared. A variable is declared in general declaration section of a Form, and hence is available to all the procedures. Local variable are recognized only in the procedure in which they declared. They can be declaring with dim and static keyword.

Local Variable:

Local variable is one that is declared inside a procedure. This variable is only available to the code inside the procedure and can be declared using dim statement as given below

Dim I as integer

Static Variables

Static variables are not reinitialized each time visual basic invokes a procedure and thus retains or preserves value even when a procedure ends.

e.g.

Static in as integer

Module Level Variables

Module level variables are available to all the procedure in the module. They are declared using Public or private keyword.

e.g.

public nk as integer private st as string

declaring a variable with public keyword makes it available throughout the application even for the other modules. A variable can have same name with different scope.

Data Type:

By default Visual Basic variables are of variant data types. The variant data type can store numeric, date/time or string data. When a variable is declared, a data is supplied for it that determines the kind of data they can store.

A list of visual basic data types are given below

Type Name Values Range

Byte 0 to 255

Boolean True or False

Integer -32,768 to 32,767

Long -2,147,483,648 to 2,147,483,647

Single -3.402823 * 103 to -1.401298 * 10 45 for negative values. 1.401298 * 10-45 to 3.402823 * 10 38 for positive values. Double -1.79 * 10 308 to -4.94 * 10 -324 for negative values

4.94 * 10 -324 to 1.79 * 10 308 for positive values Date January 1, 100 to December 31, 9999

(5)

String 0 to approximately 2 billion characters

Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Data Type Conversion

Visual Basic functions either to convert a string into an integer or vice versa and many more conversion functions. A complete listing of all the conversion functions offered by visual basic is elucidated below. Conversion To Function Boolean Cbool Byte Cbyte Currency Ccur Date Cdate Decimals Cdec Double Cdbl Integer Cint Long Clng Single Cn=sng String Cstr Variant Cvar Error CVErr

Note: A conversion function should always be placed at the right hand side of the calculation statement.

Procedure:

Visual basic programs can be broken into smaller logical components called procedures. Procedures are useful for condensing repeated operations such as the frequently used calculations, text and controls manipulation etc. The benefits of using procedures in programming are:

• It is easier to debug a program with procedures, which breaks a program into discrete logical limits.

• Procedures used in one program can act as building block for other programs with slight modification.

A procedure can be sub, function or property procedure

Sub Procedure

A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the statement between Sub and End Sub are executed.

Syntax

[private | public ] [ static] Sub Procedure_Name [ (arg_list)] [Statements]

End Sub

Argument list is separated by commas. Each argument acts like a variable in the procedure. There are two type of sub procedures namely general procedures and event procedures.

Event Procedures

An event procedure is procedure block that contains the control’s actual name, an underscore ( _ ), and the event name

(6)

Private sub Form1_Load( ) Statement block End sub

This is event for form1. Execute when load form.

General Procedures

A general procedure is declare when several event procedure perform the same action. It is good programming practice to write common statements in separate procedure and then call them in the event procedure

Function Procedures

Function are like sub procedures, except they return a value to calling procedure. They are especially useful for taking one or more pieces of data, called arguments and performing some tasks with them. Then function return value that indicate result of the task.

e.g.

The following function procedure calculates area of circle of given radius. Function Area(a as double) as double

Area = 3.14 * a^2 End Function

Control Flow Statements

Control statements are used to control the flow of program’s execution. Visual Basic supports control structures such as If -- --- -- Then, If -- --- -- Then -- -- -- Else-- End If. Select----Case and Loop structures, such as Do While---Loop, Do---Loop while and For…..Next method.

If….Then….Else statement

The If… then block is used for conditional execution of one or more statements. Syntax: If Condition Then

Statements End If

The statement is execute only if the given condition is true. The condition is usually a comparison, but it can be any expression that evaluates a numeric value

If….Then …. Else Statement

To execute one block of code if condition is false. Syntax: If Condition Then Statements Else Statements End If

Select ……..Case Statement

Select…Case structure is an alternative to If …Then ….Else If for selectively execute a single block of statement from among multiple blocks.

(7)

Select Case Index Case 0 Statements Case 1 Statements Case n Statements End Select

Select …. Case statement evaluates an expression once at the top of the block where as if…then else structure evaluates different expressions for each Else If statement.

Do While…..Loop statements

The Do While …. Loop is used to execute statements until a certain condition is met. Following do while .. loop counts from 1 to 100

Count=1

Do while count < 100 Count = count + 1 Loop

Do…Loop While Statement

The do…..loop While Statement first execute the statements and then test the condition after each execution. The following program block is same to first one(like Do While loop)

Count = 200 Do

Text1.text = str(count) Count=count + 1

Loop While count < 300

The program execute the statements between do and loop while structure in any case. Then it determines weather the count is less than 300. If so, the program again execute block until it gets false.

Do….Loop Until statement

The do….loop until structure execute the statements until the condition is satisfied. It is an infinite loop if the test fails and to get released from this loop we can use CTRL + BREAK combination or End From Run menu.

The following code entered in the Form Load() procedure illustrates the structure. Private Sub Form_load()

Do

X$ = INputBox$(“Password ?”) Loop until X$ = “Sunil”

End Sub

The For….Next Loop statement

The for…Next Loop is another way to make loops in visual basic Syntax

(8)

Statements Next [Var_name]

For I = 1 to 100 step 1 Text1.text = str(I) Next I

Exit For and Exit Do Statement

A For…Next Loop Can be terminated by an Exit For Statement. Consider the following statement block For I = 1 to 100 Text1.text = str(i) If I= 50 then Exit For End if Next

In this example loop is for 1 to 100 but we stop or exit from loop by using exit for statement in it. Same we can exit from do loop

I = 1 Do while I < 100 Text1.text = str (I) I = I+ 2 If I > 50 then Exit Do End If Loop

With ….. End With Statement

When properties are set for objects or methods are called, a lot of coding is included that acts on the same object. It is easier to read the body by implementing with With… End With statement.

For e.g suppose we want to set properties for Form then With form1 .backcolor = qbcolor(2) .enabled = True .MaxButton = false .Font = “Times” End with

In the above coding, the object form get all its properties which we set in with block.

Modules

Code in visual basic is stored in the form of modules. The three kinds of modules are Form module, Standard module, and class modules. A simple application may contain a single form and the code resides in that Form module itself. As the application grows, additional Forms are added and there may be a common code be to executed in several Forms. To avoid the duplication of code, a separate module containing a procedure is created that implements the common code. This is a standard module.

Class module is a foundation of the object oriented programming in visual basic. New objects can be created by writing code in class modules. Each module can contain variable declaration or procedures.

(9)

A sequence of variables by the same name can be referred using array. The individual elements of an array identified using an index. Arrays have upper and lower bounds and elements have to lie within those bounds. Each index number in an array is allocated individual memory space. We can declare array of type variant, user defined types and object variables.

There are two types of array

• Fixed size array: The size of array always remains the same

• Dynamic array: The size of can be changed Fixed Size Array

Fixed array can be declared by giving a name with the upper limit in the parentheses. The long data type. e.g

dim lengths(10) as Integer

In the above illustration, lengths is a name of the array and the number 10 include in the parentheses is the upper limit of the array. This create array having 10 elements with index number from 0 to 9.

Dim length(1 to 10) as Integer having lower limit 1 to upper index number 10. Dim marks(50,50) it create two dimensional array.

Dim marks(1 to 10,1 to 10) it create two dimensional array with lower and upper limits. Dynamic array

There will be a situation when the user may not know the exact size of the array at design time. Under such situation, a dynamic array can be initially declared and can add elements when needed instead of declaring the size of the array at design time.

Dim newarray( )

The actual elements can be allocate using ReDim statement ReDim newarray( n )

Each time on the executing the ReDim statement, the current data of array is lost and the default value is set. But if we want to change the size of array without lost any previous elements then use keyword Preserve ReDim Preserve newarray(20)

User-Define Data Type

Variable of different data types when combined as a single variable to hold several related information is called user-define data type.

A type statement is used to create new type. User-define type can only be private in form while in standard modules can be public or private.

e.g.

Private type student Name as string Age as integer Per as double End type e.g. Creating variables Dim s1 as student e.g. Or creating array

(10)

Dim s(10) as student

Accessing members of user-define type Variable name.member name

e.g.

text1.text = s1.name accessing name of student s1

Visual Basic Built-in Functions

Many built-in functions are offered by Visual Basic that fall under various categories.

• Date function

• Format functions

• String functions Date Functions

Now Return current system date and time. Year() Return year number from given date. Month() Return month number from given date. Day() Return day of given date.

WeekDay() Return week day number from given date. Hour() Return hour number form given time. Minute() Return minute from given time Second() return second from given time. DateAdd()

Return a date to which specific interval has been added. Syntax: DateAdd(interval,number,Date)

Where interval is “M” ,”D” or “Y” Number to add in date

Date in which you want to add. e.g.

DateAdd(“m”,3,”02/14/2002”) it return 06/02/2002 (add 3 month in date) DateDiff()

Returns a Variant (Long) specifying the number of time intervals between two specified dates. Syntax

DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]]) The DateDiff function syntax has these named arguments:

Part Description

interval Required. String expression that is the interval of time you use to calculate the difference between date1 and date2.

date1, date2 Required; Variant (Date). Two dates you want to use in the calculation.

firstdayofweek Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.

(11)

firstweekofyear Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Dim TheDate As Date ' Declare variables. Dim Msg

TheDate = InputBox("Enter a date")

Msg = "Days from today: " & DateDiff("d", Now, TheDate) MsgBox Msg

DatePart() Returns an integer containing the specified part of the given date DateValue() Convert a string into date format.

String Functions

StrComp() Compare two strings

Lcase() Convert the given string into lower case. Ucase() Convert the given string into Upper case. Len() Return a length of given string

Format() Convert a given string into given format. Lset(),Rset() Justify a string

Instr() Return a variable(long) specifying the position of the first occurrence of the string within another. Letf() Return specified number of character from left side of given string

Rigth() Return specified number of character from Right side of given string

Trim() Return a given string by removing all it’s blank space from left and right side. Mid() Return a specified number of character from mid of given string.

Ltrim()Trim all blanks of left hand side.

Rtrim() Trim all blanks of Right hand side.

Working with Forms

In visual basic, the form is the container for all the controls that makes up the user interface. A form may fill entire screen or have other forms within it. It may be a custom dialog box. When a Visual basic application is executing, each window it displays on the Desktop is Form.

Setting Form Properties Border Style

None No border is shown.

Fixed single A single-pixel width border is shown Sizable This is default setting.

Fixed Double A double-pixel width is shown around the form. Fixed ToolWindow this type of border is use for toolbars.

Sizable Toolwindow Same as fixed toolwindow, but border are resizable. Caption

The title for the window is store in the caption property. Control Box

This is determine weather the control box, available by clicking the upper left corner /icon of a window. Icon

(12)

MousePointer

This property sets the value that indicate the type of mouse pointer displayed. MaxButton/MinButton

Set max or min button of window which are present on title bar. Moveable

By setting it false it is possible to prevent the user from moving window. MDIChild

This property specifies if this window must be shown within a multiple document interface (MDI) window. StartUpPosition

Set the starting position of window.

Displaying Forms

Show Method

The show method is used to display the form object. For e.g. to display the form frmcalculator, the following code is written.

Frmcalculator.show Using Load Statement

The load statement is used to load a form or control into memory but does not display it. To load the form frmcalculator, the following code should be enter.

Hiding and Unloading Forms Using the Hide Method

The hide method hides a form. For e.g., the following code hides the form object frmcalculator Frmcalculator.Hide

Using the Unload Statement

The unload statement removes the form from the display and releases the memory. The following code should be entered to unload frmcalculator from memory.

Unload frmcalculator

Setting Run time and design time properties

Many properties can be set at either design time or runtime. At design time, the controls are added to a project, their properties set and relevant code is written.

To set properties at design time following steps are followed.

1. Select the control or object whose properties you want to set. 2. Activate the property window

3. Scroll to the property you want to set 4. Enter a new setting.

At run time properties can change by program’s code. This is done by Object.propertyname = value

e.g

(13)

Form1.backcolor = QBcolor(3)

Form1.Caption = “Sample Application” Form1.WindowStatus = VBNormal

Form1.Width = 5000 Form1.Height = 5000 End Sub

Creating and Using Controls

A control is an object that can be drawn on a Form object to enable or enhance user interaction with an application. Controls

Classification of controls

Visual Basic Controls are broadly classified as standard controls, Active X controls and insert-able objects. Standard controls such as CommandButton, Label and frame controls are contained inside .EXE file and are always include in the ToolBox which cannot be removed. ActiveX controls exist as separate files with either .VBX or .OCX extension. They include specialized controls, few from them given below

• MSChart control

• The Communication control

• The Animation control

• TreeView control

• The Picture clip control

• SysInfo control

Text Box Control

A TextBox control, some times called an edit field or edit control, display information entered time at design time, entered by the user at run time or assign any value at run time.

Some Properties of a Text Box

Name This is a name used in program to identify the control

MaxLength Set maximum no of characters that can be entered in control. MultiLine weather a control can accept multiple lines or not.

PasswordChar It replace the text of control with given character with. Text to assign text to control at design time.

Command Button

A command Button control to begin, interrupt, or end a process. When chosen, a Command Button appears pushed in and so is sometimes called push button.

Properties of a command button control

To display text on a command button control, set its caption property. An event can be activated by clicking a command button

A button’s background color can be set by setting Backcolor property. Text color of a command button can be set using forecolor property. Font can be change using font property.

Enabled or disable button

Tooltip text can be set using Tooltip property.

A button click event is handled whenever a command button is clicked. To add a click event handler, double click on button at design time, which adds a subroutine like the one given below.

Private sub Command1_Click() ...

(14)

End Sub

Using option button control

Option button a set of choices from which a user can select only one button by

• Clicking at run time.

• Assigning the value property to True in code like Option1.Value = True

• Using the shortcut keys specified in the caption of a label To disable Option button at run time its Enabled property set to False.

Using Listbox and ComboBox Controls

ListBox and ComboBox controls present a set of choices that are displayed vertically in a single column. If the number of items exceed the value that can be display, scroll bars will automatically appear on the control. These scroll bars can be scrolled up and down or left to right through the list.

Adding items to a list

It is possible to populate the list at design or at run time.

Design Time: To add items to a list at design time, click list in the property box and then add the items. Press CTRL + ENTER after adding each item.

Run Time: The AddItem method is used to add items to a list at run time. The AddItem method uses the following syntax:

Object.AddItem item, Index

The item argument is string that represents the text to add to the list.

The index argument is an integer that indicates where in the list to add the new item. Removing Items from a List

The RemoveItem method is used to remove an item from a list. The syntax for this is given below. Object.RemoveItem.index

Selecting an Item from a list

To access the items in a listbox we use the ListIndex and List properties. The list index property sets the index number of the currently selected item. The first item in the list having index number 0. ListIndex return -1 if no item is selected. The list count return total number of items in listbox.

Sorting the List

To sort the list set sorted property to True.

Using ComboBox

A Combo Box combines the features of Textbox. This control enables the user to select either by typing text into combo box or by selecting an item from list.

There are three types of Combo Box styles that are given below. Dropdown Combo (style 0)

Simple Combo (style 1) Dropdown list (style 2) Using ScrollBar Control

The Scrollbar is a commonly used control, which enables the user to select a value by positioning it at the desired location. It represents a set of values. The min max property represents the minimum and maximum value. The value property represents its current value.

(15)

Managing Menus

Creating and managing menu at Design Time

Visual Basic applications can be enhanced by adding menus to it. It offers a convenient and consistent way to group commands and easy way for users to access them.

The menu bar appears appear below the title bar and it may contain one or more menu titles. When a menu title is clicked it displays a set of menu items under that title. Each menu item corresponds to a menu control that is defined in a menu editor and performs a specific action.

Using the Menu Editor

A menu editor can be used to add new commands to the existing bars. A menu editor can be added only after opening a project. To display a menu editor command is chosen from the Tools menu or menu editor button is clicked in the tool bar.

Writing Code form menu Control

Each menu control has click event, which is execute when the menu item is selected or clicked. The following code is entered in the code window for green color option of menu.

Private sub grn_Click() Form1.backcolor= QBcolor(2) Grn.Enabled = False

Blue.Enabled = True Red.Enabled = True

End sub When the green color is selected by clicking on it, form backcolor will be change into green color and that green option form menu is make disable and to other’s enable.

Adding a Separator Bar and Shortcut key.

Separator bar is a line that separates the menu items, which is mainly useful for obtaining clarity. To add it in menu, Right click on the form select menu editor

Place the pointer where you want to insert separator In the caption TextBox ‘-‘ is typed and give any name

Title Bar Menu Bar

(16)

Using Access and Shortcut keys

Access keys allow the user to open a menu by pressing the Alt key with a letter key. To open the Edit menu in all Windows applications, for e.g. you can press Alt-E. .

Access key is designed by the programmer and they are marked with an underline character. To assign Access key to menu item, add & sign before letter. e.g. “&File”.

Shortcut Keys

Shortcut keys are similar to access key has a special meaning in menu design, but inside a opening menu, they run a command when pressed. To assign a shortcut key to a menu command, dropdown the shortcut list in the menu editor and select a keystroke.

Pop-Up Menus

A pop-up menu is a floating menu that is displayed over a form independent of the menu bar. Pop-up menus are also called context menus. Because the items displayed on the pop-up menu depend on where the pointer is located when the right mouse button is clicked.

Any menu can be displayed as a pop-up menu at run time provided it has one menu item.

The following code displays the colors menu when the user clicks right mouse button over the form at run time.

Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = 2 Then

PopupMenu cc End If

End Sub

Making menu control invisible

It run time if user wants to enable and disable to menu items, it is possible by setting the Enabled property to True or False. When a menu item is disabled, it is dimmed and cannot be selected. But it is still visible and the menu items seen.

Mnu_green.Enable = False

But if you want to hide menu item from display set visible property false for it. Mnu_green.Visbile = False

Using Check Marks

In some programs we may require check marks to be placed in the menu items. To place a check mark in a menu item, the checked property is set to true. The following example code entered in the Form_load( ) procedure places a check mark in the menu item Red.

Mnured.checked = True

Menu Control Array:

A menu control array is a set of menu items on a menu that share the name and event procedure. Each menu control array element is identified by a unique index value, indicated in the Index property box on the menu editor. When the member of the menu control array recognizes an event, visual basic passes the index property value to the event procedure as additional argument. The event procedure must include the code that can check the value of the index property.

Mouse Events

Visual basic applications respond to various mouse events, which are recognized by most of the controls. The main events are MouseDown, MouseUp and MouseMove. MouseDown occurs when the user

(17)

presses any mouse button and MouseUp occurs when the user releases any mouse button. MouseMove occurs whenever the mouse pointer is moved to a new point on the screen. These events use the arguments button, Shift, X, Y and they contain information about the Mouse’s condition when the button is clicked.

The first argument is an integer number called button. The value is 1 if left button is clicked and 2 if right button is clicked.

The second argument is an integer called shift. The value of this argument indicates weather the mouse button was clicked simultaneously with the Shift key or Alt key.

The third and fourth arguments X and Y are the coordinates of the mouse location at the mouse button was clicked

e. g.

This is program to draw a line on form with the help of mouse.

First method the starting points, when you press mouse button down to draw line (MouseDown events)

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Form1.CurrentX = X

Form1.CurrentY = Y End Sub

Second method for drawing a line on current points (Mouse/Move events)

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) If Button = 1 Then

Line (Form1.CurrentX, Form1.CurrentY)-(X, Y) End If

End Sub

Dragging and dropping

Dragging is a process of clicking the mouse button in a control and moving the mouse while holding down the mouse button. The action of releasing the mouse button after the dragging is called dropping. The following drag-and –drop properties, events and method are supported in Visual Basic.

DragMode property enables automatic or manual dragging of a control. DragIcon property specifies the icon that is display when the control is dragged.

DragDrop event is recognized when a control is dragged onto the object. DragOver event is recognized when a control is dragged over the object.

Drag method starts or stops manual dragging.

All the controls except menus, timer, lines and shapes support the above mentioned properties and method. Forms recognize the DragDrop and DragOver events but they do not support Drag method and the

properties DragMode and DragIcon.

To develop an application to explain drag and drop events we use a image, textbox and command button

Private Sub Command1_DragOver(Source As Control, X As Single, Y As Single, State As Integer)

Dim inf As String

info = "NOW DRAGGING " info = info + img.Tag

(18)

info = info + " OVER THE Exit button" info = info + " STATE" + Str(State) Text1.Text = info

End Sub

Private Sub Form_DragDrop(Source As Control, X As Single, Y As Single) Text1.Text = ""

img.Move X, Y End Sub

Private Sub Form_DragOver(Source As Control, X As Single, Y As Single, State As Integer) Dim inf As String

info = "NOW DRAGGING " info = info + img.Tag

info = info + " OVER THE FORM " info = info + " STATE" + Str(State) Text1.Text = info

End Sub

In this program when user drag image icon on form or command button related message will be display on the screen, and when release the mouse the image will be place or move on the current location of mouse pointer.

File Controls

Usually you use the Common Dialog File Open and File Save As to get file names and file paths from the user, but sometimes that just won’t do. For e.g. you have a program where you want to let user select files but don’t want to use dialog boxes, In that and similar cases, you can use the visual basic file controls: The Drive List Box, Directory List Box and File list Box

Drive List Box:

Use this tool to draw a drive list box in a form, you get currently selected drive in a drive list by using its Drive property, and when the user changes the drive in the control, a Change event is generated. But File controls always work with each other.

e.g.

Drive List box

File List box Directory List box

(19)

Here in e.g when the user selects a new drive, we pass that new drive on ot a directory list box, dir1 using that drive as the new root directory in Dir1:

Sub Drive1_Change()

Dir1.Path = Drive1.Drive End Sub

Using The Directory List Box

The directory list box control displays directories as a hierarchical set of folders. The important property of the list box is Path property, which holds the path of the current directory. When the user changes the current path, a Change events is generated. For example, when the user makes a change in directory list box, dir1, we can pass the new path to file list box, File1

Sub Dir1_Change()

File.Path = Dir1.Path End Sub

Using The File List Box Control

The file list box control lets you display the files in a directory as a list of names.

The important properties of the File list box are Path and FileName properties. In our e.g. we load file select from File List box to Picture Box and txt file in RichText Box. So when we click on File name following event get execute.

Private Sub File1_Click() On Error Resume Next Dim fname As String

fname = File1.Path + "\" + File1.FileName Text1.Text = fname

If LCase(File1.Pattern) = "*.bmp" Or LCase(File1.Pattern) = "*.gif" _ Or LCase(File1.Pattern) = "*.ico" Then Picture1.Picture = LoadPicture(fname)

ElseIf LCase(File1.Pattern) = "*.txt" Then

rtb.FileName = fname

End If End Sub

Graphics for Application

Visual Basic provides a variety of ways to create and use graphics in an application, which adds styles, interest and visual structure to the interface of an application. Graphic objects such as lines, circles and bitmaps can be displayed in visual basic in a quicker and easier way.

(20)

The number of times a twip is used by all visual basic movements, sizing and graphical drawing statements is limited to one. A twip is a unit that specifies the dimensions and location of the graphics objects. There are 1440 twips in one inch. Thses measurements designate the size when printed.

The coordinate system is a two dimensional grid that defines the location on the form or any other container which is represented as(X, Y). X represents the location of a point on the X-axis and Y represents a point on the Y-axis

A color is represented by long integer and there are four ways of specifying it at run time. They are specified using RGB function, QBColor function, and using one of the intrinsic constants listed in the Object Browser and by entering a color value directly

RGB(255,0,0) return Red color RGB(0,255,0) return Green color RGB(0,0,255) return Red color

QBcolor function takes a single number that specifies a Quick Base color number from 0 to 15 and returns a long integer that can be used in visual basic color property.

Form1.backcolor = QBColor(4)

Using Graphics Controls

Visual Basic provides three controls to create graphical applications such as image, Line and shape. These controls are very useful at design time.

The main advantage of graphics controls is that we can create an application with less code.

Line Control

A line control is a straight-line segment that is drawn at design time. The position, length, color and style of the line control can be positioned to customize the look of an application

Shape Control

A shape control is a Visual element that contains several predefined shapes. In order to view a specified shape, the control is added to the form by double clicking it. The default shape will be rectangle. The shape property is selected from the properties window, which drops down a list of shapes, from which the user can select the desired one.

The FillColor, FillStyle properties of the Shape control can be changed so that desigred color and style can be obtained.

Image Control

An image control is a rectangular portion into which picture files can be loaded. The picture files include bitmap files, icon files and metafiles.

Adding Pictures:

Line control and shape control are used for drawing geometrics shapes such as lines, circles, squares and so on. For drawing more complex figure we can use a picture file. A picture file can be loaded on a form, image control or Picture Control.

A picture can be added by the following two ways at design time.

• In the properties window of the Form, the Picture property is selected. Visual Basic displays a dialog box from which a picture file can be selected. Similarly a picture can be loaded in a PictureBox and Image control.

• A picture can be paste on form or into PictureBox or Image control A picture can be added by the following ways at run time.

• LoadPicture function is used to specify the filename and assign the picture to the Picture property. Picture1.Picture = LoaPicture(“C:\Image\sst.jpg”)

(21)

• Any picture loaded to a form, PictureBox or Image control can be copied to another Form, PictureBox or Image control.

Set picture1.picture = Image1.Picture

• A picture can be copied from ClipBoard object Removing Picture

A picture can be removed at run time using LoadPicture function without arguments. Set image1.picture = LoadPicture(“ “)

Moving and Sizing Pictures

If a form, PictureBox or an Image control is moved, the picture associated with it also moves automatically. The autosize property of a picture box can be set to True in order to automatically expand and accommodate a new picture.

Using Graphics Methods

Every graphics method draws output on a Form, PictueBox or to the printer object. The following statement draw a point on the form

Form1.PSet(500,500)

The PSet method draw a point at x, y co-ordinates that is specified by its arguments. Form1.Cls

Clear all the graphics PixelColor = point(30,40)

Point method return the color of a particular pixel. Line(x1, y1) – (x2, y2), Color

Line method draw a line from x1,y1 to x2,y2 of given color, x1 ,y1 is a starting point coordinates and x2, y2 is ending points.

Visual Basic provides a much simpler way to draw a box. Line(600,600) – (1000,1000), Qbcolor(4),B

B option is used with Line Method to draw a box.

A Circle method is used to draw a variety of circular and elliptical shapes. To draw a circle Visual Basic required the location of the circle’s center and length of its redius.

Circle(1400, 1200), 500

Multiple Document Interface (MDI)

MDI stand for Multiple Document Interface. A Multiple Document Interface is used for opening many Windows at the same time. All the document windows are contained in a parent window, which provides a workspace in the application. Visual Basic applications can have only one MDI form, which contains all the child forms. A child form is an ordinary Form that has its Child property set True. Child form are display within the internal area of MDI form at run time.

Add new MDI form to Project:

To add new MDI form, select it from project menu or right click on project name in Explorer window and select Add, MDI form.

(22)

To all other forms of your project set MDIChild property True to associate these forms with parent form. e.g.

In this example we create a MDI form having two child form Name Form1 and Form2 after clicking on Load form Option of Form menu, show form1 and on form2 show form2. window use to show list of open form

Steps:

1. Open New project

2. Add MDI form from project menu 3. Add Form from project menu

4. To form1 and Form2 set MDIChild property to True 5. Create the menu

Form

Load Form1 Load Form2 Exit

Window

Enter following code in MDI form

Private Sub loadfrm1_Click () Form1.Show

End Sub

Private Sub loadfrm2_Click () Form2.Show

End Sub

Debugging in Visual Basic

Debugging is a process by which error are identified and resolved in source code. In visual basic error can occur anywhere during entire development cycle such as

• Design time

• Compile time

• Run Time

Design Time Bugs

Errors that occurs in the IDE and before the program is compiled are called design-time bugs. These are the most common ones. These bugs are caused by misuse of some component.

The following e.g. shows a function that works as long as a textbox control is passed to it. If any other type of control (say text box, here, the extra space causes the problem) is passed, it fails to execute and an error is reported this is a design time error, which is display the moment the user navigates to the next statement. Sub settext( ctrl as text box, txt as String)

Ctrl.text = Lcase(Trim$(txt) + “ : ” + Date$ End sub

On entering the first statement of the above coding in the general declaration section, the following error is report.

(23)

Compile-time bugs are those that occur when we attempt to create the program executable file (EXE) or run the project. Visual Basic can locate compile-time bugs if the Visual Basic application is set up correctly. Visual Basic set the several points to users, which can be change as needed.

Compile-time bugs are detected by visual basic automatically when the program is compiled using F5. If the Start With Full Compile option is used, the Compile On Demand can be turned on, and the developer will not find any bugs until the line of code with the bugs is actually executed.

Compile errors occur as a result of incorrectly constructed code such as Next statement without a corresponding For statement or programming mistakes that violate the rules of Basic, such as misplace word, missing separator, or type mismatch. Compile errors included syntax errors. These include mismatched parentheses or an incorrect number of arguments passed to an intrinsic function.

Runtime bugs

A Visual Basic runtime error is the exception generated by Visual Basic when it ascertains that the code is about to perform something illegal. An illegal function could be something as simple as trying to determine the size of a file that dose not exist or attempting to multiply two numbers, the result of which exceeds the storage space that could be contained by the data type.

However, using an error handler could prevent this error dialog box from being shown and save the program from crashing. By practices we can

also use our knowledge that a particular error identified by its error number will be

generated to help guide our logic. This sort of

“inline” error handling is very powerful and can be handled using an error handler that checks for the condition of, say Error 57, and then does something to avoid the situation. This error can be finally rectified by changing the code suitably.

E.g.

Consider the following example where we declare two variable x and y. try dividing x (assign a value 9) by y (assign 0), assigning the quotient to another variable z.

Private sub Form1_load() Dim x as Integer Dim y as Integer Dim z as Integer X=9 Y=0 Z = x / y End Sub

Visual Basic Debugging Tools

The best way to keep bugs out is to prevent then in the first place. Visual Basic gives a programming several tools, include IDE options and compile directives, to help achieve this goal.

(24)

Visual Basic offer several IDE option that can help the user write better code.

• Auto Syntax Check

• Required Variable Declaration

• Auto List Members

• Auto Quick Info

• Auto data Tips

• Option Explicit

• Option Compare Text

Additional settings and debugging aids can be viewed in a dialog box shown in the fig. using the following steps

1. Select Option from Tools Menu

2. Choose the Editor tab in the Option dialog box

Require Variable declaration:

This option explicitly inserts the Option Explicit statement in each new form, module, or class created. A dim, private, public, ReDim or static statement must be used to declare a variable before the value is assigned to it. If an undeclared variable is used, an error occurs at compile time.

e.g.

Option Explicit

Private sub Form1_Load() Sum = 0

End sub

Auto Syntax Check:

The Auto Syntax Check option forces Visual Basic to check the line of code when the user moves the cursor off the line.

e.g.

Private sub Form1_load() Dim a integer

End sub

In this program Dim a here required “As” so compiler give a error message when we try to move cursor to next line.

Auto Quick Info:

The Auto Quick Info in Visual Basic display ant required or Optional parameters for methods. VB display all possible parameters while highlighting the one we are currently entering. Auto Quick Info makes it easier to use methods and properties because we no longer have to remember or look up all the arguments it’s properties and methods.

Debugging Tools are designed to help the user with logic and run-time errors. Visual Basic provides several buttons in the ToolBar that are helpful for debugging. They are

Breakpoint: Defines a line in the code window where Visual Basic suspends execution of application Instant Watch: Lists the current value of an expression while the application is in the break-mode. Calls: Presents a dialog box that shows all procedures that have been called but not yet run completely.

(25)

Visual Basic provides several built-in methods for controlling the execution of the program in real time. It is possible to execute the program line by line or procedure by procedure or a combination of the two. These basic debugging actions are called Stepping. Because it enables the developer to walk through the program, examining the variables and logic, stepping is the most powerful debugging tool offered by Visual Basic. The various debugging commands are discussed below.

Step Into: Execute the next executable line of the code in the application and steps into procedures. This enables to check every line of code as it is being executed. This option can be accessed from debug menu or by pressing F8.

Step Over: Execute the next executable line of the code in the application without stepping into procedure. The procedure the user steps over does execute, but Visual Basic does not walk through the stepped-over procedure line-by-line. Shortcut key is Shift+F8.

Step Out: Moves program execution back to the calling procedure. This is the functional equivalent of Exit sub or Exit Function. It is simple exits the current procedure without executing any more code in that procedure.

Set Next: Enables the user to move program execution to any executable line of code in the current procedure.

While debugging an application, we should clearly understand which of the three modes such as design time, run time or break mode we are in at a given time. Break mode of an application is viewed by clicking CTRL+BREAK at run time.

Using the Debugging Window

Debug window is one of Visual Basic’s window that allows to run individual commands immediately, by typing in the command and pressing the Enter key. It automatically opens at run time.

1. In break mode, the debug window can be used to execute individual line of code, View or change values of variables and properties, and view watch expressions.

2. At run time, it can be used to display data or messages as the programs as the program runs.

3. At design time, the developer can view the previous output to the Debug window, but cannot execute code.

The debug window has two part- Watch window and immediate window. The split bar separates the Debug window into two panes. The upper pane display the Watch Window. The lower pane display the Immediate Window.

Watch Window

Watch pane displays the current watch expressions, which are expressions whose values are decided by the user as code is executed. The Watch pane appears automatically if the watch expressions are defined in the project. At times we want to monitor the value of a variable for a certain state- for example to determine weather a flag is set to True or False.

Steps to add watch expression

1. Add watch command is chosen from the Debug menu. 2. The Expression is entered in the Expression box.

3. If necessary, the scope of the variables is set and an option button is selected. 4. The OK button is clicked.

Immediate Window

The immediate pane appears by default the first time the debug window is opened. From break mode, the code is executed immediately by entering it in this pane. This window is the right place for the

(26)

users to modify data or test functions during development. We can enter any valid expression in this window and VB will execute it. If a reference is made to an object outside the scope of the current code execution, Visual Basic will generate an error.

Testing data and procedure in Immediate Pane

While debugging an application, Sometimes it may necessary to execute individual procedures, evaluate expressions or assign new values to the variables or properties. The Immediate Pane can be used to accomplish new values to the variables or properties. The Immediate Pane can be used to accomplish such tasks. Expressions can be evaluated by printing in Immediate Pane. Some advantages of these facility.

•The data or message can be viewed at run time.

•Feedback is displayed in separate area, so that it does not interfere with the output that the user is seeing.

•Since the coding is saved as part of the form, these statements needs not be redefined the next time we work on the application.

e.g.

Private sub Form_load( ) Dim a as integer

Dim b, c as integer A = 10

B = 6 C = a – b

Msgbox “Value of c is “ & C Debug.print “ Value of c is :” & c End sub

On executing the above code the value of c is displayed in the Immediate window using the Debug.print statement.

Using a Breakpoint to selectively Halt Execution

At run time, a breakpoint tells VB to halt before executing a specific line of code. A breakpoint can be set or removed at design time or at break mode. To set or remove a breakpoint,

The insertion point is moved to the line of code where the breakpoint is to be set or removed.

The Toggle Breakpoint is chosen from the Debug Menu or Toggle button is chosen in the Toolbar or press shortcut key F9.

Writing Error Handlers

Visual Basic has specific built-in ways to handle runtime errors, called trappable errors. When such an error occurs, you can direct the execution of your program to an error handler, which is a section of code written specifically to deal with errors.

On Error GoTo Label.

The visual basic On error Goto statement is the foundation of handling trappable errors. When you execute an On Error GoTo Label Statement in your code. Execution is transferred to the code starting at label if a trappable error has occurred. The code following that label is your error handler.

Private Sub Form_Load() Dim a, b, c As Integer On Error GoTo diverror a = 10

b = 0 c = a / b

MsgBox "Value of C =: " & c diverror:

(27)

MsgBox "Divided by Zero Error", vbCritical, "Error" End Sub

In this example value of b is zero, if don’t trap error then our program is terminate with an error, but in this we trap error and give appropriate Message to user.

Err :

It is a object Contains information about run-time errors. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.

Main Properties of Err object Err.Number : Return error number

Err.Description : Return error description

e.g. you may show this error message in program.

MsgBox "Des: " & Err.Description & "NUMBER : " & Err.Number

On Error GoTo line#

Besides using a label to start an error handler, you can refer to an error handler by line number in visual basic, using on error goto line# statement.

e.g.

1 Private Sub Form_Load()

2 Dim a, b, c As Integer

3 On Error GoTo 8

4 a = 10

5 b = 0

6 c = a / b

7 MsgBox "Value of C =: " & c

8 MsgBox "Divided by Zero Error", vbCritical, "Error"

9 End Sub

Using On Error Resume Next

The On Error Resume Next statement provides an easy way to disregard errors, if you want to do so. Once you execute this statement, execution continues with the next line of code if the current line generates an error, and the error is disregarded.

On Error GoTo 0

To turn off error trapping, you can use the On Error GoTo 0 statement.

Err Function

Returns a Variant of subtype Error containing an error number specified by the user. Syntax

CVErr(error number)

The required errornumber argument is any valid error number. Remarks

Use the CVErr function to create user-defined errors in user-created procedures. For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely your

(28)

function will not return what you expect. In this event, CVErr allows you to return an error number that tells you what action to take.

Note that implicit conversion of an Error is not allowed. For example, you can't directly assign the return value of CVErr to a variable that is not a Variant. However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type.

e.g

Sub Test()

Debug.Print CalculateDouble("345.45robert") End Sub

' Define CalculateDouble Function procedure. Function CalculateDouble(Number)

If IsNumeric(Number) Then

CalculateDouble = Number * 2 ' Return result. Else

CalculateDouble = CVErr(2001) ' Return a user-defined error End If ' number.

(29)

Database: Using DAO, RDO, and ADO

You may wonder why there are three different sets of database object in visual basic, the reason is historical. At first, VB only support DAO, which connected to the Microsoft Jet database engine (the database engine in MS Access). Then, recognizing that there are other database types available, Microsoft created the Open database connectivity (ODBC) standard and supported ODBC with Remote Data Objects in Visual Basic. Finally For Web to access data over network Microsoft create Active Data Object (ADO) that allows connections on the same computer, over networks and through the web, and is intended to support ODBC. ADO is also called OLE DB, and in fact, it’s based on COM programming techniques.

There are two ways to work with DAO, RDO and ADO object sets in VB. The first way is working with the special controls that support them. The Data Control, Remote Data Control and ADO data control. You use them to connect to and to move through database but they don’t display actual data, you bind them to other Visual Basic controls, and those bound controls handle the display. The second way is working with the three database object sets directly in code, without controls like the data control or DAO data control, and that’s what we’ll do in the next chapter.

What are Databases?

Nearly all business applications need to store large volumes of data, organized in a format that simplifies retrieval. This is accomplished with a database management system (DBMS), a mechanism for manipulating tabular with high-level commands.

The database management system hides low-level details, such as how data are store in a database, and frees the programmers to concentrate on managing information, rather than on the specifics of manipulating files or maintaining links among them.

Each individual data entry in a table, such as a student’s name, goes into a field in the table. A collection of fields together, such as the Name and Grade fields in our table, make up a record. Each record gets its own row in a table, and each column in that row represents a different field.

A collection of records- that is, row of records where each column is a field-become a table. What’s then is a Database? A database is just a collection of one or more tables.

Evolution of computing Architectures

Let’s us discuss about the evolution of client-server architecture for various computing models. In this chapter we discuss about three architectures.

Centralized System Architecture

Companies that needed real computing power turned to the mainframe computer, which is centralized system architecture. The salient most feature of a centralized system is that the only movement of marshalling are keystrokes between the client and the host machine. Marshalling is the process of packing interface elements and sending them across process boundaries. Thus in a centralized system, keystrokes are marshalling from the terminal (client) to the host. The centralized system architecture is illustrated in fig.

(30)

Merits of Centralized System Architecture

• Excellent Security

• Centralized administration as both application logic and data reside on the same machine De-Merits of Centralized System Architecture

• Mainframe computers are very expensive to buy, lease, maintain and use.

• The limitation is that both the application and the database live within the same machine process thereby offering no way to truly partition the application logic beyond the physical limitations of mainframe.

In 1980 personal computers made an entry into the business world along with which, came the resources like printers, modems and hard-disk storage. The introduction of the local area network(LAN) and the use of file server architectures soon following the introduction of personal computer.

File Server Architecture

The file server system brought a complete change in implementation of the computer architecture from the mainframe. In this system, the application logic now executed on the client workstation instead of the server. These servers also provided access to computing resources like printer and large hard disk. The complete File Server architecture is illustrated in fig.

The merit of the file server system is the low cost entry point with flexible arrangement. Computer resources can be added or reduced as and when necessary using this system.

The drawback of the file server architecture is that all application logic is executed on the client machine. The job of the server is to provide files only to store the data. Though the application’s file might be located on the server, the application runs in the client machine’s memory space using the client’s processor. This results in the client machine’s need memory amount of power to run the application.

Taking into account the de-merits of the centralized and file server system architecture, the client server architecture made its advent.

Data Application

Data

Network Server

Terminal1 Terminal1 Terminal1 Terminal1

Keystrokes Terminal Character

(31)

Client Server Model

Client server architecture is a process involving a minimum of two independent entities, one is the client and the other is the server. The client makes a request to the server and the server services the requests and the resulting data is sent to the client. In this application, two separate applications operating independently could work together to complete a task. A well brought out implementation of this concept is the SQL based Database Management System. The client server architecture is well illustrated in fig. here, unlike the file server system, the request that goes to server in not merely a request for file in the form of disk input/output requested as series of disk blocks. Instead, instructions are communicated to an application running on the server, and the server executes those requests and sends a response to the client.

The request may take the form of the SQL query submitted to a SQL database engine. The database engine in turn processes the request and a result set is send to the client. Thus the two independent process work together to accomplish a task and exemplifies the client-server relationship.

The most popular client/server applications revolve round the use of DBMS such as Oracle and MS SQL server. These applications are referred to as backend and offer support for storage manipulation and retrieval of business persistent data. They use structure query language (SQL). As a standard method for submitting client requests.

Data Network Server

Terminal1 Terminal2 Terminal3 Terminal4

Disk I/O required

Disk Blocks

App. Logic1 App. Logic2 App. Logic3 App. Logic4

Data Network Server

Terminal1 Terminal2 Terminal3 Terminal4

Disk I/O required

Disk

App. Logic1 App. Logic2 App. Logic3 App. Logic4 Application

(32)

Thus a major advantage of Client/Server architecture is reducing traffic and, in most cases, an incredibly quicker execution time.

Two Tire and Three Tire Client Server Model

The various system architecture that has been in use have been discussed so far. Now let us move on to discuss the creation of in information system that can change with business needs, needs that mandate tighter budget and higher quality in addition to simply processing transactions generating report. To respond to the challenges being presented by the business environment a new three-tier or n-tier client/server approach has been introduced.

Two Tier Client/Server model

In two-tier model, a desktop machine operates as a client and network server function as a back-end database engine. The logic in two in two-tier model is split between the two physical location namely the server and client. The client in a two-tier model is necessarily a 4GL like Visual Basic or Power Builder. The salient point for a two-tier application is that the business logic must physically reside either on the client or be implemented on the back-end within the DBMS in the form of triggers and stored procedures. Both triggers and procedures are stored as precompiled collections of SQL statements and control-of-flow statements.

In VB, using any of the data controls that provide a graphical link to the back-end data source create a two tier client/server relationship.

Merits of two-tier

The merits of this two-tier model are – data access is simplified, allowing very rapid development of applications. The GUI is bound directly to the data source and all the details of data manipulation are handled automatically. But there is a disadvantage in this, i.e. though the data access is simplified, it is less flexible due to which the user will not have complete control of interactions with the data source.

Limitations of Two-Tier model

Not Scalable: Inability of two-tier approach to grow beyond the physical boundaries of a client and server machine.

Unmanageable: Business rules cannot be encapsulated and deployed centrally because of which sharing common process and reusing work become difficult.

Poor Performance: The graphical interface binding to the data consumes major resources on the client machine, which results in poor performance and dissatisfied clients.

Three-Tier Client/Server Model:

An improved model for client/server development resulted as an outcome of limited effectiveness of two-tiered client/server solutions. The three-tier client/server model is based on the ability to build partitioned applications. Partitioning an application breaks our code into logical components. The Service Model employed to design this architecture suggests that these components can be logically grouped into three tier. User services, Business services and Data services. The service and its location are given below.

Service Location

User Services Client Business logic Server Data services Server

(33)

On developing an application using this model and technique, each component can then be placed on a suitable machine that will provide the best performance depending on our situation and the current business need. The three-tier logic can be extended to any number of tier/services called as Multi-Tier or n-Tier architecture.

Values of three-tier client/server development

Reuse: The time invested in designing and implementing components is not wasted as they can be shared among applications.

Performance: As components can be placed on machines other than the client workstation, load processing can be shifted from a client machine that may be underpowered to a server with extra horsepower. This offers us the best possible methods for each aspect of our application’s execution, resulting in better performance.

Manageability Encapsulation of applications services into components allows us to break down large, complex applications into more manageable pieces.

Maintenance: centralizing components for reuse has an added benefit. They become easier to redeploy on making any amendments to keep pace with business needs.

Data Access Options

Visual Basic provides a variety of options to access remote Client/Server databases. They are:

Data Access Object (DAO): It communicates with the data source through the JET database engine. Data Control: It binds data-aware control to Microsoft Access and other ODBC data sources.

ODBCDirect: It allows accessing of ODBC data source through the RDO with ADO objects, bypassing JET database engine.

Remote Data Objects (RDO): It provides a framework for using code to create and manipulate components of a remote ODBC database system.

Remote Data Control (RDC): It binds the controls to an ODBC remote database.

Open Database Connectivity (ODBC): this is an API call interface to the open Database Connectivity libraries and drivers to provide data access to Microsoft SQL server and other database that provide an ODBC driver.

Visual Basic Library for SQL Server (VBSQL): it is an implementation of the DB library API specifically designed to provide access to SQL Server through a visual basic application

Active Data Object (ADO): This is a programming model that eliminates the need to choose from among DAO and RDO and all other data access methods. It is designed to provide a common bridge between different database, files systems and e-mail servers.

Data Access Objects

A DAO is a collection of object classes that model the structure of a relational database system. They provide properties and methods that allow to accomplish all the operations to manage such a system, including features for creating databases, defining tables, navigating and querying a database. Visual Basic supports Data Access Object such as DBEngine, Workspace, Database, TableDef, Field, Index and Recordset Objects.

References

Related documents