You are on page 1of 38

GIMBI TVET COLLEGE

Database Administration
LEVEL -IV

Unit of Competence
Apply object oriented programming language

Module Title: Apply object oriented programming


LG Code: ICT DBA4 05 07 11

TTLM Code : ICT DBA4 M05 01 16


Information Sheet DBA
LO1: Apply basic language syntax and layout
Introduction Programming Language
What is program?
A computer program is a sequence of instructions written using a Computer Programming Language to perform
a specified task by the computer. Programs are written to solve problems or perform tasks on a computer.
The two important terms that we have used in the above definition are:
 Sequence of instructions
 Computer Programming Language
To understand these terms, consider a situation when someone asks you about how to go to a nearby some place
(e.g. shop, hospital, etc. ). You will use Human Language to tell the way to go to the exact place, something as
follows:

 Go straight

 Move half kilometer

 Take left from the red light

 Move around one kilometer

 Search the shop at your right side


The above sequence of instructions is actually a Human Program written in English Language, which instructs
on how to reach the desired shop from a given starting point. This same sequence could have been given in any
other human language, provided the person seeking direction knows any other languages.
Computer program, which is a sequence of instructions written in a Computer Language to perform a specified
task by the computer perform something like that.
A computer program is also called computer software, which can range from two lines to millions of lines of
instructions. The program instructions are also called program source code and computer programming is also
called program coding. A computer without a computer program is just a dump box; it is programs that make
computers active.
As we have developed so many languages to communicate among ourselves, computer scientists have
developed several computer programming languages to provide instructions to the computer (i.e., to write
computer programs).
Program Design
We must have to plan our programs before typing them into code editor. For example, when builders construct
houses they don’t immediately grab their lumber and tools and start building. They first find out what the
owner of the house wants, and then they draw up the plans, order the materials, gather the workers, and finally
start building the house. The same is true in programming.
Designing the program guarantees that the entire program structure is more accurate and keeps us from having
to make changes later. If we do not properly plan every step, it is going to take us longer to create the final,
working program. It is always more difficult to make major changes after we write our program.
The hardest part of writing a program is breaking it into logical steps that the computer can follow. To write a
program we should:
1. Define the problem to be solved with the computer.
2. Design the program’s output (what the user should see).By
3. Break the problem into logical steps to achieve this output.
4. Write the program (using the editor).
5. Compile the program.
6. Test the program to assure it performs as we expect.
Apply object oriented programming language Page | 1
Information Sheet DBA

Computer Programming
The act of writing computer programs is called computer programming. In other word it is the process of
developing and implementing various sets of instructions to enable a computer to do a certain task.
Programmers translate the solutions or tasks into a language that computer can understand. As we write
programs, we must keep in mind that the computer will only do what we instruct it to do. Because of this, we
must be very careful and systematic with our instructions.
Even if some of them are known by only their developers; there more than 2500 programming languages in the
world which can be used to write computer programs and following are few of them:
 Java  C#  J#
 VB  Python  COBOL
 C  PHP  Agora
 C++  J  Delphi, etc
Programming languages allow programmers to code software. The three major families of languages are:
 Machine languages
 Assembly languages
 High-Level languages
Machine Languages
It comprised of 1s and 0s. It is the unique language of a computer. It is difficult to program because one
misplaced 1 or 0 will cause the program to fail. Example: 00000101= 5 & 00001001=9
Assembly Languages
Assembly languages are a step towards easier programming. It comprised of a set of elemental commands
which are tied to a specific processor. Assembly language code needs to be translated to machine language
before the computer processes it. Example: ADD 1001010, 1011010
High-Level Languages
The syntax of HL languages is similar to English. Historically, we divide HL languages into two groups:
 Procedural languages
 Object-Oriented languages (OOP)
Procedural Languages
Early high-level languages are typically called procedural languages. They are characterized by sequential sets
of linear commands. The focus of such languages is on structure.
Examples include C, COBOL, FORTRAN, LISP, Perl, HTML, and VBScript
Object Oriented Programming
Object-oriented programming began development in the 1960’s. Originally it coined/created by Xerox PARC to
designate a computer application that describes the methodology of using objects as the foundation for
computation. By the 1980’s, OOP rose to prominence as the programming language of choice, exemplified by
the success of C++. Object oriented programming was created because of the need to overcome the problems
that were found with using structured programming techniques. While structured programming uses an
approach which is top down, OOP uses an approach which is bottom up. First programming language to use
objects was Simula67. It was designed for the purpose of creating simulations.
Currently, OOPs such as Java, J2EE, C++, C#, Visual Basic.NET, Python and JavaScript are popular OOP
programming languages.
Some key features of the Object Oriented programming are:
 Emphasis on data rather than procedure
 Programs are divided into entities known as objects

Apply object oriented programming language Page | 2


Information Sheet DBA
 Data Structures are designed such that they characterize objects
 Functions that operate on data of an object are tied together in data structures
 Data is hidden and cannot be accessed by external functions
 Objects
 communicate with each other through functions
 New data and functions can be easily added whenever necessary
 Follows bottom up design in program design
Characteristics of Object Oriented programming language
Inheritance
Inheritance is about the ability for one class to define itself as having all the properties and methods of a
particular class, and then extending the definition of the base class by adding additional properties and methods.
Inheritance gives you the ability to use all of the properties and methods from one class within another class.
Instead of having to copy and paste code from one class to another, you use the keyword Inherits to get the
functionality from the base class.
Allows programmers to create new classes based on an existing class
Methods and attributes from the parent class are inherited by the newly-created class
New methods and attributes can be created in the new class, but don’t affect the parent class’s definition
Reasons for Using Inheritance (Advantages)
Inheritance is desirable because it:
 Promote code reusability.
 Avoid duplication of identical code.
 Reduce time consumption.
 Decrease the risk of introducing bugs in the various classes.
One thing to remember when you are considering using inheritance is that the relationship between the two
classes should be an "is a" type of relationship. For example, an Employee is a Person, and a Manager is a
Person, so these two classes can inherit from the Person class.
Encapsulation
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that
manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to
the important OOP concept of data hiding.
Most of the time when we use certain tools, we hardly pay attention to the details about the functionality of the
tool. We may also focus on different parts which make up the tool. But these require more detail which confuse
the user of the system. If the details are unwanted why show them to the users? So the method of ignoring these
unwanted details of an entity is termed as abstraction. Therefore, the creator of application might attempt to
hide these unwanted details. This action is termed as encapsulation. In other word, encapsulation is an
implementation of abstraction. Encapsulation directly leads to two main advantages:
Data Hiding: The user of the class does not come to know about the internals of the class. Hence, the user
never comes to know about the exact data members in the class. The user interacts with the data members only
through the various member functions provided by the class.
Data Security: Since the data, members are not directly available to the user directly but are available only
through the member functions a validity check can always be imposed to ensure that only valid data is been
inserted into the class. So a Date class, which contains individual data members for storing date, month and
year, will have it ensured the month is never 13 or the date is never exceeding 31.
Polymorphism
Polymorphism means the occurrence of something in several different forms. So, in object-oriented paradigm it
means the ability of an entity to exhibit different forms at runtime. However, why would such a kind of feature

Apply object oriented programming language Page | 3


Information Sheet DBA
be required? One major reason to have this is to eliminate the type inspection. With polymorphism, inspection
eradicated totally.
Abstraction
The ability to represent data at a very conceptual level without any details.

Attributes/ properties
Some of the types of information kept in objects may be thought of as attributes of the object. Properties tell
something about or control the behavior of an object, such as its name, color, size, or location. When you refer
to a property, you first name the object, add a period, and then name the property.
It describes an object; or the “adjectives” of objects. In code, usually can be identified by a “descriptive” word –
Enabled, BackColor Each attribute typically has a value from a set associated with the attribute.
Methods
Actions associated with objects are called methods. Or it is a things which an object can do; the “verbs” of
objects. In code, usually can be identified by an “action” word -- Hide, Show and Clear. Each of the predefined
objects has a set of methods that you can use.
Events
Forces external to an object to which that object can react. An event occurs when the user takes an action, such
as clicking a button, pressing a key, scrolling, or closing a window. Events also can be triggered by actions of
other objects, such as repainting a form or a timer reaching a preset point.

Classes and Objects


Classes
A class is a data type that allows programmers to create objects. A class provides a definition for an object,
describing an object’s attributes (data) and methods (operations).
With one class, you can have as many objects as required. This is analogous to a variable and a data type, the
class is the data type and the object is the variable.
Objects
Think of an object as a thing, or a noun. Objects sometimes correspond to things found in the real world. Many
of the entities that have to be dealt with in a computer system are naturally modeled as "objects". For example, a
graphics program may have objects such as "circle", "square", "menu". Or Examples of objects are forms and
controls.
Forms are the windows and dialog boxes you place on the screen; controls are the components you place inside
a form, such as text boxes, buttons, and list boxes.
Every object has both state (data) and behavior (operations on data). Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating, etc.
Objects have the characteristics those they:
i. Maintain their own state information;
ii. Can be created dynamically by the program;
iii. Need to interact with other objects as a manner of course.
An object is an instance of a class.
The .NET Framework
The Framework provides for easier development of Web-based and Windows-based applications, allows
objects from different languages to operate together, and standardizes how the languages refer to data and
objects. Several third-party vendors have created versions of other programming languages to run in the .NET
Framework.

Apply object oriented programming language Page | 4


Information Sheet DBA
The .NET languages all compile to (are translated to) a common machine language, called Microsoft
Intermediate Language (MSIL). The MSIL code, called managed code, runs in the Common Language Runtime
(CLR), which is part of the .NET Framework.

VB.Net Overview
Visual Basic .NET (VB.NET) is an object-oriented computer programming language which implemented on the
.NET Framework. In Object-Oriented Programming methodology, a program consists of various objects that
interact with each other by means of actions. The actions that an object may take are called methods. Objects of
the same kind are said to have the same type or, more often, are said to be in the same class. When we consider
a VB.Net program, it can be defined as a collection of objects that communicate via invoking each other's
methods. It is an evolution of classic Visual Basic language, it is not backwards-compatible with VB6, and any
code written in the old version does not compile under VB.NET. Like all other .NET languages, VB.NET has
complete support for object-oriented concepts. Everything in VB.NET is an object, including all of the primitive
types (Short, Integer, Long, String, Boolean, etc.) and user-defined types, events, and even assemblies. Some of
the reasons that make VB.Net a widely used language are that; it is:
 Modern, general purpose.
 Object oriented.
 Component oriented.
 Easy to learn.
 Structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 Part of .Net Framework.
Source Files
Visual Basic .NET source code is saved in files with a .vb extension. But when Visual Basic .NET code is
embedded in ASP.NET web page files such files have an .aspx extension.
Source files are plain-text files that can be created and edited with any text editor, such as WordPad and
Notepad. When you use Visual Studio .NET, source files are listed in the Solution Explorer window, and all
source is included from these files when the solution is built. When you are compiling from the command line,
all source files must appear as command-line arguments to the compile command.
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic
rules for naming classes in VB.Net are as follows:

 A name must begin with a letter that could be followed by a sequence of letters, digits 0 − 9 or
underscore.

 The first character in an identifier cannot be a digit.

 It must not contain any embedded space or symbol like ? - +! @ # % ^ & * [ ] { } . ; : " ' / and \.
However, an underscore _ can be used.

 It should not be a reserved keyword.

VB.Net Keywords
Keyword is a word that is reserved by a program because the word has a special meaning. Keywords can be
commands or parameters. Every programming language has a set of keywords that cannot be used as variable

Apply object oriented programming language Page | 5


Information Sheet DBA
names. Keywords are sometimes called reserved names so that you cannot use them as names for programming
elements such as variables or procedures.

The following table lists the VB.Net reserved keywords:


AddHandler AddressOf Alias And Namespace New Next Not
AndAlso Ansi As Assembly Nothing NotInheritabl NotOverridable Object
Auto Boolean ByRef Byte e
ByVal Call Case Catch On Option Optional Or
CBool CByte CChar CDate OrElse Overloads Overridable Overrides
CDec CDbl Char CInt
ParamArray Preserve Private Property
Class CLng CObj Const
Protected Public RaiseEvent ReadOnly
CShort CSng CStr CType
ReDim REM RemoveHandler Resume
Date Decimal Declare Default
Return Select Set Shadows
Delegate Dim DirectCast Do
Shared Short Single Static
Double Each Else ElseIf
Step Stop String Structure
End Enum Erase Error
Sub SyncLock Then Throw
Event Exit False Finally
To True Try TypeOf
For Friend Function Get
Unicode Until Variant When
GetType GoSub GoTo Handles While With WithEvents WriteOnly
If Implements Imports In Xor #Const #ExternalSource #If...Then...#Els
Inherits Integer Interface Is e
#Region - & &=
Let Lib Like Long
* *= / /=
Loop Me Mod Module \ \= ^ ^=
MustInherit MustOverrid MyBase MyClass + += = -=
e

Variable and datatypes


The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the
data within its own memory allocation and a Reference Type contains a pointer to another memory location that
holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the
stack.

Apply object oriented programming language Page | 6


Information Sheet DBA
Value Type
A Value Type stores its contents in memory allocated on the stack. When you created a Value Type, a single
space in memory is allocated to store the value and that variable directly holds a value.
If you assign it to another variable, the value is copied directly and both variables work independently.
Predefined datatypes, structures, enums are also value types, and work in the same way. Value types can be
created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack.
e.g. int x = 10;
Here the value 10 is stored in an area of memory called the stack.
Reference Type
Reference Types are used by a reference which holds a reference (address) to the object but not the object itself.
Because reference types represent the address of the variable rather than the data itself, assigning a reference
variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the
same location of the heap as the original value. Reference Type variables are stored in a different area of
memory called the heap. This means that when a reference type variable is no longer used, it can be marked for
garbage collection. Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
e.g. int[] iArray = new int[20];
Statements and Lines
VB.NET statements can be placed on one or more lines. Unlike C++, C#, and Java, there is no statement
terminator character in VB. When continuing a statement across more than one line, you must end continuation
lines with a space followed by an underscore character (_). For example, the following VB.NET statement
spans two lines:
Function CreateFullName(LastName As String , _
FirstName As String)
Namespaces
Namespaces are used in .Net to organize class libraries into a hierarchical structure and reduce conflicts
between various identifiers in a program. By helping organize classes, namespaces enable us to manage our
projects efficiently and in a meaningful way that is understood by consumers of the class library. Namespaces
enables reusable components from different companies to be used in the same program without the worry of
ambiguity caused by multiple instances of the same identifier.
Namespaces provide a logical organization for programs to exist. Starting with a top-level namespace, sub-
namespaces are created to further categorize code, based upon its purpose.
In .Net, the base class library begins at the System namespace. There are several classes at the System level
such as Console, Exception etc.
Comments
It also called remark statement. A Remark statement is a line of code shown in green. Remark statements are
non-executable. VB ignores remarks when running a project. It is used to document your program code.
Remarks are very useful for large programs. They can be used to embed comments that only programmers will
read into programs for later reference.

You can add comments to your code using the apostrophe (‘) character. Everything to the right of an apostrophe
is ignored by the VB.NET compiler:
x = y + 5 ‘Add 5 to the value of y
'Today's date
'Illustrates displaying information to read-only
NB: VB.NET does not support multiline comments like some other languages.

Apply object oriented programming language Page | 7


Information Sheet DBA
Procedures
Like in most programming languages the basic unit of executable code in VB.NET is the procedure.
A procedure is a small program that is meant to solve a relatively small problem. In fact, sometimes it is called
a sub-program. A program developer writes the procedure and a user would only see the result. A procedure is a
block of Visual Basic statements enclosed by a declaration statement ( Function , Sub , Operator , Get , Set )
and a matching End declaration. All executable statements in Visual Basic must be within some procedure.
VB supports different types of procedures while two basic types of procedures include: the subroutine (or sub)
and the function.
Sub Procedures
A Sub procedure in Visual Basic statements enclosed by the Sub and End Sub statements. The Sub procedure
performs a task and then returns control to the calling code, but it does not return a value to the calling code..
Each time the procedure is called, its statements are executed, starting with the first executable statement after
the Sub statement and ending with the first End Sub, Exit Sub, or Return statement encountered.
You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which means you
can call it from anywhere in your application that has access to the module, class, or structure in which you
defined it. A Sub procedure can take arguments, such as constants, variables, or expressions, which are passed
to it by the calling code.
Declaration Syntax
The syntax for declaring a Sub procedure is as follows:
[ modifiers ] Sub  subname [( parameterlist )]
' Statements of the Sub procedure.
End Sub
The modifiers can specify access level and information about overloading, overriding, sharing, and
shadowing.
Function Procedures
A Function procedure is a series of Visual Basic statements enclosed by the Function and End
Function statements. The Function procedure performs a task and then returns control to the calling code.
When it returns control, it also returns a value to the calling code.
Each time the procedure is called, its statements run, starting with the first executable statement after the
Function statement and ending with the first End Function, Exit Function, or Return statement
encountered.
You can define a Function procedure in a module, class, or structure. It is Public by default, which means
you can call it from anywhere in your application that has access to the module, class, or structure in which you
defined it.
A Function procedure can take arguments, such as constants, variables, or expressions, which are passed to it
by the calling code.
Declaration Syntax
The syntax for declaring a Function procedure is as follows:
VB
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function

DATA TYPES
Datatype in a programming language describes that what type of data a variable can hold. When we declare a
variable, we have to tell the compiler about what type of the data the variable can hold or which data type the
variable belongs to.
Data types refer to an extensive system used for declaring variables or functions of different types. The type of
avariable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
VB.Net provides a wide range of data types.
Apply object oriented programming language Page | 8
Information Sheet DBA

The following table shows all the data types available in VB.Net
Data Type Storage Allocation Value Range
Depends on
Boolean True or False
implementing platform
Byte 1 byte 0 through 255 (unsigned)
Char 2 bytes 0 through 65535 (unsigned)
0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on
Date 8 bytes
December 31, 9999
0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9...E+28)
with no decimal point; 0 through +/-
Decimal 16 bytes
7.9228162514264337593543950335 with 28 places to the right of the
decimal
-1.79769313486231570E+308 through -4.94065645841246544E-324,
Double 8 bytes for negative values 4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values

Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)


-9,223,372,036,854,775,808 through
Long 8 bytes
9,223,372,036,854,775,807(signed)
4 bytes on 32-bit
platform
Object Any type can be stored in a variable of type Object
8 bytes on 64-bit
platform
SByte 1 byte -128 through 127 (signed)
Short 2 bytes -32,768 through 32,767 (signed)

-3.4028235E+38 through -1.401298E-45 for negative values;


Single 4 bytes
1.401298E-45 through 3.4028235E+38 for positive values

Depends on
String 0 to approximately 2 billion Unicode characters
implementing platform
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned)
Depends on Each member of the structure has a range determined by its data type
User-Defined
implementing platform and independent of the ranges of the other members
UShort 2 bytes 0 through 65,535 (unsigned)

OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

Apply object oriented programming language Page | 9


Information Sheet DBA
Operators that take one operand are called unary operators. Operators that take two operands are called binary
operators. Unary operators use prefix notation, meaning that the operator precedes the operand (e.g., -5). Binary
operators (except for one case) use infix notation, meaning that the operator is between the operands (e.g., 1 +
2).
+ (unary plus): operator takes any numeric operand. It's not of much practical use because the value of the
operation is equal to the value of the operand.
- (unary minus): operator takes any numeric operand. The value of the operation is the negative of the value of
the operand. In other words, the result is calculated by subtracting the operand from zero. If the operand type is
Short, Integer, or Long, and the value of the operand is the maximum negative value for that type, then applying
the unary minus operator will cause a System.OverflowException error.
VB.Net is rich in built-in operators and provides following type of commonly used operators:
 Arithmetic Operators
 Comparison Operators
 Logical/Bitwise Operators
 Bit Shift Operators
 Assignment Operators
 Miscellaneous Operators
Like any programming language, VB.NET has its assortment of operators. The most common of these operators
in VB.NET are:
Type Operator Purpose Example
Math + Add 5+2=7
– Subtract 5–2=3
* Multiply 5 * 2 = 10
/ Divide 5 / 3 = 2.5
\ Integer Divide 5\2=2
^ Exponentiation 5^2 = 25
Mod Remainder after integer division 5 mod 2 = 1
String + Concatenate “one” + “two” = “onetwo”
& Concatenate “one” & “two” = “onetwo”
Assignment = Assigns the value an expression to the variable x=5+3
Comparison = Is equal to If (x = y)
< Is less than If (x < y)
<= Is less than or equal to If (x <=y)
> Is greater than If (x > y)
>= Is greater than or equal to If (x >=y)
<> Is not equal to If (x <> y)
Like Matches a pattern* If (x Like “p??r”)
Is Do object variables refer to same object If (x Is y)
Logical And True if both expressions are true If (x = 3 And y = 4)
Or True if one or both expressions are true If (x = 3 Or y=4)
Not True if the expression is False If Not (x= 5)
Xor True if one expression is true, but not both* If (x = 3 Xor y = 4)

Control Structures

Apply object oriented programming language Page | 10


Information Sheet DBA
Normally, statements in a program are executed one after another in the order in which they are written. This
process is called sequential execution.
However, various Visual Basic statements enable the programmer to specify that the next statement to be
executed might not be the next one in sequence. A transfer of control occurs when a statement other than the
next one in the program executes. We present control structures to control the order of events in their programs.
Control structures are used to select and repeat various statements to execute complex algorithms.

These control structures are categorized as: Mathematicians proved that any program, no matter how
complicated, can be written using only 3 basic control structures.
 Sequence
 Selection
 Iteration also called repetition
1. Sequence Control Structure
The sequence structure indicates instructions are to be executed one statement at a time in the
order they occur from top to bottom unless a different control structure dictates otherwise.
 Use when want to execute code line by line.
 Does not use the decision symbol.
 Execute statement one by one in linear or consecutive order

2. Selection structure
The selection structure tests a condition, and then executes one sequence of statements instead of another,
depending on whether the condition is true or false. A condition is any variable or expression that returns a
Boolean value (TRUE or FALSE). A selection structure, also called an "If-Then-Else" structure.

IF ELSE
The conditional statement IF ELSE , is use for examining the conditions that we provided, and making decision
based on that condition. The conditional statement examining the data using comparison operators as well as
logical operators.
If the condition is TRUE then the control goes to between IF and Else block, that is the program will execute
the code between IF and ELSE statements.
If the conditions is FLASE then the control goes to between ELSE and END IF block , that is the program will
execute the code between ELSE and END IF statements.
If you want o check more than one condition at the same time , you can use ElseIf .

Apply object oriented programming language Page | 11


Information Sheet DBA
If [condition]
code
Else
code
End If

If [condition]
code
ElseIf [condition]
code
ElseIf [condition]
code
Else
code
End If

Example - When we want to analyze a mark lists we have to apply some conditions for grading students
depends on the marks. Following are the grading rule of the mark list:
If the marks is greater than 80 then the student get higher first class, If the marks less than 80 and greater than 60 then
the student get first class, If the marks less than 60 and greater than 40 then the student get second class, if the marks
less than 40 then the student fail. These conditions in a VB.NET looks;
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As
System.EventArgs) Handles Button1.Click
Dim totalMarks As Integer
totalMarks = Val(TextBox1.Text)
If totalMarks >= 80 Then
MsgBox("Got Higher First Class ")
ElseIf totalMarks >= 60 Then
MsgBox("Got First Class ")
ElseIf totalMarks >= 40 Then
MsgBox("Just pass only")
Else
MsgBox("Failed")
End If
End Sub
End Class

3. Iteration or repetition control Structure

Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The
number of repetitions is based on criteria defined in the loop structure, usually a true/false expression.
Apply object oriented programming language Page | 12
Information Sheet DBA

FOR NEXT loop


Enable us to repeat a task till we reach a specified condition. This kind of for loop is useful for iterating over
arrays and for other applications in which you know in advance how many times you want the loop to iterate.
The FOR NEXT Loop, execute the loop body (the source code within For ...Next code block) to a fixed
number of times.
For var=[startValue] To [endValue] [Step]
[loopBody]
Next [var]
var : The counter for the loop to repeat the steps.
starValue : The starting value assign to counter variable .
endValue : When the counter variable reach end value the Loop will stop .
loopBody : The source code between loop body
Example: if you want to show a message box 5 times and each time you want to see how many times the
message box shows.
1. StartVal=1
2. endVal = 5
3. For var = startVal To endVal
4. Show message
5. Next var
Line 1: Loop starts value from 1
Line 2: Loop will end when it reach 5
Line 3: Assign the starting value to var and inform to stop when the var reach endVal
Line 4: Execute the loop body
Line 5: Taking next step , if the counter not reach the endVal
VB.NET Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim var As Integer
Dim startVal As Integer
Dim endVal As Integer
startVal = 1
endVal = 5
For var = startVal To endVal
MsgBox("Message Box Shows " & var & " Times ")
Next var
End Sub
End Class
When you execute this program , It will show messagebox five time and each time it shows the counter value.
If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET provides a
keyword Exit to use within the loop body.
For var=startValue To endValue [Step]
Apply object oriented programming language Page | 13
Information Sheet DBA
[loopBody]
Contition
[Exit For]
Next [var]
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim var As Integer
Dim startVal As Integer
Dim endVal As Integer
startVal = 1
endVal = 5
For var = startVal To endVal
MsgBox("Count Number:" & var)
If var = 3 Then
Exit For
End If
Next var
End Sub
End Class
FOR EACH loop
Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you
have to repeat a task till you reach a condition, in these situations you can use loop statements to achieve your
desired results.
FOR NEXT Loop, FOR EACH Loop, WHILE Loop and DO WHILE Loop are the commonly used loops in
Visual Basic.NET 2005
FOR EACH Loop usually using when you are in a situation to execute every single element or item in a group
(like every single element in an Array, or every single files in a folder or , every character in a String ) , in these
type of situation you can use For Each loop.
For Each [Item] In [Group]
[loopBody]
Next [Item]
Item : The Item in the group
Group : The group containing items
LoopBody : The code you want to execute within For Each Loop
Example, if you want to display the each character in the website name "HTTP://NET-
INFORMATIONS.COM" , it is convenient to use For Each Loop.
1. siteName = "HTTP://NET-INFORMATIONS.COM"
2. For Each singleChar In siteName
3.MsgBox(singleChar)
4. Next
Line 1: Assigning the site name in a variable
Line 2: This line is extracting the single item from the group
Line 3: Loop body
Line 4: Taking the next step

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim siteName As String
Apply object oriented programming language Page | 14
Information Sheet DBA
Dim singleChar As Char
siteName = "HTTP://Aptc.COM"
For Each singleChar In siteName
MsgBox(singleChar)
Next
End Sub
End Class
While and While loop
While .. End While Loop execute the code body (the source code within While and End while statements ) until
it meets the specified condition. The expression is evaluated each time the loop is encountered. If the evaluation
result is true, the loop body statements are executed.
While [condition]
[loop body]
End While
Condition : The condition set by the user
1. Counter = 1
2. While (counter <= 10)
3. Message
4. Counter = counter + 1
5. End While
Line 1: Counter start from 1
Line 2: While loop checking the counter if it is less than or equal to 10
Line 3: Each time the Loop execute the message and show
Line 4: Counter increment the value of 1 each time the loop execute
Line 5: End of the While End While Loop body
A while loop can be terminated when a break, goto, return, or throw statement transfers control outside the loop.
To pass control to the next iteration without exiting the loop, use the continue statement.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim counter As Integer
counter = 1
While (counter <= 10)
MsgBox("Counter Now is : " & counter)
counter = counter + 1
End While

End Sub
End Class

Modular programming
Modular programming is the process of subdividing a computer program into separate sub-programs. A module
is a separate software component. It can often be used in a variety of applications and functions with other
components of the system.
Apply object oriented programming language Page | 15
Information Sheet DBA
In other word, it is the act of designing and writing programs as interactions among functions that each
performs a single well-defined function, and which have minimal side-effect interaction between them. Put
differently, the content of each function is cohesive, and there is low coupling between functions.
Modular Programming discourages the use of control variables and flags in parameters; their presence tends to
indicate that the caller needs to know too much about how the function is implemented.
ObjectOriented programs are usually modular. ModularProgramming does not have to be ObjectOriented.
Modular Programming is heavily procedural: The focus is entirely on writing code (functions). Data is passive.
Array
In programming, a series of objects all of which are the same size and type. Each object in an array is called an
array element. For example, you could have an array of integers or an array of characters or an array of
anything that has a defined data type. The important characteristics of an array are:
 Each element has the same data type (although they may have different values).
 The entire array is stored contiguously in memory (that is, there are no gaps between elements).
Arrays can have more than one dimension. A one-dimensional array is called a vector ; a two-dimensional array
is called a matrix.
ArrayList is flexible because we can add items without any size information.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim i As Integer
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")
MsgBox("Shows Added Items")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)
MsgBox("Shows final Items the ArrayList")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
End Sub
End Class

Lo2: Apply basic OO principles in the target language


Constants & Variables in VB .NET
Constants

Apply object oriented programming language Page | 16


Information Sheet DBA
The constants refer to fixed values that the program may not alter during its execution. These fixed values are
also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal.
You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a
meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value.
Class or structure-level constants are Private by default, but may also be declared as Public, Friend, Protected,
or Protected Friend for the appropriate level of code access.
examples:
Const Pi As Double = 3.14159
Private Const CmPerInch As Double = 2.54
Public Const BookTitle As String = “ASP for Developers”
In addition to user-defined constants, VB.NET and the .NET Framework define a number of intrinsic constants.
For example, you can use the intrinsic constant CrLf anytime you wish to add a carriage return and line feed to
a string:MsgString = “An error has occurred in the program.” & _CrLf & “Click on OK to continue or
CANCEL to abort.”
VARIABLES
A variable is a name given to a storage area that our programs can manipulate. Each variable in VB.Net has a
specific type, which determines the size and layout of the variable's memory; the range of values that can be
stored within that memory; and the set of operations that can be applied to the variable.
A variable is a named memory location. They are programming elements that can change during program
execution. Data that needs to be stored in memory & accessed at a later time are stored in variables. Instead of
referring to the memory location by the actual memory address you refer to it with a variable name.
It is an identifier that is declared in a method and that stands for a value within that method. Its value is allowed
to change within the method. Each variable is of a particular type, and that type is indicated in the declaration of
the variable.
The keyword Dim indicates a variable declaration. Dim is short for dimension. In addition to dim; we use the
Private, Protected, Friend, or Public statements in VB.NET to declare a variable and its data type. A variable
declared using Dim is local to the procedure in which it is declared. To declare a variable that’s global to the
entire page, you declare the variable outside of any subroutine or function using the Private statement. Which
statement we use depends on where we wish to declare the variable. To declare a variable from within a
subroutine or function, you use the Dim statement.
The Dim statement is used at module, class, structure, procedure or block level. For example, this line declares
a variable named i whose type is Integer:
Dim i As Integer
Access Specifiers
AccessSpecifiers describes as the scope of accessibility of an Object and its members. We can control the scope
of the member object of a class using access specifiers. We are using access specifiers for providing security of
our applications. Visual Basic .Net provide five access specifiers, they are as follows:
Public, Private , Protected , Friend and ProtectedFriend .
Public : Public is the most common access specifier. It can be access from anywhere hat means there is no
restriction on accessability. The scope of the accessibility is inside class also in outside the class.
Private : The scope of the accessibility is limited only inside the classes in which they are decleared. The
Private members can not be accessed outside the class and it is the least permissive access level.
Protected : The scope of accessibility is limited within the class and the classses derived (Inherited )from this
class.
Friend : The Friend access specifier can access within the program that contain its declarations and also access
within the same assembly level. You can use friend instead of Dim keyword.

Apply object oriented programming language Page | 17


Information Sheet DBA
ProtectedFriend : ProtectedFriend is same access lebels of both Protected and Friend. It can access anywhere
in the same assebly and in the same class also the classes inherited from the same class

Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) _ Handles


Button1.Click
End Sub
Private: Private means that no other part of the programme can see this code except for our button.
Sub: Short for Subroutine. The "Sub" word tells VB that some code follows, and that it needs to be executed
Button1: This is the name of our button. Erased the word "Button1" by using Text property and change the
Name property of button in order to change the button name.
_Click ( ): This is something called an Event. In other words, when the button is clicked, the Click Event will
fire, and the code we're going to write will be executed.
End Sub: The subroutine ends right here. This signifies the end of our code.
User defined aggregation
.
• An aggregation consists of a number of (sub-)concepts which collectively is considered a new concept.

• A decomposition splits a single concept into a number of (sub-)concepts.

Lo3: Debug code


Introduction
Apply object oriented programming language Page | 18
Information Sheet DBA
Debugging is a process identifying and fixing programming error. In other word it is about locating and
correcting code errors in a computer program. Debugging is part of the software testing process and is an
integral part of the entire software development lifecycle. The debugging process starts as soon as code is
written and continues in successive stages as code is combined with other units of programming to form a
software product.
Integrated development environment (IDE)
An IDE is an application that facilitates application development. It is a computer program that makes it easier
to write other computer programs. They are used by computer programmers to edit source code, and can be
easier to use than other text editors for new programmers.
Typically, an IDE contains a code editor, a compiler or interpreter and a debugger that the developer accesses
through a single graphical user interface (GUI).
Compiler: A compiler is a special program that processes statements written in a particular programming
language and turns them into machine language or "code" that a computer's processor uses. Typically, a
programmer writes language statements in different language one line at a time using an editor. The file that is
created contains what are called the source statements. The programmer then runs the appropriate language
compiler, specifying the name of the file that contains the source statements.
When executing (running), the compiler first parses (or analyzes) all of the language statements syntactically
one after the other and then, in one or more successive stages or "passes", builds the output code, making sure
that statements that refer to other statements are referred to correctly in the final code. Traditionally, the output
of the compilation has been called object code or sometimes an object module. Where the object code is
machine code that the processor can execute one instruction at a time
Interpreter:An interpreted program, sometimes called a script , is a program whose instructions are actually a
logically sequenced series of operating system commands, handled one at a time by a command interpreter . In
turn, the command interpreter requests services from the operating system. The writer of the interpreted
program need not be concerned by low-level storage management considerations. On the other hand, an
interpreted program can not be as efficient as a compiled program, which has been processed by a language
compiler. A language compiler converts source statements into something close to the strings of 0's and 1's that
a processor ultimately is given to work on. Because this work is already done before a compiled program is run,
it runs much more quickly.
An IDE may be a standalone application, or it may be included as part of one or more existing and compatible
applications.
An IDE supports single or multiple languages.
In general, an IDE is a graphical user interface (GUI)-based workbench designed to aid a developer in building
software applications with an integrated environment combined with all the required tools at hand.
Some examples of IDE:
1. Microsoft Visual Studio
2. NetBeans
3. PyCharm
4. IntelliJ IDEA
5. Eclipse
6. Code::Blocks
7. Aptana Studio 3
8. Komodo
9. RubyMine
10. Xcode

Visual Studio IDE

Apply object oriented programming language Page | 19


Information Sheet DBA
It is a premium and powerful and customizable programming environment that contains all the tools you need
to build programs quickly and efficiently. It offers a set of tools that help you write and modify the code for
your programs, and also detect and correct errors in your programs.
IDE are capable of creating all types of programs ranging from web applications to mobile apps to video
games. This series of software includes tons of tools for compatibility testing so that you can see how your apps
run on more than 300 devices and browsers.
Microsoft's Visual Studio includes or Supported several different programming languages some of them:
        Visual Basic,
        Visual C# (C sharp),
       Visual C++ (cee-plus-plus),
       Visual F# (F sharp),
         JScript and
        Web Development (called ASP.NET).
       It also includes the .NET 4 Framework upon which these languages operate.
All of these languages compiled. This means they are translated from human readable-form to machine
readable-form to the same Microsoft Intermediate Language (MSIL).
MSIL run within the Common Language Runtime (CLR) – a component of the .NET Framework.
Visual Studio Components
When Visual Studio is installed on a computer, there are two mandatory components to the installation and an
optional third component.
 .NET Framework Class Library. This is a library of predefined class objects. It enables you to quickly build
a computer application through the use of predefined objects such as forms, text boxes, labels, buttons, drop-
down list controls, and others (mandatory).
Common Language Runtime (CLR). This component manages the execution of a programming project
written in any of the languages that are included within Visual Studio including Visual Basic as a language
(mandatory). This component is installed as part of the .NET Framework.
MSDN (Help). This is the help component and provides access to a help reference library. This is covered in
detail at the end of this set of notes. It is an optional, but highly recommended component.
Visual Studio organizes your work in projects and solutions. A solution can contain more than one project, such
as a DLL and an executable that references that DLL. The programming applications you will design and
develop are called solutions in VB. A solution can actually contain more than one project & Each solution is
stored in a folder identified by the solution name. Some of the frequently used programming tools in Visual
Studio IDE include;
* Menu Bar
* Standard Toolbar
* ToolBox
* Forms Designer
* Output Window
* Solution Explorer
* Properties Window
Launching Visual Basic
Start VB  Click the Windows Start button and locate Microsoft Visual Studio 2010
The first screen to display may require you to choose your Default Environment Settings. If this screen
displays, click the Visual Basic Development Settings option in the list box and then click the Start Visual
Studio button. 
Click the New Project link shown in the figure above to create a new project. This opens the New Project
dialog box shown below.

Apply object oriented programming language Page | 20


Information Sheet DBA

 
The first step is to start a new project and build a form.
Open your Visual Studio and select File
New Project and select Visual Basic from the New project dialog box and
 Select Windows From Application.
Enter your project name instead of WindowsApplication1 in the bottom of dialogue box and click OK
button. The following picture shows how to crate a new Form in Visual Studio.

The following picture shows how is the default Form look like.

Apply object oriented programming language Page | 21


Information Sheet DBA

At the top of the form there is a title bar which displays the forms title. Form1 is the default name; you can
change the name to your convenience. The title bar also includes the control box, which holds the minimize,
maximize, and close buttons.
If you want to set any properties of the Form, you can use Visual Studio Property window to change it.

Windows Forms

It is used to build user


interfaces. Each time you create
a Windows application, Visual
Studio will display a default
blank form, onto which you can
drag and drop controls from the
Visual Studio Toolbox window.

Set Up Work Environment


The IDE shows the default work environment in terms of the windows that are displayed. Experiment with
pinning and unpinning these windows by using the AutoHide pushpin icon for each window.
 Toolbox
 Solution Explorer
 Properties
You can also close/open these windows with the View menu.
Resetting the Default IDE Layout
Sometimes you startup VB and the IDE layout is not what you expect.
Windows you want such as Solution Explorer, Toolbox, or Properties may be closed.
The quick way to reset the layout is through the Window menu, Reset Window Layout submenu option as
shown in this figure.

Toolbox
Apply object oriented programming language Page | 22
Information Sheet DBA
Toolbox contains controls that are used to build forms. Used to add controls (tools) to a form by either double-
clicking or dragging/dropping (your option on which to use).

There are 47 basic tools in the Toolbox:


Pointer: This is the only item in the Toolbox that doesn't draw a control. It is used to resize or move a control
after it's been drawn on a form.
Label: Used for text that you don't want the user to change, such as a caption under a graphic.
Link Label: A Hyperlink label
Command Button: Used to create a button that the user can choose to carry out a command.
Text Box: Used to hold text that the user can either enter or change.
Main Menu: Adds menus under the titles bar of the form. i.e. File, Edit, …
Check Box: Used to create a box that the user can easily choose to indicate if something is true or false, or to
display multiple choices when the user can choose more than one.
Radio Button: Used in a group of option buttons to display multiple choices from which the user can choose
only one.
Group Box: Typically used to serve as a border for control with similar needs
Picture Box: Used to display graphical images (either decorative or active), as a container that receives output
from graphics methods, or as a container for other controls.
Panel: Used to host or hold other controls that belong to the same group
Datagrid: Allows users see and edit multiple rows of data simultaneously, also useful for rapid entry of large
amounts of data
List Box: Used to display a list of items from which the user can choose one. The list can be scrolled if it has
more items than can be displayed at one time
Checked List Box: Allows the user to select multiple items in a list by providing a check box for each item.
Combo Box: Used to draw a combination list box and text box. The user can either choose an item from the list
or enter a value in the text box.
List View: Displays a list of items with icons, similar to Windows explorer.
Tree View: Displays a hierarchy of nodes, like files and folders.
Tab Control: Allows the user to add multiple tabs to a form, like dividers in a notebook.
Date Time Picker: Allows the user to select a single item from a list of dates or times.
Month Calendar: Displays a calendar that allows the user to change months and select a date
Horizontal Scroll Bar: Used to provide a graphical tool for quickly navigating through a long list of items or a
large amount of information, for indicating the current position on a scale, or as an input device or
indicator of speed or quantity.
Vertical Scroll Bar: Used to provide a graphical tool for quickly navigating through a long list of items or a
large amount of information, for indicating the current position on a scale, or as an input device or
indicator of speed or quantity.
Timer: Used to generate timer events at set intervals. This control is invisible at run time.
Splitter: To resize docked controls at runtime.

Apply object oriented programming language Page | 23


Information Sheet DBA
Domain Up Down: Basically a textbox with two buttons for moving up and down in a list
Numeric Up Down: Same as DomainUpDown, except the list is composed of numbers and the up and down
arrows adjust the value of the control
Track Bar: Also called a slider. Used to move through vast amounts of data, or visually adjust a number.
Progress Bar: Set to indicate the progress of a process by displaying the status in the form of small rectangles
in a long rectangle.
Rich Text Box: A textbox that uses .rtf format.
Image List: Just like it sounds a list of images. The list can be navigated by a button that scrolls through the
images
Help Provider: Brings up the help window.
Tool Tip: Used to display text when the user moves the mouse over a control.
Context Menu: Displays a menu of frequently used commands associated with the selected item
Tool Bar: Allows the programmer to add a toolbar to his form
Status Bar: Used to allow an application to display various information about its status
Notify Icon: Used for processes that run in the background, and most of the time don’t need an interface with
the user. A good example would be virus protection software.
Open File Dialog: Brings up the window that allows the user to select a file for opening
Save File Dialog: Opens the window that lets the user select the location and name of the current open file
Font Dialog: Brings up the font selection window
Color Dialog: Allows the user to choose the current font color
Print Dialog: Brings up the typical Windows print menu
Print Preview Dialog: Opens the menu window for Print Preview settings
Print Preview Control: Opens print preview with the default settings
Error Provider: Provides a non-intrusive way of showing that there is an error with the input or in a data set.
An exclamation mark in a red square is displayed next to the error
Print Document: Prints the current document with the default printer settings
Page Setup Dialog: Opens the window that allows the user to adjust page settings like margins, headers and
footers, and orientation.

Naming Rules and Conventions


Visual Basic automatically assigns a value to the Name property of each control, for example, Label1, Label2,
Label3, or TextBox1, TextBox2, TextBox3, or Button1, Button2, Button3. However, it is difficult to
remember the difference between Label1 and Label2 so:
 if you are going to later refer to the controls, it is best to rename them to a more meaningful name,
 if you are not going to refer to the controls later, then just use the assigned default name such as Label1.
When you name an object such as a Label or TextBox or Button, you must follow these rules:
 An object name can begin with an alphabetic letter or the special “underscore” character.
 An object name can include letters, digits, and underscores.
 An object name CANNOT include a space or a punctuation mark.
 An object name CANNOT be a VB reserved word such as Button, Close, or TextBox.
 An object name can contain a VB reserved word; object names such as PrintButton, CloseButton,
NameTextBox, and MajorTextBox are legal names.
Program Coding
Programming or writing program code is the means used to cause something to happen when an event, such as a
button click occurs.
Accessing an Event Procedure

Apply object oriented programming language Page | 24


Information Sheet DBA
Double-click the Button control opens the coding window shown in the figure below. The window is called the
View Code window. You can also access the code view from the View menu or the View icon in the Solution
Explorer window.

  
Double-clicking the Button control causes VB to generate an event sub procedure named Button#_Click to
handle the Click event of the Button# control.
The Handles clause indicates that this sub procedure handles the Click event of the button named Button#.
The sub procedure ends with the line of code End Sub.
Each sub procedure must have a unique name – VB generates a name by combining the name of the control +
an underscore + the name of the event, e.g., Button#_Click.
Each sub procedure has two parameters inside of the parentheses that accompany the event name – these are
named sender and e.
e.g The form named Student Info is created as an instance of the general Form object defined in the .NET
Framework class library.
 It is declared by the Public Class Student Info statement.
 The End Class statement marks the end of the form's class definition.
Switching Between the View Designer and View Code Windows
Often you will need to switch between the View Designer and View Code windows. The different ways to do
this are:
 Click one of the tabs to display either the View Designer or View Code windows.
 Click the View Code icon in the Solution Explorer to open the coding window.
 Click the View Designer icon in the Solution Explorer to display the form for additional design layout.
 Click the View menu and select either the Code or Designer submenu options.
Accessing Intellisense
VB's Intellisense feature makes it easier for you to type programming statements. To access Intellisense simply
begin to type the name of an object such as the NameTextBox control shown in this figure – VB will pop up a
window that displays possible selections – this makes it easier for you to type code and leads to fewer typing
errors.

 
Apply object oriented programming language Page | 25
Information Sheet DBA
With the Intellisense focus on the NameTextBox, just type a dot (period) and the Intellisense will next display
all of the properties of the NameTextBox – type the letters "Te" (see the figure below) and Intellisense will
search and find the Text property and set the focus to that property for this text box control.
 

 Now type an equal sign (=) followed by your name inside double-quotes, e.g., "Douglas Bock".
* The statement you've typed should look like this inside the sub procedure – VB will provide the
necessary spacing automatically.
* This is called an Assignment Statement
The Assignment Statement
The Assignment Statement is used to assign values to a property of an object such as a control. The value on
the right side of the equal sign is assigned to the property of the object on the left side of the equal sign. 
Object.Property = Value
Assign a student name to the Text property of the TextBox control named. The assignment statements to do
this are:
  Private Sub Display1Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Display1Button.Click
'Display information for the first student
NameTextBox.Text = "Douglas Bock"
End Sub
The value is enclosed within double-quote marks which indicate the value is a string of characters and only
string data is stored to the Text property of a TextBox control.

The Clear Method


The Clear method is used to clear the contents of a TextBox control. The general way to execute a method is;
 Object.Method()
Return to the design view and double-click the Reset Form button control; this will generate a Click event sub
procedure for this button. Type a remark and two statements to clear the contents of the two TextBox controls
as shown here.
  Private Sub ResetButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ResetButton.Click
'Reset the form by clearing the TextBox controls
NameTextBox.Clear()
MajorTextBox.Clear()
End Sub
The Close Method
The Close method is used to close a form. To close a form use the keyword Me to refer to the form.
 Return to the design view and double-click the Exit button control; this will generate a Click event sub
procedure for this button.  
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ExitButton.Click
'Exit the application by closing it
Me.Close()
End Sub
Saving and Running a Project
To save a project, use the File-Save All menu.
 This will save all files in the project.
Apply object oriented programming language Page | 26
Information Sheet DBA
 You can specify the location for saving the project.

Run a project
There are several ways to run a project to test it.
 Use the Debug menu, Start Debugging option, or
 Press the F5 function key to run the project, or
 Click the shortcut green arrow on the shortcut toolbar.

 
Error handling and debugging
Program debugging

Debugging is a multistep process that involves identifying a problem, isolating the source of the problem, and
then either correcting the problem or determining a way to work around it. The final step of debugging is to test
the correction or workaround and make sure it works.

Debugging is part of the software testing process and is an integral part of the entire software development
lifecycle. The debugging process starts as soon as code is written and continues in successive stages as code is
combined with other units of programming to form a software product. In a large program that has thousands
and thousands of lines of code, the debugging process can be made easier by using strategies such as unit tests,
code reviews and pair programming.

Once an error has been identified, it is necessary to actually find the error in the code. At this point, it can be
useful to look at the code's logging and use a stand-alone debugger tool or the debugging component of an
integrated development environment (IDE). Invariably, the bugs in the functions that get most use are found and
fixed first. In some cases, the module that presents the problem is obvious, while the line of code itself is not. In
that case, unit tests -- such as JUnit and xUnit, which allow the programmer to run a specific function with
specific inputs -- can be helpful in debugging.

Apply object oriented programming language Page | 27


Information Sheet DBA
The standard practice is to set up a "breakpoint" and run the program until that breakpoint, at which time
program execution stops. The debugging component of an IDE typically provides the programmer with the
capability to view memory and see variables, run the program to the next breakpoint, execute just the next line
of code, and, in some cases, change the value of variables or even change the contents of the line of code about
to be executed.

Error handling
An act, assertion, or belief that unintentionally deviates from what is correct, right, or true. Errors in
programming can lead to a program not to run at all or run in unintended behavior. Errors can be grouped into
three categories:

1. Syntax errors

Syntax errors occur when you mistype a command or leave out an expected phrase or argument. Visual Basic
detects these errors as they occur and even provides help in correcting them. You cannot run a Visual Basic
program until all syntax errors have been corrected. A syntax error (compiler error) is a programming mistake
that violates the rules of Visual Basic, such as a misspelled property or keyword.

Occurs when the rules of VB .NET language (syntax) are violated.


Examples of syntax errors:
- Using a keyword as a variable name like as: Dim sub As String
- Incorrect use of an assignment statement like as: a + 2 = z
- An If statement structure without an End If statement like as: If ( 5 > 6) then Textbox1.Text = —Yes“
The syntax errors are identified during:
i. Design Time by:
 Placing wavy blue lines on the code that has violated VB NET syntax.
 A Task List window that displays the error type and the location of the error in the program through line
numbers
 A tool tip that displays the error type when the cursor is placed on the error.

2. Run-time errors

Run-time errors are usually beyond your programs control. Visual Basic allows you to trap such errors and
make attempts to correct them. Run-time errors are trappable. That is, Visual Basic recognizes an error has
occurred and enables you to trap it and take corrective action.• Error trapping is enabled with the On Error
statement: On Error GoTo, On Error Resume Next.

Issuing warning whether or not to continue to run the program with the syntax error (continue or break)
The user can take corrective action based on the these information

Runtime Errors
 Occurs when conditions arise during runtime that the compiler does not know how to handle
 They are also called exceptions
 They are identified through a diagnostic message box:
i. that displays the error type

Apply object oriented programming language Page | 28


Information Sheet DBA
ii. that prompts the user to press the continue or break buttons:
a. If the user presses the continue button, the program stops execution
b. If the user presses the break button, the program highlights the line that contains the error
At this point the user may take the appropriate actions
Example:
Illegal mathematical operations such as an attempt to multiply two strings. Textbox1.Text = —a“ * —b“
Programming Example: Runtime Error

On Error GoTo
On Error GoTo statements is an example of Vb.Net's Unstructured Exception Handling . VB.NET has two
types of Exception handling . Structured Error Handling and Unstructured Error handling . VB.NET using
Try..Catch statement for Structured Error handling and On Error GoTo statement is using for Unstructured
Error handling.
Error GoTo redirect the flow of the program in a given location.
On Error Resume Next - whenever an error occurred in runtime , skip the statement and continue execution on
following statements.
3. Logic errors
Logic errors are the most difficult to find. With logic errors, the program will usually run, but will produce
incorrect or unexpected results. A logic error is a human error a programming mistake that makes the program
code produces the wrong results. The Visual Basic debugger is an aid in detecting logic errors.

Exceptions
Exceptions are the occurrence of some condition that changes the normal flow of execution . For ex: you
programme run out of memory , file does not exist in the given path , network connections are dropped etc.
More specifically for better understanding , we can say it as Runtime Errors .
In .NET languages , Structured Exceptions handling is a fundamental part of Common Language Runtime .
It has a number of advantages over the On Error statements provided in previous versions of Visual Basic . All
exceptions in the Common Language Runtime are derived from a single base class , also you can create your
own custom Exception classes. You can create an Exception class that inherits from Exception class .
You can handle Exceptions using Try..Catch statement .
Try
code
exit from Try
Catch [Exception [As Type]]
code - if the exception occurred this code will execute
exit from Catch
example; Here we are going to divide a number by zero .
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim i As Integer
Dim resultValue As Integer
i = 100
resultValue = i / 0
MsgBox("The result is " & resultValue)
Catch ex As Exception

Apply object oriented programming language Page | 29


Information Sheet DBA
MsgBox("Exception catch here ..")
Finally
MsgBox("Finally block executed ")
End Try
End Sub
End Class
Finally
The code in the finally block will execute even if there is no Exceptions. That means if you write a finally block
, the code should execute after the execution of try block or catch block.
Try
code
exit from Try
Catch [Exception [As Type]]
code - if the exception occurred this code will execute
exit Catch
Finally
code - this code should execute , if exception occurred or not
The following example trying to divide a number by zero.
Try Dim i As Integer Dim resultValue As Integer i = 100 resultValue = i / 0 MsgBox("The result is " &amp;
resultValue) Catch ex As Exception MsgBox("Exception catch here ..") Finally MsgBox("Finally block
executed ") End Try
Throw Exception
You should throw exceptions only when an unexpected or invalid activity occurs that prevents a method from
completing its normal function. You can throw any type of Throwable object using the keyword throw.
Difference between Exception and Error
Exceptions are related to the application and an Error is related to the environment in which the application is
running.

Apply object oriented programming language Page | 30


Information Sheet DBA
LO4: Document activities
In computer hardware and software product development, documentation is the information that describes the
product to its users.
Software documentation is written text or illustration that accompanies computer software. It may be technical
manual, user manual or other instructional manual that facilitate the use of a software product or services.
Documentation includes source code, instructional items, error code where ever required. It may exists in any
formats like PDF, Word or CDs.
The software development document contains all preparations pertaining to the development of each unit or
module, including the software, test cases, test results, approvals, and any other items that will help to explain
the functionality of the software.
It consists of the product technical manuals and online information which explains how it operates or how to
use it, and may mean different things to people in different roles.
It also gives a comprehensive procedural description of a program. It shows as to how software is written.
Program documentation even has the capability to sustain any later maintenance or development of the
program. The program documentation describes what exactly a program does by mentioning about the
requirements of the input data and the effect of performing a programming task.

Thus, if you want to know what a program is meant to do and how it has to be executed, you should refer to the
program documentation. The most common examples would be the instruction manuals for a software product,
which is given to the end-user.

The document is dynamic and is maintained by the system development team and should he constantly updated
as the system’s development progresses. The software development folder should include the following
information for each unit:

 Description of the unit’s functionality in narrative format


 Description of development methodologies used
 Requirements in the functional requirements document allocated to this unit or module
 Completed trace ability matrix displaying the unit’s test cases satisfying the functional requirements in
the test plan
 Source code listing
 Controlled libraries/directories/tables
 All data necessary to conduct unit testing
 Unit test results and analysis
 System Technical Lead sign off for design walk-through. approval of code, and completion of each unit
 Completed Software Development Document Check-Off sheet (attached)

Fig: Stages of document preparation


Apply object oriented programming language Page | 31
Information Sheet DBA
ROLES AND RESPONSIBILITIES
The team members have the following roles and responsibilities:

 The application developer assigned the primary responsibility for the module or unit creates a file folder
for the unit, labels it according to the name of the unit, and places it in the appropriate place in the project
team file cabinet.
 The application developer(s) add copies of the indicated documentation to the folder as they are created.
 The project QA representative reviews the contents of the folder for completeness, and points out
discrepancies to the developer assigned primary responsibility for tile module or unit.
 The developer assigned primary responsibility for the module or unit completes the Software
Development Document Check-Off sheet and arranges for the System Technical Lead review and
approval when needed.
 The folder is available to all project team member for review, but if removed from the file cabinet, it must
be replaced with a cheek-out card indicating who checked it out, when, and where it will he located.
For developing a perfect software following documents are mandatory in series:
1. URS ( User Requirements Specification): The URS point wise describes all the requirements of the
software.
2. UI: Depending on the URS certain pages of the software are designed. This also includes error messages,
pop up messages etc.
3. SRS (System Requirements Specification): The SRS point wise defines system requirements depending on
the URS.
4. STC (System Test Cases): After the software is developed system testing is done with and recorded in STC
5. UAT (User Acceptance Testing): After all system test cases are successful user acceptance testing in
conducted to check if the software covers all points as mentioned in the URS and is prepared as expected
6. DTL (Defect Track Log): All bugs/defects recorded during UAT/STC are mentioned in DTL so that they
can be fixed
Importance of Documentation
For a programmer reliable documentation is always a must. The presence of documentation helps keep track of
all aspects of an application and it improves on the quality of a software product. Its main focuses
are development, maintenance and knowledge transfer to other developers. Successful documentation
will make information easily accessible, provide a limited number of user entry points, help new users
learn quickly, simplify the product and help cut support costs. Documentation is usually focused on the
following components that make up an application: server environments, business rules, databases/files,
troubleshooting, application installation and code deployment.
1. Clarify your business goals, requirements and activities:With a proper documentation, you can share the
business goals and requirement with your managers and team mates so that they have a clear vision and
goals and the activity they perform will be more towards the success.
2. Design and Specify your product: This comes in Architectural/Design documents and it gives you
complete overview of how your products look like.
3. Everything is clearly explained: When you makes End User documentation of the product of software, you
have to explain each and everything about its working.It describes each feature of the program, and assists
the user in realizing these features.
4. Any body can work on other's code: If you are a developer, it is not sufficient to write good codes only
but you also need to take cares about the documentation part, which can be helpful to other developers while
working in a team.
5. Helpful in proper communication: A good software documentation is helpful in proper communication.
The written procedure helps you to make interaction within several departments.
Types of Software Documentation

Apply object oriented programming language Page | 32


Information Sheet DBA
Software documentation, also referred to as source code documentation is a text that describes a computer
software. It explains how a software works but it can also explain how to use the software properly. Several
types of software documentation exist and can be classified into:
User Documentation
Also known as software manuals, user documentation is intended for end users and aims to help them use
software properly. It is usually arranged in a book-style and typically also features table of contents, index and
of course, the body which can be arranged in different ways, depending on whom the software is intended for.
For example, if the software is intended for beginners, it usually uses a tutorial approach and guides the user
step-by-step. Software manuals which are intended for intermediate users, on the other hand, are typically
arranged thematically, while manuals for advanced users follow reference style.
Besides printed version, user documentation can also be available in an online version or PDF format. Often, it
is also accompanied by additional documentation such as video tutorials, knowledge based articles, videos, etc.
Requirements Documentation
Requirements documentation, also referred to simply as requirements explains what a software does and shall
be able to do. Several types of requirements exist which may or may not be included in documentation,
depending on purpose and complexity of the system. For example, applications that don’t have any safety
implications and aren’t intended to be used for a longer period of time may be accompanied by little or no
requirements documentation at all. Those that can affect human safety or/and are created to be used over a
longer period of time, on the other hand, come with an exhausting documentation.
Architecture Documentation
Also referred to as software architecture description, architecture documentation either analyses software
architectures or communicates the results of the latter (work product). It mainly deals with technical issues
including online marketing and seo services but it also covers non-technical issues in order to provide guidance
to system developers, maintenance technicians and others involved in the development or use of architecture
including end users. Architecture documentation is usually arranged into architectural models which in turn
may be organised into different views, each of which deals with specific issues.
Comparison document is closely related to architecture documentation. It addresses current situation and
proposes alternative solutions with an aim to identify the best possible outcome. In order to be able to do that, it
requires an extensive research.
Technical Documentation
Technical documentation is a very important part of software documentation and many programmers use both
terms interchangeably despite the fact that technical documentation is only one of several types of software
documentation. It describes codes but it also addresses algorithms, interfaces and other technical aspects of
software development and application. Technical documentation is usually created by the programmers with the
aid of auto-generating tools.
Software Documentation standards
Standardized documentation can be defined as documents having a consistent appearance, structure and quality.
This means should be easier to read, understand and usable. Standards act as a basis for document quality
assurance.
“Using a standard means that documentation producers and customers have a consistent accepted reference for
the format and content that they will find in the documentation. For example, what documentation must be
printed? What does it mean to say that the documentation is “complete”? Does it have to include every function
and screen shot?

Apply object oriented programming language Page | 33


Information Sheet DBA

LO5: Test Code


Software testing is a process of executing a program or application with the intent of finding the software bugs.
It can also be stated as the process of validating and verifying that a software program or application or product
meets the business and technical requirements that guided its design and development.

Testing allows developers to deliver software that meets expectations, prevents unexpected results, and
improves the long term maintenance of the application. Depending upon the purpose of testing and the software
requirements, the appropriate methodologies are applied.

Purpose of Software Testing

Software testing contributes to improving the quality of the product. While finding defects / bugs is one of the
purposes of software testing, it is not the sole purpose. It also Verify and validate that the product meets the
stated requirements / specifications. Software testing is performed to verify that the completed software package
functions according to the expectations defined by the requirements.
The overall objective to not to find every software bug that exists, but to uncover situations that could
negatively impact the customer, usability and/or maintainability.
From the module level to the application level, this article defines the different types of testing. Depending upon
the purpose for testing and the software requirements/specs, a combination of testing methodologies is applied.

Types of Program Testing

There are different types of tests that inspect the different areas of your application:

Regression Tests: This is the process of running unit tests again after fixing any integration tests to make sure
your fixes haven't caused your unit tests to break. Regression testing is necessary because many times
modifications in one part of the code cause unexpected problems in a "totally unrelated" area of the code.

Functional testing: This type of testing ignores the internal parts and focus on the output is as per requirement
or not. Black-box type testing geared to functional requirements of an application.

Sanity testing: Testing to determine if a new software version is performing well enough to accept it for a
major testing effort. If application is crashing for initial use then system is not stable enough for further testing
and build or application is assigned to fix.

Load testing: Its a performance testing to check system behavior under load. Testing an application under
heavy loads, such as testing of a web site under a range of loads to determine at what point the system’s
response time degrades or fails.

Stress testing: System is stressed beyond its specifications to check how and when it fails. Performed under
heavy load like putting large number beyond storage capacity, complex database queries, continuous input to
system or database load.

Performance testing : Term often used interchangeably with ‘stress’ and ‘load’ testing. To check whether
system meets performance requirements. Used different performance and load tools to do this.
Apply object oriented programming language Page | 34
Information Sheet DBA
Usability testing: User-friendliness check. Application flow is tested, Can new user understand the application
easily, Proper help documented whenever user stuck at any point. Basically system navigation is checked in this
testing.

Install/uninstall testing: Tested for full, partial, or upgrade install/uninstall processes on different operating
systems under different hardware, software environment.

Recovery testing: Testing how well a system recovers from crashes, hardware failures, or other catastrophic
problems.

Security testing: Can system be penetrated by any hacking way. Testing how well the system protects against
unauthorized internal or external access. Checked if system, database is safe from external attacks.

Compatibility testing: Testing how well software performs in a particular hardware/software/operating


system/network environment and different combination s of above.

Comparison testing: Comparison of product strengths and weaknesses with previous versions or other similar
products.

Alpha testing: In house virtual user environment can be created for this type of testing. Testing is done at the
end of development. Still minor design changes may be made as a result of such testing.

Beta testing – Testing typically done by end-users or others. Final testing before releasing application for
commercial purpose.

Fault Tolerant Testing: Module testing verifies that individual software unit does not perform in a detrimental
or unexpected manner for illegal or out-of-range input parameters. At the application level, testing verifies that
the entire application functions together in a graceful manner according to the requirements when presented
with unexpected and/or out-of-range values.

Levels of Software Testing

Before Segue releases an application, it undergoes a thorough testing process to ensure that the app is working
in the manner in which it was intended. There are four main stages of testing that need to be completed before a
program can be cleared for use:

1. Unit Testing

Apply object oriented programming language Page | 35


Information Sheet DBA
During this first round of testing, the program is submitted to assessments that focus on specific units or
components or module of the software to determine whether each one is fully functional. The main aim of this
endeavor is to determine whether the application functions as designed. In this phase, a unit can refer to a
function, individual program or even a procedure, and a White-box Testing method is usually used to get the
job done. One of the biggest benefits of this testing phase is that it can be run every time a piece of code is
changed, allowing issues to be resolved as quickly as possible.

It’s quite common for software developers to perform unit tests before delivering software to testers for formal
testing (done by the programmer and not by testers, as it requires detailed knowledge of the internal program
design and code)

White box testing – This testing is based on knowledge of the internal logic of an application’s code. Also
known as Glass box Testing. Internal software and code working should be known for this type of testing. Tests
are based on coverage of code statements, branches, paths, conditions.

Black box testing – Internal system design is not considered in this type of testing. Tests are based on
requirements and functionality.
2. Integration Testing
Integration testing allows individuals the opportunity to combine all of the units within a program and test them
as a group. This testing level is designed to find interface defects between the modules/functions. This is
particularly beneficial because it determines how efficiently the units are running together. Keep in mind that no
matter how efficiently each unit is running, if they aren’t properly integrated, it will affect the functionality of
the software program. In order to run these types of tests, individuals can make use of various testing methods,
but the specific method that will be used to get the job done will depend greatly on the way in which the units
are defined.
3. System Testing
System testing is the first level in which the complete application is tested as a whole. The goal at this level is
to evaluate whether the system has complied with all of the outlined requirements and to see that it meets
Quality Standards. System testing is undertaken by independent testers who haven’t played a role in developing
the program. This testing is performed in an environment that closely mirrors production. System Testing is
very important because it verifies that the application meets the technical, functional, and business requirements
that were set by the customer.
4. Acceptance Testing
The final level, Acceptance testing (or User Acceptance Testing), is conducted to determine whether the
system is ready for release. During the Software development life cycle, requirements changes can sometimes
be misinterpreted in a fashion that does not meet the intended needs of the users. During this final phase, the
user will test the system to find out whether the application meets their business’ needs. Once this process has
been completed and the software has passed, the program will then be delivered to production. Normally this
type of testing is done to verify if system meets the customer specified requirements. User or customer do this
testing to determine whether to accept application.

Some general rules of testing

 A testing unit should focus on one tiny bit of functionality and prove it correct.

 Each test unit must be fully independent. Each test must be able to run alone, and also within the test suite,
regardless of the order that they are called. The implication of this rule is that each test must be loaded with
a fresh dataset and may have to do some cleanup afterwards.

 Try hard to make tests that run fast. If one single test needs more than a few milliseconds to run,
development will be slowed down or the tests will not be run as often as is desirable. In some cases, tests
can’t be fast because they need a complex data structure to work on, and this data structure must be loaded

Apply object oriented programming language Page | 36


Information Sheet DBA
every time the test runs. Keep these heavier tests in a separate test suite that is run by some scheduled task,
and run all other tests as often as needed.

 Learn your tools and learn how to run a single test or a test case. Then, when developing a function inside a
module, run this function’s tests frequently, ideally automatically when you save the code.

 Always run the full test suite before a coding session, and run it again after. This will give you more
confidence that you did not break anything in the rest of the code.

 It is a good idea to implement a hook that runs all tests before pushing code to a shared repository.

 If you are in the middle of a development session and have to interrupt your work, it is a good idea to write
a broken unit test about what you want to develop next. When coming back to work, you will have a pointer
to where you were and get back on track faster.

 The first step when you are debugging your code is to write a new test pinpointing the bug. While it is not
always possible to do, those bug catching tests are among the most valuable pieces of code in your project.

 When something goes wrong or has to be changed, and if your code has a good set of tests, you or other
maintainers will rely largely on the testing suite to fix the problem or modify a given behavior. Therefore
the testing code will be read as much as or even more than the running code. A unit test whose purpose is
unclear is not very helpful in this case.

 Another use of the testing code is as an introduction to new developers. When someone will have to work
on the code base, running and reading the related testing code is often the best thing that they can do to start.
They will or should discover the hot spots, where most difficulties arise, and the corner cases. If they have
to add some functionality, the first step should be to add a test to ensure that the new functionality is not
already a working path that has not been plugged into the interface.

Apply object oriented programming language Page | 37

You might also like