0% found this document useful (0 votes)
1K views

Modern Programming Tools - and Techniques III - Shrivastava - Ibrg

Modern Prommaming Tools and Techniques

Uploaded by

Michael
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views

Modern Programming Tools - and Techniques III - Shrivastava - Ibrg

Modern Prommaming Tools and Techniques

Uploaded by

Michael
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 362

www.lpude.

in
DIRECTORATE OF DISTANCE EDUCATION

MODERN PROGRAMMING TOOLS &


TECHNIQUES-III

Copyright 2013, Varun Bhardwaj


All rights reserved.
Produced & Printed by
FRANK BROTHERS & CO. (PUBLISHERS) LIMITED
B-41, Sector-4, NOIDA - 201301, Gautam Budh Nagar
for
Directorate of Distance Education
Lovely Professional University
Phagwara

Directorate of Distance Education


LPU is reaching out to the masses by providing an intellectual learning environment that is academically rich with most
affordable fee structure. Supported by the largest University1 in the country, LPU, the Directorate of Distance Education (DDE) is
bridging the gap between education and the education seekers at a fast pace, through the usage of technology which significantly
extends the reach and quality of education. DDE aims at making Distance Education, a credible and valued mode of learning,
by providing education without a compromise.
DDE is a young and dynamic wing of the University, filled with energy, enthusiasm, compassion and concern. Its team strives
hard to meet the demands of the industry, to ensure quality in curriculum, teaching methodology, examination and evaluation
system, and to provide the best of services to its students. DDE is proud of its values, by virtue of which, it ensures to make an
impact on the education system and its learners.
Through affordable education, online resources and a network of Study Centres, DDE intends to reach the unreached.

1. in terms of no. of students in a single campus

SYLLABUS
Modern Programming Tools & Techniques-III
Objectives:

To impart the skills needed to implement Network enabled technologies.

To enable the student to understand dot net framework classes.

To enable the student to develop multi-language support applications.

To enable the student to develop platform independent applications.

To enable the student to develop console and windows applications.

To enable the student to implementing Object oriented concepts in dot net.

To enable the student to learn file handling using dot net.

To enable the student to understand Database application development using dot net and data transmission
technology.

COURSE CONTENTS:
S. No.

Topics

1.

Introduction: What is VB.NET, Characteristics of VB.NET, VB.NET as a language in .NET Framework.

2.

Variables and Data Types: Variables and Data Types. Decision Making and Looping: If, If else if. While, do while,
for loop, Declaring Arrays. System. Array class

3.

In Built Functions: String Class, Conversion functions, other Miscellaneous Functions, Subroutines and Functions

4.

Classes & Object in VB.NET: Using Classes, object, methods. Constructors. Creating Properties and indexers. Using
Inheritance in classes.

5.

Namespaces: Meaning and its working. Using System Namespace and Object class. Exception Handling: Using Try
and Catch blocks, The Finally Section

6.

Using System. Collections: Array List, Stack, Queue, Sorted List etc.

7.

Windows Programming: Using Controls- textboxes, listbox, buttons, datetime picker, comboboxes etc.

8.

Common Dialog Boxes: OpenFileDialog, SaveFileDialog, ColorDialog, MessageBox Class and DialogResult Class.

9.

File Input Output: Working with Files and Directories. System.IO.

10.

ADO.NET: Accesing Database with ADO.NET. Executing Insertion, deletion, updation and select command with
databases. XML Basics: What is XML? Data Representation through XML. Working with XMLReader and XMLWriter
Classes.

CONTENTS
Unit 1: Introduction to Visual Basic

Unit 2:

Variables and Data Types

35

Unit 3:

Decision Making and Looping

55

Unit 4: Array
Unit 5:

In Built Functions

Unit 6:

Classes and Object in VB.NET

Unit 7: Namespaces

74
89
110
135

Unit 8:

Exception Handling

163

Unit 9:

Using System.Collections

178

Unit 10: Windows Programming

204

Unit 11: Common Dialog Boxes

234

Unit 12: File Input Output

262

Unit 13: ADO.NET

301

Unit 14: XML

323

Corporate and Business Law

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

Unit 1: Introduction to Visual Basic

Notes

CONTENTS
Objectives
Introduction

1.1

Element of Visual Basic

1.1.1

The Visual Element

1.1.2

The Language Element

1.2

Object Oriented Programming in VB.NET

1.3

Visual Basic.NET

1.3.1

The Common Language Runtime

1.3.2

Managed Execution

1.3.3

Microsoft Intermediate Language (MSIL)

1.3.4

The Just-In-Time Compiler

1.3.5

Executing Code

1.3.6 Assemblies

1.3.7

Assembly Manifest

1.3.8

An End to DLL Hell

1.3.9

Global Assembly Cache (GAC)

1.4

The Common Type System

1.4.1 Classes

1.4.2 Interfaces

1.4.3

1.4.4 Delegates

1.5

Feature of VB.NET

1.5.1

Powerful Windows-based Applications

1.5.2

Building Web-based Applications

1.5.3

Simplified Deployment

1.5.4

Powerful, Flexible, Simplified Data Access

1.5.5

Improved Coding

1.5.6

Direct Access to the Platform

1.5.7

Full Object-Oriented Constructs

1.5.8

XML Web Services

1.5.9

Mobile Applications

1.5.10 COM Interoperability

1.5.11 Reuse Existing Investments

1.5.12 Upgrade Wizard

1.6

NET Framework

1.6.1

Value Types

Visual Basic in .Net Framework

LOVELY PROFESSIONAL UNIVERSITY

Modern Programming Tools & Techniques-III

Notes

1.7

VB.NET as a Language in .NET Framework

1.7.1

Source Files

1.7.2

Identifiers

1.7.3 Keywords

1.7.4 Literals

1.7.5 Types

1.8 Summary
1.9 Keywords
1.10 Review Questions
1.11 Further Reading

Objectives
After studying this unit, you will be able to:

Explain the element of visual basic

Describe the object oriented programming in VB.NET

Discuss the framework of visual basic.net

Define common type system

Explain the feature of VB.NET

Define .NET framework

Discuss the VB.NET as a language in .NET framework

Introduction
Before we begin Visual Basic programming, let us understand some basic concepts of
programming. A computer program is an organized list of instructions that, when executed,
causes the computer to behave in a predetermined manner. Without programs, computers
are useless. Therefore, programming means designing or creating a set of instructions for the
computer to carry out certain tasks at much faster rate than human beings. A lot of people
think that computer CPU is a very intelligent thing, which in actual fact it is a dumb and
inanimate object that can do nothing without human assistance. The microchips of a CPU can
only understand two distinct electrical states, namely, the on and off states, or 0 and 1 codes
in the binary system. So, the CPU only understands combinations of 0 and 1 code, a language
which we called machine language. Machine language is extremely difficult to learn and it is
not for us laymen to master it easily. Fortunately, we have many smart programmers who wrote
interpreters and compilers that can translate human languagelike programs such as BASIC
into machine language so that the computer can carry out the instructions entered by the users.
Machine language is known as the primitive language while Interpreters and compilers like
Visual Basic are called high-level language. Some of the high-level computer languages beside
Visual Basic are FORTRAN, COBOL, Java, C, C++, Turbo Pascal, and etc.
Therefore, programming means designing or creating a set of instructions to ask the computer
to carry out certain jobs which normally are very much faster than human beings can do.

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

In order to do programming, we need to use certain computer language to communicate with


the computer. There are many computer languages out there, some of the examples are Visual
Basic, FORTRAN, COBOL, Java, C++, Turbo Pascal, Assembly language and etc. Among them,
Visual Basic is the easiest to learn because it uses a language very similar to natural human
language. It involves using words such as If, Then, Else, Goto, Select and so on, so beginners can
pick up the language very quickly.

Notes

In 2001, Microsoft released the .NET (pronounced dot net) platform. Visual Basic .NET,
or VB.NET, is an upgrade to the last version of VB (version 6.0) that conforms to the .NET
platform. As we will see in subsequent chapters, the changes in VB.NET allow programmers
to write Web or desk-top applications within the same language. In addition, VB.NET is fully
object-oriented as opposed to prior versions that had many, but not all, of the elements of an
object-oriented language. This topic is based on VB.NET. We will sometimes refer to Visual
Basic as VB, omitting .NET.
Visual Basic is a highly popular language in the commercial world because it allows for the rapid
development of Windows based programs. VB is particularly strong at creating front ends for
databases. This can be done in amazing time through the use of wizards. This page does not
cover all aspects of VB, it does not show how to do the basics like layout a form, neither does
it cover all the built in functions, as there is already plenty of help provided for these, and a
lot of it is self-evident.
Visual Basic is a high level programming language which was evolved from the earlier DOS
version called BASIC. BASIC means Beginners All-purpose Symbolic Instruction Code. It is a
very easy programming language to learn. The codes look a lot like English Language. In the
past there were many different versions of BASIC however most people today use Microsoft
Visual Basic today. It is a well developed programming language and supporting resources are
available everywhere.
On the other hand, because the user may click on certain object randomly, so each object has to
be programmed independently to be able to response to those actions (events). Therefore, a VB
Program is made up of many subprograms, each has its own program code, and each can be
executed independently and at the same time each can be linked together in one way or another.
A computer program is an organized list of instructions that, when executed, causes the computer
to behave in a predetermined manner. Without programs, computers are useless automatons.
What you can do with Visual Basic: We can program practically everything from educational
software to teach science, mathematics, language, and history, geography to financial and
accounting software to games. Indeed, there is no limit to what we can program!
Event Driven: Visual Basic is a Visual and events driven Programming Language. These are the
main divergence from the old BASIC. In BASIC, programming is done in a text-only environment
and the program is executed sequentially. In VISUAL BASIC, programming is done in a graphical
environment. In the old BASIC, we have to write program codes for each graphical object we
wish to display it on screen, including its position and its color. However, in Visual Basic, we
just need to drag and drop any graphical object anywhere on the form, and we can change its
color any time using the properties windows.
Programs and Subprograms: Because users may click on a certain object randomly, so each object
has to be programmed independently to be able to response to those actions (events). Therefore,
a VISUAL BASIC Program is made up of many subprograms, each has its own program codes,
and each can be executed independently and at the same time each can be linked together in
one way or another.

LOVELY PROFESSIONAL UNIVERSITY

Modern Programming Tools & Techniques-III

Notes

Visual Basic was initially introduced in 1991 as the first programming


language that directly supported programmable graphical user interfaces
using language-supplied objects.

1.1 Element of Visual Basic


From a programming viewpoint, Visual Basic is an object-oriented language that consists of two
fundamental parts: a visual part and a language part. The visual part of the language consists of a
set of objects, while the language part consists of a high-level procedural programming language.
These two elements of the language are used together to create applications. An application
is simply a Visual Basic program that can be run under the Windows Operating System. The
term application is preferred to the term program for two reasons: one, it is the term selected by
Microsoft to designate any program that can be run under its Windows Operating System (all
versions) and two, it is used to avoid confusion with older procedural programs that consisted
entirely of only a language element.
Thus, for our purposes we can express the elements of a Visual Basic application as:

Visual Basic Application = Object-Based Visual Part +

Procedural-Based Language Part


Thus, learning to create Visual Basic applications requires being very familiar with elements,
visual and language.

1.1.1 The Visual Element


From a users standpoint, the visual part of an application is provided within a window. This is the
graphical interface that allows the user to see the input and output provided by the application.
This user interface is referred to as the graphical user interface (GUI). From a programmers
perspective the GUI is constructed by placing a set of visual objects on a blank window, or form,
when the program is being developed. For example, consider Figure 1.1, which shows how a
particular application would look to the user. From a programmers viewpoint, the application
shown in Figure 1.1 is based on the design form shown in Figure 1.2. The points displayed on
the form are a design grid used to arrange objects on the form and are only displayed during
design time.
Figure 1.1: A Users View of an Application

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

Figure 1.2: The Design Form on which Figure 1.1 is Based

Notes

Design Form
(Initial Form Window)
Design Window

The programmer can place various objects on this form, which is itself a Visual Basic object.
When an application is run, the form becomes a window that provides the background for the
various objects placed on the form by the programmer. The objects on the window become the
controls used to direct program events. Let us take a moment to look at the objects provided in
the Visual Basic Toolbox. The standard object Toolbox, which is illustrated in Figure 1.3, contains
the objects we will use in constructing each graphical user interface.
Figure 1.3: The Standard Visual Basic Toolbox

LOVELY PROFESSIONAL UNIVERSITY

Modern Programming Tools & Techniques-III

Notes

A majority of applications can be constructed using a minimal set of objects provided by the
standard object Toolbox. This minimal set consists of the Label, TextBox, and Button objects.
The next set of objects that are more frequently found in applications include the CheckBox,
RadioButton, ListBox, and ComboBox. Finally, the Timer and PictureBox can be used for
constructing interesting moving images across the window. Table 1.1 lists this object types and
describes what each object is used for. The remaining sections of the text will describe the use
of objects in the toolbox, with special emphasis on the four objects (Label, TextBox, Button and
ListBox) that we will use in almost every application that we develop.
In addition to the basic set of controls provided in VB, a great number of objects can be purchased
either for special purpose applications or to enhance standard applications.
Table 1.1: Fundamental Object Types and Their Uses
Object Type

Use

Label

Create text that a user cannot directly change.

TextBox

Enter or display data.

Button

Initiate an action, such as a display or calculation.

CheckBox

Select one option from two mutually exclusive options.

RadioButton

Select one option from a group of mutually exclusive options.

ListBox

Display a list of items from which one can be selected.

ComboBox

Display a list of items from which one can be selected, as well as


permit user to type the value of the desired item.

Timer

Create a timer to automatically initiate program actions.

PictureBox

Display text or graphics.

Do not be overwhelmed by all of the available controls. At a minimum, we will always have
the objects provided by the standard Toolbox available to us, and these are the ones we will
be working with. Once we learn how to place the basic control objects on a form, we will also
understand how to place the additional objects, because every object used in a Visual Basic
application, whether it is selected from a standard or purchased control, is placed on a form
in the same simple manner. Similarly, each and every object contains two basic characteristics:
properties and methods.
An objects properties define particular characteristics of the object. For example, the properties
of a text box include the location of the text box on the form, the color of the box (the background
color), the color of text that will be displayed in the box (the foreground color), and whether it
is read-only or can also be written to by the user.
Methods are predefined procedures that are supplied with the object for performing specific tasks.
For example, we can use a method to move an object to a different location or change its size.
Additionally, each object from the Toolbox recognizes certain actions. For example, a button
recognizes when the mouse pointer is pointing to it and the left mouse button is clicked.
These types of actions are referred to as events. In our example, we would say that the button
recognizes the mouse-click event. However, once an event is activated, we must write our own
procedures to do something in response to the event. This is where the language element of
Visual Basic comes into play.

1.1.2 The Language Element


Before the advent of GUIs, computer programs consisted entirely of a sequence of instructions.
Programming was the process of writing these instructions in a language to which the computer

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

could respond. The set of instructions and rules that could be used to construct a program
were called a programming language. Frequently, the word code was used to designate the
instructions contained within a program. With the advent of graphical user interfaces the need
for code (program instructions) has not gone away rather, it forms the basis for responding to
the events taking place on the GUI. Figure 1.4 illustrates the interaction between an event and
a program code.

Notes

As illustrated in Figure 1.4, an event, such as clicking the mouse on a button, sets in motion a
sequence of actions. If code has been written for the event, the code is executed; otherwise the
event is ignored. This is the essence of GUIs and event-driven applicationsthe selection of
executed code depends on what events occur, which ultimately depends on what the user does.
The programmer must still write the code that performs the desired action.
Figure 1.4: An Event Triggers the Initiation of a Procedure
Public Class Form1
Inherits System.Windows.Forms.Form
Windows form Designer generated code
Private Sub Button1_Click (ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Buton1.Click
TextBox1.Text = Hello World !
End Sub
End Class

Visual Basic is a high-level programming language that supports all of the procedural
programming features found in other modern languages. These include statements to perform
calculations, permit repetitive instruction execution, and allow selection between two or more
alternatives.
Visual Basic is a visual programming environment for developing Windows
(also Web now) applications.

1.2 Object Oriented Programming in VB.NET


Information hiding is the concept of exposing only essential information and hiding the inner
logic. It is used mostly in hiding of design decisions that are most likely to change. Information
hiding also manifests in Encapsulation and Polymorphism. The term Encapsulation is used
interchangeably with information hiding Encapsulation results in encapsulating the data and
the processes into a module or other construct which presents an interface.
Polymorphism is where multiple procedures of the same name perform different tasks;
Polymorphism is the process of using a function or a procedure in different ways for different
set of inputs given. Polymorphism in VB.NET is through the definition and implementation of
a common interface. We can use polymorphism to hide logic from the programmer.
Inheritance helps we create new objects from existing objects for example we can inherit one
form from another form. One common reason to use inheritance is to create specializations of
existing classes or objects. For example, a Bank Account class might have data for an account
number, owner, and balance. An Interest Bearing Account class might inherit Bank
Account and then add data for interest rate and interest accrued along with behavior for
calculating interest earned.

LOVELY PROFESSIONAL UNIVERSITY

Modern Programming Tools & Techniques-III

Notes

Programming object mimics the behavior of a real-world object, for example when a Button on
a form perform a task when clicked some objects are visible to the user while others are not
Objects are created from classes Multiple objects can be created from the same class. For Example
The class of Dog defines all possible dogs by listing the characteristics and behaviors they can
have; the object Snoopy is one particular dog, with particular versions of the characteristics.
A Dog has fur; Snoopy has white fur.
A Class defines the abstract characteristics of an object, including the things characteristics
(its attributes, fields or properties) and the objects behaviors (the things it can do, or methods,
operations or features). One might say that a class is a blueprint or factory that describes the
nature of something. For example, the class Dog would consist of traits shared by all dogs,
such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes
provide modularity and structure in an object-oriented computer program. A class should
typically be recognizable to a non-programmer familiar with the problem domain, meaning
that the characteristics of the class should make sense in context.
The code for a class should be relatively self-contained (generally using
encapsulation). Collectively, the properties and methods defined by a class
are called members.

1.3 Visual Basic.NET


Many people have looked at VB.NET and grumbled about the changes. There are significant
changes to the language: a new optional error handling structure, namespaces, true inheritance,
free threading, and many others. Some see these changes as merely a way that Microsoft can
place a check mark next to a certain feature and is able to say, Yeah, we do that. However,
there are good reasons for the changes in VB.NET.
The world of applications is changing. This is merely a continuation of what has occurred
over the past several years. If we took a Visual Basic 1.0 developer and showed him an ntier
application with an ASP front end, a VB COM component middle tier, and a SQL Server back
end full of stored procedures, it would look quite alien to him. Yet, over the past few years, the
vast majority of developers have been using Visual Basic to create COM components, and they
have become quite versed in ADO as well. The needs for reusability and centralization (a way
to avoid distributing components to the desktop) have driven this move to the ntier model.
The move to the Web revealed some problems. Scalability was an issue, but more complex
applications had other requirements, such as transactions that spanned multiple components,
multiple databases, or both. To address these issues, Microsoft created Microsoft Transaction
Services (MTS) and COM+ Component Services. MTS (in Windows NT 4) and Component
Services (an updated MTS in Windows 2000) acted as an object-hosting environment, allowing
us to gain scalability and distributed transactions with relative ease. However, VB components
could not take full advantage of all that Component Services had to offer, such as object pooling,
because VB did not support free threading.
In the ASP/VB6 model, Microsoft had developers building a component and then calling it via
an ASP. Microsoft realized that it would be a good idea to make the component directly callable
over HTTP, so that an application anywhere in the world could use that component. Microsoft
threw their support behind SOAP, Simple Object Access Protocol, which allows developers to
call a component over HTTP using an XML string, with the data returning via HTTP in an XML
string. Components sport URLs, making them as easy to access as any other Web item. SOAP
has the advantage of having been a cross-industry standard, and not just a Microsoft creation.
At this point, we might be tempted to think that SOAP is all we need, and that we can just
stick with VB6. Therefore it is important to understand what VB.NET gives us, and why it
8

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

makes sense for we, and many other developers, to upgrade to .NET. For example, we create
components and want them to be callable via SOAP, but how do we let people know that those
components exist? .NET includes a discovery mechanism that allows we to find components
that are available to web. We will find out more about this mechanism, including the disco
file, Building Web Services with VB.NET. .NET also provides many other features, such as
garbage collection for freeing up resources, true inheritance for the first time, debugging that
works across languages and against running applications, and the ability to create Windows
services and console applications.

Notes

Before proceeding, it is important to understand a little bit more about what is meant by .NET.
There are many .NETs here. There is VB.NET, which is the new version of Visual Basic. There
is Visual Studio.NET, an Integrated Development Environment that hosts VB.NET, C#, and C++.
NET. Underlying all this is the .NET Framework and its core execution engine, the Common
Language Runtime.
In the .NET model, we write applications that target the .NET Framework. This gives them
automatic access to such benefits as garbage collection (which destroys objects and reclaims
memory for we), debugging, security services, inheritance, and more. When we compile the code
from any language that supports the .NET Framework, it compiles into something called MSIL,
or Microsoft Intermediate Language. This MSIL file is binary, but it is not machine code; instead,
it is a format that is platform independent and can be placed on any machine running the .NET
Framework. Within the .NET Framework is a compiler called the Just-In-Time, or JIT, compiler.
It compiles the MSIL down to machine code specific to that hardware and operating system.
In looking at the fundamental changes, it is important to understand that the number one feature
request from Visual Basic developers, for years, has been inheritance. VB has had interface
inheritance since VB4, but developers wanted real or implementation inheritance. Why? What
are the benefits? The main benefit of inheritance is the ability to create applications more quickly.
This is an extension of the promise of component design and reusability. With implementation
inheritance, we build a base class and can inherit from it, using it as the basis for new classes. For
example, we could create a Vehicle class that provides basic functionality that could be inherited
in both a Bicycle class and a Car class. The important point here is that Bicycle and Car inherit
the functionality, or the actual code, from the Vehicle class. In VB4, the best we could do was
inheriting the structure, minus any implementation code. In VB.NET, the functionality in that
base class is available to your other classes as is, or we can extend and modify it as necessary.
The .NET provides us with integrated debugging tools. If we have ever debugged an ASP
application that had VB COM components, we know that we had to use Visual InterDev to
debug the ASPs and VB to debug the components. If we also had C++ components in the mix,
we had to use the C++ debugger on those components. With .NET, there is one debugger.
Any language that targets the .NET Framework can be debugged with that single debugger,
even if one part of your application is written in VB.NET and calls another part written in C#
(pronounced C-Sharp), or any other language built to target the .NET Framework.
The .NET supplies a standard security mechanism, available to all parts of your application.
.NET provides a possible solution to DLL Hell, and removes much of the complexity of dealing
with COM and the registry. .NET allows us to run components locally, without requiring the
calling application to go to the registry to find components.
There are also things that VB.NET can do that we cannot do today in VB. For example, Web
Applications are a new form of project. Gone is Visual InterDev with its interpreted VBScript
code. Instead, we now build your ASP.NET pages with VB.NET (or C# or C++), and they are
truly compiled for better performance. VB.NET lets we create Windows services natively for the
first time by providing a Windows Services project type. And yes, VB.NET lets VB developers
build truly free-threaded components and applications for the first time.

LOVELY PROFESSIONAL UNIVERSITY

Modern Programming Tools & Techniques-III

Notes

Finally, we need to realize that the new language is actually going to have a version number
on it, although the final name is undecided. It might well be called VB.NET 2002. This implies
that at some point, there will be new versions of VB.NET, just as there were new versions of
VB. References to previous versions of VB will be either VB or VB6. References to VB.NET 2002
will be just VB.NET.
We have decided we need to move from Visual Basic 6 to VB.NET, and we picked up to find
out about the changes. .NET Framework why starts with the .NET Framework? The truth is
that we cannot understand VB.NET until we understand the .NET Framework. We see the .NET
Framework and VB.NET are tightly intertwined; many of the services we will build into your
applications are actually provided by the .NET Framework and are merely called into action
by your application.
The .NET Framework is a collection of services and classes. It exists as a layer between the
applications we write and the underlying operating system. This is a powerful concept: The
.NET Framework need not be a Windows-only solution. The .NET Framework could be moved
to any operating system, meaning your .NET applications could be run on any operating system
hosting the .NET Framework. This means that we could achieve true cross-platform capabilities
simply by creating VB.NET applications, provided the .NET Framework was available for other
platforms. Although this promise of cross-platform capability is a strong selling point to .NET,
there has not yet been any official announcement about .NET being moved to other operating
systems.
In addition, the .NET Framework is exciting because it encapsulates much of the basic functionality
that used to have to be built into various programming languages. The .NET Framework has
the code that makes Windows Forms work, so any language can use the built-in code in order
to create and use standard Windows forms. In addition, Web Forms are part of the framework,
so any .NET language could be used to create Web Applications. Additionally, this means that
various programming elements will be the same across all languages; a Long data type will be
the same size in all .NET languages. This is even more important when it comes to strings and
arrays. No longer will we have to worry about whether or not a string is a BStr or a CStr before
we pass it to a component written in another language.
The drag and drop design for creating the user interface in Visual Basic, is
derived from a prototype form generator developed by Alan Cooper and his
company called Tripod.

1.3.1 The Common Language Runtime


One of the major components of the .NET Framework is the Common Language Runtime, or
CLR. The CLR provides a number of benefits to the developer, such as exception handling,
security, debugging, and versioning and these benefits are available to any language built for
the CLR. This means that the CLR can host a variety of languages, and can offer a common
set of tools across those languages. Microsoft has made VB, C++, and C# premier languages
for the CLR, which means that these three languages fully support the CLR. In addition, other
vendors have signed up to provide implementations of other languages, such as Perl, Python,
and even COBOL.
When a compiler compiles for the CLR, this code is said to be managed code. Managed code is
simply code that takes advantage of the services offered by the CLR. For the runtime to work
with managed code, that code must contain metadata. This metadata is created during the
compilation process by compilers targeting the CLR. The metadata is stored with the compiled
code and contains information about the types, members, and references in the code. Among
other things, the CLR uses this metadata to:

10

Locate classes
LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

Load classes

Generate native code

Provide security

Notes

The runtime also handles object lifetimes. Just as COM/COM+ provided reference counting
for objects; the CLR manages references to objects and removes them from memory when all
the references are gone, through the process known as garbage collection. Although garbage
collection actually gives us slightly less control than we had in VB, we gain some important
benefits. For example, your errors should decrease because the number of objects that end up
hanging around due to circular references should be reduced or completely eliminated. In
addition, garbage collection ends up being much faster than the old way of destroying objects
in VB. Instances of objects we create that are managed by the runtime are called managed data.
We can interact with both managed and unmanaged data in the same application, although
managed data gives we all the benefits of the runtime.
The CLR defines a standard type system to be used by all CLR languages. This means that all
CLR languages will have the same size integers and longs, and they will all have the same type
of string no more worrying about BStrs and CStrs! This standard type system opens up the door
for some powerful language interoperability. For example, we can pass a reference of a class
from one component to another, even if those components are written in different languages. We
also can derive a class in C# from a base class written in VB.NET, or any other combination of
languages targeted to the runtime. Do not forget that COM had a set of standard types as well,
but they were binary standards. This meant that with COM, we had language interoperability
at run time. With .NETs type standard, we have language interoperability at design time.
After it is compiled, managed code includes metadata, which contains information about the
component itself, and the components used to create the code. The runtime can check to make
sure that resources on which we depend are available. The metadata removes the need to store
component information in the registry. That means moving a component to a new machine does
not require registration (unless it will be a global assembly, Building Classes and Assemblies
with VB.NET), and removing components is as simple as deleting them.
As we can see, the Common Language Runtime provides a number of benefits that are not only
new, but should enhance the experience of building applications. Other benefits that we will
see in more detail include some of the new object-oriented features to VB.NET. Many of these
new features are not so much additions to the language as they are features of the runtime that
are simply being exposed to the VB.NET.

1.3.2 Managed Execution


To understand how your VB.NET applications work, and just how much the code differs from
the VB code that Dorothy wrote in Kansas, it is important to understand managed code and how
it works. To use managed execution and get the benefits of the CLR, we must use a language
that was built for, or targets, the runtime.
Fortunately for we, this includes VB.NET. In fact, Microsoft wanted to make sure that VB.NET
was a premier language on the .NET platform, meaning that Visual Basic could no longer be
accused of being a toy language. The runtime is a language-neutral environment, which means
that any vendor can create a language that takes advantage of the runtimes features. Different
compilers can expose different amounts of the runtime to the developer, so the tool we use and
the language in which we write might still appear to work somewhat differently. The syntax of
each language is different, of course, but when the compilation process occurs, all code should
be compiled into something understandable to the runtime.

LOVELY PROFESSIONAL UNIVERSITY

11

Modern Programming Tools & Techniques-III

Notes

1.3.3 Microsoft Intermediate Language (MSIL)


One of the more interesting aspects of .NET is that when we compile your code, we do not
compile to native code. Before we VB developers panic and fear that we are returning to the
days of interpreted code, realize that the compilation process translates your code into something
called Microsoft intermediate language, which is also called MSIL or just IL. The compiler also
creates the necessary metadata and compiles it into the component. This IL is CPU independent.
After the IL and metadata are in a file, this compiled file is called the PE, which stands for either
portable executable or physical executable, depending on whom we ask. Because the PE contains
your IL and metadata, it is therefore self-describing, eliminating the need for a type library or
interfaces specified with the Interface Definition Language (IDL).

1.3.4 The Just-In-Time Compiler


Your code does not stay IL for long, however. It is the PE file, containing the IL that can be
distributed and placed with the CLR running on the .NET Framework on any operating system
for which the .NET Framework exists, because the IL is platform independent. When we run
the IL, however, it is compiled to native code for that platform. Therefore, we are still running
native code; we are not going back to the days of interpreted code at all. The compilation to
native code occurs via another tool of the .NET Framework: the Just-In-Time (JIT) compiler.
With the code compiled, it can run within the Framework and take advantage of low-level
features such as memory management and security. The compiled code is native code for the
CPU, on which the .NET Framework is running, meaning that we are indeed running native
code instead of interpreted code. A JIT compiler will be available for each platform on which the
.NET Framework runs, so we should always be getting native code on any platform running the
.NET Framework. Remember, today this is just Windows, but this could change in the future.

1.3.5 Executing Code


Interestingly, the JIT complier does not compile the entire IL when the component is first called.
Instead, each method is compiled the first time it is called. This keeps we from having to compile
sections of code that are never called. After the code is compiled, of course, subsequent calls use
the compiled version of the code. This natively compiled code is stored in memory in Beta 2.
However, Microsoft has provided a PreJIT compiler that will compile all the code at once and
store the compiled version on disk, so the compilation will persist over time. This tool is called
ngen.exe and can be used to precompile the entire IL. If the CLR cannot find a precompiled
version of the code, it begins to JIT compile it on-the-fly.
After the code starts executing, it can take full advantage of the CLR, with benefits such as the
security model, memory management, debugging support, and profiling tools.

1.3.6 Assemblies
One of the new structures we will create in VB.NET is the assembly. An assembly is a collection
of one or more physical files. The files are most often code, such as the classes we build, but
they could also be images, resource files, and other binary files associated with the code. Such
assemblies are known as static assemblies because we create them and store them on disk.
Dynamic assemblies are created at runtime and are not normally stored to disk (although they
can be).
An assembly represents the unit of deployment, version control, reuse, and security. If this
sounds like the DLLs we have been creating in Visual Basic for the past six years, it is similar.
Just as a standard COM DLL has a type library, the assembly has a manifest that contains the
metadata for the assembly, such as the classes, types, and references contained in the IL. The

12

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

assembly often contains one or more classes, just like a COM DLL. In .NET, applications are
built using assemblies; assemblies are not applications in their own rights.

Notes

Perhaps the most important point of assemblies is this: All runtime applications must be made
up of one or more assemblies.

1.3.7 Assembly Manifest


The manifest is similar in theory to the type library in COM DLLs. The manifest contains all the
information about the items in the assembly, including what parts of the assembly are exposed
to the outside world. The manifest also lists the assemblys dependencies on other assemblies.
Each assembly is required to have a manifest.
The manifest can be part of a PE file, or it can be a standalone file if your assembly has more
than one file in it. Although this is not an exhaustive list, a manifest contains:

Assembly name

Version

Files in the assembly

Referenced assemblies

In addition, a developer can set custom attributes for an assembly, such as a title and a description.

1.3.8 An End to DLL Hell


One of the great benefits of COM was supposed to be an end to DLL Hell. If we think back
for a moment to the days of 16-bit programming, we will remember that we had to distribute
a number of DLLs with a Windows application. It seemed that almost every application had
to install the same few DLLs, such as Ctrl3d2.dll. Each application we installed might have a
slightly different version of the DLL, and we ended up with multiple copies of the same DLL,
but many were different versions. Even worse, a version of a particular DLL could be placed in
the Windows\System directory that then broke many of your existing applications.
The COM was supposed to fix all that. No longer did applications search around for DLLs
by looking in their own directories, and then search the Windows path. With COM, requests
for components were sent to the registry. Although there might be multiple versions of the
same COM DLL on the machine, there would be only one version in the registry at any time.
Therefore, all clients would use the same version. This meant, however, that each new version
of the DLL had to guarantee compatibility with previous versions. This led to interfaces being
immutable under COM; after the component was in production, the interface was never supposed
to change. In concept that sounds great, but developers released COM components that broke
binary compatibility; in other words, their components modified, added, or removed properties
and methods. The modified components then broke all existing clients. Many VB developers
have struggled with this exact problem.
The .NET Framework and the CLR attempt to address this problem through the use of assemblies.
Even before .NET, Windows 2000 introduced the capability to have an application look in the
local directory for a DLL, instead of going to the registry. This ensured that we always had the
correct version of the DLL available to the application.
The runtime carries this further by allowing components to declare dependencies on certain
versions of other components. In addition, multiple versions of the same component can be
run simultaneously in what Microsoft calls side-by-side instancing or side-by-side execution.

LOVELY PROFESSIONAL UNIVERSITY

13

Modern Programming Tools & Techniques-III

Notes

1.3.9 Global Assembly Cache (GAC)


Even though components in .NET do not have to be registered, there is a similar process if we
have an assembly that is to be used by multiple applications. The CLR actually has two caches
within its overall code cache: the download cache and the global assembly cache (GAC). An
assembly that will be used by more than one application is placed into the global assembly
cache by running an installer that places the assembly in the GAC. If an assembly is not in the
local directory and not in the GAC, we can have a codebase hint in a configuration file. The
CLR then downloads the assembly, storing it in the download cache and binding to it from
there. This download cache is just for assemblies that have to be downloaded, and will not be
discussed further.
The GAC is where we place a component if we want multiple applications to use the same
component. This is very similar to what we have with registered COM components in VB6.
Placing assemblies in the GAC has several advantages. Assemblies in the GAC tend to perform
better because the runtime locates them faster and the security does not have to be checked each
time that the assemblies are loaded. Assemblies can be added to or removed from the GAC only
by someone with administrator privileges.
Where things get interesting is that we can actually have different versions of the same assembly
in the GAC at the same time.

1.4 The Common Type System


The Common Type System specifies the types supported by the CLR. The types specified by
the CLR include

ClassesThe definition of what will become an object; includes properties, methods, and
events.

InterfacesThe definition of the functionality a class can implement, but does not contain
any implementation code.

Value TypesUser-defined data types that are passed by value.

DelegatesSimilar to function pointers in C++, delegates are often used for event handling
and callbacks.

The type system sets out the rules that language compilers must follow to produce code that
is cross-language compatible. By following the type system, vendors can produce code that is
guaranteed to work with code from other languages and other compilers because all languages
are consistent in their use of types.

1.4.1 Classes
Most Visual Basic developers are familiar with classes. Classes are definitions or blueprints of
objects that will be created at runtime. Classes define the properties, methods, fields, and events
of objects. If the term fields are new to us, it simply means public variables exposed by the class;
fields are the lazy way to do properties. Together, properties, methods, fields, and events are
generically called members of the class.
If a class has one or more methods that do not contain any implementation, the class is said to
be abstract. In VB.NET, we cannot instantiate abstract classes directly; instead, we must inherit
from them. In VB6, it was possible to create a class that was just method definitions and then to
use the Implements keyword to inherit the interface. We could actually instantiate the interface
in VB6, but because it did not have any implementation code, there was no point in doing so.

14

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

In VB.NET, we can create a class that has implementation code instead of just the interface, and
then mark the class as abstract. Now, other classes can inherit from that abstract class and use
the implementation in it or override the implementation as needed. These are new concepts to
VB developers. In the past, VB had only interface inheritance, but VB.NET has real inheritance,
known as implementation inheritance.

Notes

In VB.NET, interfaces are separate from classes. In VB6, we created interfaces by creating
classes with method definitions, but no implementation code inside those methods. Classes
have a number of possible characteristics that can be set, and that are stored in the metadata. In
addition, members can have characteristics. These characteristics include such items as whether
or not the class or member is inheritable.

1.4.2 Interfaces
Interfaces in VB.NET are like the interfaces in previous versions of VB: They are definitions of
a class without the actual implementation. Because there is no implementation code, we cannot
instantiate an interface, but must instead implement it in a class.
There is one exception to the no implementation code in an interface rule: In VB.NET, we can
define what are called static members. These can have implementation code.

1.4.3 Value Types


In .NET languages, a standard variable type, such as an integer, is native to the language, and
it is passed by value when used as an argument. Objects, on the other hand, are always passed
by reference. However, a value type is a user-defined type that acts much like an object, but is
passed by value. In reality, value types are stored as primitive data types, but they can contain
fields, properties, events, and both static and nonstatic methods. Value types do not carry the
overhead of an object that is being held in memory.
If this seems confusing, think about enums. Enumerations are a special type of value type. An
enum simply has a name and a set of fields that define values for a primitive data type. Enums,
however, cannot have their own properties, events, or methods.

1.4.4 Delegates
Delegates are a construct that can be declared in a client. The delegate actually points to a method
on a particular object. The method to be pointed and the object can be set when the instance
of the delegate is created at declaration. This allows us to define calls to various methods in
different objects based on logic in your code. Delegates are most often used to handle events.
Using delegates, we can pass events to a centralized event handler.

Make the list of data types in VB.NET.

Self Assessment Questions


Multiple Choice Questions
1. Visual Basic is an object-oriented language that consists of two fundamental parts:
(a) Visual part and language part

(b) Visual part and even part

(c) Even part and language part

(d) Even part and program part

LOVELY PROFESSIONAL UNIVERSITY

15

Modern Programming Tools & Techniques-III

Notes

2. Polymorphism is the process of using a .. or a procedure in different ways for


different set of inputs given.

(a) language

(b) program

(c) function

(d) variable

3. Windows Forms in Visual Basic .NET . provide a robust container for existing
ActiveX controls.
(a) 2000

(b) 2001

(c) 2002

(d) 2003

4. Visual Basic .NET provides the easiest, most productive language and tool for rapidly
building Windows and ..
(a) Web applications

(b) Web programming

(c) Web language

(d) Web design

5. The CLR defines a standard type system to be used by all CLR .

(a) languages

(b) program

(c) function

(d) variable

1.5 Feature of VB.NET


Visual Basic .NET provides the easiest, most productive language and tool for rapidly building
Windows and Web applications. Visual Basic .NET comes with enhanced visual designers,
increased application performance, and a powerful integrated development environment (IDE).
It also supports creation of applications for wireless, Internet-enabled hand-held devices. The
following are the features of Visual Basic .NET with .NET Framework 1.0 and Visual Basic .NET
2003 with .NET Framework 1.1.

1.5.1 Powerful Windows-based Applications


Visual Basic .NET comes with features such as a powerful new forms designer, an in-place menu
editor, and automatic control anchoring and docking. Visual Basic .NET delivers new productivity
features for building more robust applications easily and quickly. With an improved integrated
development environment (IDE) and a significantly reduced startup time, Visual Basic .NET
offers fast, automatic formatting of code as we type, improved IntelliSense, an enhanced object
browser and XML designer, and much more.

1.5.2 Building Web-based Applications


With Visual Basic .NET we can create Web applications using the shared Web Forms Designer and
the familiar drag and drop feature. We can double-click and write code to respond to events.
Visual Basic .NET 2003 comes with an enhanced HTML Editor for working with complex Web
pages. We can also use IntelliSense technology and tag completion, or choose the WYSIWYG
editor for visual authoring of interactive Web applications.

1.5.3 Simplified Deployment


With Visual Basic .NET we can build applications more rapidly and deploy and maintain them
with efficiency. Visual Basic .NET 2003 and .NET Framework 1.1 makes DLL Hell a thing of
the past. Side-by-side versioning enables multiple versions of the same component to live safely
on the same machine so that applications can use a specific version of a component. XCOPY-

16

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

deployment and Web auto-download of Windows-based applications combine the simplicity


of Web page deployment and maintenance with the power of rich, responsive Windows-based
applications.

Notes

1.5.4 Powerful, Flexible, Simplified Data Access


We can tackle any data access scenario easily with ADO.NET and ADO data access. The flexibility
of ADO.NET enables data binding to any database, as well as classes, collections, and arrays, and
provides true XML representation of data. Seamless access to ADO enables simple data access
for connected data binding scenarios. Using ADO.NET, Visual Basic .NET can gain high-speed
access to MS SQL Server, Oracle, DB2, Microsoft Access, and more.

1.5.5 Improved Coding


We can code faster and more effectively. A multitude of enhancements to the code editor,
including enhanced IntelliSense, smart listing of code for greater readability and a background
compiler for real-time notification of syntax errors transforms into a rapid application
development (RAD) coding machine.

1.5.6 Direct Access to the Platform


Visual Basic developers can have full access to the capabilities available in .NET Framework 1.1.
Developers can easily program system services including the event log, performance counters and
file system. The new Windows Service project template enables to build real Microsoft Windows
NT Services. Programming against Windows Services and creating new Windows Services is not
available in Visual Basic .NET Standard, it requires Visual Studio 2003 Professional, or higher.

1.5.7 Full Object-Oriented Constructs


We can create reusable, enterprise-class code using full object-oriented constructs. Language
features include full implementation inheritance, encapsulation, and polymorphism. Structured
exception handling provides a global error handler and eliminates spaghetti code.

1.5.8 XML Web Services


XML Web services enable us to call components running on any platform using open Internet
protocols. Working with XML Web services is easier where enhancements simplify the discovery
and consumption of XML Web services that are located within any firewall. XML Web services
can be built as easily as we would build any class in Visual Basic 6.0. The XML Web service
project template builds all underlying Web service infrastructure.

1.5.9 Mobile Applications


Visual Basic .NET 2003 and the .NET Framework 1.1 offer integrated support for developing
mobile Web applications for more than 200 Internet-enabled mobile devices. These new features
give developers a single, mobile Web interface and programming model to support a broad
range of Web devices, including WML 1.1 for WAPenabled cellular phones, compact HTML
(cHTML) for i-Mode phones, and HTML for Pocket PC, handheld devices, and pagers. Please
note, Pocket PC programming is not available in Visual Basic .NET Standard, it requires Visual
Studio 2003 Professional, or higher.

1.5.10 COM Interoperability


We can maintain your existing code without the need to recode. COM interoperability enables us
to leverage your existing code assets and offers seamless bi-directional communication between
Visual Basic 6.0 and Visual Basic .NET applications.

LOVELY PROFESSIONAL UNIVERSITY

17

Modern Programming Tools & Techniques-III

Notes

1.5.11 Reuse Existing Investments


We can reuse all your existing ActiveX Controls. Windows Forms in Visual Basic .NET 2003
provide a robust container for existing ActiveX controls. In addition, full support for existing
ADO code and data binding enable a smooth transition to Visual Basic .NET 2003.

1.5.12 Upgrade Wizard


We upgrade your code to receive all of the benefits of Visual Basic .NET 2003. The Visual
Basic .NET Upgrade Wizard, available in Visual Basic .NET 2003 Standard Edition, and higher,
upgrades up to 95% of existing Visual Basic code and forms to Visual Basic .NET with new
support for Web classes and UserControls.

1.6 .NET Framework


The programming languages in Visual Studio run in 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 announced or have released versions of other
programming languages to run in the .NET Framework, including .NET versions of APL by
Dyalog, FORTRAN by Lahey Computer Systems, COBOL by Fujitsu Software Corporation, Pascal
by the Queensland University of Technology (free), PERL by ActiveState, RPG by ASNA, and Java,
known as IKVM.NET. 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.

1.6.1 Visual Basic in .Net Framework


Microsoft Visual Basic comes with Visual Studio. We also can purchase VB by itself (without the
other languages but with the .NET Framework). VB is available in an Express Edition, a Standard
Edition, a Professional Edition, and a Team System Edition. Anyone planning to do professional
application development that includes the advanced features of database management should
use the Professional Edition or the Team System Edition. We can find a matrix showing the
features of each edition in Help. The Professional Edition is available to educational institutions
through the Microsoft Academic Alliance program and is the best possible deal. When a campus
department purchases the Academic Alliance, the school can install Visual Studio on all classroom
and lab computers and provide the software to all students and faculty at no additional charge.
The .NET Framework encompasses the following:

A new way to expose operating system and other APIs. For years, the set of Windows
functionality that was available to developers and the way that functionality was invoked
were dependent on the language environment being used. For example, the Windows
operating system provides the ability to create windows (obviously). Yet, the way this
feature was invoked from a C++ program was dramatically different from the way it was
invoked from a Visual Basic program. With .NET, the way that operating system services
are invoked is uniform across all languages (including code embedded in ASP.NET pages).

This portion of .NET is commonly referred to as the .NET Framework class library.

18

A new infrastructure for managing application execution. To provide a number of sophisticated


new operating-system services including code-level security, cross-language class
inheritance, cross-language type compatibility, and hardware and operating-system
independence, among othersMicrosoft developed a new runtime environment known
as the Common Language Runtime (CLR). The CLR includes the Common Type System

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

(CTS) for cross-language type compatibility and the Common Language Specification
(CLS) for ensuring that third-party libraries can be used from all .NET-enabled languages.

Notes

To support hardware and operating-system independence, Microsoft developed the Microsoft


Intermediate Language (MSIL, or just IL). IL is a CPU-independent machine language-style
instruction set into which .NET Framework programs are compiled. IL programs are compiled
to the actual machine language on the target platform prior to execution (known as just-in-time,
or JIT, compiling). IL is never interpreted.

A new web server paradigm. To support high-capacity web sites, Microsoft has replaced its
Active Server Pages (ASP) technology with ASP.NET. While developers who are used to
classic ASP will find ASP.NET familiar on the surface, the underlying engine is different,
and far more features are supported. One difference, already mentioned, is that ASP.NET
web page code is now compiled rather than interpreted, greatly increasing execution speed.

A new focus on distributed-application architecture. Visual Studio .NET provides top-notch


tools for creating and consuming web services-vendor-independent software services that
can be invoked over the Internet.

The .NET Framework is designed top to bottom with the Internet in mind. For example,
ADO.NET, the next step in the evolution of Microsofts vision of universal data access,
assumes that applications will work with disconnected data by default. In addition, the
ADO.NET classes provide sophisticated XML capabilities, further increasing their usefulness
in a distributed environment.
An understanding of the .NET Framework is essential to developing professional Visual Basic
.NET applications.

Search more about the features of VB.NET.

1.7 VB.NET as a Language in .NET Framework


The syntax of the Visual Basic .NET language, including basic concepts such as variables,
operators, statements, classes, etc. Some material that we did expect to find in here we will seem
to be missing. For example, mathematical functions, file I/O, and form declarations are all very
much a part of developing Visual Basic .NET applications, yet they are not introduced because
they are not intrinsic to the Visual Basic .NET language.

1.7.1 Source Files


Visual Basic .NET source code is saved in files with a .vb extension. The exception to this rule
is 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, including our
old friend, Notepad. Source code can be broken into as many or as few files as desired. When we
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 we are compiling from the command
line, all source files must appear as command-line arguments to the compile command. The
location of declarations within source files is unimportant. As long as all referenced declarations
appear somewhere in a source file being compiled, they will be found.
Unlike previous versions of Visual Basic, no special file extensions are used to indicate various
language constructs (e.g., .cls for classes, .frm for forms, etc.). Syntax has been added to the

LOVELY PROFESSIONAL UNIVERSITY

19

Modern Programming Tools & Techniques-III

Notes

language to differentiate various constructs. In addition, the pseudo language for specifying the
graphical layout of forms has been removed. Form layout is specified by setting properties of
form objects explicitly within code. Either this code can be written manually, or the WYSIWYG
form designer in Visual Studio .NET can write it.

1.7.2 Identifiers
Identifiers are names given to namespaces, types (enumerations, structures, classes, standard
modules, interfaces, and delegates), type members (methods, constructors, events, constants,
fields, and properties), and variables. Identifiers must begin with either an alphabetic or
underscore character (_), may be of any length, and after the first character must consist of
only alphanumeric and underscore characters. Namespace declarations may be declared either
with identifiers or qualified identifiers. Qualified identifiers consist of two or more identifiers
connected with the dot character (.). Only namespace declarations may use qualified identifiers.
Consider this code fragment:
Imports System
Namespace ORelly.ProgVBNet
Public Class Hello
Public Shared Sub SayHello( )
Console.WriteLine(hello, world)
End Sub
End Class
End Namespace
This code fragment declares three identifiers: OReilly.ProgVBNet (a namespace name), Hello
(a class name), and SayHello (a method name). In addition to these, the code fragment uses
three identifiers declared elsewhere: System (a namespace name), Console (a class name), and
WriteLine (a method name).
Although Visual Basic .NET is not case sensitive, the case of identifiers is preserved when
applications are compiled. When using Visual Basic .NET components from case-sensitive
languages, the caller must use the appropriate case.
Ordinarily, identifiers may not match Visual Basic .NET keywords. If it is necessary to declare
or use an identifier that matches a keyword, the identifier must be enclosed in square brackets
([ ]). Consider this code fragment:
Public Class [Public]
Public Shared Sub SayHello( )
Console.WriteLine(hello, world)
End Sub
End Class
Public Class SomeOtherClass
Public Shared Sub SomeOtherMethod( )
[Public].SayHello( )
End Sub
End Class
This code declares a class named Public and then declares a class and method that use the
Public class. Public is a keyword in Visual Basic .NET. Escaping it with square brackets lets it
is used as an identifier, in this case the name of a class. As a matter of style, using keywords
20

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

as identifiers should be avoided, unless there is a compelling need. This facility allows Visual
Basic .NET applications to use external components that declare identifiers matching Visual
Basic .NET keywords.

Notes

1.7.3 Keywords
Keywords are words with special meaning in a programming language. In Visual Basic .NET,
keywords are reserved; that is, they cannot be used as tokens for such purposes as naming
variables and subroutines. The keywords in Visual Basic .NET are shown in Table 1.2.
Table 1.2: Keywords in Visual Basic .NET
ElseIf

Used in the If Else ElseIf End If construct

End

Used to terminate a variety of statements

EndIf

Used in the If Else ElseIf End If construct

Enum

Visual Basic .Net statement

Erase

Visual Basic .Net statement

Error

Used in the Error and on Error compatibility statements

Event

Visual Basic .Net statement

Explicit

Used in the Option Explicit statement

False

Boolean Literal

For

Used in the For Next and For Each Next constructs

Finally

Visual Basic .Net statement

For

Visual Basic .Net statement

Friend

Statement and access modifier

Function

Visual Basic .Net statement

Get

Used in the Property construct

GetType

Visual Basic .Net operator

GoTo

Visual Basic .Net statement, used with the On Error statement

Handles

Defines an event handler in a procedure declaration

Call

Visual Basic .Net statement

Case

Used in the Select Case construct

Catch

Visual Basic .Net statement

CBool

Data-conversion function

CByte

Data-conversion function

CChar

Data-conversion function

CDate

Data-conversion function

CDec

Data-conversion function

CDb1

Data-conversion function

Char

Used in variable declaration (intrinsic data type)

CInt

Data-conversion function

Class

Visual Basic .Net statement

CLng

Data-conversion function

CObj

Data-conversion function

Compare

Used in the Option Compare statement

CShort

Data-conversion function

CSng

Data-conversion function
Contd...

LOVELY PROFESSIONAL UNIVERSITY

21

Modern Programming Tools & Techniques-III

Notes

CStr

Data-conversion function

CType

Data-conversion function

Date

Used in variable declaration (intrinsic data type)

Decimal

Used in variable declaration (intrinsic data type)

Declare

Visual Basic .NET statement

Default

Used in the Property statement

Delegate

Visual Basic .NET statement

Dim

Variable declaration statement

Do

Visual Basic .NET statement

Double

Used in variable declaration (intrinsic data type)

Each

Used in the For Each Next construct

Else

Used in the If Else ElseIf End If construct

ElseIf

Used in the If Else Elself End If construct

End

Used to terminate a variety of statements

EndIf

Used in the If Else ElseIf ... End If construct

Enum

Visual Basic .NET statement

Erase

Visual Basic .NET statement

Error

Used in the Error and On Error compatibility statements

Event

Visual Basic .NET statement

Explicit

Used in the Option Explicit statement

False

Boolean literal

For

Used in the For Next and For Each Next constructs

Finally

Visual Basic .NET statement

For

Visual Basic .NET statement

Friend

Statement and access modifier

Function

Visual Basic .NET statement

Get

Used in the Property construct

GetType

Visual Basic .NET operator

GoTo

Visual Basic .NET statement, used with the On Error statement

Handles

Defines an event handler in a procedure declaration

If

Visual Basic .NET statement

Implements

Visual Basic .NET statement

Imports

Visual Basic .NET statement

In

Used in the For Each Next construct

Inherits

Visual Basic .NET statement

Input

Used in the FileOpen function

Integer

Used in variable declaration (intrinsic data type)

Interface

Visual Basic .NET statement

Is

Object comparison operator

Let

Reserved but unused in Visual Basic .NET

Lib

Used in the Declare statement

Like

Visual Basic .NET operator

Lock

Function name

Long

Used in variable declaration (intrinsic data type)


Contd...

22

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

Notes

Loop

Used in a Do loop

Me

Statement referring to the current object instance

Mid

String-manipulation statement and function

Mod

Visual Basic .NET operator

Module

Visual Basic .NET statement

MustInherit

Used in the Class construct

MustOverride

Used in the Sub and Function statements

MyBase

Statement referring to an objects base class

MyClass

Statement referring to the current object instance

Namespace

Visual Basic .NET statement

New

Object-creation keyword, constructor name

Next

Used in the For Next and For Each Next constructs

Not

Visual Basic .NET operator

Nothing

Used to clear an object reference

NotInheritable

Used in the Class construct

NotOverridable

Used in the Sub, Property, and Function statements

Object

Used in variable declaration (intrinsic data type)

Off

Used in Option statements

On

Used in option statements

Option

Used in Option statements

Optional

Used in the Declare, Function, Property, and Sub statements

Or

Boolean operator

OrElse

Boolean operator

Output

Used in the FileOpen function

Overloads

Used in the Sub and Function statements

Overridable

Used in the Sub and Function statements

Overrides

Used in the Sub, Property, and Function statements

ParamArray

Used in the Declare, Function, Property, and Sub statements

Preserve

Used with the ReDim statement

Private

Statement and access modifier

Property

Visual Basic .NET statement

Protected

Statement and access modifier

Public

Statement and access modifier

RaiseEvent

Visual Basic .NET statement

Random

Used in the FileOpen function

Read

Used in the FileOpen function

ReadOnly

Used in the Property statement

ReDim

Visual Basic .NET statement

Rem

Visual Basic .NET statement

RemoveHandler

Visual Basic .NET statement

Resume

Used in the On Error and Resume statements

Return

Visual Basic .NET statement

Seek

File-access statement and function

Select

Used in the Select Case construct


Contd...

LOVELY PROFESSIONAL UNIVERSITY

23

Modern Programming Tools & Techniques-III

Notes

Set

Used in the Property statement

Shadows

Visual Basic .NET statement

Shared

Used in the Sub and Function statements

Short

Used in variable declaration (intrinsic data type)

Single

Used in variable declaration (intrinsic data type)

Static

Variable declaration statement

Step

Used in the For Next construct

Stop

Visual Basic .NET statement

String

Used in variable declaration (intrinsic data type)

Structure

Visual Basic .NET statement

Sub

Visual Basic .NET statement

SyncLock

Visual Basic .NET statement

Text

Used in the Option Compare statement

Then

Used in the If Then Else EndIf construct

Throw

Visual Basic .NET statement

To

Used in the For Next and Select Case constructs

True

Boolean literal

Try

Visual Basic .NET statement

TypeOf

Used in variations of the If Then EndIf construct

Unicode

Used in the Declare statement

Until

Used in the For Next construct

Variant

Reserved but unused in Visual Basic .NET

When

Used with the Try Catch Finally construct

While

Used with the Do Loop and While End While constructs

With

Visual Basic .NET statement

WithEvents

Used in variable declaration (Dim, Public, etc.)

WriteOnly

Used in the Property statement

XOr

Visual Basic .NET operator

1.7.4 Literals
Literals are representations of values within the text of a program. For example, in the following
line of code, 10 is a literal, but x and y is not:

x = y * 10

Literals have data types just as variables do. The 10 in this code fragment is interpreted by the
compiler as type Integer because it is an integer that falls within the range of the Integer type.
Numeric Literals
Any integer literal that is within the range of the Integer type (-2147483648 through 2147483647)
is interpreted as type Integer, even if the value is small enough to be interpreted as type Byte
or Short. Integer literals that are outside the Integer range but are within the range of the Long
type (9223372036854775808 through 9223372036854775807) are interpreted as type Long. Integer
literals outside the Long range cause a compile-time error.
Numeric literals can also be of one of the floating point typesSingle, Double, and Decimal.
For example, in this line of code, 3.14 is a literal of type Double:

24

z = y * 3.14

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

In the absence of an explicit indication of type, Visual Basic .NET interprets floating point literals
as type Double. If the literal is outside the range of the Double type (1.7976931348623157E308
through 1.7976931348623157E308), a compile-time error occurs.

Notes

Visual Basic .NET allows programmers to explicitly specify the types of literals. Table 1.2 lists
Visual Basic .NETs intrinsic data types, along with the method for explicitly defining a literal
of each type. Note that for some intrinsic types, there is no way to write a literal.
String Literals
Literals of type String consist of characters enclosed within quotation-mark characters. For
example, in the following line of code, hello, world is a literal of type String:
Console.WriteLine(hello, world)
String literals are not permitted to span multiple source lines. In other words, this is not permitted:
Wrong
Console.WriteLine(hello,
World)
To write a string literal containing quotation-mark characters, type the character twice for each
time it should appear. For example:
Console.WriteLine(So then Dave said, hello, world.)
This line produces the following output:
So then Dave said, hello, world.
Character Literals
Visual Basic .NETs Char type represents a single character. This is not the same as a onecharacter string; Strings and Chars are distinct types. Literals of type Char consist of a single
character enclosed within quotation-mark characters, followed by the character c. For example,
in the following code, Ac is a literal of type Char:
Dim MyChar As Char
MyChar = Ac
To emphasize that this literal is of a different data type than a single-character string, note that
this code causes a compile-time error if Option Strict is On:
Wrong
Dim MyChar As Char
MyChar = A
The error is:
Option Strict On disallows implicit conversions from String to Char.
Date Literals
Literals of type Date are formed by enclosing a date/time string within number-sign characters.
For example:
Dim MyDate As Date
MyDate = #11/15/2001 3:00:00 PM#
Date literals in Visual Basic .NET code must be in the format m/d/yyyy, regardless of the
regional settings of the computer on which the code is written.

LOVELY PROFESSIONAL UNIVERSITY

25

Modern Programming Tools & Techniques-III

Notes

Boolean Literals
The keywords True and False are the only Boolean literals. They represent the true and false
Boolean states, respectively (of course!). For example:
Dim MyBoolean As Boolean
MyBoolean = True
Nothing
There is one literal that has no type: the keyword Nothing. Nothing is a special symbol that
represents an uninitialized value of any type. It can be assigned to any variable and passed in
any parameter. When used in place of a reference type, it represents a reference that does not
reference any object. When used in place of a value type, it represents an empty value of that
type. For numeric types, this is 0 or 0.0. For the String type, this is the empty string (). For the
Boolean type, this is False. For the Char type, this is the Unicode character that has a numeric
code of 0. For programmer-defined value types, nothing represents an instance of the type that
has been created but has not been assigned a value.
Summary of Literal Formats
Table 1.3 shows all of Visual Basic .NETs intrinsic types, as well as the format for writing literals
of those types in programs.
Note the following facts about forming literals in Visual Basic .NET:

There is no way to represent a literal of type Byte. However, this does not mean that literals
cannot be used in situations where type Byte is expected. For example, the following code
is fine:

Dim MyByte As Byte = 100

Even though the Visual Basic .NET compiler considers 100 to be of type Integer in this
example, it recognizes that the number is small enough to fit into a variable of type Byte.

Types not shown in Table 1.3 cannot be expressed as literals.

1.7.5 Types
Types in Visual Basic .NET are divided into two categories: value types and reference types.
Value types minimize memory overhead and maximize speed of access, but they lack some
features of a fully object-oriented design (such as inheritance). Reference types give full access
to object-oriented features, but they impose some memory and speed overhead for managing
and accessing objects. When a variable holds a value type, the data itself is stored in the variable.
When a variable holds a reference type, a reference to the data (also known as a pointer) is stored
in the variable, and the data itself is stored somewhere else. Visual Basic .NETs primitive types
include both value types and reference types. For extending the type system, Visual Basic .NET
provides syntax for defining both new value types and new reference types.
All reference types derive from the Object type. To unify the type system, value types can be
treated as reference types when needed. This means that all types can derive from the Object type.
Arrays
Array declarations in Visual Basic .NET are similar to those in Visual Basic 6 and other languages.
For example, here is a declaration of an Integer array that has five elements:
Dim a(4) As Integer
The literal 4 in this declaration specifies the upper bound of the array. All arrays in Visual Basic
.NET have a lower bound of 0, so this is a declaration of an array with five elements, having
indexes 0, 1, 2, 3, and 4.
26

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

The previous declaration is of a variable named a, which is of type array of Integer. Array types
implicitly inherit from the .NET Frameworks Array type (defined in the System namespace)
and, therefore, have access to the methods defined in that type. For example, the following code
displays the lower and upper bounds of an array by calling the Array classs GetLowerBound
and GetUpperBound methods:

Notes

Dim a(4) As Integer


Console.WriteLine(LowerBound is & a.GetLowerBound(0).ToString( ))
Console.WriteLine(UpperBound is & a.GetUpperBound(0).ToString( ))
The output is:
LowerBound is 0
UpperBound is 4
Note that the upper bound of the array is dynamic: it can be changed by methods available in
the Array type.
Array elements are initialized to the default value of the element type. A types default value
is determined as follows:

For numeric types, the default value is 0.

For the Boolean type, the default value is False.

For the Char type, the default value is the character whose Unicode value is 0.

For structure types, the default value is an instance of the structure type with all of its
fields set to their default values.

For enumeration types, the default value is an instance of the enumeration type with its
internal representation set to 0, which may or may not correspond to a legal value in the
enumeration.

For reference types (including String), the default value is Nothing.

We can access array elements by suffixing the array name with the index of the desired element
enclosed in parentheses, as shown here:
For i = 0 To 4
Console.WriteLine(a(i))
Next
Arrays can be multidimensional. Commas separate the dimensions of the array when used in
declarations and when accessing elements. Here is the declaration of a three-dimensional array,
where each dimension has a different size:
Dim a(5, 10, 15) As Integer
As with single-dimensional arrays, array elements are initialized to their default values.
Initializing arrays
Arrays of primitive types can be initialized by enclosing the initial values in curly brackets ({}).
For example:
Dim a( ) As String = {First, Second, Third, Fourth, Fifth}
Notice that when arrays are initialized in this manner, the array declaration is not permitted to
specify an explicit size. The compiler infers the size from the number of elements in the initialize.

LOVELY PROFESSIONAL UNIVERSITY

27

Modern Programming Tools & Techniques-III

Notes

To initialize multidimensional arrays, include the appropriate number of commas in the arrayname declaration and use nested curly brackets in the initializer. Here is a declaration of a
two-dimensional array having three rows and two columns:
Dim a(,) As Integer = {{1, 2}, {3, 4}, {5, 6}}
This declaration produces the following array:
a(0,0)=1 a(0,1)=2
a(1,0)=3 a(1,1)=4
a(2,0)=5 a(2,1)=6
When initializing multidimensional arrays, the innermost curly brackets correspond to the
rightmost dimension.
Dynamically allocating arrays
Use the New keyword to allocate arrays of any type. For example, this code creates an array of
five Integers and initializes the elements as shown:
Dim a( ) As Integer
a = New Integer(4) {1, 2, 3, 4, 5}
If the array elements would not be initialized by the allocation, it is still necessary to include
the curly brackets:
Dim a( ) As Integer
allocates an uninitialized array of five Integers
a = New Integer(5) {}
Curly brackets are required so the compiler would not confuse the array syntax with constructor
syntax.
Note also the meaning of this declaration by itself:
Dim a( ) As Integer
This is the declaration of a reference that could point to a single-dimensional array of Integers,
but does not yet. Its initial value is Nothing.
Collections
A collection is any type that exposes the ICollection interface (defined in the System.Collections
namespace). An interface is an agreement in which the type will expose certain methods,
properties, and other members. By exposing the ICollection interface, a type ensures that it can
be used anywhere a collection is expected.) In general, collections store multiple values and
provide a way for iterating through those values. Specialized collection types may also provide
other means for adding and reading values. For example, the Stack type (defined in the System.
Collections namespace) provides methods, such as Push and Pop, for performing operations
that are appropriate for the stack data structure.
The Visual Basic .NET runtime provides a type called Collection (defined in the Microsoft.
VisualBasic namespace) that mimics the behavior of Visual Basic 6 collections and exposes the
ICollection interface.
Using the Collection type

28

Create a new collection object.

Dim col As New Collection( )

Add some items to the collection.

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

col.Add(Some value)

col.Add(Some other value)

col.Add(A third value)

Iterate through the collection and output the strings.

Dim obj As Object

For Each obj In col

Dim str As String = CType(obj, String)

Notes

Console.WriteLine(str)
Next
The Collection types Add method adds items to the collection. Although strings are added to
the collection, the Add method is defined to take items of type Object, meaning that any type
can be passed to the method. After items are added to the collection, they can be iterated using
the For Each statement. Because the Collection class is defined to store items of type Object, the
loop variable in the for each statement must be of type Object. Because the items are actually
strings, the code in example converts the Object references to String references using the CType
function. The output of the code in example is:
Some value
Some other value
A third value
The items in a Collection object can also be iterated using a numerical index. The Collection
object has a Count property, which indicates the number of items in the collection. The next
example is precisely the same as above example, except that it iterates through the Collection
object using a numerical index and a standard for loop.
Using a numerical index on a collection object

Create a new collection object.

Dim col As New Collection( )

Add some items to the collection.

col.Add(Some value)

col.Add(Some other value)

col.Add(A third value)

Iterate through the collection and output the strings.

Dim i As Integer

For i = 1 To col.Count

Dim str As String = CType(col(i), String)

Console.WriteLine(str)
Next
Note that to access an item by index, the index number is placed within parentheses following
the name of the Collection reference variable, as shown again here:
col(i)
The syntax of the Add method is:
Public Sub Add( _
ByVal

LOVELY PROFESSIONAL UNIVERSITY

29

Modern Programming Tools & Techniques-III

Notes

Item As Object, _
Optional ByVal
Key As String = Nothing, _
Optional ByVal
Before As Object = Nothing, _
Optional ByVal
After As Object = Nothing _
)
The parameters are:
Item
The item to add to the collection.
Key
An optional string value that can be used as an index to retrieve the associated item. For example,
the following code adds an item to a collection and then uses the key value to retrieve the item:
Dim col As New Collection( )
col.Add(Some value, Some key)
...
Dim str As String = CType(col(Some key), String)
Console.WriteLine(str)
The output is:
Some value
Before
The item before which the new item should be added.
After
The item after which the new item should be added.

Very Busy (VB) Mail Server


e can place an order and ship it to us. We also help with shopping for gifts; your
order can be gift wrapped and sent anywhere you wish.

The company title will be shortened to VB Mail Order. Include this name on the
title bar of the first form of each project that we create for this case study.
Wer first job is to create a project that will display the name and telephone number for the
contact person for the customer relations, marketing, and order processing, and shipping
departments.
Include a button for each department. When the user clicks on the button for a department,
display the name and telephone number for the contact person in two labels. Also include
identifying labels with Text Department Contact and Telephone Number.
Be sure to include a button for Print and one for Exit. Include a label at the bottom of the
form that holds your name.
Contd...

30

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

Notes

Test Data
Department

Department Contact

Telephone Number

Customer Relations

Tricia Mills

500-1111

Marketing

Michelle Rigner

500-2222

Order Processing

Kenna DeVoss

500-3333

Shipping

Eric Andrews

500-4444

Valley Boulevard Auto Center


Valley Boulevard Auto Center will meet all of your automobile needs. The center has facilities
with everything for your vehicles including sales and leasing for new and used cars and
RVs, auto service and repair, detail shop, car wash, and auto parts.
The company title will be shortened to VB Auto Center. This name should appear as the title
bar on the first form of every project that we create throughout the text for this case study.
Your first job is to create a project that will display current notices. Include four buttons
labeled Auto Sales, Service Center, Detail Shop, and Employment Opportunities.
One label will be used to display the information when the buttons are clicked. Be sure to
include a Print button and an Exit button.
Include your name in a label at the bottom of the form.
Test Data
Button

Label Text

Auto Sales

Family wagon, immaculate condition $12,995

Service Center

Lube, oil, filter $25.99

Detail Shop

Complete detail $79.95 for most cars

Employment Opportunities

Sales position, contact Mr. Mann 551-2134 x475

Video Bonanza
This neighborhood store is an independently owned video rental business. The owners
would like to allow their customers to use the computer to look up the aisle number for
movies by category.
Create a form with a button for each category. When the user clicks on a button, display the
corresponding aisle number in a label. Include a button to print and one to exit.
Include a label that holds your name at the bottom of the form and change the title bar of
the form to Video Bonanza.
We may change the font properties of the labels to the font and size of your choice. Include
additional categories, if you wish.
Follow good programming conventions for object names; include remarks at the top of every
procedure and at the top of the file.
Test Data
Button

Location

Comedy

Aisle 1

Drama

Aisle 2

Action

Aisle 3
Contd...

LOVELY PROFESSIONAL UNIVERSITY

31

Modern Programming Tools & Techniques-III

Notes

Sci-Fi

Aisle 4

Horror

Aisle 5

New Releases

Back Wall

Very Very Boards


This chain of stores features a full line of clothing and equipment for snowboard and
skateboard enthusiasts. Management wants a computer application to allow their employees
to display the address and hours for each of their branches.
Create a form with a button for each store branch. When the user clicks on a button, display
the correct address and hours.
Include a label that holds your name at the bottom of the form and change the title bar of
the form to Very Very Boards.
We may change the font properties of the labels to the font and size of your choice. Include
a Print button and an Exit button. Follow good programming conventions for object names;
include remarks at the top of every procedure and at the top of the file.
Store Branches: The three branches are Downtown, Mall, and Suburbs. Make up hours and
locations for each.
Questions

1. How you can manage the auto enter in web based system?

2. When you make a call and then server is busy? Explain how the server handle this
situation.

Self Assessment Questions


Multiple Choice Questions
6. Visual Basic was initially introduced in ..
(a) 1990

(b) 2005

(c) 1991

(d) 1980

7. Select is a
(a) condition

(b) loop

(c) data type

(d) statement

8. Visual Basic is a high level programming language which was evolved from the earlier
DOS version called .
(a) BASIC

(b) FORTRAN

(c) Digital operating system

(d) Perl

9. Visual Basic is a driven Programming Language.


(a) class and event

(b) Visual and events

(c) Visual and class

(d) only event

10. A majority of applications can be constructed using a minimal set of objects provided by
the standard object

32

(a) OS

(b) Toolbox

(c) system

(d) .Net framework

LOVELY PROFESSIONAL UNIVERSITY

Unit 1: Introduction to Visual Basic

11. Programming object mimics the behavior of a real-world .


(a) system

(b) example

(c) class

(d) object

Notes

12. A Class defines the abstract characteristics of a .


(a) class

(b) object

(c) framework

(d) None of these.

True or False
13. The programmer can place various objects.
(a) True

(b) False

14. Arrays can be multidimensional. Commas separate the dimensions of the array when
used in declarations and when accessing elements.
(a) True

(b) False

15. Information hiding is the concept of polymorphism only essential information and hiding
the inner logic.
(a) True

(b) False

1.8 Summary

The .NET Framework is a collection of services and classes.

Assembly represents the unit of deployment, version control, reuse, and security.

Interfaces in VB.NET are like the interfaces in previous versions of VB.

A multitude of enhancements to the code editor, including enhanced IntelliSense, smart


listing of code for greater readability and a background compiler for real-time notification
of syntax errors transforms into a rapid application development (RAD) coding machine.

XML Web services enable we to call components running on any platform using open
Internet protocols.

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.

Visual Basic .NET source code is saved in files with a .vb extension.

Literals of type String consist of characters enclosed within quotation-mark characters.


Literals of type Date are formed by enclosing a date/time string within number-sign
characters.

Collection is any type that exposes the ICollection interface (defined in the System.
Collections namespace).

1.9 Keywords
Class: It defines the abstract characteristics of a object, including the things characteristics (its
attributes, fields or properties) and the objects behaviors (the things it can do, or methods,
operations or features).
Information Hiding: This is the concept of exposing only essential information and hiding the
inner logic.
Inheritance: It helps us create new objects from existing objects for example we can inherit one
form from another form.

LOVELY PROFESSIONAL UNIVERSITY

33

Modern Programming Tools & Techniques-III

Notes

Keywords: These are words with special meaning in a programming language.


New Web Server Paradigm: It support high-capacity web sites, Microsoft has replaced its Active
Server Pages (ASP) technology with ASP.NET.
Polymorphism: This is where multiple procedures of the same name perform different tasks;
Polymorphism is the process of using an function or a procedure in different ways for different
set of inputs given.
Source Files are Plain: These are the text files that can be created and edited with any text
editor, including our old friend, Notepad. Source code can be broken into as many or as few
files as desired.
Visual Basic .NET runtime: It provides a type called Collection (defined in the Microsoft.
VisualBasic namespace) that mimics the behavior of Visual Basic 6 collections and exposes the
ICollection interface.
Visual Basic: This is a high level programming language which was evolved from the earlier
DOS version called BASIC.
1. Write you first VB program.
2. Write a program using literal.

1.10 Review Questions


1. Describe the process of visual program design and development.
2. Explain the term object-oriented programming.
3. Explain the concepts of classes, objects, properties, methods, and events.
4. Identify the elements in the Visual Studio environment.
5. Identify syntax errors, run-time errors, and logic errors.
6. Use AutoCorrect to correct syntax errors.
7. Write short notes on

Event Driven

Programs and Subprograms

8. Explain the element of Visual Basic


9. Explain the benefits of standard visual basic toolbox

10. Describe the Common Language Runtime in brief.

Answers for Self Assessment Questions


1. (a)

2. (c)

3. (d)

4. (a)

5. (c)

6. (c)

7. (d)

8. (a)

9. (b)

10. (b)

11. (d)

12. (b)

13. (a)

14. (a)

15.

(b)

1.11 Further Reading


A Programmers Introduction to Visual Basic.Net, by Craig Utley.

http://media.visual-paradigm.com/media/documents/dbva40npg/pdf/
dbva_dotnet_programmer_guide

34

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

Unit 2: Variables and Data Types

Notes

CONTENTS
Objectives
Introduction
2.1 Variables

2.1.1

Variable Scope and Lifetime

2.1.2

Variables of Built-In Objects

2.2 Operators

2.2.1

Mathematical Expressions

2.2.2

Event-Driven Programming

2.2.3

The Relational Operators

2.3

Data Types

2.3.1

Comments on Data Types

2.4 Summary
2.5 Keywords
2.6

Review Questions

2.7

Further Reading

Objectives
After studying this unit, you will be able to:

Explain the data types

Describe the operators

Discuss the variables

Introduction
Although you can create a complete database without writing code, in some cases, some tasks
cannot be performed automatically. For these tasks, you must temporarily use values that you
can change at will and dismiss when not needed anymore.
A variable is a value that you put into the computer memory when necessary. The value
is lost when the application closes. To proceed, you must communicate to the computer that
you will need a portion of its memory to hold a certain value. When you communicate this,
the computer reserves the necessary portion for you and makes it available when you need it.
Communicating your intention is also referred to as declaring a variable. Because there can be
various values used while the application is running, the computer would need two pieces of
information to hold a value: a name that can be used to identify the portion of memory and the
amount of memory that will be necessary to store the value.
You often need to store values temporarily when performing calculations with Visual Basic.
For example, you might want to calculate several values, compare them, and perform different
operations on them, depending on the result of the comparison. You need to retain the values
if you want to compare them, but you do not need to store them in a property.

LOVELY PROFESSIONAL UNIVERSITY

35

Modern Programming Tools & Techniques-III

Notes

Visual Basic, like most programming languages, uses variables for storing values. Variables
have a name (the word you use to refer to the value the variable contains) and a data type
(which determines the kind of data the variable can store). Arrays can be used to store indexed
collections of related variables.
Constants also store values, but as the name implies, those values remain constant throughout
the execution of an application. Using constants can make your code more readable by providing
meaningful names instead of numbers. There are a number of built-in constants in Visual Basic,
but you can also create your own.
Data types control the internal storage of data in Visual Basic. By default, Visual Basic uses the
Variant data type. There are a number of other available data types that allow you to optimize
your code for speed and size when you do not need the flexibility that Variant provides.

2.1 Variables
A variable is temporary storage space for numbers, text, and objects. Variables are constantly
being created and destroyed and will not hold any values after your program have ended. If
you wish to save the values of variables or other data then before allocating storage space for
a variable you need to decide what the variables lifetime will be, or in other words, which
procedures and which modules should have access to the variables value.

Procedure-level variables are created with a Dim statement placed right in the procedure
where it is going to be used. The value of a procedure level variable cannot be accessed
outside it is procedure. When the procedure finishes (End Sub or End Function), the
variable is destroyed and memory allocated to the variable is released.

Module-level variables are created with a Private statement in the general declarations
section of a Form or code module. The value of the module level variable is available to
every procedure in that module. Memory allocated to the module-level variable is not
destroyed until the module is Unloaded.

Global variables are created with a Public statement in the general declarations section
of a Form or code module. The value of a Global variable is available to any procedure,
in any Form or code module. Memory allocated to a Global variable is not released until
your program shuts down.

It would certainly be easier to make every variable Global. You would not have to think twice
about it is availability at any given time. But sometimes, every byte of memory counts, so do
not give your variables any more life than they actually require.
Having discussed the procedure declaration statement we now need to discuss the statements
contained within the procedure. We deal first with variable, constants and data type.
As with procedures we need to define the scope of the data. We can also specify the length of time
to keep data in a variable or constant its lifetime. This can prevent unexpected re-initialization
of variables and allow retention of a variables value between calls to a procedure. We can also
specify the amount of memory allocated to the data. Keeping this to the minimum for the task
obviously uses less memory but also makes the macros run faster.
Variables are named areas in memory in which you store data while the workbook containing
the code is open. The rules for naming variables are the same as those for naming procedures.
To minimize the time you spend understanding and debugging code use

36

Each variable for one purpose only,

Names that indicate what the variable represent in the problem.

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

By default VB allows you to create variables simply by using them in your code. (Other languages,
e.g. C require you to explicitly declare variables before using them). Hence the statement

Notes

tempVal = Worksheets(1).Range(A1).Value
Assigns the value in Cell A1 to the variable tempVal. This is an implicit variable declaration.
Used in this way VB creates a variable of Variant data type (see later for the types). [Variant
data types can contain any data, including strings, numbers, dates and objects].
Although it is convenient to let VB create variables whenever you need them it is a DANGEROUS
practice and is to be discouraged. It can lead to subtle errors which are hard to track down.
For example
tempVal = Worksheets(1).Range(A1).Value
Worksheets(1).Range(A1).Value = _
Worksheets(1).Range(A2).Value
Worksheets(1).Range(A2).Value = temVal
Was written with the intention that it swops the contents of cells A1 and A2 but it does not.
After it is run cell A1 contains the value previously in cell A2, and cell A2 is empty! Do you
see the error?
Explicit declaration of variables is a safer technique and makes the code more reliable. To explicitly
declare a variable use the Dim, Private, Public, or Static keyword to specify the variables scope,
lifetime and data type.
Explicit variable declaration helps prevent you from inadvertently

Creating a new variable by misspelling an existing one,

Re-using an existing one with a different meaning in the problem, when a new one should
be created, so overwriting the value stored in it.

It also speeds execution of the code as VB does not have to determine the data type of each
variable while the code is running.
The simplest form of explicit variable declaration creates a new variable of Variant type with
procedure-level scope, the value in the variable only being preserved while the procedure is
running, e.g.
Sub AreaOfCircle()
Dim radius, area
Radius = InputBox(Circle radius is)
Area = 3.14159 * radius ^ 2
MsgBox the area of the circle is & area
End Sub
You can specify that VB generates an error message whenever it finds a name used as a variable
that has not previously been declared explicitly as a variable. At the top of the module put Option
Explicit. This forces variables to be declared before they are used. It is recommended that you
use the Option Explicit statement in all your modules.

2.1.1 Variable Scope and Lifetime


A variable is more than just a simple data repository. Every variable is a dynamic part of the
application and can be used at different times during the programs execution. The declaration
of a variable establishes more than just the name and data type of the variable. Depending on
the keyword used to declare the variable and the placement of the variables declaration in

LOVELY PROFESSIONAL UNIVERSITY

37

Modern Programming Tools & Techniques-III

Notes

the programs code, the variable might be visible to large portions of the applications code.
Alternatively, a different placement might severely limit where the variable can be referenced
in the procedures within the application.
The visibility of a variable or procedure is called its scope. A variable that can be seen and used
by any procedure in the application is said to have public scope. Another variable, one that is
usable by a single procedure, is said to have scope that is private to that procedure. There are
many analogies for public and private scope. Variables declared within a procedure are local
to that procedure and cannot be used or referenced outside that procedure.
In each case, the Dim keyword was used to define the variable. Dim is shorthand for dimension
and is a rather archaic expression that instructs Visual Basic to allocate enough memory to
contain the variable that follows the Dim keyword. Therefore, Dim i As Integer allocates less
memory (2 bytes) than Dim s As Double (8 bytes). There is no way to make a variable declared
within a procedure visible outside of that procedure.
The public keyword is used to make a variable visible throughout an application. Public can
be used only at the module level and cannot be used within a procedure. Usually, the Public
keyword is used only in standard modules that are not part of a form. Every variable declared
in the general section of the standard module is public throughout the application unless the
Private keyword is used. Private restricts the visibility of a variable to the module in which the
variable is declared.
When you declare a variable in a procedure, only code within that procedure can access or
change the value of the variable. The scope is local to the procedure. Sometimes you need a
variable available to all procedures within the same module or even to all modules in the same
workbook. The scope attached to variable declaration is
Declaration

Scope

Dim or Static within a procedure

Procedure only

Dim or Private at top of module

Private, available to all procedures in module

Public at top of module

Public, available to all procedures in all module


in workbook

It is a good idea to use the narrowest scope for your variables as it helps reduce errors. A variables
lifetime is the time for which VB preserves the value in the variable. The values in private and
public variables are preserved while the workbook is open. However if you edit a module all
modules in a workbook are recompiled and all variables are reset to their initial values. Although
variables declared by Dim or Static have the same scope they have different lifetimes. Variables
declared with Static exit the whole time the workbook is open and their values are retained
between calls to the procedure. Variables declared by Dim exist ONLY while the procedure is
running and their values are not preserved nor are the memory allocated to them. The next
time the procedure is run the local variables are re-initialized. Thus to preserve the value of
a local variable you must declare it with the Static keyword. Consider the following example:
Function RunningTotal(num)
Static accumulation
accumulation = accumulation + num
RunningTotal = accumulation
End Function
If accumulation were declared with Dim the previous value would not be preserved and the
function would simply return the value with which it was called! Private variable are available
38

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

to all procedures in a module where they are declared. Public variables are available to every
procedure in any module in the workbook where they are declared. A public variable retains
its value from the time a value is assigned to it until the workbook is closed (or a procedure
is edited).

Notes

A program can have as many variables as you need it to have. Before you can use a variable,
you must create the variable by defining the variable first. When you define a variable, you tell
Visual Basic these two things:

The name of the variable

The data type of the variable

Once you define a variable, that variable always retains its original data type. The Dim statement
defines variables. Using Dim, you tell Visual Basic

That you need a variable

Reminder division is Reminder division is what to name the variable

What kind of variable you want

Dimshort for dimensionis a Visual Basic statement that you write in an applications Code
window. Dim reserves the space for the variable.
We are now ready to attach code to our application. As objects are added to the form, Visual
Basic automatically builds a framework of all event procedures. We simply add code to the
event procedures we want our application to respond to. But before we do this, we need to
discuss variables.
Variables are used by Visual Basic to hold information needed by your application. Rules used
in naming variables:

No more than 40 characters

They may include letters, numbers, and underscore (_)

The first character must be a letter

You cannot use a reserved word (word needed by Visual Basic)

Variables can be defined in two ways:


1.
Dim VarName (In this declaration variable can hold data of any size or format.)

Or

2.
Dim VarName AS DataType
VarName is a name that you supply. When Visual Basic executes the Dim statement at runtime,
it creates a variable in memory and assigns it the name you give in the VarName location of
the statement.
Dim A As Integer
Dim B As Double
Dim C As date
Dim D As String
Dim E As boolean
Reducing Dim with Variable Suffix Characters: There is a set of suffix characters for variable
names that you can use to specify a variables data type without having to define the variable

LOVELY PROFESSIONAL UNIVERSITY

39

Modern Programming Tools & Techniques-III

Notes

first. Here listed the suffix characters for constant values. Variables use the more complete
version shown here:
Suffix

Data Type

Example

Integer

Age%

&

Long

Amount&

Single

Distance!

Double

KelvinTemp#

Currency

Pay@

String

LastName$

The statement Option Explicit cannot appear in the (general) section of the Code window because
the suffix characters are not enough to define variables.

2.1.2 Variables of Built-In Objects


We know that how to declare a variable from a built-in data type. Besides these types, Microsoft
Access and Microsoft Visual Basic ship with various objects and classes. Sometimes you will
need to refer to such objects in your code. In most cases, you will need to first declare a variable
of the desired type before using it.
To declare a variable of an object, you should first make sure you know the
type of object you want.
Variable of Type Object
Every object you will use in your application is primarily of type Object. In many cases, you
will be able to directly use the object in your application. In some other cases, you will first need
to declare the variable and initialize it before using it. Also, in many cases, you can declare a
variable and specify its particular type. In some cases, you may not know or may not need to
specify the particular type of the object you want to use. In this case, when declaring the variable,
you can specify its type as Object. When using the Object type to declare a variable, the variable
should be one of the existing VBA types of object and not one of the basic data types we saw
earlier. This would be done as follows:
Dim objVariable As Object
After this declaration, you should then initialize the variable and specify the actual type it would
be. To initialize a variable declared as a VBA object, use the Set operator.
We mentioned that the IntelliSense does not work on all objects. The Object object do not use
the IntelliSense.
The variable should be one of the existing VBA types of object and not one
of the basic data types we saw earlier.
The Application Object
A Microsoft Access database is an object of type Application. In your code, to declare a variable
of this type, you can type:
Dim app As Application
If you want to refer to such an object outside of Microsoft Access, you must qualify it with the
Access object. For example, from an application such as Microsoft Word, to declare a variable
that refers to a Microsoft Access database, the above declaration would be made as:
Dim app As Access.Application
Even in Microsoft Access, you can still use Access.Application.

40

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

Notes

The Database Object


To support databases, Microsoft Access provides a data type named Database. This data type
allows you to get a reference to the database you are using. To get a reference to a database,
declare a variable of this type. Here is an example:
Dim curDatabase As Database
Every object you will use in your application is primarily of type Object.

Self Assessment Questions


Multiple Choice Questions
1. Visual Basic supports the use of .......... operators that produce true or false results based
on data values.
(a) five

(b) six

(c) seven

(d) eight

2. Every variable is a dynamic part of the application and can be used at .. during
the programs execution.
(a) one time

(b) same time

(c) more time

(d) different time

3. A is temporary storage space for numbers, text, and objects.


(a) program

(b) language

(c) variable

(d) application

True or False
4. A variable is a value that you put into the computer memory when necessary.
(a) True

(b) False

5. There is a set of suffix characters for variable names that you can use to specify a variables
data type without having to define the variable first.

(a) True

(b) False

2.2 Operators
These are many operators in the language:

2.2.1 Mathematical Expressions


Data values and controls are not the only kinds of assignments that you can make. With the
Visual Basic math operators, you can calculate and assign expression results to variables when
you code assignment statements that contain expressions. It is easy to make Visual Basic do
your math. Table describes Visual Basics primary math operators. There are other operators, but
the ones in Table will suffice for most of the programs that you write. Look over the operators.
You are already familiar with most of them because they look and act just like their real-world
counterparts.

LOVELY PROFESSIONAL UNIVERSITY

41

Modern Programming Tools & Techniques-III

Notes

The primary mathematical operators:


Operator

Example

Description

Net + Disc

Adds two values

Price 4.00

Subtracts one value from another

Total * Fact

Multiplies two values

Tax / Adjust

Divides one value by another ****

Adjust ^ 3

Raises a value to a power

& or +

Name1 & Name2

Concatenates two strings

Operator Precedence
The order in which mathematical operators used when formula is solved.
Operators

Order of Precedence

()

Values within parentheses are always evaluated first.

Exponentiation (raising a number to a power) is second.

Negation (creating a negative number) is third.

*/

Multiplication and division is forth.

Integer division is fifth.

Mod

Reminder division is Sixth.

Addition and subtraction are last.

2.2.2 Event-Driven Programming


Text1

Change

Private Sub Text1_Change()


End Sub

Change
Click
DblClick
DragDrop
DragOver
GotFocus
KeyDown
KeyPress
KeyUp
LinkClose
LinkError
LinkNotifiy

Each object in visual basic has a predefined set of events it can respond to. These events are
listed for each object in the procedure drop-down list box in the code window. You can write
an event procedure for any of these events, and if that event occurs in the program, Visual Basic
will execute the event procedure that is associated with it. Partial listing of the events for Text
box object is shown below:
Events Common to Many Controls
Event

Occurs When

Change

The user modifies the text box or combo box.

Click

The user clicks and object with the primary mouse button
(usually the left button).

Dbclick

The user double-clicks an object with the primary mouse button.

DragDrop

The user drage a control to another location.


Contd...

42

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

DragOver

An object is dragged over a control.

GotFocus

An object receives the focus.

KeyDown

A key is pressed while and object has the focus.

KeyPress

A key is pressed and released while an object has the focus.

KeyUp

A key is released while an object has the focus.

LostFocus

The focus has left an object.

MouseDown

A mouse button is pressed while the mouse pointer is over an object.

MouseMove

The mouse cursor is moved over an object.

MouseUp

A mouse button is released while the mouse pointer is over an object.

Notes

2.2.3 The Relational Operators


Visual Basic supports the use of six operators that produce true or false results based on data
values. You can combine them operators with the If statement to add power to your programs.
You use the relational operators to compare data values. They are easy to use. If you take any
two numbers, one number is always being greater than, equal to, or less than the other.
Operator

Usage

Description

>

Sale > Goal

The greater than operator. Returns true if the value on the


left side of > is numerically or alphabetically greater than
the value on the right. Otherwise, false.

<

Pay < 2000.00

The less than operator. Returns true if the value on the left
side of < is numerically or alphabetically less than the value
on the right. Otherwise, false.

Age = Limit

The equal to operator (sometimes called the equal operator).


Returns true if the values on both sides of = are equal to
each other. Otherwise, false.

>=

FirstName >=
Mike

The greater than or equal to operator. Returns true if the


value on the left side of >= is numerically or alphabetically
greater than or equal to the value on the right. Otherwise,
false.

<=

Num <=
lblAmt Cap ion

The less than or equal to operator. Returns true if the value


on the left side of <= is numerically or alphabetically less
than or equal to the value on the right. Otherwise, false.

<>

txtAns.Text <>
Yes

The not equal to operator. Returns true if the value on the


left side of <> is numerically or alphabetically unequal to
the value on the right. Otherwise, false.

Logical Operators
Three additional operators, AND, OR, and NOT, look more like commands than operators. AND,
OR, and NOT are called logical operators. They enable you to combine two or more relational
tests. Table describes the logical operators.

Operator

Usage

Description

And

If (A > B) AD)

Returns true if both sides of the And are true. Therefore, A


must be than B and C must be less than D. Otherwise, the
expression return result.

Or

If (A > B) OD)

Returns true if either side of the Or is true. Therefore, A


must be grater than B or C must be less than D. If both sides
of the Or are false, the expression returns a false result.

Not

If Not (Ans =

Produces, the opposite true or false result. Therefore, if Ans


holds **** the Not turns the true result to false.

LOVELY PROFESSIONAL UNIVERSITY

43

Modern Programming Tools & Techniques-III

Notes

Visual Basic supports the use of six operators that produce true or false results
based on data values.

Write a program to show the use of logical operators.

2.3 Data Types


Each type takes up a certain amount of memory, allows a specific range of values and is best
suited for particular kinds of data.
A data type tells the computer the kind of value you are going to use. There are different kinds
of values for various purposes. Before assigning a data type to a variable, you should know how
much space a data type will occupy in memory. Different variables or different data types use
different amounts of space in memory. The amount of space used by a data type is measured
in bytes.
To specify the data type that will be used for a variable, after typing Dim followed by the name
of the variable, type the As keyword, followed by one of the data types we will review next.
The formula used is:
Dim VariableName As DataType
This technique allows you to declare one variable on its line. In many assignments, you will
need to declare more than one variable. To do this, you have two alternatives. You can declare
each variable on its own line. This would be done as follows:
Dim Variable1 As DataType1
Dim Variable2 As DataType2
Dim Variable3 As DataType3
You can also declare more than one variable on the same line. To do this, use only one Dim
keyword but separate each combination of a name and data type with a comma. This would
be done as follows:
Dim Variable1 As DataType1, Variable2 As DataType2
Dim Variable3 As DataType3
Microsoft Visual Basic also provides special characters for some data types so that, instead of
specifying a data type, you can use that character. We will indicate what character for what type.
Type name

Storage size

Range

Integer

2 bytes

32,768 to 32,767

Long

4 bytes

2,147,483,648 to 2,147,483,647

Single

4 bytes

3.402823E38 to 1.401298E45 (negative)


1.4012298E45 to 3.402823E38 (positive)

Double

8 bytes

1.79769313486232E308 to
4.94065645841247E324 (negative)
4.94065645841247E324 to
1.7976931486232E308 (positive)

Currency

8 bytes

9223372033685477.5808 to
922337203685477.5807
Contd...

44

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

String

1 byte per character

0 to approx 65,500 characters

Boolean

2 bytes

True or False

Date

8 bytes

January 1, 100 to December 31, 9999

Object

4 bytes

Any Object reference

Variant

16 bytes + 1 byte for


each character

Null, Error, any numeric value valid for any numeric


data type, any text, object or array

Notes

Decimal numbers can be expressed in their usual form, 3.14159 or as mmmEeee (or mmmDeee)
where mmm is the mantissa and eee is the exponent, e.g. 3.4024E-34 with mmm = 3.4024 and eee = 34.

2.3.1 Comments on Data Types


Integer
If a variable will always contain integer numbers declare it as Integer or Long. If it may contain
fractional numbers declare it as Single, Double or Currency. Beware. A variable (or constant) of
any numerical type can contain any numerical data. Hence assigning a value of 3.7 to a variable
of Integer data type does NOT produce a computing error (even though 3.7 is not an integer)
but will produce a mathematical error as VB rounds off (it does NOT truncate) the fractional
part before assigning it to the Integer. Thus the value becomes 4 in this example.
A variable of the numeric data types is initialized to zero (0) after It is declared and before you
assign a value to it.
An integer is a natural number. To declare a variable that would hold a number that ranges
from 32768 to 32767, use the Integer data type. The integer type should always be used when
counting things such as books in a library or students in a school; in this case you would not
use decimal values. Here is an example of declaring an integer variable:
Private Sub Form_Load()
Dim Tracks As Integer
End Sub
When declaring an integer variable, you can omit the As Integer expression and terminate the
name of the variable with %. Here is an example:
Private Sub Form_Load()
Dim Tracks%
End Sub
If you have a value that needs to be converted into a natural number, you can call CInt() using
the following formula:
Number = CInt(Value to Convert)
Between the parentheses of CInt(), enter the value, text, or expression that needs to be converted.
Byte
If you are planning to use a numeric value in your program, you have a choice from different
kinds of numbers that Microsoft Access and Microsoft Visual Basic can recognize. You can use
the Byte data type for a variable that would hold a natural number that ranges from 0 to 255.
You can declare it as follows:
Private Sub Form_Load()
Dim StudentAge As Byte
End Sub

LOVELY PROFESSIONAL UNIVERSITY

45

Modern Programming Tools & Techniques-III

Notes

If the user enters a certain value in a control and you want to convert it to a small number, you
can use CByte(). The formula to use would be:
Number = CByte(Value to Convert to Byte)
When using CByte(), passing that value between the parentheses.
String
This data type will always contain a character string and not a numeric value. It is initial value
is (the empty string). When assigning a value use double quotation marks e.g.
dataName = Giuseppe Verdi
dataName = Left(dataName, 8) gives Guiseppe
A string is a character or a combination of characters that constitutes text of any kind and almost
any length. To declare a string variable, fuse the String data type. Here is an example:
Private Sub Form_Load()
Dim CountryName As String
End Sub
You can omit the As String expression. Instead, to indicate that you are declaring a String
variable, you can end its name with the $ symbol. Here is an example:
Private Sub Form_Load()
Dim CountryName$
End Sub
If you have a value that is not primarily text and you want to convert it to a string, use CStr()
with the following syntax:
CStr(Value To Convert to String)
In the parentheses of the CStr(), enter the value that you want to convert to string.
Long
A long integer is a number that can be used for a variable involving greater numbers than
integers. To declare a variable that would hold such a large number, use the Long data type.
Here is an example:
Private Sub Form_Load()
Dim Population As Long
End Sub
Alternatively, you can omit the As Long expression and end the variable name with the @ symbol
to indicate that you are declaring a Long integer variable. Here is an example:
Private Sub Form_Load()
Dim Population@
End Sub
To convert a value to a long integer, call CLng() using the following formula:
Number = CLng(Value to Convert)
To convert a value to long, enter it in the parentheses of CLng().
Single
In computer programming, a decimal number is one that represents a fraction. Examples are
1.85 or 426.88. If you plan to use a variable that would that type of number but precision is not

46

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

your main concern, declare it using the Single data type. Here is an example:

Notes

Private Sub Form_Load()


Dim Distance As Single
End Sub
If you want, you can omit the As Single expression in the declaration. Instead, you can type !
at the end the name of the variable to still indicate that you are declaring a Single variable.
Here is an example:
Private Sub Form_Load()
Dim Distance!
End Sub
If you have a value that needs to be converted, use CSng() with the following formula:
Number = CSng(Value to Convert)
Double
If you want to use a decimal number that requires a good deal of precision, declare a variable
using the Double data type. Here is an example of declaring a Double variable:
Private Sub Form_Load()
Dim Distance As Double
End Sub
Instead of the AS Double expression, you can omit it and end the name of the variable with the
# character to indicate that you are declaring a Double variable. Here is an example:
Private Sub Form_Load()
Dim Distance#
End Sub
To convert a value to double-precision, use CDbl() with the following formula:
Number = CDbl(Value to Convert)
In the parentheses of CDbl(), enter the value that needs to be converted.
Boolean Data Type
These contain a logical value i.e. True or False. The initial value is False.
A variable is considered Boolean if it can hold only one of two values, either true or false, 0
or no 0, Yes or No. To declare such a variable, use the Boolean keyword. Here is an example:
Private Sub Form_Load()
Dim IsMarried As Boolean
End Sub
To actually use a Boolean variable, you can assign a value to it. To initialize a Boolean variable,
assign it a True or a False value. By default, if you declare a Boolean variable but do not initialized
it, it receives a value of False. A Boolean variable can also deal with numeric values. The False
value is equivalent to 0. For example, instead of False, you can initialize a Boolean variable with
0. Any other numeric value, whether positive or negative, corresponds to True:
Private Sub cmdBooleanVariable_Click()
Dim isBoolean As Boolean
isBoolean = -792730
End Sub

LOVELY PROFESSIONAL UNIVERSITY

47

Modern Programming Tools & Techniques-III

Notes

The number can be decimal or hexadecimal:


Sub cmdBooleanVariable_Click()
Dim EmployeeIsMarried As Boolean
EmployeeIsMarried = &HFA26B5
End Sub
After declaring the variable and when using it, you can specify its value as True or as False. To
convert a value or an expression to Boolean, you can call the CBool() function.
As mentioned already, value is referred to as Boolean if it can be either true or false. As you
may imagine, the essence of a Boolean value is to check that a condition is true or false, valid or
invalid. In your code, you can stored a Boolean value in a variable. To declare such a variable,
use the Boolean keyword. Here is an example:
Sub cmdBooleanVariable_Click()
Dim EmployeeIsMarried As Boolean
End Sub
Date
These contain date and time values, e.g. someDate = #3-6-99 13:21#. The initial value is 12:00:00
on December 30, 1899.
In Visual Basic, a Date data type is used to specify a date or time value. Therefore, to declare
either a date or a time variables, use the Date data type. Here are two examples:
Private Sub Form_Load()
Dim DateOfBirth As Date
Dim KickOffTime As Date
End Sub
If you have a string or an expression that is supposed to hold a date or a time value, to convert
it, use CDate() based on the following formula:
Result = CDate(Value to Convert)
In the parentheses of CDate(), enter the value that needs to be converted.
Object
These contain a reference to an object within Excel. You assign an object variable with the Set
statement, e.g.
Dim wks As Object
Set wks = Worksheets(1)
Object variables are initialized to the value Nothing.
Variant
This type allows the variable to hold most types of data. The initial value is Empty. VB
automatically performs the conversions e.g.
Private varValue Variant type by default
varValue = 17 contains two character string 17
varValue = varValue 9 now contains numeric value 8
varValue = VP & varValue now contains the three
characters VP8

48

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

A Variant can be used to declare any kind of variable. You can use a variant when you cannot
make up your mind regarding a variable but, as a beginning programmer, you should avoid it.

Notes

Here is a table of various data types and the amount of memory space each one uses:
Data Type

Description

Range

1-byte binary data

0 to 255

Integer

2-byte integer

32,768 to 32,767

Long

4-byte integer

2,147,483,648 to 2,147,483,647

4-byte floating-point
number

3.402823e+38to
1.401298e45(negative values)

Byte

Single
1.401298e45to
3.402823e+38(positive values)

Double

8-byte floating-point
number

1.79769313486231e+308to
4.94065645841247e324
(negative values)
4.94065645841247e324to
1.79769313486231e+308(positive values)

Currency

8-byte number with


fixed decimal point

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

String

String of characters

Zero to approximately two billion


characters

8-byte date/time
value

January 1, 100 to December 31, 9999

Date

When naming your variables, besides the rules reviewed previously, you can start a variables
name with a one to three letters prefix that could identify the data type used.
Constants
You may need to use quantities that have constant values (e.g. p). A constant is a name that
takes the place of the number or string that does not change. It is like a variable but you cannot
modify it. There are two types of constants
1. Built-in (or intrinsic) provided by the application. All Excel built-in constants start with
xl in the name.

2. Symbolic or user-defined.

You declare a constant using the Const keyword. You can specify its scope (private by default,
or public), e.g.
Const constPi = 3.14159
Const constCodeName As String = Enigma
Const constTwoPi = constPi * 2

Search more about the data types.

LOVELY PROFESSIONAL UNIVERSITY

49

Modern Programming Tools & Techniques-III

Notes

Successful Migration of ERP-System


with 650,000 Lines of Code from VB6 to .NET
Client Challenge

n Austrian manufacturing company with worldwide market presence relies on a


highly optimized, in-house developed ERP-system based on Microsoft Basic Version
6 (VB6), consisting of 33 applications, covering almost all business processes.

Since April 2008 applications developed with the VB6 Integrated Development Environment
(IDE) are no longer supported by Microsoft. In addition the, the VB6.0 runtime will not be
guaranteed after 2011. Therefore the following options were considered:

Re-write the system manually in Visual Basic .NET.

Migrate the systems to .NET and improve the quality through refactoring.

Find a package to replace the systems and undertake the required systems integration.
The results of an extensive technical and commercial evaluation by SIS Datenverarbeitung
GmbH showed a .NET migration to be the superior choice for the following reasons:

Protection of extensive investment in highly optimized systems.

Functional equivalence (1:1) of migrated applications.

Short timeframe: full port within 12 months or less.

Reduced risks and costs of migration vs. other options.


The Chosen Approach
To facilitate a migration automated to the greatest possible extent SIS conducted an inventory
of the existing code-base, identifying critical and difficult functions.
During the software evaluation phase SIS run a 25K prototype through all the conversion
programs. It took 2.5 hours to get a compile-able and run-able VB.NET project with VB
Migration Partner, and 13 hours with its closest competitor. The reduced effort, the ability
to use programs and support for the convert-test-fix were the main reasons for choosing
Code Architects software.
After successful migration of the prototype the actual migration was performed as follows:

Assurance of functional equivalence through detailed inventory of existing functions.

Detailed migration-plan: tasks, restrictions, risk-analysis.

Validation of tools, processes, results and cost.

Migration infrastructure with multiple code-path: reference-, development-, test- and


production-system.

Configuration Management tool to track status of code.

Extensive checklists for manual optimization during migration.

Knowledge-base for future maintenance-guidelines.

5-step quality assurance:

o 100%-code-Review, checks and refactoring of migrated code.


Contd...

50

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

Notes

o Unit-tests.

o Function- and performance-tests.

o Integration and trial-runs.

o Performance profiling to validate performance after migration.


Benefits
The selected conversion software allowed to successfully migrating 650,000 lines of code
within 6 months with a total effort of 18 man-months, excluding code review and refactoring.
Another set of 300,000 lines of code will be migrated within three months.
Since the core applications of the ERP-System are mission critical to the clients operation,
highest priority was assigned to achieve functional equivalence of the migrated systems: all
functional changes were avoided to ensure that the old and new systems function identically.
VB Migration Partners support library ensured that all VB-related methods and controls
work identically in the converted VB.NET application, whereas its code generation engine
prevented subtle behavioral differences from being accidentally introduced.
Changes to look and feel and data-structures were also avoided to minimize education
and training of users (approximately 350). Improved performance and software-quality was
achieved through extensive refactoring.
Quote From the Customer
VB Migration Partner from Code Architects delivered fewer compilation and runtime errors
than all its competitors. Its migration programs and the convert-test-fix methodology proved
to be powerful and flexible enough to handle a large VB6 application (650K lines of code)
with ease, the documentation is excellent, and Code Architects tech support has always
been very responsive.
Questions

1. What is Integrated Development Environment (IDE)?

2. Explain the Enterprise Resource Planning (ERP).

Self Assessment Questions


Multiple choice questions
6. Variant can be used to declare any kind of ...
(a) data type

(b) variable

(c) constant

(d) constraints

7. The internal storage of data in Visual Basic by default, Visual Basic uses the .
data type.
(a) variant

(b) double

(c) string

(d) long

8. Microsoft Access provides a data type named .


(a) variant

(b) double

(c) string

(d) database

LOVELY PROFESSIONAL UNIVERSITY

51

Modern Programming Tools & Techniques-III

Notes

9. Database data type allows you to get a to the database you are using.

(a) tool

(b) .dll file

(c) reference

(d) variable

10. Communicating your intention is also referred to as declaring a .


(a) variable

(b) database

(c) class

(d) object

11. Variables are used by Visual Basic to hold information needed by your ..
(a) program

(b) server

(c) system

(d) application

12. In computer programming, a decimal number is one that represents a .


(a) zero and fraction

(b) integer

(c) fraction

(d) decimal

13. If you want to use a decimal number that requires a good deal of precision, declare a
variable using the data type.
(a) double

(b) long

(c) string

(d) integer

True or False
14. The computer would need two pieces of information to hold a value.
(a) True

(b) False

15. Every object you will use in your application is primarily of type class.
(a) True

(b) False

2.4 Summary

52

A variable is a value that you put into the computer memory when necessary.

Visual Basic, like most programming languages, uses variables for storing values.

When you declare a variable in a procedure, only code within that procedure can access
or change the value of the variable.

A Microsoft Access database is an object of type Application.

Data values and controls are not the only kinds of assignments that you can make.

Each object in visual basic has a predefined set of events it can respond.

A data type tells the computer the kind of value you are going to use.

You can also declare more than one variable on the same line.

Microsoft Visual Basic also provides special characters for some data types.

A variable will always contain integer numbers declare it as Integer or Long.

LOVELY PROFESSIONAL UNIVERSITY

Unit 2: Variables and Data Types

2.5 Keywords

Notes

Constants: It stores values, but as the name implies, those values remain constant throughout
the execution of an application.
Data Types Control: The internal storage of data in Visual Basic by default, Visual Basic uses
the Variant data type.
Data Values and Controls: These are not the only kinds of assignments that you can make.
Decimal Numbers: It can be expressed in their usual form, 3.14159 or as mmmEeee (or mmmDeee)
where mmm is the mantissa and eee is the exponent, e.g. 3.4024E-34 with mmm = 3.4024 and eee = 34.
Dim-Short for Dimension: This is a Visual Basic statement that you write in an applications
Code window.
Explicit: This declaration of variables is a safer technique and makes the code more reliable.
String: This data type will always contain a character string and not a numeric value.
Variables Declared by Dim: It exist ONLY while the procedure is running and their values are
not preserved nor are the memory allocated to them.
Variables: These are named areas in memory in which you store data while the workbook
containing the code is open.
VB-Related Methods and Controls: It works identically in the converted VB.NET application,
whereas its code generation engine prevented subtle behavioral differences from being
accidentally introduced.
Visual Basic: It supports the use of six operators that produce true or false results based on
data values.
1. Write a program to conversion of data type.
2. Write a program to concatenate two strings.

2.6 Review Questions


1. What are objects?
2. What are the variables?

3. Define the data type.

4. What do you understand by constant?


5. Explain the operators.
6. Difference between data types and variable.
7. Explain the terms
(a) Double
(b) String
(c) Variant
(d) Byte
8. Describe the Boolean type data type.

LOVELY PROFESSIONAL UNIVERSITY

53

Modern Programming Tools & Techniques-III

Notes

9. Explain that, how to define a variable?

10. Define variables of built-in objects.

Answers for Self Assessment Questions


1 (a)

2 (b)

3 (d)

4 (a)

6. (b)

7. (a)

8. (d)

9.

11. (d)

12. (c)

13. (a)

(c)

14. (a)

5 (c)
10.

(a)

15.

(b)

2.7 Further Reading


The Complete Reference Books - VB.NET, by Jeffrey R. Shapiro

http://ftp.ku.ac.th/pub/manual/VB.NET%20-%20(OReilly)%20
Programming%20Visual%20Basic%20%20NET.

54

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

Unit 3: Decision Making and Looping

Notes

CONTENTS
Objectives
Introduction
3.1 Looping
3.2

The If Statement

3.3

If-Else Statement

3.4

While Statement

3.5

Do-While Statement

3.6

For Statement

3.7 Summary
3.8 Keywords
3.9

Review Questions

3.10 Further Readings

Objectives
After studying this unit, you will be able to:

Explain the decision making

Define conditional operators

Define looping

Discuss the different types of loops

Introduction
A loop executes statements repeatedly. It often has an upper and lower bound. Certain loops,
such as the For-loop, proceed through a range of values. A step indicates the progression. Other
loops, such as While, continue until a condition is met.
A loop is something that goes round and round and round. If someone told you to move your
finger around in a loop, you did know what to do immediately. In programming, loops go
round and round and round, too. In fact, they go round and round until you tell them to stop.
You can programme without using loops. But it is an awful lot easier with them.
All comparison operators produce true or false results. In other words, the comparison is either
true or the comparison is false. The mathematical operators produce numeric values, whereas
the comparison operators produce only true or false values. The rest of the program can use the
true or false comparison operator result to make decisions. Comparison operators are operators
that compare data values against each other and produce true or false results.
If a certain condition is true, you direct the program to take one course of action. If the condition
is false, you direct the program to do something else. Blocks of code for making decisions are
called Decision Structures.

LOVELY PROFESSIONAL UNIVERSITY

55

Modern Programming Tools & Techniques-III

Notes

Visual Basic lets you test conditions and perform different operations depending on the results
of that test. You can test for a condition being true or false, for various values of an expression,
or for various exceptions generated when you execute a series of statements.
The following Figure 3.1 shows a decision structure that tests for a condition being true and
takes different actions depending on whether it is true or false.
Taking different actions when a condition is true and when it is false.
Figure 3.1: Decision Structure
Previous code

Is the condition true?


Yes

No

Perform actions for


when condition is true

Perform actions for


when condition is false

Next code to run

3.1 Looping
A loop is something that goes round and round and round. If someone told you to move your
finger around in a loop, you would know what to do immediately. In programming, loops go
round and round and round, too. In fact, they go round and round until you tell them to stop.
You can programme without using loops. But it is a lot easier with them.
Consider this:
You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this
Dim answer As Integer
answer = 1 + 2 + 3 + 4
MsgBox answer
Fairly simple, you think. And not much code, either. But what if you wanted to add up a
thousand numbers? Are you really going to type them all out like that? It is a lot of typing. A
loop would make life a lot simpler.
A loop executes statements repeatedly. It often has an upper and lower bound. Certain loops,
such as the For-loop, proceed through a range of values. A step indicates the progression. Other
loops, such as While, continue until a condition is met.
Microsoft Visual Basic 2005 is an evolution of the Visual Basic language
that is engineered for productively building type-safe and object-oriented
applications.
Be aware while using comments in VB.NET. The VB.NET does not support
multiline comments like some other languages.

56

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

3.2 The If Statement

Notes

Perhaps the most important statement in a program is the If statement. If performs one of
two possible code actions, depending on the result of the comparison. In other words, If uses
comparison operator results to test data. If might execute one or more lines of subsequent code,
depending on the result of a comparison.
Before If, the code you wrote executed sequentially, one statement after another. If lets your
program be more decisive and execute only parts of the program if the data warrants partial
execution. For example, suppose you were writing an invoicing system. In such a system, no
sales tax should be computed for tax-exempt organizations, so your program would skip over
the tax computation code when processing such organizations. If makes decisions. If a condition
is true, the body of the if statement executes.
Consider the Figure 3.2 below,
Figure 3.2: The If Statement

CONDITION?

FALSE

TRUE
ONE OR MORE
STATEMENTS
TO BE EXECUTED
IF CONDITION
IS TRUE

Here is one format of If:


If Condition Then
One or more Visual Basic statements
End If
End If tells Visual Basic where the body of the If statement ends.
Dim a As Integer

Dim b As Integer

a = 3

b = 4

If a > b Then

MsgBox (a is greater than b)

Else


MsgBox (b is greater than a)


End If
LOVELY PROFESSIONAL UNIVERSITY

57

Modern Programming Tools & Techniques-III

Notes

The parentheses are not required around the condition in an If, but they help separate the test
from the rest of the code. In addition, the indentation helps illustrate the code that appears
inside the If statements body.
There is a shortcut form of If that you might run across. The single-line If statement has a format
that looks like this:
If condition Then VB Statement
The single-line If does not require an End If statement because the condition and the body of the
If reside on the same line. Single-line If statements do not provide for easy program maintenance.
If you decide that you want to add to the body of the If, you must convert the single-line If to
a multiple-line If, and you might forget to then add End If. Therefore, even if the body of an
If statement takes only one line, code the If as a multiple-line If...End If statement to make the
program more maintainable.

Write a program using if statement.

Self Assessment Questions


Multiple choice questions

1. A ............... executes statements repeatedly.

(a) loop

(b) data

(c) structure

(d) None of these

2. Uses comparison operator results to ..


(a) Find data

(b) Design data

(c) Both (a) and (b) (d) Test data


3. Blocks of code for making decisions are called ..

(a) PHP

(b) Java

(c) Decision Structures

(d) All of these

True or False
4. If uses comparison operator results to test data.
(a) True

(b) False

5. Microsoft Visual Basic 2005 is not object-oriented applications.


(a) True

(b) False

3.3 If-Else Statement


Whereas If executes code based on the conditions true condition, the Else statement executes
code based on the conditions false condition. Else is an optional part of the If statement. Else
specifies the code that executes if the condition is false.

58

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

Notes

Consider the Figure 3.3 below,


Figure 3.3: The IfElse Statement

The complete format of the If statement with Else is as follows:


If condition Then
One or more Visual Basic statements
Else
One or more Visual Basic statements
End If
num = Int(Text1.Text) Input

If (num > 0) Then

strReply = You have a car!

Else

strReply = You do not have a car!

End If

If (num > 1) Then strReply = Are you rich!

display our comment

Label1.Caption = strReply

Select Case
If you have a lot of conditional statements, using If...Then...Else could be very messy. For multiple
conditional statements, it is better to use Select Case.

LOVELY PROFESSIONAL UNIVERSITY

59

Modern Programming Tools & Techniques-III

Notes

The format is:


Select Case expression
Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
Block of one or more VB statements
Case value4
.
.
.
Case Else
Block of one or more VB Statements
End Select
The data type specified in expression must match that of Case values.

Examination Grades
Dim grade As String

Private Sub Compute_Click( )


grade=txtgrade.Text
Select Case grade
Case

result.Caption=High Distinction

Case A-

Case B

Case C

Case Else

result.Caption=Distinction

result.Caption=Credit

result.Caption=Pass

result.Caption=Fail

End Sub

End Select

Please note that grade is a string, so all the case values such as A are of String data type.








60

Dim mark As Single

Private Sub Compute_Click()


Examination Marks
mark = mrk.Text

Select Case mark


Case Is >= 85

comment.Caption = Excellence

Case Is >= 70

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

comment.Caption = Good
comment.Caption = Above Average

Case Is >= 50

Case Else

Notes

Case Is >= 60

comment.Caption = Average
comment.Caption = Need to work harder

End Select

End Sub

Write a program using select case statement.

3.4 While Statement


Use a While...End While structure when you want to repeat a set of statements an indefinite
number of times, as long as a condition remains True. If you want more flexibility with where
you test the condition or what result you test it for, you might prefer the Do...Loop Statement.
If condition is true, all of the statements run until the End While statement is encountered.
Control then returns to the While statement, and condition is again checked. If condition is still
true, the process is repeated. If it is False, control passes to the statement that follows the End
While statement.
The While statement always checks the condition before it starts the loop. Looping continues
while the condition remains true. If condition is False when you first enter the loop, it does not
run even once.
The condition usually results from a comparison of two values, but it can be any expression that
evaluates to a Boolean Data Type value (True or False). This expression can include a value of
another data type, such as a numeric type, that has been converted to Boolean.
You can nest while loops by placing one loop within another. You can also nest different kinds
of control structures within one another.
Consider the Figure 3.4 below,
Figure 3.4: The While Statement

LOVELY PROFESSIONAL UNIVERSITY

61

Modern Programming Tools & Techniques-III

Notes

Exit While
The Exit While statement can provide another way to exit a While loop. Exit While immediately
transfers control to the statement that follows the End While statement.
You typically use Exit While after some condition is evaluated (for example, in an If...Then...Else
structure). You might want to exit a loop if you detect a condition that makes it unnecessary
or impossible to continue iterating, such as an erroneous value or a termination request. You
can use Exit While when you test for a condition that could cause an endless loop, which is a
loop that could run an extremely large or even infinite number of times. You can then use Exit
While to escape the loop.
You can place any number of Exit While statements anywhere in the While loop.
When used within nested While loops, Exit While transfers control out of the innermost loop
and into the next higher level of nesting.
The Continue While statement immediately transfers control to the next iteration of the loop.
In the following example, the statements in the loop continue to run until the
index variable is greater than 10.

Dim index As Integer = 0

While index <= 10

Debug.Write(index.ToString & )

index += 1

End While

Debug.WriteLine()

Output: 0 1 2 3 4 5 6 7 8 9 10

The following example illustrates the use of the Continue While and Exit While statements.
Dim index As Integer = 0
While index < 100000
index += 1
If index is between 5 and 7, continue
with the next iteration.
If index >= 5 And index <= 8 Then
Continue While
End If
Display the index.
Debug.Write(index.ToString & )
If index is 10, exit the loop.
If index = 10 Then
Exit While
End If
End While
Debug.WriteLine()
Output: 1 2 3 4 9 10
The following example reads all lines in a text file. The OpenText method opens the file and
returns a StreamReader that reads the characters. In the While condition, the Peek method of
62

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

the StreamReader determines whether the file contains additional characters.

Notes

Private Sub ShowText(ByVal textFilePath As String)

If System.IO.File.Exists(textFilePath) = False Then


Else

Debug.WriteLine(File Not Found: & textFilePath)



D im sr As System.IO.StreamReader
OpenText(textFilePath)

System.IO.File.

While sr.Peek() >= 0

Debug.WriteLine(sr.ReadLine())

End While

sr.Close()

End If

End Sub

The While...Exit While statement replaces the old While...Wend statement of


earlier versions of VB.

3.5 Do-While Statement


The Do While loop is perhaps the most common looping statement that you will put in Visual
Basic programs.
Here is the format of the Do While loop:
Do While condition
Block of one or more VB statements
Loop
Consider the Figure 3.5 below,
Figure 3.5: The DoWhile Statement
SOME STATEMENT
BEFORE
LOOP BEGINS

STATEMENT 1
OF
LOOP BODY
STATEMENT 2
OF
LOOP BODY
T
CONDITION?
F
SOME STATEMENT
AFTER
LOOP FINISHES

LOVELY PROFESSIONAL UNIVERSITY

63

Modern Programming Tools & Techniques-III

Notes

The block of code continues looping as long as condition is true. Whether you insert one or
several lines of code for the block does not matter. It is vital, however, for the block of code to
somehow change a variable used in condition.
The block of code keeps repeating as long as the Do While loops condition continues to stay
true. Eventually, condition must become false or your program will enter an infinite loop and
the user will have to break the programs execution by pressing the Ctrl+Break key combination.
An infinite loop is a loop that never terminates.
The Do While loop continues executing a block of Visual Basic statements as long as condition
is true. As soon as condition becomes false, the loop terminates.
As long as condition is true, the block of code in the body of the loop continues executing. When
condition becomes false, the loop terminates. After the loop terminates, Visual Basic begins
program execution at the statement following the Loop statement because Loop signals the end
of the loop. As soon as Do Whiles condition becomes false, the loop terminates and does not
execute even one more time. The Do Whiles condition appears at the top of the loop. Therefore,
if condition is false the first time the loop begins, the body of the loop will never execute.

Do while counter <=1000


num.Text=counter

Loop

counter =counter+1

The above example will keep on adding until counter >1000.


The Do Until Loop
Whereas the Do While loop continues executing the body of the loop as long as the condition
is true, the Do Until loop executes the body of the loop as long as the condition is false. The
programs logic at the time of the loop determines which kind of loop works best in a given
situation.
Do Until works almost exactly like they Do While loop except that the Do Until loop continues
executing the body of the loop until the condition is true. Like the Do While, the Do Until is
a multiline looping statement that can execute a block of code that is one or more lines long.
Figure 3.6: The DoUntil Statement
SOME STATEMENT
BEFORE
LOOP BEGINS

STATEMENT 1
OF
LOOP BODY
STATEMENT 2
OF
LOOP BODY
F
CONDITION?
T
SOME STATEMENT
AFTER
LOOP FINISHES

64

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

Notes

Do Until (condition)
Block of one or more Visual Basic statements
Loop

3.6 For Statement


Use a For...Next structure when you want to repeat a set of statements a set number of times.
When a For...Next loop starts, Visual Basic evaluates start, end, and step. This is the only time
it evaluates these values. It then assigns start to counter. Before it runs the statement block, it
compares counter to end. If counter is already larger than the end value (or smaller if step is
negative), the For loop ends and control passes to the statement following the Next statement.
Otherwise the statement block runs.
Each time Visual Basic encounters the Next statement, it increments counter by step and returns
to the For statement. Again it compares counter to end, and again it either runs the block or
exits the loop, depending on the result. This process continues until counter passes end or an
Exit For statement is encountered.
The loop does not stop until counter has passed end. If counter is equal to end, the loop continues.
The comparison that determines whether to run the block is counter <= end if step is positive
and counter >= end if step is negative.
Changing the value of counter while inside a loop can make it more difficult to read and debug
your code. Changing the value of start, end, or step does not affect the iteration values determined
when the loop was first entered.
Consider the Figure 3.7 below,
Figure 3.7: For Statement

LOVELY PROFESSIONAL UNIVERSITY

65

Modern Programming Tools & Techniques-III

Notes

Step Argument
The value of step can be either positive or negative. It determines loop processing as follows:
Step value

Loop executes if

Positive or zero

counter <= end

Negative

counter >= end

If not specified, step defaults to 1.


Counter Argument
If counter has not been declared outside this loop, you must declare it in the For statement. In
this case, the scope of counter is the body of the loop. However, you cannot declare counter
both outside and inside the loop.
You can optionally specify counter in the Next statement. This improves the readability of your
program, especially if you have nested For loops. You must specify the same variable as the one
that appears in the corresponding For statement.
The data type of counter determines the type of the iteration, and must be one of the following:

A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

An enumeration that you declare by using an Enum Statement (Visual Basic).

An Object.

A type T that has the following operators, where B is a type that can be used in a Boolean
expression.

Public Shared Operator >= (op1 As T, op2 As T) As B

Public Shared Operator <= (op1 As T, op2 As T) As B

Public Shared Operator (op1 As T, op2 As T) As T

Public Shared Operator + (op1 As T, op2 As T) As T

The start, end, and step expressions can evaluate to any data type that widens to the type of
counter. If you use a user-defined type for counter, this means you might have to define the
CType conversion operator to convert the types of start, end, or step to the type of counter.
Nesting Loops
You can nest For loops by putting one loop within another. However, each loop must have a
unique counter variable. You can also nest different kinds control structures within each other.
If a Next statement of an outer nesting level is encountered before the Next of an inner level,
the compiler signals an error. However, the compiler can detect this overlapping error only if
you specify counter in every Next statement.
Exit For
The Exit Statement immediately exits the ForNext loop and transfers control to the statement
following the Next statement.
You can put any number of Exit For statements in a ForNext loop. When used within nested
ForNext loops, Exit For exits the innermost loop and transfers control to the next higher level
of nesting.
Exit For is often used after you evaluate some condition, for example in an If...Then...Else
structure. You might want to use Exit For for the following conditions:

66

Continuing to iterate is unnecessary or impossible. This might be caused by an erroneous


value or a termination request.

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

An exception is caught in a Try...Catch...Finally. You might use Exit For at the end of the
Finally block.

There an endless loop, which is a loop that could run a large or even infinite number of
times. If you detect such a condition, you can use Exit For to escape the loop

The Continue For statement transfers control immediately to the next iteration of the loop.

Notes

The following example illustrates the use of the ForNext statement. A loop
counter variable is incremented with each iteration of the loop. The step
argument is not specified, so it defaults to 1.

For index As Integer = 1 To 5

Debug.Write(index.ToString & )

Next
Debug.WriteLine()

Output: 1 2 3 4 5

In the following example, the counter and step arguments are Double floating
point numbers.

For number As Double = 2 To 0 Step 0.25

Debug.Write(number.ToString & )

Next
Debug.WriteLine()

Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0

The following example demonstrates nested For...Next structures that have different step values.
The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop
counter variable for every iteration of the loop.
For indexA = 1 To 3
Create a new StringBuilder, which is used
to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
Append to the StringBuilder every third number
from 20 to 1 descending.
For indexB = 20 To 1 Step -3
sb.Append(indexB.ToString)
sb.Append()
Next indexB
Display the line.
Debug.WriteLine(sb.ToString)
Next indexA
Output:
20 17 14 11 8 5 2
20 17 14 11 8 5 2
20 17 14 11 8 5 2

LOVELY PROFESSIONAL UNIVERSITY

67

Modern Programming Tools & Techniques-III

Notes

The following example removes all elements from a generic list. Instead of a For Each...Next
Statement (Visual Basic), a For...Next statement that iterates in descending order is used. This
is because the removeAt method causes elements after the removed element to have a lower
index value.
Dim lst As New List(Of Integer) From {10, 20, 30, 40}
For index As Integer = lst.Count - 1 To 0 Step -1
Next

lst.RemoveAt(index)

Debug.WriteLine(lst.Count.ToString)
Output: 0
The following example illustrates the use of the Continue For and Exit For statements.
For index As Integer = 1 To 100000

If index is between 5 and 7, continue


with the next iteration.

If index >= 5 And index <= 8 Then


Continue For

End If

Display the index.

Debug.Write(index.ToString & )

If index is 10, exit the loop.


If index = 10 Then
Exit For

Next

End If

Debug.WriteLine()
Output: 1 2 3 4 9 10

The following example iterates through an enumeration that is declared by using an Enum
Statement (Visual Basic).
Public Enum Mammals
Buffalo
Gazelle

Mongoose

Rhinoceros
Whale

End Enum

Public Sub ListSomeMammals()

For mammal As Mammals = Mammals.Gazelle To Mammals.Rhinoceros


Next

Debug.Write(mammal.ToString & )

Debug.WriteLine()

Output: Gazelle Mongoose Rhinoceros

End Sub

In the following example, the statement parameters use a class that has operator overloads for
the +, , >=, and <= operators.

68

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

Private Class Distance

Notes

Public Property Number() As Double

Public Sub New(ByVal number As Double)


Me.Number = number

End Sub

Define operator overloads to support For...Next statements.


ublic Shared Operator +(ByVal op1 As Distance, ByVal op2 As
P
Distance) As Distance
Return New Distance(op1.Number + op2.Number)

End Operator

ublic Shared Operator -(ByVal op1 As Distance, ByVal op2 As


P
Distance) As Distance
Return New Distance(op1.Number - op2.Number)

End Operator

ublic Shared Operator >=(ByVal op1 As Distance, ByVal op2 As


P
Distance) As Boolean
Return (op1.Number >= op2.Number)

End Operator

ublic Shared Operator <=(ByVal op1 As Distance, ByVal op2 As


P
Distance) As Boolean
Return (op1.Number <= op2.Number)

End Operator

End Class

Public Sub ListDistances()

Dim distFrom As New Distance(10)


Dim distTo As New Distance(25)

Dim distStep As New Distance(4)

For dist As Distance = distFrom To distTo Step distStep


Next

Debug.Write(dist.Number.ToString & )

Debug.WriteLine()

Output: 10 14 18 22

End Sub

Conditional Structures

rogram Specification: Write a program to receive a series of numbers from keyboard


until 1 is entered to stop the program. Then the program outputs the average of the
inputted numbers except the last number 1.

Below is a program written by a student:

1. Program FindAverage;

2. var Count : integer;

Contd...

LOVELY PROFESSIONAL UNIVERSITY

69

Modern Programming Tools & Techniques-III

Notes

3. Num, Sum, Average : real;

4. begin

5. Count := 0;

6. Sum := 0;

7. repeat

8. writeln(Enter a number (1 to end):);

9. readln(Num);

10. Count := Count + 1;

11. Sum := Sum + Num

12. until Num = 1;

13. Average := (Sum+1)/(Count- 1);

14. writeln(The average of the inputted numbers is, Average:0:2)

15. end.

Sample output 1:
Enter a number(1 to end): 50
Enter a number(1 to end): 60
Enter a number(1 to end): 60
Enter a number(1 to end): 70
Enter a number(1 to end): 50
Enter a number(1 to end): 1
The average of the inputted numbers is 58.00
It seems that there is no error in the program above. However, what is the output if the first
inputted number is 1?
Sample output 2:

Enter a number(1 to end): 1

run-time error!
The problem is due to the expression (Sum+1)/(Count1) in line 13. If the first inputted
number is 1, the expression becomes (1+1)/(11), i.e. 0/0. A Divided by zero error will
occur.
To solve this problem, we should check the content of variable Count before execute the
expression (Sum+1)/(Count1). If the value of variable Count is 1, that means the first
inputted number is 1, a suitable message should be displayed. Below is a suggested solution:

1. Program FindAverage;

2. var Count : integer;

3. Num, Sum, Average : real;

4. begin

5. Count := 0;
Contd...

70

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

Notes

6. Sum := 0;

7. repeat

8. writeln(Enter a number (1 to end):);

9. readln(Num);

10. Count := Count + 1;


11. Sum := Sum + Num
12. until Num = 1;
13. if Count = 1 then
14. writeln(No number is inputted!)
15. else
16. begin
17. Average := (Sum+1)/(Count1);
18. writeln(The average of the inputted numbers is, Average:0:2)
19. end
20. end.
Sample output 3:

Enter a number(1 to end): 1

No number is inputted!
Questions

1. Analyse the question and explain.

2. Give the correct output of the above program, if it is wrong.

Self Assessment Questions


Multiple choice questions

6. Which of the following is NOT an Arithmetic operator in C#.NET?

(a) the next Else statement is activated.


(b) the next If statement is activated.
(c) the next Then statement is activated.
(d) the End If statement is activated.

7. The End If statement is required:

(a) in all IfThen statements.

(b) in all Multi-line statements with Else.

(c) in Single Line statements.

(d) Both a and b.

8. Which statements are optional in an If. Then statement?


(a) If

(b) Then

(c) Else

(d) Both a and b.

LOVELY PROFESSIONAL UNIVERSITY

71

Modern Programming Tools & Techniques-III

Notes

9. Which selection process is an example of multiple branches from a single expression?

(a) IfThen

(b) Select Case

(c) DoLoop

(d) ForNext

10. How many times is the test expression of a Select Case evaluated?
(a) 0

(b) 1

(c) 2

(d) Once for each Case.

11. Which is not a type of Select Case test construct?


(a) simple value

(b) complex value

(c) relational value with Is

(d) range of values with To

12. What happens in a Select Case construct when a test value matches the test expression?
(a) The corresponding block of statements is run.
(b) The next Case test value is checked.
(c) The Case Else statement is run.
(d) The Select Case construct is exited.
13. Do...Loop is an iterative statement because it:
(a) selects a block of statements to run.
(b) runs the same block of statements repeatedly.
(c) selects a block of statements and runs it repeatedly.
(d) selects a block of statements and runs it a specified number of times.
14. Which is true of a DoLoop?
(a) The While condition goes after the Do keyword.
(b) The Until condition goes after the Do keyword.
(c) The While condition goes after the Loop keyword.
(d) All of the above.
15. Which DoLoop statement should be used to process test scores where a test score over
100 is a signal to stop the processing?
(a) Do While Score > 100

(b) Do Until Score > 100

(c) Loop While Score > 100

(d) Loop Until Score > 100

3.7 Summary

72

A loop is something that goes round and round and round. If someone told you to move
your finger around in a loop, you did know what to do immediately.

Loop executes statements repeatedly. It often has an upper and lower bound. Certain
loops, such as the For-loop, proceed through a range of values.

Loop allows you to repeat an action for a number of times or until a specified condition
is matched.

IF executes code based on the conditions true condition, the Else statement executes code
based on the conditions false condition.

LOVELY PROFESSIONAL UNIVERSITY

Unit 3: Decision Making and Looping

Use a While...End While structure when you want to repeat a set of statements an indefinite
number of times, as long as a condition remains True.

The While statement always checks the condition before it starts the loop.

For...Next statement repeats a set of statements a set number of times.

Notes

3.8 Keywords
Comparison Operators: Compares data values against each other and produce true or false results.
Decision Structures: Blocks of code for making decisions.
Infinite loop: It is a loop that never terminates.
Iteration: It is to repeat an action or process.
Loop: It enable us to execute a series of expressions multiple numbers of times.
1. Write a program to print the table of 5.
2. Write a program using do while loop.

3.9 Review Questions


1. Explain Conditional Operators and its types.

2. Describe For Statement.


3. Explain the concept of Decision Structures.

4. How does a loop becomes an infinite loop. Explain Briefly.

5. How does Select Case works better in multiple conditional statements.

6. What is the difference between Do-While and Do-Until Statement?


7. Explain Nesting of Loops.

8. Explain the difference between Step Argument and Counter Argument.

9. You can also nest different kinds of control structures within one another. How?

10. Explain the concept of multiple branches from a single expression.

Answers for Self Assessment Questions


1. (a)

2. (d)

3. (c)

4. (a)

5. (b)

6. (c)

7. (b)

8. (c)

9. (b)

10. (b)

11. (b)

12. (a)

13. (b)

14. (d)

15. (b)

3. 10 Further Readings
Microsoft Visual Basic .NET Deluxe Learning Edition, by Michael Halvorson.
Programming VB.NET - A Guide For Experienced Programmers, by Peter Kitson.

http://www.homeandlearn.co.uk/net/nets1p20.html

LOVELY PROFESSIONAL UNIVERSITY

73

Modern Programming Tools & Techniques-III

Unit 4: Array

Notes

CONTENTS
Objectives
Introduction
4.1

Types of Arrays

4.1.1

Fixed-Size Arrays

4.1.2

Dynamic Arrays

4.2

Split Function

4.3

Join Function

4.4

Adding New Elements

4.4.1

4.5

Multidimensional Arrays

4.6

System. Array Class

4.7

Retrieving the Contents of an Array

Erasing an Array

4.8 Summary
4.9 Keywords
4.10 Review Questions
4.11 Further Reading

Objectives
After studying this unit, you will be able to:

Define array and its type

Explain the split function

Define join function

Describes the multidimensional arrays

Discuss system. array class

Introduction
Arrays are a vital part of programming, as they allow the programmer to store more than one
value in a variable, whilst retaining a single reference. If we think of a variable as a single slot
in memory (or a box) that can contain data of a certain type - number, character, etc. then an
array is the equivalent of a box divided into partitions, each containing a piece of data. Of course,
because the array box is storing more information than a single variable box, it is much bigger: it
needs more memory. We can use the same name to access the variable, but we need some way
to differentiate between the individual slots. To this we use an index into the array. For example,
supposing we have an array that is 100 units wide, we might access the hundredth unit thus:
My Array [99] = 3;

74

LOVELY PROFESSIONAL UNIVERSITY

Unit 4: Array

This example also illustrates another feature of most arrays - the index is usually zero based.
In other words, the index to the first item is [0] and the index to the last item is [number of
elements 1]

Notes

In many programming languages, a string is treated as an array of characters. Usually these


arrays are terminated with a null character to indicate the end of the string. This allows software
to process strings without knowing the dimension of the array at design time. A collection of
strings is still possible, however, by using a multidimensional array.
Arrays are programming constructs that store data and allow us to access them by numeric
index or subscript. Arrays help us create shorter and simpler code in many situations. Arrays
in Visual Basic .NET inherit from the Array class in the System namespace. All arrays in VB are
zero based, meaning, the index of the first element is zero and they are numbered sequentially.
You must specify the number of array elements by indicating the upper bound of the array. The
upper bound is the number that specifies the index of the last element of the array. Arrays are
declared using Dim, ReDim, and Static, Private, Public and Protected keywords. An array can have
one dimension (linear arrays) or more than one (multidimensional arrays). The dimensionality
of an array refers to the number of subscripts used to identify an individual element. In Visual
Basic we can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
The following code demonstrates arrays.
Imports System. Console
Module Module1
Sub Main ()
Dim sport (5) As String
Declaring an array
Sport (0) = Soccer
Sport (1) = Cricket
Sport (2) = Rugby
Sport (3) = Aussie Rules
Sport (4) = Basketball
Sport (5) = Hockey
Storing values in the array
Write Line ( Name of the Sport in the third location & & sport (2))
Displaying value from array
End Sub
End Module

4.1 Types of Arrays


An array is a lot like a CD rack. We know: one of those rectangular boxes with slots to slide
CDs in, each above another. There are two types of Visual Basic arrays: fixed-size and dynamic.

4.1.1 Fixed-Size Arrays


A fixed-size array most closely matches our CD rack analogy. There are a limited number of
slots we can slide CDs into. Pretend we have three CDs one by the Deft ones, another by Tool,
and a third by Disturbed. To fit all of these in our rack, the rack must contain at least three slots.
So we declare our CD rack as having three slots:
Dim strCDRack (0 to 2) As String

LOVELY PROFESSIONAL UNIVERSITY

75

Modern Programming Tools & Techniques-III

Notes

We have just made a variable strCDRack that contains three slots (#0, #1, and #2) and is of a
String data type. Now we can insert our CDs into it:
Dim strCDRack (0 to 2) As String
StrCDRack (0) = Deft ones
StrCDRack (1) = Tool
StrCDRack (2) = Disturbed
Notice that each of the three new lines starts off with the variable name and then gives an
element number before having a value assigned. This is like numbering the slots on our CD
rack starting at 0 up to 2 and then inserting a CD into each slot.
The format for declaring an array is:
Dim|Public|Private Array Name (Subscript) As Data Type

Dim, Public, and Private declare the array and its scope. Using Dim in a procedure
will make the array only available from within that procedure. Using it in the General
Declarations section will make it available to all procedures in that module. Private has
the same effect and should be used only at the modular level. Using Public will make the
array available throughout the project.

Array Name is the name of the array.

Subscript is the dimensions of the array.

Data Type is any valid data type.

4.1.2 Dynamic Arrays


The new Charlotte Church CD came out but our rack only has three slots. We do not want to
throw away any of our CDs to make room for the new one so we decide to use our ultimate
building skills to attach another slot. We start building:
Dim strCDRack() As String
ReDim strCDRack(0 to 2) As String
strCDRack(0) = Deftones
strCDRack(1) = Tool
strCDRack(2) = Disturbed
We have just dimensioned our array another way that allows for expansion. Notice that the
subscript of the Dim statement is missing. This is OK; it tells VB that our array is a dynamic
array, meaning that we can change its size with ReDim.
Dim strCDRack() As String
ReDim strCDRack(0 to 2) As String
strCDRack(0) = Deftones
strCDRack(1) = Tool
strCDRack(2) = Disturbed
ReDim Preserve strCDRack(0 to 3) As String
strCDRack(3) = Charlotte Church
This snippet has two more lines, the first redimensioning the array one element larger and the
second setting this elements value. Notice the Preserve keyword: it forces Visual Basic to retain
all existing elements values. Without this keyword all our old CDs would be lost and we would
be stuck with just Charlotte Church.

76

LOVELY PROFESSIONAL UNIVERSITY

Unit 4: Array

Notes

The ReDim keywords syntax is:


ReDim [Preserve] Array Name (Subscript) As Data Type

ReDim is the keyword that denotes we are redimensioning an array.

Preserve is an optional keyword that forces Visual Basic to retain all existing elements
values. Without it all elements will return to their default values. (Numeric data types
to 0, variable-length strings to (a zero-length string), fixed-length strings filled with
zeros, and variants to empty.)

Array Name is the name of the array.

Subscript is the dimensions of the array

Data Type is any valid data type. The data type cannot be changed from its initial declaration
when using the ReDim keyword. (Unless it was initially declared as a Variant.)
The Visual Basic compiler does not enforce output-only rules. You should
never read from an output parameter; it may contain nothing. Always assign
a new array.

4.2 Split Function


Sometimes we run into situations where we want to take the information from within a given
string, separate it into multiple strings, and then place those strings in an array. For example,
say we had this code:
Dim cdList As String
cdList = Nevermind, OK Computer, I Care Because You Do, Icky
Thump
It would be nice if we could easily take that list and put it in an array, would not it? This could
be done by using Visual Basics built in string functions, however, writing and updating that
code could prove to be time consuming and tedious. Luckily for us, Visual Basic 6.0 provides
a built in function called split that allows us to easily parse out information from a string and
place it into an array. It has the following syntax:
ArrayName = split(Sting Input[, Delimiter[, Length Limit[, Compare
Mode]]])
String Input is the string that we want to parse.

Delimiter is an optional parameter that indicates what type of string separates the elements
in the input string. By default this parameter is set to . That would mean an input
string of This is a test would yield an array of 4 elements ( This , is , a , test).

Length Limit is the maximum size our output array can be. The text remaining to be
parsed will be set as the final element in the array.

Compare Mode. By default, Visual Basic compares strings character by character using
their ASCII values. However, we can use different modes that will cause Visual Basic to
compare strings differently. For example, vbTextCompare causes string comparisons to
be case insensitive. This parameter effects how the Delimiter parses Input String.

The following is an example showing how to parse the list we showed earlier:
Dim strCDRack() As String
Dim cdList As String
Dim i As Integer

LOVELY PROFESSIONAL UNIVERSITY

77

Modern Programming Tools & Techniques-III

Notes

cdList = Nevermind, OK Computer, I Care Because You Do, Icky


Thump
strCDRack = Split(cdList, , )
For i = LBound(strCDRack) To UBound(strCDRack)
MsgBox strCDRack(i)
Next

4.3 Join Function


The split function allowed us to break strings down into arrays, is there a function that allows
us to take arrays and make them one big long string? Yes, yes there is, and it is called join. Join
is a very simple function. It has the following syntax:
String Name = join (Array Input [, Delimiter])

Array Input is the array that we want to place into a string.

Delimiter is an optional parameter that indicates what we want to place between elements
is added to the string. By default this parameter is set to .

Dim strFriends (0 to 6) As String, lngPosition as Long


strFriends(0) = Shyam
strFriends(1) = Mahesh
strFriends(2) = Surbhi
strFriends(3) = Gopal
strFriends(4) = Ganesh
strFriends(5) = Satya
strFriends(6) = Sunny
Dim my Friends As String
This will produce the following string: Bianca, Jeana, Sam, Jenna,
Erin, Carolyn, Kate
My Friends = Join (strFriends, , )
MsgBox my Friends

Write the program in join function.

Self Assessment Questions


Multiple Choice Questions

1. All arrays in VB are zero based, meaning, the index of the first element is .............. and
they are numbered sequentially.

(a) zero

(b) one

(c) two

(d) three

2. There are two types of Visual Basic arrays: ................ and dynamic.

78

(a) fixed- zero

(b) fixed-size

(c) fixed-dynamic

(d) dynamic

LOVELY PROFESSIONAL UNIVERSITY

Unit 4: Array

3. Visual Basic we can specify up to .......... dimensions.


(a) 30

(b) 31

(c) 32

(d) 33

Notes

4. Arrays are declared using Dim, ReDim, and Static, Private, Public and Protected .............. .
(a) variables

(b) keywords

4.4 Adding New Elements


Sometimes we have an array that needs to keep growing, and we do not know what the upper
bound will end up being. Maybe we are making a crappy MP3 player and need to ask the user
to input song names. We might do something like this:
Dim strSongNames () As String Array of song names
Dim blDimensioned As Boolean Is the array dimensioned?
Dim strText As String To temporarily hold names
Dim lngPosition as Long Counting
The array has not yet been dimensioned:
blDimensioned = False
Do Ask for a song name
StrText = Input Box ( Enter a song name : )
If strText <> Then Has the array been dimensioned?
If blDimensioned = True Then
Yes, so extend the array one element large than its current upper bound.
Without the Preserve keyword below, the previous elements in our
array would be erased with the resizing
ReDim Preserve strSongNames (0 To UBound (strSongNames) + 1) As
String
Else
No, so dimension it and flag it as dimensioned.
ReDim strSongNames (0 To 0) As String
blDimensioned = True
End If
Add the song name to the last element in the array.
StrSongNames (UBound (strSongNames)) = strText
End If
Loop Until strText =
Display entered song names:
For lngPosition = LBound (strSongNames) To UBound (strSongNames)
MsgBox strSongNames (lngPosition)
Next lngPosition
Erase array
Erase strSongName

LOVELY PROFESSIONAL UNIVERSITY

79

Modern Programming Tools & Techniques-III

Notes

4.4.1 Erasing an Array


We should always erase our array when we are done using it, especially if we are using dynamic
arrays. It is rather easy:
Dim strFriends(0 to 2) As String
strFriends(0) = Shyam
strFriends(1) = Mahesh
strFriends(2) = Surbhi
Erase strFriends
Multidimensional arrays in C using firstly in 1972.

Write the program multidimensional arrays.

4.5 Multidimensional Arrays


Multidimensional arrays can be thought of as arrays-of-arrays. For example, to visualize a two
dimensional array we could picture a row of CD racks. To make things easier, we can imagine
that each CD rack could be for a different artist. Like the CDs, the racks would be identifiable
by number. Below we will define a two dimensional array representing a row of CD racks. The
strings inside of the array will represent album titles.
Here we will define an array where the first dimension contains 2
elements and
the second dimension contains 4 elements
ReDim cdRack(0 to 1, 0 to 3) As String
A CD rack for the Beatles
cdRack(0, 0) = Rubber Soul
cdRack(0, 1) = Revolver
cdRack(0, 2) = The White Album
cdRack(0, 3) = Let It Be
A CD rack for the Rolling Stones
cdRack(1, 0) = Sticky Fingers
cdRack(1, 1) = Beggars Banquet
cdRack(1, 2) = Let It Bleed
cdRack(1, 3) = Tattoo You
The first item of the first dimension is an array for Beatles CDs while the second item of the first
dimension is an array for Rolling Stones CDs. We could also add a third dimension if we wanted.
Keeping with our CD rack analogy, we could picture this third dimension as a hallway with
several rooms. Inside of each room would be a row of CDs racks. If we wanted our hallways
to have 10 rooms, each with CD racks like the ones in the above example, we could declare
our array as follows:

80

LOVELY PROFESSIONAL UNIVERSITY

Unit 4: Array

Dim cdRackHallway(0 to 9, 0 to 1, 0 to 3) As String

Notes

In Visual Basic 6.0, we can create arrays with up to 60 dimensions. In Visual Basic .NET, the
maximum number of dimensions an array can have are 32. Most arrays we will need to deal
with will only be one or two dimensions. Multidimensional arrays can require a decent amount
of memory, so use them with care, especially large multidimensional arrays.
Lastly, for multidimensional arrays it should be noted that only the last dimension can be
resized. That means that given our example above, once we created the array with two CD
racks, we would not be able to add more racks, we would only be able to change the number
of CDs each rack held. Example:
Here we will define an array where the first dimension contains 2
elements and
the second dimension contains 4 elements
ReDim cdRack(0 to 1, 0 to 3) As String
A CD rack for the Beatles
cdRack(0, 0) = Rubber Soul
cdRack(0, 1) = Revolver
cdRack(0, 2) = The White Album
cdRack(0, 3) = Let It Be
A CD rack for the Rolling Stones
cdRack(1, 0) = Sticky Fingers
cdRack(1, 1) = Beggars Banquet
cdRack(1, 2) = Let It Bleed
cdRack(1, 3) = Tattoo You
ReDim Preserve cdRack(0 to 1, 0 to 4) As String
Lets add another Beatles CD
cdRack(0, 4) = Abby Road
Lets add another Rolling Stones CD
cdRack(1, 4) = Exile on Main St.
Von Neumann wrote the first array-sorting program (merge sort) in 1945,
during the building of the first stored-program computer.

4.6 System. Array Class


Arrays are one of the fundamental data structures in programming languages, providing a storage
area for sequential data values. System. Array is the base class for all arrays in the common
language runtime. It has methods for creating, manipulating, searching, and sorting the arrays
we have talked about so far. System. Array implements several interfaces, like ICloneable, IList,
ICollection, and IEnumerable. It also has many properties and methods to aid us in determining
information about our array.
The Length property of the array returns the total number of elements in all of the arrays
dimensions. The Rank property returns the rank the number of dimensions of the array, which
is useful in multidimensional arrays. We can use the Clear function to reset a range of array
elements to zero or to a null reference.
The GetLowerBound function returns the lower bound of the specified dimension in an array.
GetLowerBound (0) returns the lower bound for the indexes of the first dimension of an array,

LOVELY PROFESSIONAL UNIVERSITY

81

Modern Programming Tools & Techniques-III

Notes

and GetLowerBound (1) returns the lower bound for the indexes of the last dimension of an
array. The GetUpperBound function returns the upper bound of the specified dimension in an
array. GetUpperBound (0) returns the upper bound for the indexes of the first dimension of an
array, and GetUpperBound (1) returns the upper bound for the indexes of the last dimension
of an array.
Using the Copy function, we can copy a range of elements from one array, starting at the specified
source index, and paste them into another array, starting at the specified destination index:
There are three ways to enumerate array elements:

Using the for each loop structure

Looping with a for loop along the length of the array

Using the Get Enumerator function and implementing IEnumerator


Looping Through Array Class Objects

Class Test

Shared Sub TestForEach(ByRef myArray As Integer())


For Each x As Integer In myArray

Console.WriteLine(x)
Next

End Sub

Shared Sub TestForWithLength(ByRef myArray As [Object]())


For x As Integer = 0 To myArray.Length - 1

Console.WriteLine(myArray(x))
Next

End Sub

Shared Sub TestForEnum(ByRef myArray As System.Array)

Dim i As Integer = 0

Dim myEnumerator As System.Collections.IEnumerator


myArray. GetEnumerator()

Dim cols As Integer = myArray.GetLength(myArray.Rank - 1)


While myEnumerator.MoveNext()
If i < cols Then
i += 1

Else

Console.WriteLine()

i = 1

End If

Console.WriteLine(myEnumerator.Current)

End While

Shared Sub Main()

End Sub

an int array and an Object array

Dim myIntArray As Integer() = New Integer(4) {5, 4, 3,


2, 1}

TestForEach(myIntArray)
82

LOVELY PROFESSIONAL UNIVERSITY

Unit 4: Array

Notes

an Object array

Dim myObjArray As [Object]() = New [Object](4) {99, 98,


97, 96, 95}

TestForWithLength(myObjArray)

another object array

For i As Integer = myObjArray2.GetLowerBound(0)


myObjArray2.GetUpperBound(0)

Dim myObjArray2 As Array = Array.CreateInstance(Type.


[GetType]( System.Object ), 5)

To

myObjArray2.SetValue(i * i, i)

Next

TestForEnum(myObjArray2)
Console.ReadLine()

End Sub

(Figure 4.1 shows the output of the program)

End Class

Figure 4.1: Output of the Example

Public Class DemoArray

Public Shared Sub Main()

C
reates and initializes a new integer array and a new
Object array.

Dim myIntArray() As Integer = {1, 2, 3, 4, 5}

Prints the initial values of both arrays.

Console.Write(integer array:)

Dim myObjArray() As Object = {26, 27, 28, 29, 30}


Console.WriteLine(Initially,)
PrintValues(myIntArray)

Console.Write(Object array: )

PrintValues(myObjArray)

LOVELY PROFESSIONAL UNIVERSITY

83

Modern Programming Tools & Techniques-III

Notes

C
opies the first two elements from the integer array
to the Object array.

System.Array.Copy(myIntArray, myObjArray, 2)

onsole.WriteLine(ControlChars.NewLine + After copying


C
the first two _


Prints the values of the modified arrays.

+ elements of the integer array to the Object array,)

PrintValues(myIntArray)

Console.Write(integer array:)

Console.Write(Object array: )

PrintValues(myObjArray)

C
opies the last two elements from the Object array
to the integer array.

System.Array.Copy(myObjArray, myObjArray.GetUpperBound(0)
- 1, myIntArray, _
myIntArray.GetUpperBound(0) - 1, 2)

Prints the values of the modified arrays.

+ elements of the Object array to the integer array,)

PrintValues(myIntArray)

onsole.WriteLine(ControlChars.NewLine + After copying


C
the last two _

Console.Write(integer array:)

Console.Write(Object array: )

PrintValues(myObjArray)

End Sub

Overloads Public Shared Sub PrintValues(myArr() As Object)

For Each i In myArr

Dim i As Object

Console.Write(ControlChars.Tab + {0}, i)

Next i

Console.WriteLine()

End Sub

Overloads
Integer)

Public

Shared

Sub

PrintValues(myArr()

Dim i As Integer

For Each i In myArr

Console.Write(ControlChars.Tab + {0}, i)

Next i

Console.WriteLine()

End Sub

End Class
Output

This code produces the following output.

Initially,

84

LOVELY PROFESSIONAL UNIVERSITY

As

Unit 4: Array

integer array:
1 2 3 4 5

Object array:
26 27 28 29 30

Notes

After copying the first two elements of the integer array to the Object array,

integer array:
1 2 3 4 5

Object array: 1 2 28 29 30

After copying the last two elements of the Object array to the integer array,

integer array: 1

Object array: 1 2 28 29 30

29

30

4.7 Retrieving the Contents of an Array


Now that we know how to build an array, we might ask how to retrieve its contents. Say we
have built an array of our friends names:
Dim strFriends(0 to 6) As String
strFriends(0) = Shyam
strFriends(1) = Mahesh
strFriends(2) = Surbhi
strFriends(3) = Gopal
strFriends(4) = Ganesh
strFriends(5) = Satya
strFriends(6) = Sunny
We want to display their names in successive message boxes, so we construct a loop:
Dim strFriends(0 to 6) As String, lngPosition as Long
strFriends(0) = Shyam
strFriends(1) = Mahesh
strFriends(2) = Surbhi
strFriends(3) = Gopal
strFriends(4) = Ganesh
strFriends(5) = Satya
strFriends(6) = Sunny
For lngPosition = LBound(strFriends) To UBound(strFriends)
MsgBox strFriends(lngPosition)
Next lngPositionlngPositionlngPosition
There are two new functions in that snippet of code. LBound and UBound are used to determine
the lower and upper bounds of an array. Because strFriends has a lower bound of 0 and an upper
bound of 6. These functions allow we to iterate through an array with a dynamic size and they
keep we from having to keep track of the arrays size our self. With each iteration of that loop,
lngPosition will count up from 0 to 6. By accessing the array as strFriends (lngPosition) we are
greatly reducing the amount of code we have to write.

LOVELY PROFESSIONAL UNIVERSITY

85

Modern Programming Tools & Techniques-III

Notes

Array Class

ointer-based arrays have a number of problems. For example, a program can easily
walk off either end of an array, because C++ does not check whether subscripts
fall outside the range of an array (the programmer can still do this explicitly though).
Arrays of size n must number their elements 0, . . . , n 1; alternate subscript ranges are not
allowed. An entire non-char array cannot be input or output at once; each array element must
be read or written individually. Two arrays cannot be meaningfully compared with equality
operators or relational operators (because the array names are simply pointers to where
the arrays begin in memory and, of course, two arrays will always be at different memory
locations). When an array is passed to a general-purpose function designed to handle arrays of
any size, the size of the array must be passed as an additional argument. One array cannot be
assigned to another with the assignment operator(s) (because array names are const pointers
and a constant pointer cannot be used on the left side of an assignment operator). These and
other capabilities certainly seem like naturals for dealing with arrays, but pointer-based
arrays do not provide such capabilities. However, C++ does provide the means to implement
such array capabilities through the use of classes and operator overloading.
In this example, we create a powerful array class that performs range checking to ensure
that subscripts remain within the bounds of the Array. The class allows one array object
to be assigned to another with the assignment operator. Objects of the Array class know
their size, so the size does not need to be passed separately as an argument when passing
an Array to a function. Entire Arrays can be input or output with the stream extraction and
stream insertion operators, respectively. Array comparisons can be made with the equality
operators == and !=.
This example will sharpen your appreciation of data abstraction. You will probably want to
suggest other enhancements to this Array class. Class development is an interesting, creative
and intellectually challenging activityalways with the goal of crafting valuable classes.
Questions
1. Explain the pointer-based arrays.
2. Describes the powerful array class.

Self Assessment Questions


True or False

5. Delimiter is an optional parameter that indicates what type of string separates the elements
in the input string.

(a) True

(b) False

6. The Length property of the array does not returns the total number of elements in all of
the arrays dimensions.
(a) True

(b) False

7. There are two new functions in that snippet of code. LBound and UBound are used to
determine the lower and upper bounds of an array.
(a) True

(b) False

Multiple Choice Questions


86

8. What is the value of the index for the first element in a VB.NET array?

(a) 0

(b) 1

(c) 2

(d) 3

LOVELY PROFESSIONAL UNIVERSITY

Unit 4: Array

9. Which method will return the number of elements in an array?


(a) Dimension

(b) Length

(c) Number

(d) Size

Notes

10. In the statement, Dim Days (7) as String, what part of the array does the number 7 refer
to?
(a) Array name

(b) Data type

(c) Lower bound

(d) Upper bound

11. What is required to reference an element in an array?


(a) Array name

(b) Index value of the element

(d) both a and b.

(c) Element value

12. Which method will arrange the elements of an array in alphabetical order?
(a) Arrange

(b) Assemble

(c) Order

(d) Sort

13. The number of variables allowed in a structured is:


(a) 0
(b) 1
(c) 2
(d) any number of variables can be declared in an array
14. An array of controls can be populated by:
(a) Assigning existing controls to the array.
(b) Creating controls and assigning them to the array.
(c) Borrowing controls that will automatically assign them to the array.
(d) Both (a) and (b).

4.8 Summary

Arrays are a vital part of programming, as they allow the programmer to store more than
one value in a variable, whilst retaining a single reference.

Arrays are programming constructs that store data and allow us to access them by numeric
index or subscript. Arrays help us create shorter and simpler code in many situations.

Delimiter is an optional parameter that indicates what type of string separates the elements
in the input string. By default this parameter is set to .

Arrays are one of the fundamental data structures in programming languages, providing
a storage area for sequential data values. System. Array is the base class for all arrays in
the common language runtime.

Array implements several interfaces, like ICloneable, IList, ICollection, and IEnumerable.
It also has many properties and methods to aid us in determining information about our
array.

LOVELY PROFESSIONAL UNIVERSITY

87

Modern Programming Tools & Techniques-III

Notes

4.9 Keywords
Array: An array is a systematic arrangement of objects, usually in rows and columns. Specifically,
it may refer to in computer science.
Delimiter: A delimiter is a sequence of one or more characters used to specify the boundary
between separate, independent regions in plain text or other data streams.
Interfaces: It help to define the various properties, methods and events that classes are able to
implement.
Parameter: Parameter can be interpreted in mathematics, logic, linguistics, environmental science
and other disciplines.
Snippet: It is a programming term for a small region of re-usable source code, machine code or
text. Ordinarily, these are formally-defined operative units to incorporate into larger programming
modules.
1. Write a program to retrieve the elements one by one from the array.
2. Write a program to concatenate two arrays.

4.10 Review Questions


1. Define array and its type.

2. Explain the split function.


3. What is the join function?
4. How we can add new elements?

5. Define multidimensional arrays.

6. Discuss system. array class.


7. How can retrieve the contents of an array?
8. Give an example of looping through array class objects.

9. Define snippet.

10. How can we erase an array?

Answers for Self Assessment Questions


1. (a)

2. (b)

3. (c)

4. (a)

4. (b)

5. (a)

6. (b)

7. (a)

8. (a)

9. (b)

10. (d)

11. (d)

12. (d)

13. (d)

14. (d)

4.12 Further Reading


Programming Visual Basic .Net, by Jesse Liberty.

http://books.google.co.in/books?id=ZTTpsIQCaikC&pg=PA190&dq=array+
in+vb.net&hl=en&sa=X&ei=5F7-T_juMM3orQePqZnIBg&ved=0CHEQ6AEw
CQ#v=onepage&q=array%20in%20vb.net&f=false

88

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

Unit 5: In Built Functions

Notes

CONTENTS
Objectives
Introduction
5.1

Visual Basic .NET Functions

5.2

String Class

5.2.1

5.3

Conversion Functions

5.3.1

Type Conversion Functions

5.3.2

Val Function

5.4

Miscellaneous Functions

5.5

Subroutines and Functions

5.5.1 Subroutine

Creating an Object from a Class

5.6 Summary
5.7 Keywords
5.8

Review Questions

5.9

Further Reading

Objectives
After studying this unit, you will be able to:

Explain the built functions

Define string class

Describe in detail the, conversion functions

Define miscellaneous functions

Discuss the types subroutines and functions

Introduction
The VB has numerous built-in functions for processing strings. Most VB string-handling functions
return a string, although some return a number (such as the Len function, which returns the
length of a string and functions like Instr and InstrRev, which return a character position within
the string). The functions that return strings can be coded with or without the dollar sign ($) at
the end, although it is more efficient to use the version with the dollar sign.
A procedure is referred to as built-in if it shipped with its programming language. To make
your job a little easier, the Visual Basic language is equipped with many procedures that you
can use right away in your program. Based on this, before creating your own procedure, first
check whether the functionality you are looking for is already implementing in one of the
available procedures because those that ship with the Visual Basic language are highly reliable
and should be preferred.

LOVELY PROFESSIONAL UNIVERSITY

89

Modern Programming Tools & Techniques-III

Notes

Before using a built-in procedure, you must of course be familiar with it. This comes either by
consulting the documentation or by experience. This means that you must know its name, its
argument(s), its return value, and its role. The Visual Basic programming language provides one
of the richest libraries you will ever see. In fact, it is the richest of the .NET-based languages,
giving you access to functions that are not directly available to other languages such as C# or
C++/CLI. Because there so many of those functions, we will review only the most usually used.
Eventually, when necessary, in other lessons, we may introduce new ones.

5.1 Visual Basic .NET Functions


Visual Basic .NET has many built-in functions for manipulating text and carrying out
mathematical operations, as well as the ability to format data in both standard and user-defined
styles. We start by looking at two functions that are both frequently used and at the same time
relatively easy to get to grips with the MsgBox() function and the InputBox() function. We will
then look at some of the more commonly-used string-handling and math functions, and the
ways in which numerical, date and time values can be represented.
MsgBox() function
The MsgBox() function displays a message in a pop-up message box. The user is expected to
respond by clicking on a button in order to be able to continue. The format of the statement
used to invoke a message box is as follows:
returnVal = MsgBox(prompt, style Val, title)
The prompt parameter is a string value (either a string literal or a string variable) that supplies the
message to be displayed. The style Val parameter is either an integer style value from 0 to 5 or
a named constant (that can be used instead of the corresponding integer value) that determines
what command buttons will appear on the message box. The title parameter is another string
literal or string variable that supplies the title for the message box.
Message Box Styles
Style value

Named constant

Buttons displayed

0 vbOkOnly

Ok

vbOkCancel

Ok and Cancel

vbAbortRetryIgnore

Abort, Retry and Ignore

vbYesNoCancel

Yes, No and Cancel

vbYesNo

Yes and No

vbRetryCancel

Retry and Cancel

The returnVal value returned by the MsgBox() function is an integer value that indicates which
button the user has clicked in response to the message box being displayed. The possible return
values together with the named constants that may be used in their stead.
Message Box Return Values

90

Return value Named constant

Buttons clicked

1 vbOk

Ok

2 vbCancel

Cancel

3 vbAbort

Abort

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

4 vbRetry

Retry

5 vbIgnore

Ignore

6 vbYes

Yes

7 vbNo

No

Notes

The message box can be further embellished by the inclusion of an icon that will appear beside the
message. In VB.NET, there are four icons available. The icon is included either by incrementing
the style value by a fixed constant value, or by the inclusion of a second named constant.
Message Box Icons

Value

Named constant

Icon

16 vbCritical
32 vbQuestion

48

vbExclamation

64

vbInformation

The following two program statements would produce exactly the same message box, and are
essentially equivalent to one another:
MsgBox(This message is for info!, 64, Info)
MsgBox(This message is for info!, vbOKOnly + vbInformation, Info)
InputBox() function
The InputBox() function displays a pop-up input box into which the user can type a message.
The user is expected to enter their message, then click on a button (Cancel or OK) in order
to continue. The format of the statement used to invoke an input box is as follows:
Return String = InputBox(prompt, title, default Text, xpos, ypos)
The return String returned by the InputBox() function is the text entered by the user. The
prompt parameter is a text string (either a string literal or a string variable) that prompts the
user to enter some information. The title parameter is another string literal or string variable
that supplies the title for the input box. The default Text parameter can be used to enter default
content in the input box (although it would probably be left blank in most cases). The xpos and
ypos parameters specify the x and y coordinates for the input box on screen.

Write the program using InputBox function in VB.NET.

5.2 String Class


The String Class represents character strings. The following sections describe how to work with
VB.NET String class. The String data type comes from the System.
String class: The String type represents a string of Unicode Characters. The String class is a
sealed class, so you cannot inherit another class from the String class.

LOVELY PROFESSIONAL UNIVERSITY

91

Modern Programming Tools & Techniques-III

Notes

The string object is immutable, it cannot be modified once it created, that means every time you
use any operation in the String object, you create a new String Object. So if you are in a situation
in continuous operation with String Object it is recommended to use System.Text.StringBuilder.
System. Text. String Builder class to modify a string without creating a new object.
The object is the structure that contains data and methods of handling data. An object contains
data through fields and properties:

Field: stores data and is similar to a variable;

Property: retrieves and changes the value of a field with Get and Set procedures; data are
isolated and the values of fields are validated.

An object contains methods that are implemented actions. The methods of an object have the
form of procedures. An action recognized by an object called the event [...]. A class can implement
interfaces in all aspects defined in these ones. Interface is a collection of programming elements
and does not contain the implementation. Types of classes depending on the source definition:

Included in VB.NET;

Built in other applications;

Built or updated by developer within application.

Class acts as a data type and the developer can define variables of this type. The variables are
called objects, containing data and actions. As example, consider the class of Task objects, with
the following fields:

cDenTask: task name;

cTipTask: task category;

cResTask: name of responsible task;

cPrioTask: category of task priority.

Fields cDenTask, cTipTask and cResTask are defined by String, and Boolean field is cPrioTask.
All fields are defined with Private modifier [...], which means that access is restricted to source
code developed in the class. Accessing and modifying the fields are made through properties
DenTask, Tip Task, ResTask and PrioTask.
Public Class Task
Fields
Private cDenTask As String
Private cTipTask As String
Private cResTask As String
Private cPrioTask As Boolean
Properties class Task
Property field cDenTask
Public Property DenTask()
Get
Return cDenTask
End Get
Set(ByVal value)

92

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

CDenTask = value

Notes

End Set
End Property
Property field cTipTask
Public Property Tip Task()
Get
Return cTipTask
End Get
Set(By Val value)
CTipTask = value
End Set
End Property
Property field cResTask
Public Property ResTask()
Get
Return cResTask
End Get
Set(By Val value)
cResTask = value
End Set
End Property
Property field cPrioTask
Public Property PrioTask()
Get
Return cPrioTask
End Get
Set(By Val value)
cPrioTask = value
End Set
End Property
function in class Task
Public Function ModificaPrioritate(By Val prioNou As
Boolean) As
StringcPrioTask = prioNou
Dim res As String
res = It was modified the task priority for value &_
CPrioTask & !
Return res

LOVELY PROFESSIONAL UNIVERSITY

93

Modern Programming Tools & Techniques-III

Notes

End Function
example constructor without parameters
Public Sub New()
cDenTask = New Task
cTipTask = Type New Task
cResTask = Responsible New Task
cPrioTask = False
End Sub
overloading constructor - version constructor with
parameters
Public Sub New(By Val denT As String, By Val tipT
As String, _
By Val resT As String, By Val prioT As Boolean)
cDenTask = denT
cTipTask = tipT
cResTask = resT
cPrioTask = prioT
End Sub
End Class
Besides the fields and properties, the class Task defined above contains a method called
ModificaPrioritate built as a procedure of type Function and two overloaded constructor methods.
Constructor method is special, being implemented by the procedure Sub New. Code of constructor
method is executed before the rest of the code defined in the class of objects.
When the objects are not used, they are destroyed through the reference-tracing garbage collection
system. Destruction of objects is based on special method called destructor and implemented by
the procedure Sub Finalize. Unlike the constructor method, destructor is not called explicitly,
the system dealing with automatic dialing of destructor.

5.2.1 Creating an Object from a Class


Our function is not much use until we can get it up and running. (Here, Get it up and running
means create an object from our class.) To do that, double click the button on your Form, and
add the following code to it:
Dim NewCode As String
Dim objConvertPostcode As ConvertPostcode
objConvertPostcode = New ConvertPostcode
NewCode = objConvertPostcode.DoConvert(TextBox1.Text)
TextBox1.Text = NewCode
The first line just sets up a new String variable called NewCode. Whatever is returned from our
function will be stored inside of this variable.
The next line is where the action starts:
Dim objConvertPostcode as ConvertPostcode

94

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

The variable name objConvertPostcode is just something we made up ourselves. The obj prefix
means Object, and this is for our benefit, to remind us that the type of data inside it holds an
Object, rather than a plain old Integer or String.

Notes

After you type the word As, and then hit your spacebar, you will see a popup box appear.
If you type the letters conv, you will see the list automatically move down. The Class your
created should be on that list, as in the next image:

You can double click the name of your Class to add it to your code.
But what you are doing in this step is setting up a pointer to your Class. You are telling VB where
the Class can be found, and then storing this inside of the variable called objConvertPostcode.
If VB does not know where your Class is then it cannot create an Object from it.
The next line of code is the one that creates a new object from your Class:
objConvertPostcode = New ConvertPostcode
You type the Name of your variable first, then an equals sign. To the right of the equals sign
comes the word New. This is what tells VB to create a New Object. And the class its creating
the New Object from is the one called ConvertPostcode.
You can actually type all of that on the same line:
Dim objConvertPostcode As ConvertPostcode = New ConvertPostcode
This does two jobs: sets a pointer to where the Class is, and creates a new Object from the Class.
But there are reasons why you do not want to do it this way. One is that Objects take up space
in memory. And you only really need to create them when they are needed. For example, what
if the textbox was blank? You would want to check for this and invite the user to try again. If
you have written everything on one line, then you have already created the Object before the
Textbox has been checked. Instead, you could do something like this:
If TextBox1.Text = Then MsgBox Please try again
Exit Sub
Else
objConvertPostcode = New ConvertPostcode
End If
Here is, the textbox is being checked first. If the user has left it blank then we bail out. If not,
THEN we create an Object from our Class.

LOVELY PROFESSIONAL UNIVERSITY

95

Modern Programming Tools & Techniques-III

Notes

The next line in our code was this:


NewCode = objConvertPostcode.DoConvert(TextBox1.Text)
First, we type the name of the variable we want to store the result of our Method into. In our
case, the one called NewCode. After the equals sign, we type the name of our Object variable:
objConvertPostcode
As soon as you type a full stop after your Object variable, you should see a popup box with the
name of your new method on the list:

The image above shows you that the name of our Method Do Convert has been recognized
by VB. (You can tell It is a Method because of the purple block next to it.) But notice the tool
tip - It is the first line from our Function!
In between the round brackets, VB is telling us what type of data needs to be passed over to the
Method - a String of text. The second As String tells you that the Method returns a value that
needs to be stored somewhere. So if you have set up a Method that returns a value (a Function)
then you need to store it in a variable.

5.3 Conversion Functions


Visual Basic contains built-in conversion functions that handle the conversion of date and time,
character strings, numbers and more. Some of these functions compile so that the expression
evaluation code contains the conversion code, which can result in improved performance. The
functionality of some of the conversion functions is contained in Visual Basic built-in methods
such as ToString().

5.3.1 Type Conversion Functions


Mixed mode assignment statements were shown in a previous topic (i.e., a string was assigned
to an integer; a single was assigned to a string, etc.). VB would perform the necessary conversions
in these cases wherever it could. Such conversions are called implicit conversions.
In VB, you can also use a set of functions that explicitly convert (or cast) one type of data
to another. The set of functions that enable you to do this all begin with the letter C: CBool,
CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, and CVar. In addition, two older
functions, Val and Str, enable you to convert from a string to a number and from a number to
a string, respectively. Each function is described below:
CBool l takes any valid expression and converts it to Boolean. Values of zero convert to False,
all others to True. If the expression is String, it must be a string that can be converted to
a number (like 123). The strings True and False will also work; any other string
will result in an error.

96

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

blnTest = CBool(50) blnTest = True


blnTest = CBool(0) blnTest = False

blnTest = CBool(26) blnTest = True

blnTest = CBool(True blnTest = True

blnTest = CBool(False) blnTest = False

blnTest = CBool(ABC) *** Error ***

CByte

converts an expression to a Byte data type. The value of the expression is


rounded up, must not exceed 255, and must not be negative.

Notes

bytX = CByte(125.5678) bytX = 126



bytX = CByte(300.99) error


CCur

converts an expression to a Currency data type. The expression must be a


number (or a string representation of a number) that is with the Currency
range. The result is rounded off at the 4th digit after decimal point.

Examples: CurX = CCur(1234.56789) curX = 1234.5679

CurX = CCur(1234.56782) curX = 1234.5678


CDate

converts a numeric or string expression to a Date data type. (For numeric


expressions, 0 represents the date 12/30/1899. Negative values represent
dates before 12/30/1899; positive values represent dates after. The decimal
portion of a number represents the time for example, .5 = noon.) Numeric
or string arguments outside of the range of the Date data type (1/1/100 thru
12/31/9999) results in an error.

Examples: dtmTest = CDate(1/1/2000) dtmTest = 1/1/2000

dtmTest = CDate(January 1, 2000) dtmTest = 1/1/2000

dtmTest = CDate(123) dtmTest = 5/2/1900

dtmTest = CDate(123.456) dtmTest= 5/2/1900 10:56:38aAM

dtmTest = CDate(ABC) error

CDbl

converts an expression to a Double data type. The expression must be a number


(or a string representation of a number) that is within the Double range.
DblTest = CDbl(1058.930) dblTest = 1058.93

CDec

converts an expression to a Decimal data type. The expression must be a


number (or a string representation of a number) that is within the Decimal
range (roughly, a 29 digit number with a varying decimal point).

The Decimal data type is not a stand alone VB data type and can only be used
with Variant data types.

The following example stores the Decimal representation of 123.456 in vntDecValue and tells
VB to use the Decimal sub-type with the Variant variable vntDecValue:
VntDecValue = CDec(123.456)

LOVELY PROFESSIONAL UNIVERSITY

97

Modern Programming Tools & Techniques-III

Notes

c onverts an expression to an Integer data type. The expression must be a number (or a
string representation of a number) that is within the Integer range. Values with digits
after the decimal point are automatically rounded to the nearest integer.

CInt

IntX = CInt(-1.2) intX = 1


IntX = CInt(-1.9) intX = 2

IntX = CInt(3.69) intX = 4

IntX = CInt(3.3) intX = 3

CLng

converts an expression to a Long data type. The expression must be a number


(or a string representation of a number) that is within the Long range. Values
with digits after the decimal point are automatically rounded to the nearest
integer.
lngX = CLng(-1.2) lngX = 1

lngX = CLng(-1.9) lngX = 2

lngX = CLng(3.69) lngX = 4

lngX = CLng(3.3) lngX = 3

CSng

converts an expression to a Single data type. The expression must be a number


(or a string representation of a number) that is within the Single range.
SngTest = CSng(1058.930) sngTest = 1058.93

CStr

converts a variable of any data type to a string. If the argument is a Date, the
short format date (m/d/yy) is returned. If the argument is Boolean, the
string True or False is returned. If the argument is a number, a string
representation of the number is returned.

Examples: dtmTest = #08/02/2001#

blnTest = False

sngTest = 123.456

strTest = CStr(dtmTest) strTest = 8/2/01

strTest = CStr(blnTest) strTest = False

strTest = CStr(sngTest) strTest = 123.456

CVar

converts a variable to a Variant. If the argument is numeric, the result is a


Double; for non-numeric values, the result is a String.

5.3.2 Val Function


The Val function is a more generic (and less efficient) way to convert a string to a number.
Technically, it returns a Double data type. It strips all blanks from a string argument and then
converts the remaining characters to a number. The Val function recognizes a leading sign, digits,
and a decimal point as part of a number; it will stop scanning the string at the first character
that cannot be considered part of a number. If the string cannot be converted to a number, 0
will be returned.
Examples: lngX = Val(1615 198th Street N.E.)

98

lngX = 1615198

intX = Val(2457)

intX = 2457

intX = Val(2457)

intX = 2457

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

IntX = Val(24 and 57)

intX = 24

sngX = Val(1234.56)

sngX = Val(1,234.56)

sngX = 1

dblX = Val(ABC)

dblX = 0

Notes

sngX = 1234.56

Although less efficient than the Cxxx functions, one advantage to using Val is that if the string
argument cannot be converted to a number, Val will simply return 0, whereas the equivalent
Cxxx function would return a Type Mismatch error.
The Str(or Str$) Function
The Str function is an older function (dating back to earlier versions of BASIC) that converts a
number to a string. When numbers are converted to strings, a leading space is always reserved
for the sign of number. If number is positive, the returned string contains a leading space and the
plus sign is implied. The Str function recognizes only the period (.) as a valid decimal separator.
Examples: Dim strTest As String

strTest = Str$(123) Returns 123.

strTest = Str$(123.45) Returns 123.45.

StrTest = Str$(789.001) Returns 789.001.

Conversion Classes
You can convert one data type to another type using the Convert class. The Convert class has a
number of static methods, beginning with To and ending with the target data type for example,
ToInt32 or ToByte. If successful, the returned instance is an object of the target data type. Not
all Strings and Arrays 645 conversions will be possible when using the Convert method, so use
a try-catch block if you think you may get uncertain results.
Example of Convert Class:
Imports System.Collections.Generic
Imports System.Linq
Imports System. Text
Module Conversion Class
Sub Main()
Dim intExample As Int32 = 19
the methods inside convert
Console.WriteLine(Convert.ToString, result = {0},
Convert.ToString(intExample)) Console.WriteLine(Convert.
ToBoolean, result = {0}, Convert.ToBoolean(intExample))
displays True
Console.WriteLine(Convert.ToByte, result = {0}, Convert.
ToByte(intExample)) Console.WriteLine(Convert.ToChar,
result = {0}, Convert.ToChar(intExample)) Console.
WriteLine(Convert.ToDouble, result = {0}, Convert.
ToDouble(intExample)) Console.ReadLine()
End Sub
End Module
Output:

LOVELY PROFESSIONAL UNIVERSITY

99

Modern Programming Tools & Techniques-III

Notes

If you want to convert strings into dates, you can use the Parse method for the DateTime data
type or you can use the ToDateTime method. Both achieve the same objective. Because users
sometimes incorrectly enter dates, do not forget to include appropriate exception handling to
make sure that any conversion errors are caught. If you want to provide more control over
parsing a date, use the Parse Exact method.
CultureInfo Class
As shown in below example, the CultureInfo class contains cultural information like Display
Name, Calendar, and various official abbreviations.
CultureInfo Class

Imports System.Collections.Generic

Imports System.Linq

Imports System. Text

Imports System. Globalization

Module Conversion Class

Sub Main()

Dim c As New CultureInfo(tr)

Console.WriteLine(The
c.DisplayName)

Console.WriteLine(The parent culture is: {0}, c.Parent.


DisplayName) Console.WriteLine(The three letter ISO
language name is: {0}, ThreeLetterISOLanguageName)

Console.WriteLine(The default calendar for this culture


is: {0} & vbLf & vbLf, Calendar.ToString())

CultureInfo

Console.ReadLine()

End Sub

End Module

Output:
100

LOVELY PROFESSIONAL UNIVERSITY

is

set

to:

{0},

Unit 5: In Built Functions

Notes

As demonstrated in below example, the Region Info class contains regional


information, including Display Name, currency information, and official
abbreviations. Region Info also contains a static property to retrieve the
Current Region.
Region Info Class:

Imports System.Collections.Generic

Imports System.Linq

Imports System. Text

Imports System. Globalization

Module Conversion Class

Sub Main()

Dim r As New Region Info(tr)Console.WriteLine(The name


of this region is: {0}, r.Name)

Console.WriteLine(Is this region metric : {0} & vbLf


& vbLf, r.IsMetric) Console.ReadLine()

End Sub.

End Module.

Write the program in Val Function in VB .NET.

Self Assessment Questions


Multiple Choice Questions

1. The Val function is a more generic (and less efficient) way to convert a string to a ..............

(a) variable

(b) single number

(c) number

(d) more number

2. The Input Box() function displays a .............. input box into which the user can type a
message.

(a) push-up

(b) pop-up

(c) Both (a) and (b)

(d) None of these

3. The expression must be a number (or a string representation of a number) that is within
the ....................

(a) short range

(b) long range

(c) middle range

(d) None of these

True or False
4. The title parameter is another string literal or string variable that supplies the title for the
input box.

(a) True

(b) False
LOVELY PROFESSIONAL UNIVERSITY

101

Modern Programming Tools & Techniques-III

Notes

5. The String type represents a string of Unicode Characters.

(c) True

(d) False

5.4 Miscellaneous Functions


In given the List of miscellaneous Function in VB .Net.
SNo Function Name

102

Category

Return Type

1.

CallByName Function

Miscellaneous Function

Variant

2.

Choose Function

Miscellaneous Function

Variant

3.

Command Function

Miscellaneous Function

Variant(String)

4.

CreateObject Function

Miscellaneous Function

Object Reference

5.

DoEvents Function

Miscellaneous Function

Integer

6.

Environ Function

Miscellaneous Function

String

7.

Error Function

Miscellaneous Function

Error

8.

GetAllSettings Function

Miscellaneous Function

Array

9.

GetAutoServerSettings Function Miscellaneous Function

Array

10.

GetObject Function

Miscellaneous Function

Object Reference

11.

GetSetting Function

Miscellaneous Function

Variant

12.

IIf Function

Miscellaneous Function

Variant

13.

IMSStatus Function

Miscellaneous Function

Integer

14.

InputBox Function

Miscellaneous Function

String

15.

IsEmpty Function

Miscellaneous Function

Boolean

16.

IsError Function

Miscellaneous Function

Boolean

17.

IsMissing Function

Miscellaneous Function

Boolean

18.

IsNull Function

Miscellaneous Function

Boolean

19.

IsNumeric Function

Miscellaneous Function

Boolean

20.

IsObject Function

Miscellaneous Function

Boolean

21.

LoadPicture Function

Miscellaneous Function

Picture

22.

LoadResData Function

Miscellaneous Function

Array

23.

LoadResPicture Function

Miscellaneous Function

Picture

24.

LoadResString Function

Miscellaneous Function

String

25.

MsgBox Function

Miscellaneous Function

Integer

26.

Partition Function

Miscellaneous Function

Variant(String)

27.

QBColor Function

Miscellaneous Function

Long

28.

RGB Function

Miscellaneous Function

Long

29.

Rnd Function

Miscellaneous Function

Single

30.

Shell Function

Miscellaneous Function

Variant(Double)

31.

Spc Function

Miscellaneous Function

String

32.

Switch Function

Miscellaneous Function

Variant

33.

Tab Function

Miscellaneous Function

String

34.

TypeName Function

Miscellaneous Function

String

35.

VarType Function

Miscellaneous Function

Integer

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

5.5 Subroutines and Functions

Notes

A subroutine would be code that is reused, like a shop in a game. Every time the user goes to
the shop, the program will go back to the Shops Subroutine, and if the user bought an item, it
would call a Buy Item function. The purpose of a function is to take in a number of values or
arguments, do some calculations with those arguments and then return a single result.
Maurice Wilkes, David Wheeler, and Stanley Gill are credited with the
invention of the concept of subprogram, which they termed a closed subroutine.

5.5.1 Subroutine
A subroutine is a code construct.
A code construct is a pattern of coding. Examples;- For Loops, Do Whiles Loops, Sub ... End
Sub, Function .... End Function
A subroutine is a self contained section of code, that;Has Inputs: Possible
Has Output: Never
1

Private sub PrintHelloWorld()

Console.WriteLine(Hello World)

End Sub

Where you put your code to handle a button click is particular type of subroutine called An
Event Handler
Indicated by the Handles Button1.Click.
1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal


e As System.EventArgs) Handles Button1.Click

Functions
A function is a self contained section of code, that:
Has Inputs: Generally Yes
Has Output: Always
1

Function SquareOfNumber(ByVal As Decimal) As Decimal

Return x * x

End Function

Subroutines and Functions may contain calls to other Functions and Subroutines.
01

Function Factorial (ByVal As Decimal) As Decimal

02

Dim f As Decimal = 1

03

While x > 1

04

f = f * x

05

x -= 1

06 End While
07 Return f
08

End Function

09

LOVELY PROFESSIONAL UNIVERSITY

103

Modern Programming Tools & Techniques-III

Notes

10

Function FactorialSquared(ByVal x Decimal) As Decimal

11

Return SquareOfNumber(Factorial(x))

12

End Function

That is the basics of Functions and Subroutines.


For the more the adventurous what all the arguments of the preceding Functions and Subroutines
have in common?
All the arguments are preceded by a ByVal.
There are two basic types (the object type of the arguments excluded) of argument.

By Val This a copy of the object passed in. You can do what you like to this and it would
not change the original object passed in as the argument.

ByRef This Reference to the actual object. What you do to this affects the original object
passed in as the argument.

A ByRef argument allows the programmer to get information out of a Subroutine, like a Function
Example (Trivial): Increase the value of two Doubles by 2.
1

Public Sub IncreaseBothBy2(ByRef A As Double, ByRef B As


Double)

2 A+=2
3 B+=2
4

End Sub

Example: Clear the text of any textbox.


1

Sub ClearTextbox(ByRef Tb As Textbox)

Tb. Text =

End Sub

Why Use Subroutines?


You may ask yourself why subroutines would even be used. Why would not you simply
put all of your code in one place? Subroutines are useful because they eliminate redundancy.
Consider a complicated program like a word processor. When certain actions are performed,
such as closing the program, opening a file, or closing an individual file, the word processor
would probably check to see if you had modified your document. If the user had modified the
document since they opened it, the user would be prompted to save the file before performing
the action. You could imagine that checking if the document was modified, prompting the user,
and acting on the input would require many lines of code. If the programmer had literally typed
this code into all of the places in the program where this check was to be made, it would still
work fine. However, what would happen if the way the program handles documents changed,
and therefore this code needed to be changed? The programmer would have to change the
code in every place where this check was made. Even worse, what if the programmer changed
the code in a few places but not in another? This would lead to bugs that are difficult to track
down. Instead, if this code was put in a subroutine, the subroutine would simply be called from
all of these places. If the code then needed to be changed, the programmer would only have to
change it in one place; inside the subroutine. By doing this, subroutines eliminate redundant
code, making the entire program easier to manage.

104

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

To avoid from error in the program, do not call a subroutine from within
another program.

Notes

Implementing Subroutines with Arrays

e are going to implement a function that passes an array. This function is called
findMin which finds the minimum value in an array.

findMin
Here is a simple C function that finds the minimum value of an array of n values passed
in, and returns it.
int findMin( int arr[], int n ) {
int min = arr[ 0 ] ;
int i ;
for( i = 0 ; i < n ; i++ )
{
if( arr[ i ] < min )
min = arr[ i ] ;
}
return min ;
}
Arrays are really just pointers, and in MIPS, pointers are 32 bits (at least, MIPS R2000/
R3000---later MIPS CPUs use 64 bits of addresses). Thus, we can pass the pointers using the
argument registers since those registers can store 32 bits.
It is often quite convenient that registers store the same number of bits as addresses.
Implementation
Here is the implementation in MIPS. We assume arr is stored in $a0 and n is stored in $a1.
We use $t0 to store min and $t1 to store i. Notice this is a leaf procedure. So, we would not
use the stack. Also notice that loading a word at the address stored in $a0 access arr[ 0 ].
findMin:

lw $t0, 0($a0) # min = arr[0]

li $t1, 0 # i = 0

LOOP:

bge $t1, $a1, END # branch ! (i < n)

add $t2, $t1, $t1 # t2 = 2 * i

add $t2, $t2, $t2 # t2 = 4 * i

add $t2, $t2, $a0 # t2 = arr + (4 * i)

lw $t3, 0( $t2 ) # t3 = arr[ i ]

bge $t3, $t0, INCR # branch ! (arr[i] < min)


Contd...

LOVELY PROFESSIONAL UNIVERSITY

105

Modern Programming Tools & Techniques-III

Notes

move $t0, $t3 # min = arr[i]

INCR:

addi $t1, $t1, 1 # i++

j LOOP # back to top of loop

END:

move $v0, $t0 # retval = min

jr $ra # return

The awkward part is computing the address of the array element. Recall that & arr[ i ] is
arr + ( sizeof(int) * i ) where we assume sizeof(int) is 4 bytes. Thus, we must compute 4 * i.
There are two ways to do this. Multiply by 4 (which involve some complications of its own)
or add the number to itself twice (which seems awkward).
Also notice where the branch statement for the if-statement goes. If the condition is false,
it jumps to the increment.
Making the Call
How do we call findMin? If arr is a label which is conveniently declared in the data segment,
then all we do is something like:
la $a0, arr # set arg 0
li $a1, 10 # set arg 1
jal findMin
move $t0, $v0 # save return value to $t0
findMin, version 2
This is the same function as before, at least, in the purpose of the function. It finds the
minimum value in an array and returns it.
int findMinTwo( int * arr, int n ) {
int min = * arr ;
int i ;
for( i = 0 ; i < n ; i++ )
{
if( *arr < min )
min = * arr ;
arr++ ; // POINTER ARITHMETIC: Move arr forward 1 element
}
return min ;
}
The difference in this version is that we treat the arr as a pointer variable, and move the
pointer forward one element at a time.
In the first version, findMin, we did not alter arrs value. Instead, each iteration, we computed
the offset from the start of the array to element i of the array. We summed the offset and
arr and storing the sum into a temporary register. Then, we loaded the array element from
the address stored in this temporary register.
Contd...

106

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

As you can see, the first version is more complicated to explain and implement in MIPS,
even though it is somewhat easier to understand the array version than the pointer version
(because most people understand arrays better than pointers, even though, in C, the two
are related to one another).

Notes

Implementation
Here is the implementation in MIPS. We assume arr is stored in $a0 and n is stored in $a1.
We use $t0 to store min. This version is somewhat simpler because we modify arr, which we
did not do before, and we do not need to do the more difficult computations of addresses
as in the previous version.
findMinTwo: lw $t0, 0($a0) # min = arr[0]

li $t1, 0 # i = 0

LOOP:

bge $t1, $a1, END # branch ! (i < n)

lw $t2, 0( $a0 ) # t2 = * arr

bge $t2, $t0, INCR # branch ! (*arr < min)

move $t0, $t2 # min = * arr

INCR:

addi $a0, $a0, 4 # Move arr forward 1 element

addi $t1, $t1, 1 # i++

j LOOP # back to top of loop

END:

move $v0, $t0 # retval = min

jr $ra # return

This code is shorter and more efficient than the array version. This is one reason why a good
knowledge of pointers can help you write more efficient code. However, realize the tradeoffs
between efficient code, and code that is easy to follow and maintain.
Questions
1. What you understand with this case?
2. Implement a subroutine with the arrays.

Self Assessment Questions


Multiple Choice Questions

6. Visual Basic .NET has built-in functions for manipulating text and carrying
out mathematical operations.

(a) single

(b) many

(c) double

(d) None of these

7. The MsgBox () function displays a message in a . message box.

(a) push-up

(b) pop-up

(c) both

(d) None of these

8. Destruction of objects is based on special method called .

(a) constructor

(b) destructor

(c) reflector

(d) None of these

LOVELY PROFESSIONAL UNIVERSITY

107

Modern Programming Tools & Techniques-III

Notes

9. VB would perform the necessary conversions in these cases wherever it could. Such
conversions are called ..

(a) Implicit Conversions

(b) Explicit Conversion

(c) Internal Conversion

(d) None of these

10. CDate converts a numeric or expression to a Date data type.


(a) Int

(b) Float

(c) Double

(d) String

11. CBool takes any valid expression and converts it to


(a) Boolean

(b) Int

(c) Double

(d) String

12. CByte converts an expression to a Byte data type. The value of the expression is rounded
up, must not exceed ., and must not be negative.

(a) 233

(b) 255

(c) 254

(d) 355

13. The Str function is an older function (dating back to earlier versions of BASIC) that
converts .

(a) number to a string

(b) numeric to double

(c) numeric to int

(d) None of these

14. CCur converts an expression to a data type.


(a) Currency

(b) Int

(c) Float

(d) String

15. Constructor method is called to create the .


(a) Object

(b) Class

(c) both

(d) None of these

5.6 Summary

108

A procedure is referred to as built-in if it shipped with its programming language.

The Visual Studio team saw a good opportunity to implement, deploy, and showcase a
real-world site using .NET technologies.

A Web site, http://beta.visualstudio.net, was created as the central location to gather this
information, collect bug reports from users, and distribute updated information to the beta
test sites.

The str function is an older function (dating back to earlier versions of BASIC) that converts
a number to a string.

Visual Basic contains built-in conversion functions that handle the conversion of date and
time.

The log files generated allow the development team to further streamline the development
to address actual customer usage needs.

LOVELY PROFESSIONAL UNIVERSITY

Unit 5: In Built Functions

5.7 Keywords

Notes

Boolean: A Boolean stores a value indicating True or False. It can be used as an expression
in an If-statement. It can also store the result of an expression. Booleans are used throughout
VB.NET programs.
Converting between Data types: In Visual Basic, data can be converted in two ways: implicitly,
which means the conversion is performed automatically, and explicitly, which means you must
perform the conversion.
String-handling: String handling is the use of various methods to manipulate a string into a
form that a program needs it in .You will already know that a string is a variable that stores text.
Subroutines: Subprogram is a part of source code within a larger computer program that performs
a specific task and is relatively independent of the remaining code.
Create a sub routine.

5.8 Review Questions


1. What is the String-handling?

2. Explain the subroutines.

3. Define Str function.

4. Describes the Val function with example.

5. Discuses the MsgBox function.

6. Describe in detail the Subroutines and Functions.

7. Define CBool.

8. How many types of conversion functions.

9. Write the five names miscellaneous functions.

Answers for Self Assessment Questions


1. (c)

2. (b)

3. (b)

4.

(a)

5.

(a)

6. (b)

7. (b)

8. (b)

9.

(a)

10.

(d)

11. (a)

12. (b)

13. (a)

14.

(a)

15.

(a)

5.9 Further Reading


VB.NET Language in a Nutshell, by Steven Roman, Ron Perusal, Paul Lomax.

http://books.google.co.in/books?id=bMiCJU1KY5MC&printsec=frontcover
&dq=vb.net&hl=en&sa=X&ei=EML_T7W_Ms3QrQfUqLyKBg&sqi=2&ved=
0CHgQ6AEwCQ#v=onepage&q=vb.net&f=false

LOVELY PROFESSIONAL UNIVERSITY

109

Modern Programming Tools & Techniques-III

Unit 6: Classes and Object in VB.NET

Notes

CONTENTS
Objectives
Introduction
6.1

Using Classes, Object, Methods

6.1.1

Uses for Classes

6.1.2

Create a Class

6.1.3

Creating an Object from a Class

6.1.4

Create a Method

6.2 Constructor
6.3

Creating Properties and Indexers

6.3.1

Creating Properties

6.3.2

Creating Indexer

6.4

Using Inheritance in Classes

6.4.1

Importing in Class

6.5 Summary
6.6 Keywords
6.7

Review Questions

6.8

Further Readings

Objectives
After studying this unit, you will be able to:

Define classes, objects, methods

Explain the constructors

Define the properties and indexers

Describes the inheritance in classes

Introduction
Visual Basic is an object-oriented programming language. An object encapsulates both data and
the methods (procedures) that act on the data. The details of the data structures used and the
implementation of the methods are hidden within the object. All the programmer needs to
know is what tasks the object can perform, and the parameters required by the object in order
to perform those tasks. Visual Basic controls (i.e. those found in the Toolbox) are predefined
objects, and include Labels, Textboxes, Buttons and other controls. No matter how many textboxes
you create on a form, for example, they all have the same properties and methods. Essentially,
a class is a template from which an object is created, and specifies the properties and methods
that will be common to all objects of that class. Each textbox you place on a form is therefore
an instance of the class Textbox, for which you can set properties and invoke methods.

110

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

The value of a property can be manipulated by two kinds of procedure - one to set the value and

Notes

the other to get the value. Such procedures are sometimes referred to successor methods. Objects
can be created by the programmer as instances of user-defined types (classes) that are defined
in a separate class module. Like standard VB controls, they have properties and methods and
can respond to events. The set of properties, methods, and events for a particular class is called
the class interface. Two (or more) different classes may have the same interface, and carry out
identical tasks, even though they carry out the task differently. The occurrence of two or more
classes that have behaviors with the same name and functionality but different implementations
is called polymorphism.
Applications communicate with objects through the properties and methods they expose, and the
events they raise. When you program with Visual Basic, you are working with objects (such as
the controls you place on a form) by manipulating their properties and calling their methods.
The action takes place within the objects event procedures, which are executed in response to
the occurrence of some event. Events are said to be raised (in other words they are considered
to have occurred) when certain conditions are met.
A class means collection of methods/functions. Method/function accepts parameters; process
set of codes which you have written in the module/function and returns the output to the caller.
Collection of class is called Class Library. When you compile the Class Library it becomes a DLL.
A class in VB.Net is declared using the keyword Class and its members are enclosed with the
End Class marker. A class is simply an abstract model used to define new data types. A class
may contain any combination of encapsulated data (fields or member variables), operations that
can be performed on the data (methods) and accessors to data (properties).
The general syntax of a class looks as following:
public Class test
.....Variables
.....methods
.....properties
.....events
End Class
The above syntax created a class named Test. Fields, Properties, Methods, and Events are members
of the class. They can be declared as Public, Private, Protected, Friend or Protected Friend.
Fields and Properties represent information that an object contains. Fields of a class are like
variables and they can be read or set directly. For example, if you have an object named House,
you can store the numbers of rooms in it in a field named Rooms. Properties are retrieved and
set like fields but are implemented using Property Get and Property Set procedures which
provide more control on how values are set or returned.
Methods represent the objects built-in procedures. For example, a Class named Country may
have methods named Area and Population. You define methods by adding procedures, Sub
routines or functions to your class. For example, implementation of the Area and Population
methods discussed above might look like this

LOVELY PROFESSIONAL UNIVERSITY

111

Modern Programming Tools & Techniques-III

Public Class Country

Notes

Public Sub Area()


Write(--------)
End Sub
Public Sub population()
Write(---------)
End Sub
End Class
Objects are instance of the class. Classes and Objects are very much related to each other. Without
objects you cannot use a class. To create an object for this class we use the new keyword and
that looks like this: Dim obj as new Test().
The following code defines the Class and Objects in VB.NET:
Module Module1

Public Class test define class test

Dim a As Integer = 5

Dim b As Integer = 6

Dim c As Integer

Sub add()

c=
a+b

Console.Write( addition of two number :=)

Console.WriteLine(c)

End Sub

End Class

Sub Main()

Dim obj As New test()


obj.add() creating a Object obj for test class

End Sub

End Module
In this example test define the Class and obj defines the objects of class test.

6.1 Using Classes, Object, Methods


Object-Oriented Programming (OOP) is a method of software design and construction. It is the
next logical progression, after structured programming, to improve your code reusability and
maintainability. Put another way, OOP is a method of designing individual software components
(classes) with associated behaviors (methods) and data limitations (properties), and that helps
you piece these components together to create a complete application.
The best thing about OOP is that it allows you to group data into discrete variables contained
within a class in your program. This data is separate and distinct from any other class in your
application. No class can interfere with the data in any other class without going through a
specific interface on that class.
Each object defines its functionality as a set of properties and methods that it will respond to.
Other code can call these methods on the object and have them perform some behavior and
use the properties to retrieve or change some information. In this way, code cannot affect the

112

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

information or processes of other objects directly. As you build a class, you will see how to build
this functionality using properties and methods.

Notes

6.1.1 Uses for Classes


Classes are the heart and soul of an object-oriented language. You will find yourself using
classes whenever you write even the simplest of programs in Visual Basic .NET. The Microsoft
.NET Framework makes extensive use of classes, and so should you. Below are some common
uses of classes:

Wrapping up the representation and set of operations you perform on a database table,
for example adding, editing, deleting, and retrieving data.

Wrapping up the set of operations and data for dealing with text files such as reading,
writing, and indexing the lines of text within the file.

Wrapping up all global variables in a program into properties within a class. This can
help with keeping track of the amount of free-floating global that somehow seem to
work their way into many programs.

6.1.2 Create a Class


Let us create a class representing a line of text. To do this, you create a property to return the
line of text and a read-only property that returns the length of the text. You will also create a
method that returns the first word in the line. As you perform all of these steps, you will learn
the correct way to create a class. You will build a form like the one shown in Figure 6.1 to test
the Line class as you build it.
Figure 6.1: This Form Allows Testing Each Property and Method of Line class

To Create the Form


1. Open Visual Studio .NET.

2. Select Visual Basic Project from the tree-view on the left-hand side of the screen.
3. Select Windows Application as the project template.
4. Set the name of the application to Class Creation.

5. In the Solution Explorer window, select the Form1.vb form and rename it to frmLineTest.
vb. To rename a form in the Solution Explorer window, right-click the form and choose
Rename on the shortcut menu.

6. Create the form shown in Figure 6.1 by adding the appropriate controls and setting the
properties of those controls as outlined in Table 6.1.

LOVELY PROFESSIONAL UNIVERSITY

113

Modern Programming Tools & Techniques-III

Notes

Table 6.1: Controls Used to Build the Form to Test the Line Class
Control Type

Property

Value

Label

Name

Label1

Text

Line of Text

Name

txtLine

Text

The rain in Spain stays


mainly in the plain

Name

btnDisplay

Text

Display Length

Name

txtLength

Read only

True

Name

btnGetWord

Text

Get Word

Name

txtWord

Textbox

Command Button
Textbox
Command Button
Textbox

Text
Read Only

True

To create the Line class


1. Open the Add New Item dialog box by clicking Project and then clicking Add Class.
2. Set the Name property to Line and click OK.

3. You will now see a new file appear in your project and a code window within the Visual
Studio .NET environment. In the Code window, there will be some code that looks like
this:
Public Class Line
End Class

All of the properties and methods that create for this class must be entered between these lines
of code.
6.1.3 Creating an Object from a Class
Our function is not much use until we can get it up and running. (Here, Get it up and running
means create an object from our class.) To do that, double click the button on your Form, and
add the following code to it:
Dim NewCode As String
Dim objConvertPostcode As ConvertPostcode
ObjConvertPostcode = New ConvertPostcode
NewCode = objConvertPostcode.DoConvert (TextBox1.Text)
TextBox1.Text = NewCode
The first line just sets up a new String variable called NewCode. Whatever is returned from our
function will be stored inside of this variable.
The next line is where the action starts:
Dim objConvertPostcode As ConvertPostcode

114

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

The variable name objConvertPostcode is just something we made up ourselves. The obj prefix
means Object, and this is for our benefit, to remind us that the type of data inside it holds an
Object, rather than a plain old Integer or String.

Notes

After you type the word As, and then hit your spacebar, you will see a popup box appear.
If you type the letters conv, you will see the list automatically move down. The Class your
created should be on that list, as in the next Figure 6.2:
Figure 6.2: ConvertPostcode Function

You can double click the name of your Class to add it to your code.
But what you are doing in this step is setting up a pointer to your Class. You are telling VB where
the Class can be found, and then storing this inside of the variable called objConvertPostcode.
If VB does not know where your Class is then it cannot create an Object from it.
The next line of code is the one that creates a new object from your Class:
ObjConvertPostcode = New ConvertPostcode
You type the Name of your variable first, then an equals sign. To the right of the equals sign
comes the word New. This is what tells VB to create a New Object. And the class its creating
the New Object from is the one called ConvertPostcode.
You can actually type all of that on the same line:
Dim objConvertPostcode As ConvertPostcode = New ConvertPostcode
This does two jobs: Sets a pointer to where the Class is, and creates a new Object from the Class.
But there are reasons why you do not want to do it this way. One is that Objects take up space
in memory. And you only really need to create them when they are needed. For example, what
if the textbox was blank? You did want to check for this and invite the user to try again. If you
have written everything on one line, then you have already created the Object before the Textbox
has been checked. Instead, you could do something like this:
If TextBox1.Text = Then
MsgBox Please try again
Exit Sub
Else
ObjConvertPostcode = New ConvertPostcode
End If

LOVELY PROFESSIONAL UNIVERSITY

115

Modern Programming Tools & Techniques-III

Notes

Here, the textbox is being checked first. If the user has left it blank then we bail out. If not, then
we create an Object from our Class.
The next line in our code was this:
NewCode = objConvertPostcode.DoConvert (TextBox1.Text)
First, we type the name of the variable we want to store the result of our Method into. In our
case, the one called NewCode. After the equals sign, we type the name of our Object variable:
ObjConvertPostcode
As soon as you type a full stop after your Object variable, you should see a popup box with the
name of your new method on the list:
Figure 6.3: DoConvert Function

The image above shows you that the name of our Method Do Convert has been recognized
by VB. (You can tell it is a Method because of the purple block next to it.) But notice the tool
tip it is the first line from our Function!
In between the round brackets, VB is telling us what type of data needs to be passed over to
the Method - a String of text. The second As String tell you that the Method returns a value
that needs to be stored somewhere.
So if you have set up a Method that returns a value (a Function) then you need to store it in a
variable.
To get at the Method inside of your class, first type the name of your Object variable and type
a full stop. Look for the name of your Method in the pop up list that appears.
The final line of the code just assigns the value returned from the Method back to the textbox:
TextBox1.Text = NewCode
Run your code and test it out. Click your Button and you should see the postcode change from
ts1 4jh to TS1 4JH.
The modern concept of object and the object-oriented approach to
programming were introduced by the Simula programming language
originally released in 1967.

6.1.4 Create a Method


A method in a class can be a procedure that performs some sort of operation on the data within
the class. Or a method could be a function that performs some operation on the data, and returns
that data back from the class. To be able to call a method from an instance of this class, the
method must be declared Public. If a method is declared Private, only other methods within
the class can call that method. Creating a method in Visual Basic .NET is exactly the same as
in Visual Basic 6.0.
116

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

Let us create a method in the Line class that breaks up the line of text passed into the class
into each separate word. This method is a function that returns the first word contained in the
line of text you pass in. If you used the string that was given to you when creating the form,
the line of text will be The rain in Spain stays mainly in the plain. In this case, the first word
returned will be The.

Notes

1. Open the Line.vb class in design mode.


2. Just below your. Property statements, create the following method:

3. Public Function GetWord() As String

4. Dim astrWords() As String

5.

6. astrWords = Split(mstrLine, )

7.
8. Return astrWords(0)

9. End Function

The GetWord method converts the string to an array of individual words using the Split function.
The Split function has been around since Visual Basic 6.0 and is passed a string and a delimiter
to find. Split starts with the first character in the string and continues moving through the string
until it finds the delimiter. Once found, it takes all of the string up to that point and creates a
new array element. It then continues processing the string in this manner until the complete
string has been put into array elements.
After converting the string to an array, you may return any word in the sentence you pass into
the Line class. This example only returns the first word by accessing the first element of the
array. In Visual Basic .NET, all arrays are zero-based just like the default in Visual Basic 6.0.
The difference here is that you cannot make anything other than a zero-based array in Visual
Basic .NET and you could in Visual Basic 6.0.
Note another way you could have written the code to separate the words in the mstrLine variable
into an array is to use the Split method on the String object as shown below.
astrWords = mstrLine.Split(.ToCharArray())
Follow the steps below to try out this new GetWord method you just wrote.
1. Open the frmLineTest form in design mode.

2. Double-click the Get Word button. This will open the code window with the btnGetWord_
Click event procedure created for you.

3. Add the following code to this event procedure, as shown in the example below.

4. Private Sub btnGetWord_Click(ByVal sender As Object,_

5. ByVal e As System.EventArgs)

6.

7. Dim oLine As New Line()

8.

9. oLine.Line = txtLine.Text

10. txtWord.Text = oLine.GetWord()


11.
12. End Sub

LOVELY PROFESSIONAL UNIVERSITY

117

Modern Programming Tools & Techniques-III

Notes

This event procedure first creates a new instance of the Line class into the object variable oLine.
You next set the Line property on the line class by getting the value from the Text property of
the txtLine text box. Finally, you call your new GetWord method and it returns a string value.

6.2 Constructor
Constructors are special methods that provide control over the initialization of Objects.
Any programmer who has worked on OOPs programming will know that there are many
situations in which objects have to be initialized, before use. Where do we come across
the need for initialization of Objects? The common initialization tasks include opening
of files, connecting to a database and reading the values of registry keys. And to use all
member variables and services of the class, we need to instantiate the Class. A constructor
is used in a database application to instantiate the class. One scenario in which we use the
constructor is in the business layer. Assume that we are developing a class (tran class) for
handling the transactions in a database application. The constructor is used in the Tran
Class, to instantiate the class. Database programming using visual basic, c# (c sharp) SQL
server. A constructor is nothing more than a subroutine named New. When the class is
instantiated, New (constructor) is fired. We can place the startup code just like we do in
Form_Load in windows applications and Page_Load in web applications.
The life of an object ends after it goes out of scope or is set to nothing and is released
by the .NET Framework. Visual Basic uses procedure called destructors to control the
release of system resources. Constructors and destructors together support the creation
and destruction of objects.
There are two types of constructors.

Shared constructors

Instance constructors

Shared Constructors
Implementation of Shared constructors are used to initialize the shared variables of a type. Shared
variables are created using the Shared keyword and store values that can be shared by all the
instances of a class. Shared constructors have an implicit public access. A shared constructor
will not run more than once during a single execution of a program. The following example
is an illustration of the shared constructor. Public Class class1 Shared x As Integer Shared Sub
New() x=0 End Sub End Class
We can increment the value of a shared variable in an instance constructor to keep track of the
number of instances created in a class. The following code illustrates the use of a shared variable
within an instance constructor. Sub New x=x+1 MessageBox.Show (Number of instances are:
& i) End Sub to test how shared constructor works, create a form and name it as Form1 and
place a button Button1. Public Class Form1 Inherits System.windows.Forms.Form Private Sub
Button1_Click(ByVal sender As System.Object, Byval e As System.EvenArgs) Handles Button1.
Click
Dim c1 As class1 = New class1 Dim c2 As class1 = New class1 End Sub End Class The above
code illustrates the use of a shared variable within an instance constructor to keep track of the
number of instances of a class.
Instance Constructor
Instance constructors are used to initialize variables that are declared with Dim, Public, Private,
and Friend, Protected, and Protected Friend keywords. Write the following code in the class
module.
118

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

Notes

Public Class ItemClass


Private ItemCode As String
Private ItemName As String
Private ItemDescription As String
Private ItemCategory As String
Private ItemPrice As Single
Private ItemUnit As String
Public Sub New(ByVal Category As string)

ItemCategory = Category

End Sub
End Class
In the Instance Constructor, the statement, ItemCategory = Category assigns Item Category to
class variable ItemCategory. To test how Instance constructor works, create a form and name
it as Form1 and place a button Button1. Public Class Form1 Inherits System.windows.Forms.
Form Private Sub Button1_Click(ByVal sender As System.Object, Byval e As System.EvenArgs)
Handles Button1.Click Dim objItem As New ItemClass(I) End Sub End Class This is how
we can instantiate the Item class which in turn calls the instance constructor. In Visual Basic,
you were unable to pass data when you created a new instance of a class. This meant you had
to create the object, remember to call an initialization method, and pass data to that method.
If you forgot to initialize the object, your object failed. Although you might remember to call
this initialization method, if other programmers used your class, they may not know to call it.
This problem has been solved in Visual Basic .NET as the constructor method can now be passed
data. The constructor method is called New in Visual Basic .NET. By default, Visual Basic .NET
creates this New method for you without you having to do anything. You would not see this
code within your code module, but it is there implicitly. If you wish to pass some data to this
New method, you need to explicitly create it.
You can place the New constructor anywhere within your class, but you might want to choose a
standard location, such as always near the top of your class definition. By doing this, you will be
able to declare, initialize an object variable, and set the data for the Line object, all in one step.
1. Open the Line.vb class in your project.
2. Add the Sub New, as shown below, to your Line class:
3. Public Class Line
4. Private mstrLine As String
5.
6. Public Sub New(ByVal Value As String)

7. mstrLine = Value

8. End Sub

The New constructor is a procedure that you write to accept one or more parameters. In the code
you just wrote, you created a parameter called Value. You then took the value and assigned it
to the private variable mstrLine. Now you need to change the procedures in your form, so you
pass the value from txtLine text box to the constructor.
1. Open your frmLineTest.vb form.

LOVELY PROFESSIONAL UNIVERSITY

119

Modern Programming Tools & Techniques-III

Notes

2. You will need to change both the btnDisplay_Click event procedure and the btnGetWord_
Click event procedures to declare the oLine variable as shown below.

4. Dim oLine As New Line(txtLine.Text)

The New keyword tells Visual Basic .NET to create a new instance of Line and pass the data
that is contained within the Text property of the txtLine text box to the New constructor.
You need to change both event procedures before you can run the project. By changing the
New procedure to accept a parameter, any declaration of the Line class must now pass some
data when declaring the object.

Write a program to create constructor.

Self Assessment Questions


Multiple Choice Questions

1. Implementation of Shared constructors is used to initialize the of a type.

(a) variable

(b) shared variable

(c) value

(d) create variable

2. A constructor is used in a database application to instantiate the ..


(a) class

(b) program

(c) array

(d) data

3. The New constructor is a procedure that you write to accept one or more ...
(a) array

(b) application

(c) value

(d) parameters

4. There are types of constructors.


(a) one

(b) two

(c) three

(d) four

True or False
5. A method in a class can be a procedure that performs some sort of operation on the data
within the class.
(a) True

(b) False

6.3 Creating Properties and Indexers


The syntax for creating a property is fairly simple, but quite different from what you did in Visual
Basic. You first use the keyword Property, followed by a name of the property, and then the
type of data this property will return or set. To return the data contained in the private variable
mstrLine, you use the Get End Get block. This block is like the old Property Get function in
Visual Basic. This block of code executes any code between the Get End Get block and returns
a string value. In Visual Basic .NET, you can use the Return statement to return data.

6.3.1 Creating Properties


To create a property within a class, you can either create a field (i.e. a Public variable), or you
can create a Private variable and expose the Private variable using a Property statement. There
are several reasons why you want to only expose properties through a Property statement.
120

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

You can create a read-only or write-only property, as opposed to a Public variable, which
will always be read-write.

You can add error handling within a Property statement to check for invalid values being
set. You cannot check for invalid values when setting a Public variable because there is
no code that runs in response to setting a Public variable.

You can expose calculated values as properties even if they are not stored as actual data
within the class. An example of this is a Length property. You probably do not want to
store the length of a line of text, as it could change.

Notes

You will now create two properties named Line and Length for the Line class. You will first
create a private variable to hold the line of data that you store within the class. Next, you will
create the Property statements for these two new properties. Modify the class in your project
so it looks like the code shown below.
Public Class Line
Private mstrLine As String
Property Line() As String
Get
Return mstrLine
End Get
Set(ByVal Value As String)
mstrLine = Value
End Set
End Property
ReadOnly Property Length() As Integer
Get
Return mstrLine.Length
End Get
End Property
End Class
The Set End Set block is like the old Property Let procedure you used in Visual Basic. This block
accepts a parameter named Value. Value is the default name that is automatically created for
you by Visual Studio. You can change it if you want. You can take the value passed to this Set
block and place it into your private variable. This is the point where you can place any error
handling code you wish. For example, you might check to make sure that the data passed to the
Value parameter is not filled in with a word like Test. If a junk word is passed in, you might
choose to raise an error that this is not a valid value for this property.
Visual Basic objects can have methods, fields, and properties. If you have worked with Visual
Basic before, you are familiar with properties, which you use to set configuration data for objects,
such as the text in a text box or the width of a list box. Using properties provides you with an
interface to set or get the value of data internal to an object. You declare properties using Get
and Set procedures in a Property statement (and, as you might expect, the syntax has changed
from VB6):
[ <attrlist> ] [Default] [Public | Private | Protected | Friend |
Protected Friend] [ReadOnly | WriteOnly] [Overloads | Overrides]
[Overridable | NotOverridable] | MustOverride | Shadows | Shared]

LOVELY PROFESSIONAL UNIVERSITY

121

Modern Programming Tools & Techniques-III

Notes

Property
Varname ([parameter list]) [As typename] [Implements interfacemember]
[<Attrlist>] Get
[Block]
End Get
[<Attrlist>] Set (ByVal Value As typename)
[Block]
End Set
End Property
Here are the parts of this statement that are different from the keywords used in the Sub
statement. (See the Immediate Solution Creating Sub Procedures):

DefaultMakes this a default property. Default properties can be set and retrieved without
specifying the property name, and must accept parameters.

ReadOnlySpecifies that a propertys value can be retrieved, but it cannot be the modified.
ReadOnly properties contain Get blocks but no Set blocks.

WriteOnlySpecifies that a property can be set but its value cannot be retrieved. WriteOnly
properties contain Set blocks but no Get blocks.

varnameA name that identifies the Property.

parameter listThe parameters you use with the property. The list default is ByVal.

typenameThe type of the property. If you do not specify a data type, the default type
is Object.

interfacememberWhen a property is part of a class that implements an interface, this is


the name of the property being implemented.

GetStarts a Get property procedure used to return the value of a property. Get blocks
are optional unless the property is ReadOnly.

End GetEnds a Get property procedure.

SetStarts a Set property procedure used to set the value of a property. Set blocks are
optional unless the property is WriteOnly. Note that the new value of the property is
passed to the Set property procedure in a parameter named Value when the value of the
property changes.

End SetEnds a Set property procedure.

Visual Basic passes a parameter named Value to the Set block during property assignments, and
the Value parameter contains the value that was assigned to the property when the Set block was
called. Here is an example where it is creating a read/write property named Prop1 in Module2,
and storing the value of property in a private text string named PropertyValue in Module2:
Module Module1
Sub Main()
End Sub
End Module
Module Module2
Private PropertyValue As String
Public Property Prop1() As String
122

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

Get

Notes

Return PropertyValue
End Get
Set(ByVal Value As String)
PropertyValue = Value
End Set
End Property
End Module
Now it can be referred to Prop1 of Module2, setting it and reading its value, like this:
Module Module1
Sub Main()
Module2.Prop1 = 2
System. Console.WriteLine(Prop1= & Module2.Prop1)
System. Console.WriteLine(Press Enter to continue...)
End Sub
End Module
Module Module2
Private PropertyValue As String
Public Property Prop1() As String
Get
Return PropertyValue
End Get
Set(ByVal Value As String)
PropertyValue = Value
End Set
End Property
End Module
Prop1 = 2
Press Enter to continue...
You also can index properties by passing an index value when referring to a property. Here
is an example; in this case, creating a property array by adding an index value that you must
specify each time you use the property:
Public Module Module1
Private Data(200) As Integer

Public Property Property1(ByVal Index As Integer) As
Integer
Get
Return Data(Index)
End Get
Set(ByVal Value As Integer)

LOVELY PROFESSIONAL UNIVERSITY

123

Modern Programming Tools & Techniques-III

Notes

Data(Index) = Value
End Set
End Property
End Module
Now instead of referring to the property simply as Property1, It must use an index value, such
as Property1(5), which refers to a particular element in the property array: Scope, and Exception
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Module1.Property1(5) = 1
MsgBox(Module1.Property1(5))
End Sub

6.3.2 Creating Indexer


Indexers, another nifty feature of VB.NET, are similar to the overloaded [] (array subscript)
operator in C++. An indexer allows you to access a class instance in terms of a member array.
An indexer declaration may include a set of attributes; a new modifier; a valid combination of
the public, private, protected, and internal access modifiers; and one of the virtual, override,
or abstract modifiers.
The type of an indexer declaration specifies the element type of the indexer introduced by
the declaration. Unless the indexer is an explicit interface member implementation, the type
is followed by the keyword this. For an explicit interface member implementation, the type is
followed by an interface type, a period (.), and the keyword this. Unlike other members, indexers
do not have user defined names.
The formal parameter list of an indexer corresponds to that of a method, with two differences: at
least one parameter must be specified, and the ref and out parameter modifiers are not permitted.
The accessors specify the executable statements associated with reading and writing indexer
elements.
Even though the syntax for accessing an indexer element is the same as that for an array element,
an indexer element is not classified as a variable. Thus, it is not possible to pass an indexer
element as a ref or out parameter.
It is an error for an indexer accessor to declare a local variable with the same name as an indexer
parameter. With these differences in mind, all rules defined in apply to indexer accessors as
well as property accessors.
Indexers and properties, although very similar in concept, differ in the following ways:

124

A property is identified by its name whereas an indexer is identified by its signature.

A property is accessed through a simple-name or a member-access whereas an indexer


element is accessed through an element-access.

A property can be a static member whereas an indexer is always an instance member.

A get accessor of a property corresponds to a method with no parameters whereas a get


accessor of an indexer corresponds to a method with the same formal parameter list as
the indexer.

A set accessor of a property corresponds to a method with a single parameter named


value whereas a set accessor of an indexer corresponds to a method with the same formal
parameter list as the indexer, plus an additional parameter named value.
LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

Notes

Indexer Example
Imports System

Imports System.Net

Class GetDNSaliases

Private m_arrAlias As String()

Dim iphe As IPHostEntry = Dns.GetHostByAddress(strHost)

Public Sub Fetch(ByVal strHost As String)

m_arrAlias = iphe.Aliases
End Sub


Default Public ReadOnly Property Item(ByVal nIndex As Integer)
As String
indexer
Get

Return m_arrAlias(nIndex)
End Get

End Property

Public ReadOnly Property Count() As Integer


property
Get

Return m_arrAlias.GetUpperBound(0)
End Get

End Property
End Class

Class MyApp

Public Shared str1 As String


Public Shared Sub Main()

Dim myGetDNSaliases As New GetDNSaliases()


Do

Try


Console.WriteLine(write a valid IP Address and press
ENTER (to exit enter q).)
If (str1 = Console.ReadLine()) = q Then
Exit Try
End If

myGetDNSaliases.Fetch(str1)

Dim nCount As Int32 = myGetDNSaliases.Count


Console.WriteLine(Found {1} aliases for IP {0}, str1,
nCount)
Dim i As Int32 = 0
While i < nCount

Console.WriteLine(myGetDNSaliases(i))


System.Math.Max(System.Threading.Interlocked.
Increment(i), i - 1)
End While

Catch e As Exception

LOVELY PROFESSIONAL UNIVERSITY

125

Modern Programming Tools & Techniques-III

Notes


Console.WriteLine(Exception occurred!{0} & vbCr & vbLf,
e.ToString())
Finally

final code to be executed


End Try

Loop While True

Console.ReadLine()

End Sub

End Class
The code in this listing generates the display in Figure 6.4.
Figure 6.4: Screen Output Generated From Example

Visual Basic .NET 2003 was released in April 2003. This release became the
first version in the history of visual basic to provide programming tools for
Pocket PCs and other mobile devices; it also had better XML features and
support for Windows Server 2003.

Write a program creating indexer.

6.4 Using Inheritance in Classes


Inheritance is a powerful way of expressing the relationships between types and reusing code
across multiple types. Often, types in a program share the same characteristics. For example, a
program may contain types that represent a customer and an employee.
A key feature of OOP is reusability. It is always time saving and useful if we can reuse something
that already exists rather than trying to create the same thing again and again. Reusing the
class that is tested, debugged and used many times can save us time and effort of developing
and testing it again. Once a class has been written and tested, it can be used by other programs
to suit the programs requirement. This is done by creating a new class from an existing class.
The process of deriving a new class from an existing class is called Inheritance. The old class is
called the base class and the new class is called derived class. The derived class inherits some

126

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

or everything of the base class. In Visual Basic we use the Inherits keyword to inherit one class
from other. The general form of deriving a new class from an existing class looks as follows:

Notes

Public Class One


End Class
--Public Class Two
Inherits One
--End Class

6.4.1 Importing in Class


Class Customer
Public Name As String
Public Address As String
Public City As String
Public State As String
Public ZIP As String

Public CustomerID As Integer

End Class
Class Employee
Public Name As String
Public Address As String
Public City As String
Public State As String
Public ZIP As String
Public Salary As Integer
End Class
In this situation, both the Customer and Employee classes contain a number of identical fields.
This is because the two classes each describe a person, and a person has certain characteristics,
such as a name and address, that exist independent of whether or not they are a customer or
an employee.
This commonality between the Customer type and the Employee type can be expressed through
inheritance. Instead of repeating the same information in both types, you can create a class called
Person that contains the common characteristics of a person.
Class Person
Public Name As String
Public Address As String
Public City As String
Public State As String
Public ZIP As String
End Class

LOVELY PROFESSIONAL UNIVERSITY

127

Modern Programming Tools & Techniques-III

Notes

The class Person represents all the characteristics of a person that exist independent of whether
the person is a customer or an employee. Once the Person class is defined, the Customer and
Employee classes can inherit all the members of the Person class. This means that the classes
have to define only the members that are unique to each class.
Class Customer
Inherits Person

Public CustomerID As Integer

End Class
Class Employee
Inherits Person
Public Salary As Integer
End Class
When one class inherits members from another class, the inheriting class derives from the other
type. The type being derived from is called the base type. A type inherits all the members that
the base type defines, including methods and events. So the Employee and Customer classes
still have fields named Name, Address, City, State, ZIP, and Phone, even though they do not
explicitly declare them, because they inherit them from Person. For example, the classes can
be used as follows.
Module Test
Sub Main()

Dim c As Customer = New Customer()

c.Name = John Smith

Dim e As Employee = New Employee()

e.Name = Jane Doe

End Sub

End Module
Visual Basic .NET supports only single inheritance, which means that a class can derive
from only one base type.A class that derives from another, can in turn, be derived from
by another class. For example, Employee can be further specialized by classes such as
Manager and Programmer.
Class Programmer

Inherits Employee

Public Project As String


End Class
Class Manager

Inherits Employee

Public Programmers () As Programmer


End Class

128

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

In this example, the Programmer class contains the members defined in its immediate base
class, Employee, as well the members defined in Employees base class, Person. Related
types can be viewed as a hierarchy with a tree structure as in Figure 6.5.

Notes

Figure 6.5: An Inheritance Hierarchy


Object
Person

Employee

Customer

Programmer

Manager

Obviously, a type cannot directly or indirectly inherit from itself. Also, notice that the type Object
is at the top of the inheritance hierarchy. If a class does not explicitly inherit from another class,
it inherits from Object by default. Thus, Object is always the common root of all inheritance
hierarchies. Also notice that in this type hierarchy, the most general types are at the top of the
tree. As you move down the hierarchy, the classes at each level become more specialized and
specific. Inheritance is a very powerful way of expressing the relationships between types.
An important thing to keep in mind about inheritance and accessibility is that a derived class
does not have access to its base classes Private members. Private members can be accessed only
by the immediate type in which they are defined. Protected members, however, can be accessed
within an inheritance hierarchy. The Protected access level restricts access to a member to only
the class itself, but it extends access to all derived classes as well.
Further more examples of inheritance can be discussed below:
Example:
Module Module11
Sub Main()
Dim c As Child
c = New Child
c.P1()
c.C1()
Console.ReadLine ()
End Sub
End Module
Public Class Parent
Public Sub P1()
Console.WriteLine (Parent P1)
End Sub
End Class
Public Class Child: Inherits Parent
Public Sub C1()
Console.WriteLine (Child C1)
End Sub
End Class

LOVELY PROFESSIONAL UNIVERSITY

129

Modern Programming Tools & Techniques-III

Notes

Example:
Module Module12
Sub Main()
Dim obj As New SubClass
obj.DoSomething()
Console.ReadLine()
End Sub
End Module
Public Class Parent
Public Overridable Sub DoSomething()
Console.WriteLine(Hello from Parent)
End Sub
End Class
Public Class SubClass
Inherits Parent
Public Overrides Sub DoSomething()
Console.WriteLine(Hello from SubClass)
End Sub
End Class
Be careful with multiple inheritances. Sometimes the names of classes can be
misleading about their actual behavior.

Visual Basic History

isual Basic (VB) is a third-generation event-driven programming language and


integrated development environment (IDE) from Microsoft for its COM programming
model first released in 1991. Visual Basic is designed to be relatively easy to learn and
use. Visual Basic was derived from BASIC and enables the rapid application development
(RAD) of graphical user interface (GUI) applications, access to databases using Data Access
Objects, Remote Data Objects, or ActiveX Data Objects, and creation of ActiveX controls
and objects. Scripting languages such as VB and VBScript are syntactically similar to Visual
Basic, but perform differently.
The History of Visual Basic dates back to 1991 when VB 1.0 was introduced. The core of
Visual Basic was built on the older BASIC language, which was a popular programming
language throughout the 1980s.
Alan Cooper had developed a drag-and-drop interface in the late-1980s; Microsoft approached
him and asked his company, Tripod, to develop the concept into a form building application.
Tripod developed the project for Microsoft. It was called Ruby and it did not include a
programming language at all. Microsoft decided to bundle it with the BASIC programming
language, creating Visual Basic. Ruby also provided the ability to load dynamic link libraries
containing additional controls (then called gizmos), which later became the VBX interface.
Brief History of Visual Basic (1.0 to 6.0)
Visual Basic 1.0 for Windows was released in May 1991 at a trade show in Atlanta, Georgia.
Contd...

130

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

Visual Basic 2.0 was released in November 1992. The programming environment was easier
to use, and its speed was improved. Notably, forms became core objects, thus laying the
foundational concepts of class modules as were later offered in VB4.

Notes

Visual Basic 3.0 was released in 1993 and came in Standard and Professional versions. VB3
included version 1.1 of the Microsoft Jet Database Engine that could read and write Jet (or
Access) 1.x databases.
Visual Basic 4.0 was released in August 1995. It was the first version that could create 32-bit
as well as 16-bit Windows programs. It also introduced the ability to write non-GUI classes
in Visual Basic. While previous versions of Visual Basic had used VBX controls, Visual Basic
now used OLE controls (with files names ending in .ocx) instead. These were later to be
named ActiveX controls.
With version 5.0 release in February 1997, Microsoft released Visual Basic exclusively for
32-bit versions of Windows. Programmers who preferred to write 16-bit programs were
able to import programs written in Visual Basic 4.0 to Visual Basic 5.0, and Visual Basic 5.0
programs could easily be converted with Visual Basic 4.0. Visual Basic 5.0 also introduced
the ability to create custom user controls, as well as the ability to compile to native Windows
executable code, speeding up calculation-intensive code execution. A free, downloadable
Control Creation Edition was also released for creation of ActiveX controls.
Visual Basic 6.0 released in mid 1998 improved in a number of areas including the ability
to create web-based applications. VB6 has been the most successful version in the history of
Visual Basic, it has entered Microsofts non-supported phase as of March 2008. Although
the development environment is no longer supported, the runtime is supported on Windows
Vista, Windows Server 2008 and Windows 7.
Mainstream Support for Microsoft VB 6.0 ended on March 31, 2005. Extended support ended
in March 2008. In response, the Visual Basic user community expressed its grave concern
and lobbied users to sign a petition to keep the product alive. Microsoft has so far refused
to change their position on the matter.
Brief History of Visual Basic .NET (7.0 to 9.0)
Visual Basic .NET is Microsofts designated successor to VB 6.0, and is part of Microsofts .NET
platform. It compiles and runs using the .NET Framework and is not backwards compatible
with VB 6.0. An automated conversion tool exists, but for most projects automated conversion
is impossible. Visual Basic.NET is designed to create .NET applications, Windows or Web
applications, and Web Services.
In 2005, Microsoft released Visual Studio 2005, which included Visual Basic 8.0 and the
.NET Framework 2.0. Visual Basic 2005 is the name used to refer to this update as Microsoft
decided to drop the .NET portion of the title. The new features included Design-time
expression evaluation, My pseudo- namespace, dynamically generated classes and Data
Source binding for easier database client/server development. These enhancements were
mainly intended to reinforce VBs focus as a rapid application development platform and
further differentiate it from C#.
In 2005, Microsoft also launched the Visual Basic 2005 Express as part of the Visual Studio
Express product range, The Express editions are free development tools having a streamlined
version of the user interface, and lack more advanced features of the standard versions.
Microsoft created these for students, hobbyists and novices. This was a milestone event in
the history of visual basic as it was the first time VB became available free of cost.
Contd...

LOVELY PROFESSIONAL UNIVERSITY

131

Modern Programming Tools & Techniques-III

Notes

In 2008, Microsoft launched Visual Studio 2008 including VB 9.0 and the .NET Framework
3.5. Visual Basic 2008 as it is known includes features like Anonymous types, support for
LINQ, Lambda expressions and XML literals. In 2008, Microsoft also released the free Visual
Basic 2008 Express as an updated version of Visual Basic 2005 Express.
Microsoft has tested the beta 2 version of their upcoming release Visual Basic 2010 (VB 10.0)
which is part of the Visual Studio 2010 with .NET Framework 4.0. This version includes
many Compiler and Language improvements like Auto-Implemented Properties, Collection
Initializes and Implicit Line Continuation. The Integrated Development Environment included
new features like Highlighting References and IntelliSense Suggestion Mode.
Though-out the History of Visual Basic the focus has always been on rapid application
development and that is what makes Visual Basic such a widely used programming
environment.
Questions

1. What language was used in building of core Visual Basic?

2. Which one is the first version of Visual Basic could create 16 bit as well as 32 bit windows
program?

Self Assessment Questions


Multiple Choice Questions
6. Which language is not a true object-oriented programming language?
(a) VB.NET

(b) VB 6

(c) C++

(d) C#

7. Visual Studio .NET provides which feature:

(a) debugging

(b) application deployment

(c) syntax checking

(d) All of these.

8. Which does the solution explorer not display?


(a) Form Properties

(b) Reference Folder

(c) Form File

(d) Assemble File

9. An object is composed of:


(a) properties

(b) methods

(c) events

(d) All of these

10. Which statement about objects is true?


(a) One object is used to create one class.
(b) One class is used to create one object.
(c) One object can create many classes.
(d) One class can create many objects.
11. What is the extension for a Visual Basic web form interface file?

132

(a) asp

(b) aspx

(c) asp.vb

(d) aspx.vb

LOVELY PROFESSIONAL UNIVERSITY

Unit 6: Classes and Object in VB.NET

12. Which of the following is part of an object?


(a) Methods

(b) Properties

(c) Instances

(d) Both (a) and (b).

Notes

13. Methods are used to represent:


(a) actions

(b) classes

(c) data

(d) events

14. Inheritance makes it easier to:


(a) Reuse and modify existing modules of code.
(b) Write and read code by sharing method names.
(c) Hide and protect data from external code.
(d) Both (a) and (b).
15. What is the suggested order for the definition of class elements from first to last?
(a) Constructs, fields, methods, properties
(b) Properties, constructs, fields, methods
(c) Fields, properties, constructs methods
(d) Constructs, properties, fields, methods

6.5 Summary

Visual Basic is an object-oriented programming language. An object encapsulates both data


and the methods (procedures) that act on the data.

Visual Basic controls (i.e. those found in the Toolbox) are predefined objects, and include
Labels, Textboxes, Buttons and other controls.

Classes are the heart and soul of an object-oriented language.

A class means collection of methods/functions. Method/function accepts parameters;


process set of codes which have written in the module/function and returns the output
to the caller.

Objects are instance of the class. Fields and Properties represent information that an object
contains.

Methods represent the objects built-in procedures.

6.6 Keywords
Dynamic-link Library (DLL): Dynamic-link library is Microsofts implementation of the
shared library concept in the Microsoft Windows andOS/2 operating systems. These
libraries usually have the file extension DLL, OCX (for libraries containing ActiveX
controls), or DRV (for legacy system drivers).
Encapsulation: Encapsulation is used to refer to one of two related but distinct notions,
and sometimes to the combination.
Error Handling: The error handling construct in Visual Studio .NET is known as structured
exception handling. The constructs used may be new to Visual Basic users, but should be
familiar to users of C++ or Java.

LOVELY PROFESSIONAL UNIVERSITY

133

Modern Programming Tools & Techniques-III

Notes

Template: Template when used in the context of file format refers to a common feature
of many software applications that define a unique non-executable file format intended
specifically for that particular application.
1. Implement the multiple inheritances.
2. Write a program using copy constructor.

6.7 Review Questions


1. Define the concept of classes in VB.Net.

2. Explain the objects in VB .Net.

3. What Methods are used in VB .Net?


4. Write a program to creating a class.

5. Define constructor and types of constructor.

6. What is Properties in VB .Net?


7. Define indexers. Write down a program in VB .Net.

8. What is Inheritance? Define it in contrast of VB .Net.

9. What is encapsulation in VB .Net?


10. Define error-handling in VB .Net.

Answers for Self Assessment Questions


1. (b)

2. (a)

3. (d)

4. (b)

5. (a)

6. (b)

7. (d)

8. (a)

9. (d)

10. (d)

11. (b)

12. (d)

13. (a)

14.

(a)

15.

(c)

6.8 Further Readings


Object-Oriented Programming with Visual Basic .NET, by J. P. Hamilton.
Visual Basic.Net Programming, by Harold Davis.

http://www.codeproject.com/Articles/8825/Object-Oriented-ProgrammingIn-VB-NET

134

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

Unit 7: Namespaces

Notes

CONTENTS
Objectives
Introduction
7.1

Meaning and its Working

7.1.1

Declaring a Namespace

7.1.2

Accessing Members of a Namespace

7.1.3

Nesting a Namespace

7.1.4

Aliases of the Namespaces

7.1.5 Assemblies

7.2

Object and Class

7.3

Creating Your First Class Library

7.3.1

Adding a Souped-Up Class

7.3.2

Creating Properties

7.3.3

Building a Test Client

7.3.4

Read-only and Write-only Properties

7.3.5

Parameterized Properties

7.3.6

Default Properties

7.3.7

Constructors in Your Classes

7.3.8

Classes without Constructors

7.3.9

Adding Methods to Classes

7.3.10 Adding Events

7.4

Creation of Namespaces

7.4.1

Creating Your Own Namespaces

7.4 Summary
7.5 Keywords
7.6

Review Questions

7.7

Further Readings

Objectives
After studying this unit, you will be able to:

Explain the meaning and its working

Describe the object and class

Understand the creating your first class library

Define namespaces

LOVELY PROFESSIONAL UNIVERSITY

135

Modern Programming Tools & Techniques-III

Notes

Introduction
A namespace designates a collection of programming elements, organized and classed for grouping
operations and easy access. At the namespace level, the programming elements include:

Classes of objects [...];

Structures [...];

Modules [...];

Interfaces [...];

Delegates [...];

Enumeration [...];

Other namespaces.

Namespaces can be organized, aggregated into an assembly [...]. An assembly can contain
multiple namespaces, which can contain other namespaces.
By default, the executable file created with Visual Studio environment contains a namespace
with a name identical to that of project. More assemblies can use the same namespace.
Explicit definition of a namespace is done in VB.NET with specifications Namespace and End
Namespace. It considers an application of type Console Application. It defines the namespace
ProiectNou that contains:

A namespace called Formular1;

A class called GrupOp which contains two methods: Adun and Imp.

The namespace Formular1 contains the class GrupOp with an event two methods: Dif and Prod.
It notes the presence of two classes of objects with the same name GrupOp, but included in
different namespaces: ProiectNou, respectively Formular1.
The namespace ProiectNou is defined on the same level as the procedure Main is defined.
Namespace ProiectNou

Namespace Formular1

Class GrupOp

Public Event CalculOp(ByVal x As Integer, ByVal y As Integer)

Public Function Dif(ByVal a As Integer, ByVal b As Integer)_

As Integer
Return a - b
End Function

Public Function Prod(ByVal a As Integer, ByVal b As Integer)_

As Long
Return a * b
End Function

End Class

End Namespace
Class GrupOp

136

Public Function Adun(ByVal a As Integer, ByVal b As Integer)_

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

As Integer

Notes

Return a + b

End Function

Public Function Imp(ByVal a As Integer, ByVal b As Integer)_

As Double

Return a / b

End Function

End Class

End Namespace
Module Module1

Sub Main()

Dim calc As NameSpaceApp.ProiectNou.GrupOp

calc = New NameSpaceApp.ProiectNou.GrupOp

MsgBox(4+6= & calc.Adun(4, 6))

Dim calcNou As NameSpaceApp.ProiectNou.Formular1.GrupOp

calcNou = New NameSpaceApp.ProiectNou.Formular1.GrupOp

MsgBox(4*6= & calcNou.Prod(4, 6))

End Sub

End Module
In the procedure Main, it is noted that to define a variable of type GrupOp it has to specify
the complete path to the class GrupOp by expressions NameSpaceApp.ProiectNou.GrupOp
andNameSpaceApp.ProiectNou.Formular1.GrupOp. Otherwise, the application cannot be
compiled because it does not know where to extract the definition of the class GrupOp from.
NameSpaceApp is namespace at project level created by Visual Studio environment. Referring
of a programming item in VB.NET source code is done by specification Imports. Referring the
programming elements is done starting with the namespace with the highest level of aggregation
and it provides the paths of subcollections included in namespace by using operator.
Imports NameSpaceApp.ProiectNou.Formular1
Thus, it accesses the programming element GrupOp included in Formular1, which it is included
in the namespace ProiectNou. The namespace ProiectNou is defined in the namepsace at the
application level, called with the same name like the project NameSpaceApp. The complete referring
of the list of items in the programming elements included in namespaces, avoids conflict by their
given identical names. For ease of operation with elements of namespace, it can assign an alias to
refer a program element included in a namespace. Alias allows direct reference to this element.
Imports GrupOperatii = NameSpaceApp.ProiectNou.Formular
If the first example, namespace was defined in the same file with VB.NET source code module
that has been used elements defined in ProiectNou. If ProiectNou namespace is defined in another
source file included in the project NameSpaceApp, then before developing the module Module1
it should be included specifications Imports, as it follows:
Imports G1 = NameSpaceApp.ProiectNou
Imports G2 = NameSpaceApp.ProiectNou.Formular1
Module Module1
Sub Main()

Dim calc As G1.GrupOp


LOVELY PROFESSIONAL UNIVERSITY

137

Modern Programming Tools & Techniques-III

Notes

calc = New G1.GrupOp

MsgBox(4+6= & calc.Adun(4, 6))

Dim calcNou As G2.GrupOp

calcNou = New G2.GrupOp

MsgBox(4*6= & calcNou.Prod(4, 6))

End Sub

End Module
The namespace ProiectNou has the same definition, but included in another source file in the
application NameSpaceApp. In a namespace, the following programming elements cannot be
defined: properties [...], procedures [...], variables [...] and events [...]. These elements are defined
in source code containers: modules, structures and classes.
Why we need it?
We must add a reference of the Namespace object before using that object in a project. Several
references are automatically added in the project by default. Imports keyword is used to add
a reference of a name space manually.

7.1 Meaning and its Working


Namespaces are a way to define the classes and other types of information into one hierarchical
structure. System is the basic namespace used by every .NET code. If we can explore the System
namespace little bit, we can see it has lot of namespace user the system namespace. For example,
System.IO, System.Net, System.Collections, System.Threading, etc.
Namespaces organize the objects defined in an assembly. Assemblies can contain multiple
namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and
simplify references when using large groups of objects such as class libraries.
Namespaces allow you to create a system to organize your code. A good way to organize your
namespaces is via a hierarchical system. You put the more general names at the top of the
hierarchy and get more specific as you go down. This hierarchical system can be represented
by nested namespaces. By placing code in different sub-namespaces, you can keep your code
organized.
Namespaces are used as an organizational system a way of presenting program components
that are exposed to other programs and applications.
Namespaces are always Public; therefore the declaration of a namespace cannot include access
modifiers. However, the components within the namespace may have Public or Friend access.
If it is not stated, the default access type is Friend.
Some Namespaces and their use
System: Includes essential classes and base classes for commonly used data types, events,
exceptions and so on
System.Collections: Includes classes and interfaces that define various collection of objects such
as list, queues, hash tables, arrays, etc
System.Data: Includes classes which lets us handle data from data sources
System.Data.OleDb: Includes classes that support the OLEDB .NET provider
System.Data.SqlClient: Includes classes that support the SQL Server .NET provider

138

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

System.Diagnostics: Includes classes that allow to debug our application and to step through
our code

Notes

System.Drawing: Provides access to drawing methods


System.Globalization: Includes classes that specify culture-related information
System.IO: Includes classes for data access with Files
System.Net: Provides interface to protocols used on the internet
System.Reflection: Includes classes and interfaces that return information about types, methods
and fields
System.Security: Includes classes to support the structure of common language runtime security
system
System.Threading: Includes classes and interfaces to support multithreaded applications
System.Web: Includes classes and interfaces that support browser-server communication
System.Web.Services: Includes classes that let us build and use Web Services
System.Windows.Forms: Includes classes for creating Windows based forms
System.XML: Includes classes for XML support
Example
Imports System

Imports allow access to classes in the referenced Namespace only not in its
internal or child Namespaces. If we want to access internal Namespace we
might need to write:-

Imports System.Collections
Namespace are basically used to avoid naming collisions, when we have multiple classes with
the same name, and it is also helpful for organizing classes libraries in hierarchal structure.
Namespaces allow us to organize Classes so that they can be easily accessed in other applications.
Namespace also enable reusability.
A class in .Net Framework cannot belong to multiple Namespaces. One class should belong to
only one Namespace. VB.NET does not allow two classes with the same name to be used in a
program.
The System namespace contains fundamental classes and base classes that define commonlyused value and reference data types, events and event handlers, interfaces, attributes, and
processing exceptions.
Other classes provide services supporting data type conversion, method parameter manipulation,
mathematics, remote and local program invocation, application environment management, and
supervision of managed and unmanaged applications.

Write the program using Imports System.Collections.

7.1.1 Declaring a Namespace


We can define a Namespace by using Namespace keyword. The syntax for declaring a
Namespace is

LOVELY PROFESSIONAL UNIVERSITY

139

Modern Programming Tools & Techniques-III

Notes

Namespace <Namespace_name>

// Classes and/or structs and/or enums etc.

End Namespace
Example
Namespace MyNamespace

class with in a namespace

Public Class Class1


Public Shared Function disp() function declared within the class

Console.Write(hello & vbCrLf)

End Function
End Class
End Namespace

All the classes in .Net Framework belongs to System Namespace. The system
Namespace has built-in VB functionality and all other Namespaces are based
on this system Namespace.

Search more about the namespaces.

7.1.2 Accessing Members of a Namespace


We can access member of a Namespace by using dot(.) operator also known as period operator.
The members of a Namespace are the variable, procedure, classes that are defined within a
Namespace. To access the member of a namespace in a desired location type the name of the
namespace followed by dot or period operator followed by the desired member of the namespace.
Example:
MyNamespace.Class1.disp() Accessing elements of the MyNamspace
We can access member of a namespace in different ways. The following program shows accessing
the element of namespace in different ways:Imports System
Namespace Birds user defined namespace Bird
Class Parrot Parrot is a class in the namespace Animals

Public Shared Function fly() Fly is a function in this Class


Console.WriteLine(Parrot can fly)
End Function

P
ublic Shared Function color() color is another function in
parrot class
Console.WriteLine(normally Parrots are green)
End Function

Public Shared Function type()

C
onsole.WriteLine(Different type of parrot are found around
the world)
End Function
End Class
End Namespace
140

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

Module Module1

Notes

Public Function myfunction()


Dim P As Birds.Parrot
P = New Birds.Parrot()
P.type() accessing member of the namespace bird
End Function
Sub main()
Console.Clear()
Birds.Parrot.fly() accessing member of the namespace
C
onsoleApplication5.Birds.Parrot.color()
access member of the namespace

another

way

to

myfunction()
End Sub
End Module
Output:

7.1.3 Nesting a Namespace


Nesting a Namespace means create a namespace inside a namespace. A good way to organize
namespaces is put them in a hierarchal order, i.e. general name at the top of the hierarchy and
put specific name at the lower level.
Example:
Imports System
Namespace outer declare an outer namespace
Public Class nameout

P
ublic Shared Function disp() create a function inside a
outer namespace
Console.WriteLine(hi this is outer name space)
End Function
End Class

Namespace inner decalre an inner namespace


Public Class nameinn

LOVELY PROFESSIONAL UNIVERSITY

141

Modern Programming Tools & Techniques-III

Notes

P
ublic Shared Function disp() create a function inside
the inner namespace
Console.WriteLine(hi this is inner namespace)
End Function
End Class
End Namespace
End Namespace

Module module1

Sub main()

Console.Clear()

o
uter.nameout.disp() accesing function of the outer
namespace

o
uter.inner.nameinn.disp() accessing fucntion of the inner
namespace
End Sub
End Module
Output:

You cannot have two classes with the same name in the same scope. Means class
overloading is not allowed.

Example:
Namespace MyNamespace

Public Class one sample class with in a namespace


P
ublic Shared Function disp() function
class
Console.Write(hello & vbCrLf)
End Function
End Class

Public Class one this is not allowed


Public Shared Function disp1()
Console.Write(hi)
142

LOVELY PROFESSIONAL UNIVERSITY

declared

within

the

Unit 7: Namespaces

End Function

Notes

End Class
End Namespace

You can avoid this by putting classes with same name in different scope.
Example

Namespace outerscope sample class with in a namespace


Public Class one

Public Shared Function disp() function declared within the class


Console.Write(hello class with outerscope & vbCrLf)
End Function
End Class

Namespace innerscope

Public Class on
same class with different scope
Public Shared Function disp1()

C
onsole.Write(hi this class is wihtin innerscope of outscope
namespace & vbCrLf)
End Function
End Class

End Namespace
End Namespace

Module module1
Sub main()

Console.Clear()

outerscope.one.disp()

outerscope.innerscope.one.disp1()
End Sub

End Module
Output:

Visual Basic language/platform that was sold throughout the 1990s as a rapid
application development (RAD) tool for Windows programming.

LOVELY PROFESSIONAL UNIVERSITY

143

Modern Programming Tools & Techniques-III

Notes

7.1.4 Aliases of the Namespaces


Aliases are created when we have nested Namespaces. It is easy to access the members of the
namespaces by the alias. An alias is a shortcut for a nested namespace. An alias of a namespace
is created with the help of imports keyword. Aliasing is useful when we are working with a
large project.
Example:
Imports ally = ConsoleApplication6.outerscope.innerscope creating an
alias name for inner scope
Namespace outerscope sample class with in a namespace
Public Class one

Public Shared Function disp() function declared within the class


Console.Write(hello class with outer scope & vbCrLf)
End Function
End Class

Namespace innerscope

Public Class one same class with different scope


Public Shared Function disp1()

C
onsole.Write(hi accessing the member with the alias name
& vbCrLf)
End Function
End Class
End Namespace
End Namespace

Module module1
Sub main()

Console.Clear()

o
uterscope.one.disp() accessing
namespace without alias name
a
lly.one.disp1() accessing
name

member

End Sub

End Module
Output:

144

LOVELY PROFESSIONAL UNIVERSITY

member
of

the

of

the

innerscope

outerscope
by

alias

Unit 7: Namespaces

7.1.5 Assemblies

Notes

An assembly is the building block of a .NET application. It is a self describing collection of code,
resources, and metadata (data about data, example, name, size, version of a file is metadata
about that file). An Assembly is a complied and versioned collection of code and metadata that
forms an atomic functional unit. Assemblies take the form of a dynamic link library (.dll) file
or executable program file (.exe) but they differ as they contain the information found in a type
library and the information about everything else needed to use an application or component.
All .NET programs are constructed from these Assemblies. Assemblies are made of two parts:
manifest, contains information about what is contained within the assembly and modules,
internal files of IL code which are ready to run. When programming, we do not directly deal
with assemblies as the CLR and the .NET framework takes care of that behind the scenes. The
assembly file is visible in the Solution Explorer window of the project.
An assembly includes:

Information for each public class or type used in the assembly information includes class
or type names, the classes from which an individual class is derived, etc.

Information on all public methods in each class, like, the method name and return values.
(if any)

Information on every public parameter for each method like the parameters name and
type.

Information on public enumerations including names and values.

Information on the assembly version (each assembly has a specific version number).

Intermediate language code to execute.

A list of types exposed by the assembly and list of other assemblies required by the
assembly.
The System namespace contains fundamental classes and base classes that
define commonly-used value and reference data types, events and event
handlers, interfaces, attributes, and processing exceptions.

7.2 Object and Class


In Visual Basic you will work with objects, which have properties, methods, and events. Each
object is based on a class.
Objects
Think of an object as a thing, or a noun. 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.
Properties
Properties tell something about or control the behavior of an object, such as it is name, color,
size, or location. You can think of properties as adjectives that describe objects.
When you refer to a property, you first name the object, add a period, and then name the
property. For example, refer to the Text property of a form called SalesForm as SalesForm.Text
(pronounced sales form dot text).
Methods
Actions associated with objects are called methods. Methods are the verbs of object-oriented
programming. Some typical methods are Close, Show, and Clear. Each of the predefined objects

LOVELY PROFESSIONAL UNIVERSITY

145

Modern Programming Tools & Techniques-III

Notes

has a set of methods that you can use. You will learn to write additional methods to perform
actions in your programs.
You refer to methods as Object.Method (object dot method). For example, a Show method
can apply to different objects: BillingForm.Show shows the form object called BillingForm;
ExitButton.Show shows the button object called ExitButton.
Events
You can write procedures that execute when a particular event occurs. 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
A class is a template or blueprint used to create a new object. Classes contain the definition of
all available properties, methods, and events.
Each time that you create a new object, it must be based on a class. For example, you may
decide to place three buttons on your form. Each button is based on the Button class and is
considered one object, called an instance of the class. Each button (or instance) has its own set
of properties, methods, and events. One button may be labeled OK, one Cancel, and one
Exit. When the user clicks the OK button, that buttons Click event occurs; if the user clicks
on the Exit button, that buttons Click event occurs. And, of course, you have written different
program instructions for each of the buttons Click events.
An Analogy
If the concepts of classes, objects, properties, methods, and events are still a little unclear, maybe
an analogy will help. Consider an Automobile class. When we say automobile, we are not
referring to a particular auto, but we know that an automobile has a make and model, a color,
an engine, and a number of doors. These elements are the properties of the Automobile class.
Each individual auto is an object, or an instance of the Automobile class. Each Automobile object
has its own settings for the available properties. For example, each object has a Color property,
such as MyAuto.Color = Blue and YourAuto.Color = Red.
The methods, or actions, of the Automobile class might be Start, SpeedUp, SlowDown, and Stop.
To refer to the methods of a specific object of the class, use MyAuto.Start and YourAuto.Stop.
The events of an Automobile class could be Arrive or Crash. In a VB program you write
procedures that specify the actions you want to take when a particular event occurs for an object.
For example, you might write a procedure for the YourAuto.Crash event.
The .NET Framework
The programming languages in Visual Studio run in 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 announced or have released versions of other
programming languages to run in the .NET Framework, including .NET versions of APL by
Dyalog, FORTRAN by Lahey Computer Systems, COBOL by Fujitsu Software Corporation,
Pascal by the Queensland University of Technology (free), PERL by ActiveState, RPG by ASNA,
and Java, known as IKVM.NET.
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.

146

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

Notes

Visual Basic
Microsoft Visual Basic comes with Visual Studio. You also can purchase VB by itself (without the
other languages but with the .NET Framework). VB is available in an Express Edition, a Standard
Edition, a Professional Edition, and a Team System Edition. Anyone planning to do professional
application development that includes the advanced features of database management should
use the Professional Edition or the Team System Edition. You can find a matrix showing the
features of each edition in Help. The Professional Edition is available to educational institutions
through the Microsoft Academic Alliance program and is the best possible deal. When a campus
department purchases the Academic Alliance, the school can install Visual Studio on all classroom
and lab computers and provide the software to all students and faculty at no additional charge.
Creating Objects
Creating objects and persisting them with Telerik OpenAccess ORM is as easy as working with
non-persisting ones. The scope object is an object that should be disposed after accomplishing the
required operations. This can be done by calling the scope.Dispose() method or implementing
the using clause.
Dim scope As IObjectScope = ObjectScopeProvider1.GetNewObjectScope()
you could see in some expamples that this can also be done with
Database.Get(DatabaseConnection1).GetObjectScope();
there is absolutely no difference
Using scope
scope.Transaction.Begin()
Dim o As New Order(John Smith, New DateTime(2008, 12, 12),
Teleriks Address)
o.Details.Add(New OrderDetail(RadControls for WinForms, 799.9f, 3))
o.Details.Add(New OrderDetail(OpenAccess ORM, 399.9f, 3))
o.Details.Add(New OrderDetail(RadControls for ASP .NET, 799.9f, 5))
scope.Add(o)
scope.Transaction.Commit()
End Using
So making an object and its children to persist is very easy. It is required to add only the root
object of the object graph to have all persistent entities handled automatically. Telerik OpenAccess
ORM will care about the rest like adding the records in the ObjectDetail table and in the join
table. That is called persistence by reachability. You should notice that your classes must be
marked as [Telerik.OpenAccess.Persistent] so the ORM can traverse through the three of objects
and persist all of them. If it finds any non-persistent class it will throw an exception.
In case you want to exclude a field from being persisted, e.g. a callback delegate, mark it with
the Telerik.OpenAccess.

Self Assessment Questions


Multiple Choice Questions
1. The namespace Formular1 contains the class GrupOp with an event two methods Dif
and .....................
(a) prob

(b) proc

(c) prod

(d) proe

LOVELY PROFESSIONAL UNIVERSITY

147

Modern Programming Tools & Techniques-III

Notes

2. The Framework provides for easier development of web-based and ............ applications.
(a) program-based

(b) windows-based

(c) oriented-based

(d) web-deigns

3. Creating objects and persisting them with Telerik Open Access ........... is as easy as working
with non-persisting ones.

(a) ORM

(b) CLR

(c) MSIL

(d) OMR

4. A class in .Net Framework cannot belong to ............. Namespaces.


(a) single

(b) double

(c) multiple

(d) more

True or False
5. Nesting a Namespace means create a namespace inside a namespace.
(a) True

(b) False

7.3 Creating Your First Class Library


To see how to build your first class library, start Visual Studio.NET and from the Start Page,
click Create New Project. From the New Project dialog box, choose Visual Basic Projects in the
Project Types list box, and then choose Class Library in the Templates list box. Name the project
Healthcare and click the OK button.
At this point, a new class is created for you. The first thing you might notice is that the class
does not have a designer by default, making it different from most VB.NET application types.
Instead, you start with basically the same thing you had in VB6: an empty class.
Right now, you have one class, named Class1. Here is where things start to diverge from VB6.
In VB6, you had one class per class module, and these were compiled into a single component.
Class modules had a .CLS extension. In VB.NET, your module has a .VB extension, and a single
source code file can contain more than one class. One or more source code files can be compiled
into an assembly. You can create a new class at any time using the Class...End Class block.
In the code window, change the class definition line to name the class Patient. In other words,
change this line:
Public Class Class1
To this:
Public Class Patient
You have now changed the class name, but if you look in the Solution Explorer window, or just
look at the tab on the current code window, you see the filename is still.
Class1.vb.
Right-click on the Class1.vb icon in the Solution Explorer and choose Rename. Name the file
Healthcare.vb. You should see the tab in the main code window change to reflect the new
filename. What you have done is change the name of the file that holds one or more classes.

7.3.1 Adding a Souped-Up Class


You already have your first class, which was created for you when you created the class library.
This class is now called Patient, but it does not have a constructor (Public Sub New) as most
new files in VB.NET do. You can add your own constructor if you want your class to have one.

148

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

It is also possible to create a new class that comes with a designer and a constructor already
created. In the Solution Explorer, right-click on the project name, choose Add, and then choose
Add Component. From the dialog that opens, choose Component class and click Open. This adds
a new file to the project, which has only a class in it. This class, however, includes a designer,
as shown in Figure 7.1.

Notes

Figure 7.1: A New Class Created with a Designer and a


Constructor Already Created

The new class includes a designer, so you can perform actions such as dragging database
connections to the designer to make it easier to create data components.
Double-clicking on the designer opens the code window. You can see that there is more code
in this class than in the class that was created with the class library project. If you examine the
code, you will notice the following line:
Inherits System.ComponentModel.Component
This line makes the class inherit from the base Component class in System.ComponentModel.
If you added that line to your Healthcare class, you would have access to the designer there.
For now, you will return to the generic Healthcare class you created earlier.

7.3.2 Creating Properties


You can now start adding properties to your class, but be aware that the syntax for creating
Visual properties has changed. Add a FirstName property by first creating a private variable.
Inside the class, add the following code:
Dim msFirstName as String
Now, add the following code. Realize that as soon as you type the first line, most of the rest
of the code will be filled in for you by the IDE. You will still have to add the Return and the
assignment.

LOVELY PROFESSIONAL UNIVERSITY

149

Modern Programming Tools & Techniques-III

Notes

Public Property FirstName() As String


Get
Return msFirstName
End Get
Set(ByVal Value As String)
msFirstName = Value
End Set
End Property
Notice the new syntax for creating properties. No longer do you create matching Public Property
Get/Public Property Let procedures. Instead, you create a Public Property block and then add
a Get and a Set section to it. There is no Let anymore, which makes life easier.
Also notice that this property does not accept an argument, as you would have had to do with a
Public Property Let in VB6. This means that you no longer have to have the value passed in as
a parameter; instead, if the user passes in a value, it is put in the Value variable automatically.

7.3.3 Building a Test Client


Now, it is time to test this class. True, it has only one property, but you need to see how to call
this class in a client application. From the File menu, choose New and then Project. This time,
add a Windows Application. Name it HealthcareClient but before you click OK, make sure
that you select the Add to Solution radio button. The default is to close the current solution
and open a new one. By choosing to add this new project to the current solution, you have the
equivalent of a VB6 group.
After you click the OK button, the new project is loaded into the Solution Explorer, as shown
in Figure 7.2. As in VB6, the project name that appears in bold in the Solution Explorer is the
project that will start when you start the application. Simply right-click on the HealthcareClient
project and choose Set as StartUp Project from the pop-up menu.
Figure 7.2: The Solution Explorer Showing Two Projects Loaded at Once

150

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

In the Solution Explorer, right-click on the References node for the HealthcareClient project
and choose Add Reference. The Add Reference dialog box will appear. Click on the Projects
tab and you should see your Healthcare project. It is already highlighted, but the OK button
is disabled, as you can see in Figure 7.3. Click the Select button to move Healthcare into the
Selected Components box, and then click the OK button.

Notes

Figure 7.3: The Add Reference Dialog Box

Now, on the form in HealthcareClient, add a button. Double-click the button to get to the code
window, and enter the following code for the Button1_Click event procedure:
Protected Sub button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles button1.Click
Dim Patient As New Healthcare.Patient()
Patient.FirstName = Bob
msgbox(Patient.FirstName)
End Sub
This code should look very familiar to VB6 developers. After adding a reference, you instantiate
the object by setting the variable Patient to a New Healthcare.cPatient. If you are used to VB6,
you might be tempted to try this shortcut and type this line of code:
Dim Patient As New Patient()
If you type the line this way, however, you will get an error that says User-defined type not
defined: Patient. This shows that you need to have the name of the component fully qualified.
The word Healthcare in this case is not the assembly name; instead, it is the namespace.
To get around this problem, you can import the namespace containing the Patient class. Remember
that all projects have a default namespace, and the default name of this default namespace is

LOVELY PROFESSIONAL UNIVERSITY

151

Modern Programming Tools & Techniques-III

Notes

the same as the project. Therefore, if you go to the top of the code module and add an Imports
statement, the shortcut reference to the Patient class will work. Your Imports statement must
go at the top of the module, and it will look like this:
Imports Healthcare
You might have noticed in the code that you used the New keyword to create the object. In
VB6, you could use the New keyword in two ways. Here is the first way:
Dim Patient as New Healthcare.Patient
In VB6, this code works, but it is not the best way to create objects. When you use this method,
the object is not actually created until you call the first property or method. In fact, each call to
a property or method requires a check to see whether the object has already been instantiated.
To avoid this overhead, you should have been using this method in VB6:
Dim Patient as Healthcare.cPatient
Set Patient = New Healthcare.cPatient
In VB.NET, however, the following two methods are considered equivalent:

7.3.4 Read-only and Write-only Properties


Returning to the class library you are creating, you should notice that the property you created,
FirstName, has both a Get and Set section in the Property block. In VB6, to make a property
read-only, you simply did not create a Public Property Let statement. To create a write-only
property, you did not create the Public Property Get.
You might be tempted to try to create a read-only property by simply leaving out the Set...End
Set block. However, VB.NET handles read-only and write-only properties differently: You must
add a keyword to the property declaration. To create a readonly property named Age (you can
assume that It is calculated from the persons date of birth), your code would look like this:

Public ReadOnly Property Age() As Single

Get

get Date of Birth (DOB)

calculate age from DOB


return age
End Get
End Property
Creating a write-only property is equally simple. Just put the keyword WriteOnly in the property
declaration, and have only a Set...End Set block in the property procedure.

7.3.5 Parameterized Properties


It is possible to create a parameterized property. Using the example of a patient, consider that a
patient is likely to have several physicians attending to him at any one time. Therefore, although
your Healthcare class library might have a Physician class, the Patient will likely hold a collection
of Physician objects. You would be able to access this collection through a parameterized property
and walk through this collection.
Creating a parameterized property is fairly straightforward: You simply add a parameter to
the property procedure. If you have a Physicians property that walks through a collection of
Physician objects, the code would look something like this:

152

Dim PhysiciansList As New Collection()

Public ReadOnly Property Physicians(ByVal iIndex As Integer) _

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

Notes

As Physician
Get

Return

CType(PhysiciansList(iIndex), Physician)

End Get
End Property
You might notice several unusual things in this code. First of all, the basic functionality is there,
in that you pass in an index value and get back a particular object in a collection. Notice also
that even though the PhysiciansList is defined as a Collection data type, Option Strict prevents
an automatic conversion from a Collection type to a Physician type. Therefore, you must run
the CType function and pass both the object you want to convert and the type of the class (or
object) into which it should be converted. Only then will the return actually succeed.

7.3.6 Default Properties


With the caveat that defaults properties without parameters were gone. However, if a property
has one or more parameters, it can be the default property. Therefore, the Physicians property
in Patient could be a default property.
Making a property the default property is as simple as adding the word Default in front of
the property declaration. To make the Physicians property the default, your declaration would
look like this:
Default Public ReadOnly Property _
Physicians(ByVal iIndex As Integer) As Physician
Now, in your client program, you could call the default property on the Patient object. The last
two lines of this code snippet are equivalent:
Imports Healthcare
...
Dim Patient As New Patient()
Dim Phys As New Physician()
Phys = Patient.Physicians(1)
Phys = Patient(1) equivalent to line above

7.3.7 Constructors in Your Classes


The one class you have built so far, Patient, did not come with a constructor; in other words,
there was no Sub New available when you first created the class library. Constructors can be
quite useful because they allow you to instantiate an object with some values already in it.
For example, assume that you wanted the Patient to allow you to pass in a PatientID when you
instantiated the object. That means you could write code that would create the object and, at
creation time, read a database and fill in the properties for that patient. Your new definition for
the Sub New would look like this:
Public Sub New(Optional ByVal iPatientID As Integer = 0)
Your client code could now instantiate the object and pass in a value at instantiation. Either of
the following lines would allow you to create an instance of the object with a value already set:
Dim Patient As New Patient(1)
Dim Patient As Patient = New Patient(1) equivalent to line above

LOVELY PROFESSIONAL UNIVERSITY

153

Modern Programming Tools & Techniques-III

Notes

7.3.8 Classes without Constructors


Obviously, your classes do not have to have constructors. If you just use the Class...End Class
block to create a new class, you will not be provided with a Sub New. Whether or not a class has
constructors or implements System.ComponentModel.Component, the class can still have properties
and methods, and can be created just like any other class. The Physicians class that has been
used in previous examples could look something like this:
Public Class Physician
Dim miPhysID As Integer
Public Property PhysicianID() As Integer
Get
Return miPhysID
End Get
Set
miPhysID = Value
End Set
End Property
Public ReadOnly Property Age() As Single
Get
get Date of Birth (DOB)
calculate age from DOB
return age
End Get
End Property
End Class

7.3.9 Adding Methods to Classes


Adding a method to your class is done the same way it was done in VB6. If you want to create
an Admit method in the Patient class, your code might look something like this:
Public Function Admit() As Boolean
add patient to database, notify billing, etc.
Return True
End Function
The call to this from the client is equally simple:
If Patient.Admit Then...
Before you begin thinking that there are not any changes in methods, understand that there are
major changes in defining methods. However, the changes are specific to inheritance.

7.3.10 Adding Events


To add an event to your class, use the Event keyword. Imagine that you wanted to add an event
to the class that notified you when you had pending lab results. You could create the event
using code like this inside the class that needs to fire the event:
Event LabResult(ByVal LabType As String)
This just creates the event definition in your code. To actually cause the event to fire, you will
have to add a RaiseEvent statement elsewhere in the code. For example, if you set a PatientID
154

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

property, you can go check a database for any new lab results for that patient. If there are new
lab results, you could raise an event. Your code would look similar to this:

Notes

Dim miPatientID As Integer


Public Property PatientID() As Integer

Get
Return miPatientID
End Get
Set

miPatientID = Value

check labs database for this patient


if there are new lab results

RaiseEvent LabResult(CBC)

End Set
End Property
If this were a real procedure, you would not hard-code CBC into the event, but would instead
pull the lab type from the database.

7.4 Creation of Namespaces


Perhaps one of the most confusing aspects of VB.NET for VB developers is the concept of a
namespace. A namespace is a simple way to organize the objects in an assembly. When you
have many objects, such as in the System namespace provided by the runtime, a namespace
can simplify access because it is organized in a hierarchical structure, and related objects appear
grouped under the same node.
For example, say you wanted to model the objects, properties, and methods for a pet store.
You might create the PetStore namespace. You could then create some subnamespaces. For
example, you might sell live animals and supplies as two major categories. Within the live
animals category, you might sell dogs, cats, and fish. If this sounds like an object model, it can
be thought of as similar. However, none of these are actual objects. You could have a namespace
called PetStore.Animals.Dogs, and in this namespace you would find the classes and methods
necessary for dealing with dogs. If you wanted to handle the inventory, you might find that in
PetStore.Supplies. If you wanted to look at the kinds of dog food you have in stock, you might
look in PetStore.Supplies.Dogs. Where the physical classes exist is up to you; they all can be in
one big assembly, but logically separated into these various namespaces.
If you want to use the objects in an assembly without having to fully qualify them each time,
use the Imports statement. Doing so allows you to use the names of the objects without fully
qualifying their entire namespace hierarchy.
For example, when you created your first VB.NET project, Your First VB.NET Application,
you saw some Imports statements at the top of the forms code module. One of those statements
was Imports System.WinForms. That statement made all the classes, interfaces, structures,
delegates, and enumerations available to you without you having to qualify the full path. That
means the following code is legal:
Dim x as Button
Without the Imports System.WinForms statement, your line of code would have to look like this:
Dim x as System.WinForms.Button

LOVELY PROFESSIONAL UNIVERSITY

155

Modern Programming Tools & Techniques-III

Notes

In fact, the MsgBox that you know and love can be replaced by the System.WinForms.MessageBox
class. MsgBox still works for compatibility, but it is actually part of the Microsoft.VisualBasic.
Interaction namespace, which contains a number of methods that approximate functions in
previous versions of VB.
If you are wondering why Microsoft pulled out some language elements and made them part
of the runtime, it should be fairly obvious: so that any language targeting the runtime, on any
platform, would have access to common functionality. That means that you can go into C# and
have a message box, just by importing System.WinForms and calling the MessageBox class.
MessageBox is quite powerful the Show method has twelve variations of it.

7.4.1 Creating Your Own Namespaces


You are free to create your, own namespaces inside your assemblies. You can do this simply by
inserting your own Namespace...End Namespace block. Inside the namespace block, you can
have structures, classes, enums, interfaces, and other elements. You must name the namespace
and it becomes what someone would import. Your code might look like this:
Namespace VolantTraining
Public Class Customer
code here
End Class
Public Class Student
code here
End Class
End Namespace
Namespaces can be nested within other namespaces. For example, your namespace might look
something like this:
Namespace VolantTraining
Namespace Customer
Class Training
...
End Class
Class Consulting
...
End Class
End Namespace
Namespace Student
...
End Namespace
End Namespace
Here you have one namespace, VolantTraining, that holds two other namespaces: Customer and
Student. The VolantTraining.Customer namespace holds the Training and Consulting classes,
so you could have customers who have used your training services and customers who have
used your consulting services.
If you choose not to create explicit namespaces, all your classes and modules still belong to
a namespace. This namespace is the default namespace and is the name of your project. You

156

LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

can see this namespace, and change it if you want, by clicking viewing the Project Properties
dialog box for your project. The text box labeled Root Namespace represents the root namespace
for your project. If you declare a namespace within your project, it is subordinate to this root
namespace. Therefore, if the root namespace of your applications Project1, then the full namespace
for VolantTraining would be Project1.VolantTraining.

Notes

Namespaces are always public; therefore the declaration of a namespace cannot


include access modifiers.
VB takes about eight seconds to run on my machine. It might run a significantly
longer or shorter time on your machine. The good news is the VB.NET IDE
runs on a separate thread, so if you find yourself waiting forever, just click
on the IDE and choose Stop Debugging from the Debug menu.

Using the .NET Framework Queue class in VB.NET

he Queue class is a type of collection in which items are added to the end of the
collection, and are removed from the start of the collection, much like a line for the
store checkout. This is often described as first in, first out (FIFO) behaviour. Such a
collection is useful if there is a bottleneck in an application (such as validating credit cards
or despatching orders) and the items in the collection need to be processed in a first come,
first served basis.
Note that the .NET Frameworks Queue class should not be confused with Microsoft Message
Queuing, which is a completely different and unrelated technology!
Creating an instance of the Queue class
To create an instance of a queue class, the New keyword can be used. There are two main
constructors of note. The first constructor of the class is without any arguments, i.e.
Dim MyQueue As New Queue
The second constructor specifies an integer as the initial size for the queue. The following
example creates a queue which can be used to hold 24 objects:
Dim MyQueue As New Queue(24)
Since the queue class automatically grows beyond the specified capacity if the initial capacity
was insufficient, it is not usually necessary to specify the size of the queue. However, doing
so, especially if you know the queue will be especially large, or fixed in length, can lead to
a slight application performance increase.
Note that when you are intending to use the Queue class, it is sometimes necessary to
import the Systems.Collections namespace by using the Imports System.Collections VB.NET
statement.
Adding objects to the Queue
To add an object to a queue, the Enqueue method is invoked. There is only constructor for
this method, with a single argument: the object to be added to the Queue. Any object can
be added to an instance of the Queue class - from basic objects such as integers and strings
to other classes and even other Queue classes. It is also possible to add null values using
the VB.NET Nothing keyword or the System.DBNull.Value class. Each Queue can contain
many different types of objects. The code below shows a variety of objects added to an
instance of a Queue class:
Contd...
Dim MyQueue As New Queue(4)

LOVELY PROFESSIONAL UNIVERSITY

157

Modern Programming Tools & Techniques-III

Notes

Dim MyOtherQueue As New Queue


Dim MyNumber As Integer = 24
Dim MyText As String =ASP Documentation Tool
MyQueue.Enqueue(MyNumber)
MyQueue.Enqueue(MyText)
MyQueue.Enqueue(MyOtherQueue)
MyQueue.Enqueue(System.DBNull.Value)
Again, if adding the object to the queue causes the size of the queue to exceed the current
size of the queue, then the queue is automatically resized to allow the object to be added
to the queue.
Examining the Queue and removing objects from the Queue
An object may be removed from the queue by invoking the Dequeue() method.
Dim DequeuedObject As Object
DequeuedObject = MyQueue.Dequeue()
There may be occasions when you would like to examine an object before it is removed from
a queue. This is possible by making use of the Peek() method. This method is identical to
Dequeue, but it does not actually remove the object from the queue:
Dim DequeuedObject As Object
DequeuedObject = MyQueue.Peek()
To determine the number of items in the queue, the Count property always contains an
integer value for the number of items in the queue.
Resizing the Queue
The queue can be resized by invoking the TrimToSize() method. This method is helpful for
applications in which it is useful to minimise memory usage, as resizing the queue to its
current capacity reduces the amount of memory allocated to the queue object.
Emptying the Queue
There is also a Clear() method, which as its name suggests, can be used to completely empty
the queue class.
Searching the Queue
To find out if an object is in a queue, the Contains() method can be used. The object to be
searched for is used as the methods argument. Since the method invokes the Object.Equals
method, it cannot be used if the objects are not exactly the same. This means that in the case
of String objects, the search is case sensitive. The following example illustrates this:
Dim MyQueue As New Queue()
Dim MyText As String=ASPDocTool
MyQueue.Enqueue(MyText)
If MyQueue.Contains(aspdoctool) Then
Response.Write(found aspdoctool)
Else
Response.Write(did not find aspdoctool)
End If

158

LOVELY PROFESSIONAL UNIVERSITY

Contd...

Unit 7: Namespaces

The string aspdoctool will not be found in this Queue class due to the case sensitive search
being used by the Contains() method.

Notes

Iterating through objects in the Queue


It is possible to loop through the items in the queue by using the queues GetEnumerator
method. Although an iterator cannot be used to modify the items in the queue, it allows
more sophisticated searching of the queue than is possible using the Contains() method.
While iterating the queue, the Current property can be used to find out about the current
item being iterated. The code sample below shows how to loop through the items in a queue
using the queues GetEnumerator method:
Create an enumerator for a queueand loops through
the (objects) in the queue. Shows the type of each object
in the queue and its string representation
Dim QueueEnumerator As IEnumerator= MyQueue.GetEnumerator()
While QueueEnumerator.MoveNext
Dim ObjectType As System.Type
ObjectType = QueueEnumerator.Current.GetType
Response.Write(object name=& ObjectType.Name)
Response.Write(string representation = & _
QueueEnumerator.Current.ToString &)
End While
Other Useful Queue Methods
The Clone() method can be used to create a copy of a queue:
Dim MyOtherQueue As Queue()
MyOtherQueue =MyQueue.Clone()
There are also two methods for converting a Queue to an array. The ToArray() method
creates a new array from a Queue. The CopyTo() method copies the Queue to an existing
array. The CopyTo method takes two arguments: the array to which the Queue needs to be
copied, and the starting position of the Queues contents within the existing array.
To summarize, the Queue collection is one of the many benefits that the .NET Framework
offers over Visual Basic 6.0 and VBScript. The Queue collection is well worth considering
if you are building any type of system that has to process items with a resource that has
limited availability.
Questions
1. Explain the Queue methods in VB.NET.
2. Describes the Queue class.

Self Assessment Questions


Multiple Choice Questions

6. Namespaces are similar in concept to a folder in a computer file system, like..

(a) Objects

(b) Classes

(c) files

(d) folders

LOVELY PROFESSIONAL UNIVERSITY

159

Modern Programming Tools & Techniques-III

Notes

7. Namespaces enable classes to have a unique name or we can say that it is a naming
scheme for grouping related types.

(a) logical

(b) systematical

(c) static

(d) dynamic

8. System.Collections includes classes and interfaces that define various collections of objects
such as ..

(a) list

(b) queues

(c) hash tables

(d) All of these

9. Namespaces are always ..

(a) Single

(b) System

(c) Public

(d) Private

10. is quite powerful the Show method has twelve variations of it.
(a) Microsoft

(b) System.IO

(c) MessageBox

(d) None of these

11. The logical grouping construct is known as Namespace or we can say that the group of
code having specific name is a
(a) Method

(b) Namespace

(c) Class

(d) Object

12. Nesting a Namespace means create a namespace inside a ..


(a) program

(b) event

(c) Method

(d) Namespace

13 Aliases are created when we have Namespaces.


(a) Nested

(b) System: Includes

(c) System.IO

(d) System.Drawing

True or False
14. If you choose not to create explicit namespaces, all your classes and modules still belong
to a namespace.
(a) True

(b) False

15. A class in .Net Framework can belong to multiple Namespaces.


(a) True

(b) False

7.4 Summary

160

Creating classes (or objects) is one of the most common things for a VB developer to do.

There is also a big difference in the fact that you compile assemblies instead of COM
components.

There is an important concept in dealing with assemblies that is not covered due to time
and size constraints, and that is how assemblies handle versioning.
LOVELY PROFESSIONAL UNIVERSITY

Unit 7: Namespaces

A Namespace is access by using dot(.) operator also known as period operator.

If you choose not to create explicit namespaces, all your classes and modules still belong
to a namespace. This namespace is the default namespace and is the name of your project.

To add an event to your class, use the Event keyword. Imagine that you wanted to add
an event to the class that notified you when you had pending lab results.

A property has one or more parameters; it can be the default property.

You might be tempted to try to create a read-only property by simply leaving out the
Set...End Set block.

We must add a reference of the Namespace object before using that object in a project.

Software projects consist of several pieces of code such as classes, declaration, procedures
and functions etc., known as the component or identifiers of the software project.

Notes

7.5 Keywords
Assemblies: It can contain multiple namespaces, which can in turn contain other namespaces.
Events: These are write procedures that execute when a particular event occurs.
Imports System.Collections: These Namespace are basically used to avoid naming collisions,
when we have multiple classes with the same name, and it is also helpful for organizing classes
libraries in hierarchal structure.
Methods: The actions associated with objects are called methods.
Namespace: It is a simple way to organize the objects in an assembly.
System.Collections: It includes classes and interfaces that define various collections of objects
such as list, queues, hash tables, arrays, etc.
System.Globalization: It includes classes that specify culture-related information.
System.Net: This namespace provides interface to protocols used on the internet.
System.Reflection: It includes classes and interfaces that return information about types, methods
and fields.
System: This includes essential classes and base classes for commonly used data types, events,
exceptions and so on.
1. Create your own class library and run a program from it.
2. Construct and run a nested Namespace.

7.6 Review Questions


1. Why we need the namespace?

2. Explain the meaning of a namespace and also discuss the working.

3. Describe the object and class of a namespace.


4. How you can create your class library?

5. Define the creation of namespaces.

6. Explain in brief the declaration of a Namespace.

LOVELY PROFESSIONAL UNIVERSITY

161

Modern Programming Tools & Techniques-III

Notes

7. Write a short note on:


(a) Accessing Members of a Namespace
(b) Nesting a Namespace

8. What do you understand by assemblies? Also explain its features.

9. Explain the constructors in your classes and classes without constructors. And also explain
how to add methods into classes?

10. Define how you create properties, how you handle read-only, write only, and default
properties, and how you can handle events.

Answers for Self Assessment Questions


1. (c)

2. (a)

3. (a)

4. (c)

6. (b)

7. (a)

8. (d)

9.

(c)

10.

(c)

11. (b)

12. (d)

13. (a)

14.

(a)

15.

(b)

7.7 Further Readings


Programming in Visual Basic, by E. Balagurusamy.
VB.Net Black Book, by Wiley

www.passport.net for additional information

162

LOVELY PROFESSIONAL UNIVERSITY

5. (a)

Unit 8: Exception Handling

Unit 8: Exception Handling

Notes

CONTENTS
Objectives
Introduction
8.1

Concept of Exception Handling

8.1.1

Try Catch and Finally Keywords

8.1.2

Giving the User Information about an Exception

8.1.3

Catching Only Certain Exceptions

8.1.4

The Try-Catch Statement

8.1.5

Catch Blocks Using Try

8.2

The Finally Section

8.3 Summary
8.4 Keywords
8.5

Review Questions

8.6

Further Readings

Objectives
After studying this unit, you will be able to:

Explain the using try and catch blocks for exception handling

Define the try finally section

Introduction
Exception handling is crucial since the robustness of software depends on how effectively
a program deals with exceptions. Basically exceptions are the run time error. Only perfect
programmers create perfect code from the beginning. The rest must address imperfections along
the way to developing a successful application. Luckily for us Microsoft Visual Basic .NET
offers two ways of handling exceptions. The first unstructured follows the exception-handling
conventions of earlier versions of Visual Basic. The second, structured, handles exceptions in
ways that resemble exception handling in Microsoft Visual C# and Microsoft Visual C++.
At Developers who are transitioning from earlier versions of Visual Basic to Visual Basic
.NET, provides an overview of structured and unstructured exception handling. It includes
considerations that help you choose the right exception-handling alternative, the approaches
involved in each alternative, how to create your own exceptions, and the exception objects
properties. By the time you are finished, you should understand how and when to incorporate
exception handling in your code.
Exception handling is an in built mechanism in .NET framework to detect and handle run time
errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies
that occur during the execution of a program. They can be because of user, logic or system
errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET
run time environment provide a default mechanism, which terminates the program execution.

LOVELY PROFESSIONAL UNIVERSITY

163

Modern Programming Tools & Techniques-III

Notes

VB.NET provides three keywords try, catch and finally to do exception handling. The try encloses
the statements that might throw an exception whereas catch handles an exception if one exists.
The finally can be used for doing any cleanup process.
Exceptions are unforeseen errors that happen in your programs. Most of the time, you can, and
should, detect and handle program errors in your code. For example, validating user input,
checking for null objects, and verifying the values returned from methods are what you expect,
are all examples of good standard error handling that you should be doing all the time.
However, there are times when you do not know if an error will occur. For example, you can
not predict when you will receive a file I/O error, run out of system memory, or encounter a
database error. These things are generally unlikely, but they could still happen and you want
to be able to deal with them when they do occur. This is where exception handling comes in.
When exceptions occur, they are said to be thrown. What is actually thrown is an object that
is derived from the System.
Exception class provides several methods and properties for obtaining information on what went
wrong. For example, the Message property provides summary information about what the error
was, the Stacktrace property provides information from the stack for where the problem occurred,
and the ToString() method is overridden to reveal a verbose description of the entire exception.
Identifying the exceptions you will need to handle depends on the routine you are writing. For
example, if the routine opened a file with theSystem.IO.File.OpenRead() method, it could throw
any of the following exceptions:

SecurityException

ArgumentException

ArgumentNullException

PathTooLongException

DirectoryNotFoundException

UnauthorizedAccessException

FileNotFoundException

NotSupportedException

It is easy to find out what exceptions a method can raise by looking in the .NET Frameworks
SDK Documentation. Just go to the Reference/Class Library section and look in the Namespace/
Class/Method documentation for the methods you use. The exception in the list above were found
by looking at the OpenRead() method definition of the File class in the System.IO namespace.
Each exception identified has a hyperlink to its class definition that you can use to find out
what that exception is about.

8.1 Concept of Exception Handling


Visual Basic .NET or Visual Basic offers structured exception handling that provides a powerful,
more readable alternative to On Error Goto error handling, which is available in previous
versions of Microsoft Visual Basic. Structured exception handling is more powerful because
it allows you to nest error handlers inside other error handlers within the same procedure.
Furthermore, structured exception handling uses a block syntax similar to the If...Else...End
Ifstatement. This makes Visual Basic .NET and Visual Basic code more readable and easier to
maintain.

164

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

This provides an overview of structured and unstructured exception handling in Visual Basic
.NET. It includes considerations that help you choose the right exception-handling alternative, the
approaches involved in each alternative, how to create your own exceptions, and the exception
objects properties. A table at the end lists the predefined exception classes and their derived
classes Exception Handling in VB.NET.

Notes

If any exception occurs inside the try block, the control transfers to the appropriate catch block
and later to the finally block. But in VB.NET, both catch and finally blocks are optional. The try
block can exist either with one or more catch blocks or a finally block or with both catch and
finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally
block. We can say that the statements inside the finally block is executed always. Note that it
is an error to transfer control out of a finally block by using break, continue, return or go to.
In VB.NET, exceptions are nothing but objects of the type Exception. The Exception is the
ultimate base class for any exceptions in VB.NET. The VB.NET itself provides couple of standard
exceptions. Or even the user can create their own exception classes, provided that this should
inherit from either Exception class or one of the standard derived classes of Exception class like
DivideByZeroExcpetion Argument Exception etc.
The following are defined as:

Try Catch and Finally keywords.

Giving the user information about an exception.

Catching only certain exceptions.

8.1.1 Try Catch and Finally Keywords


The Try, Catch and Finally keywords are usually referred to as Error Handling. Handling
exceptions with these methods will stop your application from receiving runtime errors (errors
encountered during running the application) caused by exceptions.
When you handle these errors, VB.NET gives you the ability to get a wealth of information
about the exception and ways to let your application correspond according to them. Before we
get into getting exception information, let us talk the complete basics.

Try- The Try keyword will tell the compiler that we want to handle an area for errors.

Catch - The Catch keyword tells the application what to do if an error occurs. It will stop
the application from crashing, and let the application do the rest.

Finally - The Finally keyword will occur regardless if the Try method worked successfully
or a Catch method was used. The Finally keyword is optional.

Here is an example of a basic Try to Catch method:


Try
Create a new integer variable.
Dim anInteger As Integer = 0
Divide zero by zero to produce a DivideByZeroException exception.
anInteger \= 0
Catch ex As Exception
Show an error telling the user an error occurred.
MessageBox.Show(An error occurred)

LOVELY PROFESSIONAL UNIVERSITY

165

Modern Programming Tools & Techniques-III

Notes

Finally
Tell the user that it has got to the Finally statement.
MessageBox.Show(This has finally happened.:))
End Try
Now, if you edit the above code where anInteger equals 1, and where an Integer \= 0 gets
changed into an Integer \= 1, you will not get an error, and will skip to the finally method.

8.1.2 Giving the User Information about an Exception


Giving the user information about an exception is relatively easy. We will now invoke an
exception by trying to use a malformed path on an IO function. This will be the circumstance
an ArgumentException.
01 Give user information about an exception.
02 Try
03 we will purposely create a File Exception for the
04 purpose of this example. We will be invoking the exception
05 by providing a path of an illegal form.
06 Dim fileContents As String = System.IO.File.ReadAllText(iShould notWork :))
07 Catch ex As Exception
08 Ex.ToString will give the user a large technical dump.
09 MessageBox.Show(To String:& ex.ToString)
10 Ex. Message will give the user a brief, more user friendly error message.
11 MessageBox.Show(Message: & ex. Message)
12 End Try
You will notice we have changed Catch to Catch ex As Exception. By adding this, it will create
a new ex variable and get information about the exception. ex.ToString() will give the user a
large technical dump of the error that occured.ex.Message will give a more to the point error
message that does not look ugly.

8.1.3 Catching Only Certain Exceptions


Sometimes it is good to be precise about what kind of exception you are trying to check for.
Say we want to check if there is a DivideByZeroException exception, but there could be a risk
of an ArgumentException with a malformed path. What do we do?
Because VB.NET supports multiple Catch keywords, we have the ability to check for both
exceptions! Here is an example demonstrating this concept.
01 Give user information about an exception.
02 Try
03 Create a new integer variable.
04 Dim anInteger As Integer = 0
05 Divide zero by zero to produce a DivideByZeroException exception.
06 anInteger \= 0

166

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

07 Purposely provide an invalid argument to produce an ArgumentException.

Notes

08 Dim fileContents As String = System.IO.File.ReadAllText(iShould notWork :))


09 Catch exDivide As DivideByZeroException
10 Show an error telling the user a DivideByZeroException occured.
11 MessageBox.Show(The application tried to divide by zero!)
12 Catch exArgs As ArgumentException
13 Show an error telling the user an ArgumentException occured.
14 MessageBox.Show(The application tried to provide an invalid argument!)
15 Finally
16 Tell the user that it has got to the Finally statement.
17 MessageBoxShow (That was intense!: D)
18 End Try
If a Divide by Zero Exception is thrown, it will be caught and will skip to the Finally method (same
goes for the ArgumentException). Modify the above code to alternate between exceptions etc.
Exception handling in VB.Net provides uniform, structured and type-safe handling errors.

The System. Exception is the super class of exception.

Well-Defined exception classes exist for system level errors- such as overflow, divide-byzero, and null references- which are treated on par with applications level errors.

VB.net contains inner exceptions. When a new exception is thrown from an existing
exception, the new exceptions inner exception can carry the existing exception.

Checked and unchecked statements are used to control overflow checking.

An exception raised in VB.NET but handled in a C# program is handled in the same way
as one raised in C# but handled in VB.NET. There is a uniform way of handling errors.

VB provides a structured way of handing errors: the block of code where errors accepted is
guarded by try-catch blocks where exceptions are handled.
There are two types of exceptions: exceptions generated by an executing program and exceptions
generated by the common language runtime.System.Exception is the base class for all exceptions
in VB.NET. Several exception classes inherit from this class including Application Exception
and System Exception.These two classes form the basis for most other runtime exceptions.Other
exceptions that derive directly from System. Exception includes IOException,WebException etc.
The common language runtime throws System Exception. A user program rather than the runtime
throws the Application Exception. The System Exception includes the Execution Engine Exception,
Stack Overflows Exception etc. It is not recommended that we catch System Exceptions nor is
it good programming practice to throw SystemExceptions in our applications.
1. System. Out of Memory Exception
2. System. Null Reference Exception
3. Syste.Invalid Cast Exception
4. Syste.Array Type Mismatch Exception
5. System. Index out Of Range Exception

LOVELY PROFESSIONAL UNIVERSITY

167

Modern Programming Tools & Techniques-III

Notes

6. System. Arithmetic Exception


7. System.Devide by Zero Exception

8. System. Overflow Exception

8.1.4 The Try-Catch Statement


The basic syntax for Try-Catch exception handler is simply the following:
The Try Statement identifies the beginning of an error handler:
Try
Statements that might produce a runtime error
Catch
Statements to run if runtime errors occur
Finally
Optional statements to run whether an error occur or not
End Try
The statement between the Try Catch keywords is called protected code because any runtime
errors resulting from these statements would not cause the program to crash.

Try

prcTextFile.StartInfo.FileName = (C:\Program Files\ErrorHandler\


VbNetError.txt)

prcTextFile.Start ()

Catch

MessageBox.Show (Unable to locate the desired file)

Finally

MessageBox.Show (Error Handler Complete)

End Try

In a real program you will probably want to use the Finally code block to update important
variables or properties, display data, or perform other cleanup operations.
Some Important Properties of Exception class:

StackTrace: This StackTrace property can be used to determine where the error occurred.

Message: The Message property returns a description to the errors cause.

InnerException: The InnerException property can be used to create and preserve a series
of exceptions during exception handling.

HelpLink: The HelpLink property can hold a URL to a help file that provides extensive
information about the cause of exception. Processing Errors Using Try - - - Catch

A runtime error, or program crash, is an unexpected problem in a Visual Basic program from
which the program can not recover. It is not that Visual Basic do not smart enough to handle
the glitch; it is just that Visual Basic has not been told what to do when something goes wrong.
Fortunately you do not have to live with the occasional errors that cause your programs to crash.
You can write special Visual Basic runtimes, called structured error handlers, to respond to
runtime errors. An error handler handles a runtime error by telling the program how to continue

168

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

when one of its statements does not work. Error handlers are placed in the event procedures,
in which there is a potential for trouble, or in generic functions or subprograms that handle
errors for you systematically. As their name implies, error handlers handle, or trap, a problem
by using the Try - Catch statements and a special error handling object Err. The Err object has
a Number property that identifies the error number and a Description property that allows you
to print a description of the error.

Notes

This code example is a simple Try...Catch block that first checks for Arithmetic Exception and
then checks for generic exceptions.

Imports System
Sub Main()

Dim x as Integer = 0

Try

Dim y as Integer = 100 / x

Catch ex As Arithmetic Exception

MessageBox.Show(ex. Message)

Catch ex As Exception

MsgBox(ex.Message)

End Try

End Sub Main

This code example is a Try...Catch...Finally block associated with an application that opens a file
for examination. Note that the Finally statement gets executed even though Exit Sub appears
before it in the code.

Imports System

Sub OpenMyFile

Dim thisFile As Object

Try

FileOpen (1, thisFile, OpenMode.Input)

Catch ex As Exception

MsgBox (ex.Message)

Exit Sub

Finally

FileClose(1)

End Try

End Sub

Write the program using try, catch and finally in exception handling.

An error can be occurred using the try keyword without catch.

8.1.5 Catch Blocks Using Try


The previous part is here Runtime Errors VB.NET has an inbuilt class that deals with errors.
The Class is called Exception. When an exception error is found, an Exception object is created.
The coding structure VB.NET uses to deal with such Exceptions is called the try catch structure.

LOVELY PROFESSIONAL UNIVERSITY

169

Modern Programming Tools & Techniques-III

Notes

In the coding area for your button, type the word Try. Then hit the return key on your keyboard.
VB.NET completes the rest of the structure for you:
Try
Catch ex As Exception
End Try
The try word means Try to execute this code. The catch word means Catch any errors here.
The ex is a variable, and the type of variable it is an Exception object.
Move your line of code from the previous section to the Try part:
Try
rt1.LoadFile(C:\test10.txt, RichTextBoxStreamType.PlainText)
Catch ex As Exception
End Try
When you run your programmers, VB will Try to execute any code in the Try part. If everything
goes well, then it skips the Catch part. However, if an error occurs, VB.NET jumps straight to
Catch. Add the following to your Catch part:
MsgBox(ex.Message)
Your coding window should look like this:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Try
rtl.LoadFile(C:\test10.txt, RichTextBoxStreamType.PlainText)
Catch ex As Exception
MsgBox (ex.Message)
End Try
End Sub

Because ex is an object variable, it now has its own Properties and methods. One of these is the
Message property. Run your programmers and test it out. Click your button. You should see
the following error message (See Figure 8.1):
Figure 8.1: Could not Found Error Message

The message is coming from the additional Information section of the error message we saw
earlier, the one we did not handle. But the point about this new message box is that it will
not crash your programmers. You have handled the Exception, and displayed an appropriate
message for the user.
If you know the kind of error that a programmer might throw, you can get what Type it is from
the Error message box you saw earlier. This one:

170

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

Figure 8.2: Filenotfound Exception

Notes

Click the View Details links under Actions to see the following:
Figure 8.3: View Details

The first line tells us the Type of Exception it is:


System.IO.FileNotFoundException
You can add this directly to the catch part. Previously, you were just catching any error that
might be thrown:
Catch ex As Exception
But if you know a file not found error might be thrown, you can add that to the Catch line,
instead of Exception:
Catch ex As System.IO.FileNotFoundException
You can keep the Exception line as well. (You can have as many Catch parts as you want.) This
will Catch any other errors that may occur:
Try
rt1.LoadFile(C:\test10.txt, RichTextBoxStreamType.PlainText)
Catch ex As System.IO.FileNotFoundException
MsgBox(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try

LOVELY PROFESSIONAL UNIVERSITY

171

Modern Programming Tools & Techniques-III

Notes

There is one last part of the Try Catch Statement that VB.NET does not add for you -Finally:
Try
Catch ex As Exception
Finally
End Try
The Finally part is always executed, whether an error occurs or not. You typically add a Finally
part to perform any cleanup operations that are needed. For example, you may have opened
a file before going into a Try Catch Statement. If an error occurs, the file will still be open.
Whether an error occurs or not, you still need to close the file. You can do that in the Finally part.
But Microsoft advice that you always use Try Catch Statements in your code. However,
throughout the rest of this course, for convenience sake, we would not be using them much.
Even when we should be.But that is no excuse for you not to use them!
In the next part, we will take a look at Logic Errors
On 8 March 2005, a petition was set up in response to Microsofts refusal to
extend its mainstream support for VB6.

Write a program to set tab order in VB.NET?

Self Assessment Questions


Multiple choice questions
1. VB.NET provides . keywords.
(a) two

(b) three

(c) four

(d) five

2. There are two types of exceptions, exceptions generated by an executing program and
....................................
(a) Exceptions generated by the common language runtime
(b) Exceptions program by the common language runtime
(c) Exceptions generated by the executing program
(d) Exceptions program by the Microsoft Intermediate Language

3. The coding structure VB.NET uses to deal with such Exceptions is called the try....................

(a) catch structure

(b) try catch structure

(c) finally structure

(d) finally structure

4 The try word means ......................

(a) Try to handling this code

(b) Try to execute handling

(c) Try to execute error

(d) Try to execute this code

True or False

5. Exception handling is an in-built mechanism in .NET framework to detect and handle run
time errors.

(a) False

172

(b) True

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

8.2 The Finally Section

Notes

The code in the Finally block, if there is one, is always executed in a TryCatchFinally
statement, even if there was no exception, and even if you execute an Exit Try statement. This
allows you to deallocate resources and so on; here is an example with a Finally block:
Module Module 1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine(The answer is {0}, int3)
Catch e as System.OverflowException
System.Console.WriteLine (Exception: Arithmetic overflow!)
Catch e as System.ArgumentException
System.Console.WriteLine(Exception: Invalid argument value!)
Catch e as System.ArgumentOutOfRangeException
System.Console.WriteLine(Exception: Argument out of range!)
Finally
System.Console.WriteLine (Execution of sensitive code & is complete)
End Try
End Sub
End Module
And here is what you see when you execute this console application:
Exception: Arithmetic overflow!
Execution of sensitive code is complete
You see that the Finally in try Catch will execute allways after any parts of the execution of the
try catch block.
Is it any different to just skip the finally section and just run it after, outside the try catch block?
1: Try ... Catch ... Finally ... End Try
Try





Do something
Catch ex As Exception
Handle exception
Finally
Do cleanup
End Try
2: Try ...... Catch ........ End Try ....... Do they finally stuff outside

Try
Do something

Catch ex As Exception

Handle exception

End Try

LOVELY PROFESSIONAL UNIVERSITY

173

Modern Programming Tools & Techniques-III

In the context of IEEE 754 floating point hardware the term exception is used

Notes

in a different sense to its typical usage in programming languages to refer in


general to exceptional conditions: IEEE 754 defines an exception as an event
that occurs when an operation on some particular operands has no outcome
suitable for every reasonable application.

Handling Errors in eScript


Requirement

On Service Agreement list applet we have a button move to batch

User can select all contracts, or 1 or more contracts using CTRL button, and move these
to his batch for executing renewals.

User should not be able to add same contract twice in renewal batch for this User key
has been used and if user tries to do this he will get Record with same values already
exists error
In eScript code if we ignore or suppress this particular error and if this comes it should
execute the code for next error.
Solution
In the Applet server Script write the code to implement following logic (I am not providing
the complete code).
var isRecord = BC.FirstSelected();
while(isRecord)
{
Call a workflow and pass the field values that are part of user key
isRecord = BC.NextSelected();
}
In the Workflow it would query for the record with the values that are passed.
If record is found then go to End step otherwise call the Business Service to create a new
record or may be use Insert step and avoid all scripting all together.
The decision to use Insert Step or BS will depend on how complex the logic is to create the
record.
If it is simple insertion then pass the values of the required field in the workflow and use it
in insert step but if certain kind of data manipulation or validations are required then you
can use a BS to do your job.
Questions

174

1. What is the exception in e scripting?

2. How the exception does was handled?

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

Self Assessment Questions

Notes

Multiple choice questions


6. Exception handling is an in built mechanism in .NET framework to detect and handle
..
(a) Run time errors

(b) Execution time error

(c) Compile time error

(d) None of these.

7. Structured exception handling uses a block syntax similar to the If statement.

(a) If....EndElse

(b) End...Else...If

(c) If...Else...End

(d) None of these.

8. The . keywords are usually refered to as Error Handling


(a) try and finally

(b) catch and finally

(c) try and catch

(d) try, catch and finally

9. property can be used to determine where the error occurred.

(a) HelpLink

(b) StackTrace

(c) InnerException

(d) None of these.

10. VB.NET provides three keywords


(a) try, cleanup and finally

(b) try, catch and finally

(c) on error goto, try and finally

(d) None of these.

11. Checked and unchecked statements are used to control .. checking.


(a) overloading

(b) overflow

(c) Both (a) and (b) (d) None of these.


12. 12. Caching type supported by ASP.Net
(a) Output Caching

(b) Data Caching

(c) Both (a) and (b) (d) None of these.


13. Which of the following is not a member of ADODB Command object?
(a) ExecuteScalar

(b) ExecuteStream

(c) Open

(d) ExecuteReader

14. File extension used for ASP.NET files is:


(a) .web

(b) .asp

(c) .aspx

(d) None of these.

True or False
15. Try- the Try keyword will tell the compiler that we want to handle an area for errors
(a) False

(b) True

LOVELY PROFESSIONAL UNIVERSITY

175

Modern Programming Tools & Techniques-III

Notes

8.3 Summary

Since the robustness of software depends on how effectively a program deals with
exceptions. Basically exceptions are the run time error.

Exception handling is an in built mechanism in .NET framework to detect and handle run
time errors.

Structured exception handling is more powerful because it allows you to nest error handlers
inside other error handlers within the same procedure.

VB provides a structured way of handling errors: the block of code where errors accepted
is guarded by try-catch blocks where exceptions are handled.

If any exception occurs inside the try block, the control transfers to the appropriate catch
block and later to the finally block. But in VB.NET, both catch and finally blocks are optional.

The Try, Catch and Finally keywords are usually referred to as Error Handling. Handling
exceptions with these methods will stop your application from receiving runtime errors
(errors encountered during running the application) caused by exceptions.

The common language runtime throws System Exception. A user program rather than
the runtime throws the Application Exception.

8.4 Keywords
ArgumentException: A method can be called with invalid arguments. A method can be called
with invalid arguments. An ArgumentException may be thrown in this case. Exceptions use
derived types to indicate their meaning, but this does not give them extra abilities. Semantically,
ArgumentException indicates that a method was called with an invalid argument.
Catch: Catching and dealing with exceptions is a standard programming task.
Cleanup process: Code Cleanup is available in Visual Basic as well. Thus you are not supposed
to organize your code manually.
Error Handling: In previous versions of Visual Basic, the best practice for handling errors was
put On Error Goto in every routine, but there is no On Error statement in Visual Basic.
On Error Goto: In previous versions of Visual Basic, the best practice for handling errors was
put On Error Goto in every routine, but there is no On Error statement in Visual Basic.
Sensitive code: A case-sensitive code is the letters or numbers you type in, but the letters must
be capitalized in order for the code to be valid.
URL: URL stands for Uniform Resource Locator. A URL is a formatted text string used by Web
browsers, email clients and other software to identify a network resource on the Internet. Network
resources are files that can be plain Web pages, other text documents, graphics, or program.
1. Write a program to handle exception using try-catch block.
2. Write a program to show the use of finally block.

176

LOVELY PROFESSIONAL UNIVERSITY

Unit 8: Exception Handling

8.5 Review Questions

Notes

1. What is the exception handling?


2. Explain the short notes try catch and finally keywords.

3. Explain the some important properties of exception class.


4. Described the samples of structured exception handling.

5. What is the concept of catch blocks using try?


6. Write a structure of catch blocks using try?

7. Explain the processing errors using try and catch.

8. Write an example of a try to catch methods.


9. How many systemexceptions applications in uses of exception handling?

10. Write a statement between the try and catch keywords is called protected code because
any runtime errors resulting?

Answers for Self Assessment Questions


1. (b)

2. (a)

3. (a)

4. (d)

6. (a)

7. (c)

8. (d)

9.

12. (c)

13. (c)

11. (b)

(b)

14. (a)

5. (a)
10.

(b)

15. (b)

8.6 Further Readings


VB.NET Language in a Nutshell, by Steven Roman.
Professional Refactoring In Visual Basic, by Danijel Arsenovski.

http://www.codeproject.com/Articles/13658/VB-NET-Error-Handling

LOVELY PROFESSIONAL UNIVERSITY

177

Modern Programming Tools & Techniques-III

Unit 9: Using System.Collections

Notes

CONTENTS
Objectives
Introduction
9.1 ArrayList

9.1.1

Use of ArrayList

9.1.2

Properties and Methods Used in ArrayList

9.2 HashTable
9.3 Stack

9.3.1

Common Functions

9.3.2 Implementation

9.3.3

Usage Scenarios

9.4 Queue

9.4.1

Common Functions

9.4.2

Use of Queue

9.5

Sorted List

9.5.1

Advantages and Disadvantages of Using a SortedList

9.6 BitArray
9.7 BitVector32
9.8 Summary
9.9 Keywords
9.10 Review Questions
9.11 Further Readings

Objectives
After studying this unit, you will be able to:

Understand the system.collections namespace and its types

Define what is arraylist class and its uses

Explain the advantages and disadvantages of using a sorted list

Discuss the concept of LIFO and FIFO

Introduction
The System.Collections namespace exposes many classes that can work as data containers, such
as collections and dictionaries. You can learn the features of all these objects individually, but a
smarter approach is to learn about the underlying interfaces that these classes might implement.
All the collection classes in the .NET Framework implement the ICollection interface, which
inherits from IEnumerable and defines an object that supports enumeration through a foreach

178

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

loop. The ICollection interface exposes a read-only Count property and a CopyTo method, which
copies the elements from the collection object to an array.

Notes

The ICollection interface defines the minimum features that a collection-like object should have.
The .NET Framework exposes two more interfaces whose methods add power and flexibility
to a collection object: IList and IDictionary.
Many classes in the .NET Framework implement the IList interface. This interface inherits from
ICollection, and therefore from IEnumerable, and represents a collection of objects that can be
individually indexed. All the implementations of the IList interface fall into three categories:
read-only (the collections elements cannot be modified or deleted, nor can new elements be
inserted), fixed size (existing items can be modified, but elements cannot be added or removed),
and variable size (items can be modified, added, and removed).
Figure 9.1 shows the interface inheritance for the core interfaces:
Figure 9.1: Interface Inheritance for the Core Interfaces

The Figure 9.1 can be read as follows:


The IList and IDictionary interfaces derive from the ICollection interface, which in turn
derives from IEnumerable.

The IEnumerable interface is associated with IEnumerator.

The IDictionaryEnumerator interface derives from IEnumerator.

9.1 ArrayList
The ArrayList class is found in the system.collection namespace. The ArrayList is an extremely
effective and helpful class in VB .net. ArrayList is dissimilar to an array because the number
of its objects (elements) can grow dynamically. For example, a programmer can easily add an
object at the end of the list by using the method Add(). Also multiple elements can be added by
using the method AddRange(). Also inserting an object somewhere with the list of elements can
be added by using either the method Insert() or InsertRange(), which allows for the insertion
of multiple values. Similarly a programmer can remove an item or multiple items by using
Remove() and RemoveRange() respectively.

9.1.1 Use of ArrayList


The most obvious reason for using ArrayList, in comparison to regular array, is that ArrayList
can be expanded in runtime. While arrays are helpful and much more effective comparing to
individual variables, they are inflexible and fixed in their size. It is extremely difficult to change
the number of array elements as your code is executing. Further a programmer can resize the
number of elements dynamically with an ArrayList.

LOVELY PROFESSIONAL UNIVERSITY

179

Modern Programming Tools & Techniques-III

Notes

Since ArrayList is a .NET technology, it is available for C# also. When programmers switch from
C or C++ to C#, they realize that there is no dynamic memory allocation. Further, the reason
for not having the dynamic memory allocation is that ArrayList can do the same functionality
but easier. As a result, programmers do not have to worry about freeing the memory or concern
themselves with array bound overflow.

9.1.2 Properties and Methods Used in ArrayList


Table 9.1 and 9.2 are showing the common properties used in ArrayList:
Table 9.1: Common Properties
Name

Description

Capacity

Gets or sets the number of elements that the ArrayList can


contain.

Count

Gets the number of elements actually contained in the


ArrayList.

IsFixedSize

Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly

Gets a value indicating whether the ArrayList is read-only.

IsSynchronized

Gets a value indicating whether access to the ArrayList is


synchronized (thread safe).

Item

Gets or sets the element at the specified index.

SyncRoot

Gets an object that can be used to synchronize access to the


ArrayList.

Table 9.2: Common Methods


Name

Description

Add

Adds an object to the end of the ArrayList.

AddRange

Adds the elements of an ICollection to the end of the ArrayList.

BinarySearch

Overloaded. uses a binary search algorithm to locate a specific


element in The sorted ArrayList or a portion of it.

Clear

Removes all elements from the ArrayList.

Clone

Creates a shallow copy of the ArrayList.

Contains

Determines whether an element is in the ArrayList.

CopyTo

Overloaded. Copies the ArrayList or a portion of it to a onedimensional Array.

Equals

Overloaded. Determines whether two Object instances are


equal. (Inherited From Object.)

FixedSize

Overloaded. Returns a list wrapper with a fixed size, where


elements are Allowed to be modified, but not added or
removed.

GetRange

Returns an ArrayList which represents a subset of the elements


in the Source ArrayList.

GetType

Gets the Type of the current instance. (Inherited from Object.)

IndexOf

Overloaded. Returns the zero-based index of the first


occurrence of a value in the ArrayList or in a portion of it.
Contd...

180

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Insert

Inserts an element into the ArrayList at the specified index.

InsertRange

Inserts the elements of a collection into the ArrayList at the


specified index.

LastIndexOf

Overloaded. Returns the zero-based index of the last occurrence


of a value in the ArrayList or in a portion of it.

ReadOnly

Overloaded. Returns a list wrapper that is read-only.

Remove

Removes the first occurrence of a specific object from the


ArrayList.

RemoveAt

Removes the element at the specified index of the ArrayList.

RemoveRange

Removes a range of elements from the ArrayList.

Reverse

Overloaded. Reverses the order of the elements in the ArrayList


or a portion of it.

SetRange

Copies the elements of a collection over a range of elements


in the Array-

Notes

List.
Sort

Overloaded. Sorts the elements in the ArrayList or a portion


of it.

ToArray

Overloaded. Copies the elements of the ArrayList to a new


array.

ToString

Returns a String that represents the current Object. (Inherited


from Object.)

TrimToSize

Sets the capacity to the actual number of elements in the


ArrayList.
1 Imports System

3 Module Module1

5 Sub Main()

7 Dim myArrayList As New ArrayList(4)

9 myArrayList.Add(Bit)

10 myArrayList.Add(Byte)

11 myArrayList.Add(Kilobyte)

12

13 Console.WriteLine(Initial Addition of Elements:)

14 Console.WriteLine(The capacity of MyArrayList is ----> & MyArrayList.


Capacity)

15 Console.WriteLine(The number of used items is -------> & MyArrayList.


Count)

LOVELY PROFESSIONAL UNIVERSITY

181

Modern Programming Tools & Techniques-III

Notes

16 Console.WriteLine(------------------)

17

18 MyArrayList.Add(Megabyte)

19 MyArrayList.Add(Gigabyte)

20

21 Console.WriteLine(After Adding Two More Elements:)

22 Console.WriteLine(The capacity of MyArrayList is ----> & MyArrayList.


Capacity)

23 Console.WriteLine(The number of used items is -------> & MyArrayList.


Count)

24 Console.WriteLine(------------------)

25 End Sub

26

27 End Module

This example shows the dynamic nature of an arraylist. In line 7 above, myarraylist was created
as an arraylist with four elements. Lines 9 through 11, show how to assign values To the elements
of myarraylist using the method add(). As a result of the adding the three values, the following
will take place in the memory:

myarraylist(0) = bit

myarraylist(1) = byte

myarraylist(2) = kilobyte

In order to show a value on the screen in console mode, we need to use console class and
write-Line() or write( ) method. Once the method writeline( ) finishes printing a line, it advance
theCarriage return to the next line, while the method write( ) does not.
Line 14 prints the capacity of myarraylist, using the myarraylist.capacity( )method. The resultIs 4.
We reserved 4 items for the arraylist initially and we used 3, therefore the capacity has not been
totally used. it is still 4. When we used the method count( ) with myarraylist.count(), it shows in
the output the value 3. The value 3 indicates that only three elements out of the f have been used.
Line 18 and 19 added two more values to MyArrayList. It was not MyArrayList created to hold
only four elements initially? Yes, but adding two more values will exceed the original size of
MyArrayList, therefore MyArrayList immediately doubled its capacity to eight elements. This is
exactly the reason for calling ArrayList a dynamic structure. Printing the new capacity and the
number of items used in myArrayList seen in line 21 through 24 will prove that the capacity is
eight and the number of the assigned items is five.
It is interesting to see how ArrayList doubles its own capacity (size) dynamically as soon as we
exceed the original size by one more element. This flexibility is very hard to obtain using array,
especially during running time.
ArrayList is a very powerful structure. It contains helpful properties (characteristics) and
powerful methods (processes) that save programmers hours. An ArrayList is dynamic which
allows for the expansion or shrinking of the number of its own elements. This ability itself
provides programmers with the capacity to maximize their code without having to worry about
redimensioning their arrays frequently, since ArrayLists have come to the rescue.
You create an ArrayList and then create three synchronization wrapper objects, each of which
exposes the ICollection interface. Since each of the wrapper objects actually manipulates the

182

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

same underlying array, the SyncRoot object used by each of the wrappers is the non-thread-safe
ArrayList, as depicted in Figure 9.2:

Notes

Figure 9.2: Non-thread-safe ArrayList


ArrayList
(thread safe)

ArrayList
(thread safe)

ArrayList
(thread safe)

ArrayList
(sync root)

Array

Write a program to create an ArrayList.

9.2 HashTable
The Hashtable class represents a dictionary of associated keys and values, implemented as a
hash table. A hashtable is a proven way of efficiently storing and retrieving values using the
hash of a key value.
Using the Hashtable class is straightforward. You can create an instance of the Hashtable class
and use a text indexer to set and retrieve associated keys and values.
You can determine if a key is contained within the hash table using the ContainsKey method.
Using VB.NET, you would write:
If ourSession.ContainsKey(value1) = True Then
Response.Write(The key value1 is in the Hashtable)
End If
You could of course use the Contains method to determine if a key is present, but since all that
does is call the ContainsKey method, there is no point. You can determine if a specified value is
held within the Hashtable using the ContainsValue method. Using VB.NET, you would write:
If ourSession.ContainsValue(Wrox) = True Then
Response.Write(The value Wrox is in the Hashtable)
End If
Figure 9.3 demonstrates the creation of a Hashtable, and the use of the ContainsKey and
ContainsValue methods:
Although the Hashtable allows any object type to be used as a key, only those types that
override System.Object.GetHashCode and System.Object.Equals should actually be used. All
of the primitive types in .NET, such as integer and string, override these methods and are safe
to use as keys.
A hashtable depends on hash codes to uniquely identify keys. Hash codes are numbers that,
where possible, uniquely identify a single object instance of a specific type. A perfect hash code
algorithm will always return a hash code that is unique to a single instance of a specific type.

LOVELY PROFESSIONAL UNIVERSITY

183

Modern Programming Tools & Techniques-III

Notes

Figure 9.3: Creation of Hashtable

A good candidate for a hash code is something along the lines of the identity field for a row
within a database. The Hashtable class uses hash codes to provide efficient and fast lookups.
When creating custom types, you also have to implement a good hash code algorithm.
Hash codes enable classes like Hashtable to efficiently store and retrieve values. When an item
is added to a Hashtable, the hash code of its associated key is used to determine a slot in which
an item can be held. If a key with the same hash code does not already exist at the slot located
using the hash code, the value can be saved. If the slot is already full, System.Object.Equals is
called to determine if the key already in the slot is in fact equal to the one used to locate the slot.
If both keys are equal, an exception is thrown. If the keys are different, a new key and value is
added to the hash table in a different slot.
For these reasons, any type used as a key within a hash table must:

Implement an efficient hash code algorithm that (where possible) uniquely identifies an
object of a specific type. This means that you must override System.Object.GetHashCode.

Override the System.Object.Equals method and provide an efficient comparison of two


object instances. Typically, you would implement this by comparing the hash codes (if
you can be sure that the hash code is always unique), or key fields that are held within a
type as fields.

9.3 Stack
The .NET includes a Stack class inside the System.Collections namespace. It is efficient because
it is implemented using a System.Collections.ArrayList, so if you need to consume a stack, it is
a better idea to use the built in .NET stack class.
A stack is a data structure that allows adding and removing objects at the same position. The
last object placed on the stack is the first one to be removed following a Last in First out (LIFO)
data storing method.

9.3.1 Common Functions


The most common functions to manipulate a stack are:

184

Push(element): Adds a new object to the last position of the stack.

Pop(): Returns and removes the last object of the stack.

Peek(): Returns the last object without removing it.

IsEmpty(): Validates if the stack is empty.


LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

9.3.2 Implementation

Notes

There are many ways to implement a stack. You can use a stack:

To keep the demonstration simple, even though you might consider using a linked list to
allow dynamic resizing.

To define the maximum size of the stack at compilation time, but you might also define
it at runtime.

To use an index to store the last object position (bottom of the stack) at any time.

Each time a Push() operation is done, it validate if the stack has enough space, then increment
the index, and add the new object. Each time a Pop() operation is done and validate if the stack
IsEmpty() then decrease the index, and return the last object. Each time a Peek() operation is
done, it validate if the stack IsEmpty(), and return the last object.
The following sample code illustrates a sample VB.Net stack implementation:
Imports System
Namespace DotNetTreats.DataStructures
Public Class Stack
Private Const MaxSize As Integer = 100
Private _items As Object() = New Object(MaxSize - 1){}
Private _currentIndex As Integer = -1
Public Sub New()
End Sub
Public Sub Push(ByVal element As Object)
If _currentIndex >= MaxSize 1 Then
Throw New InvalidOperationException(Stack is full)
End If
_currentIndex += 1
_items(_currentIndex) = element
End Sub
Public Function Pop() As Object
If IsEmpty() Then
Throw New InvalidOperationException(No elements in
stack)
End If
Dim element As Object = _items(_currentIndex)
_items(_currentIndex) = Nothing
_currentIndex = 1
Return element
End Function
Public Function Peek() As Object
If IsEmpty() Then
Throw New InvalidOperationException(No elements in
stack)

LOVELY PROFESSIONAL UNIVERSITY

185

Modern Programming Tools & Techniques-III

Notes

End If
Return _items(_currentIndex)
End Function
Public Function IsEmpty() As Boolean
If _currentIndex < 0 Then
Return True
Else
Return False
End If
End Function
End Class
End Namespace

9.3.3 Usage Scenarios


Once the stack is implemented, a program can consume it. The following console application
represents a simple way to consume the stack.
Scenario 1: Simple Consumer
Imports System

Namespace DotNetTreats.DataStructures
Friend Class stackconsumer
Public Sub New()
End Sub

<STAThread> _

Shared Sub Main(ByVal args As String())


simple stack consumer

Dim stack As Stack = New Stack()


Dim x As Integer = 9

Dim y As String = foo

Console.WriteLine(Push 9)
stack.Push(x)

Console.WriteLine(stack.Peek().ToString())
Console.WriteLine(Push foo)
stack.Push(y)

Console.WriteLine(stack.Peek().ToString())

Console.WriteLine(Pop -> foo, 9 is at the top now.)


stack.Pop()

Console.WriteLine(stack.Peek().ToString())
Expression validator

Dim eval As ExpressionValidator


ExpressionValidator()
Console.WriteLine(Write an equation.)
Dim result
ReadLine())

As

Boolean

New

eval.Validate(Console.

If result Then

186

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Console.WriteLine(Valid)

Notes

Else
Console.WriteLine(Invalid)
End If
End Sub
End Class
End Namespace
Scenario 2: Expression validation
Equations as well as some string expressions use parenthesis, braces and brackets to open and
close parts of the expression. Many programs require validating if in a given string expression,
all the opening parenthesis have a matching closing parenthesis (balanced expressions). Some
compilers check if functions have balanced opening and closing brackets. Some XML and HTML
editors check if all the tags have a corresponding closing tag.
To solve this kind of problems it is recommended to use a stack. The general idea is to parse
a string character by character. Each time an opening parenthesis or tag is found, a Push()
operation is executed, and each time a corresponding closing parenthesis or tag is found a Pop()
operation is executed. If the program finishes parsing the document and the stack IsEmpty() ,
the equation or expression is valid; otherwise, if the stack has elements, then some matching
parenthesis are missing and the expression is invalid.
The following sample represents an expression validation with a stack.
Initial expression: ((X+Y) 1)*2

The first parenthesis is parsed ((X+Y) 1)*2 and a Push() operation is executed.

The second parenthesis is parsed ((X+Y) 1)*2 and a Push() operation is executed.

A closing parenthesis is parsed ((X+Y) 1)*2 and a Pop() operation is executed.

A closing parenthesis is parsed ((X+Y) 1)*2 and a Pop() operation is executed.

The stack is empty so the expression is valid.

The following sample code validates expressions that use the following characters: ( ), { },
and [ ].
Imports System

Namespace DotNetTreats.DataStructures
Public Class ExpressionValidator

Public Function Validate(ByVal equation As String)


As Boolean
Dim stack As Stack = New Stack()
Dim i As Integer = 0

Do While i < equation.Length

Dim current As Char = equation.Chars(i)


Select Case current

Case (c, [c, {c


stack.Push(current)

Case )c, ]c, }c

If stack.IsEmpty() Then

LOVELY PROFESSIONAL UNIVERSITY

187

Modern Programming Tools & Techniques-III

Return False

Notes

End If

Dim x As Char = CChar(stack.Pop())

If (x = (c AndAlso current <> )c) OrElse (x =


[c AndAlso current <>]c) OrElse (x = {c AndAlso
current <>}c) Then
Return False
End If

End Select
i += 1
Loop

If stack.IsEmpty() Then
Return True
End If

Return False
End Function
End Class

End Namespace
Some more examples of stack can be discussed as follows:
Example:
This example shows how you can Push elements to the top of a Stack repeatedly. Then, we use
the For Each looping construct to display the Stack in the order from first to last. You can see
that the most recently added element (1000) is at the top of the Stack.
Program that uses Stack [VB.NET]
Module Module1

Sub Main()

Dim stack As Stack(Of Integer) = New Stack(Of Integer)


stack.Push(10)
stack.Push(100)
stack.Push(1000)
Display stack elements.
For Each value As Integer In stack
Console.WriteLine(value)
Next
End Sub
End Module
Output
1000
100
10

188

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Notes

Example:
This example introduces the Pop and Peek functions on the Stack. With Pop, you take the top
element off of the Stack and it is stored in the return value. It no longer is part of the Stack.
With Peek, you take the top element and copy it to the return value, but it is not removed. To
avoid exceptions with an empty stack, use the Count property and test it against zero.
Program that uses Pop and Peek [VB.NET]
Module Module1
Sub Main()
Dim stack As Stack(Of Integer) = New Stack(Of Integer)
stack.Push(10)
stack.Push(100)
stack.Push(1000)
Test Pop.
Dim value As Integer = stack.Pop
Console.WriteLine(Element popped: {0}, value)
Test Peek.
value = stack.Peek
Console.WriteLine(Element peeked: {0}, value)
End Sub
End Module
Output
Element popped: 1000
Element peeked: 100
The stack was first proposed in 1946, in the computer design of Alan M.
Turing (who used the terms bury and unbury) as a means of calling and
returning from subroutines.

9.4 Queue
Queues are one of the common classic data structures found in computer science. A queue
is simply a First-In-First-Out (FIFO) buffer where new items are added to the end of the list
and the item at the front of the list is processed first. Implementing one in VB has not always
been easy due to the lack of pointers. While there were some ways to work around this, the
programming could get messy and difficult to understand. However, the Queue collection type
was introduced in the original .NET Framework and now, in the .NET Framework 2.0, we now
have the generic Queue class to make it a breeze to implement.
As with other .NET Generic Collection classes, the queue is a type-safe collection. This means
that you must define the type of object that is to be queued and only objects of that type can be
placed in the queue. Here are a few examples:
Dim NameQueue As Queue(Of String)
Dim MailQueue As Queue(Of Net.Mail.MailMessage)
Dim OrderQueue As Queue(Of OrderDetailItems)

LOVELY PROFESSIONAL UNIVERSITY

189

Modern Programming Tools & Techniques-III

Notes

9.4.1 Common Functions


The basic operations of a queue are:

Enqueue

Dequeue

Enqueue places a new item at the end of the queue while Dequeue removes the first item in the
queue from the list and returns it to the caller. The queue automatically expands to accommodate
new members. Here are some simple examples:
NameQueue.Enqueue(CurrentName)
Do While MailQueue.Count > 0
SendMail(MailQueue.Dequeue)
Loop
If you wanted to view the next item in the queue without removing it, you can use the Peek
function as seen in this example:
If IsSignedUp(MailQueue.Peek.To) Then
SendMarketingEmail(MailQueue.Dequeue)
Else
SendSignUpEmail(MailQueue.Dequeue)
End If
To further manage the Queue there is the Clear command that removes all of the contents of the
Queue and the Count property to get the current number of items in the queue. There is also
the Contains function that you can use to find out if a particular item is already in the queue.
Example:
If Not FileNameQueue.Contains(NewFileName) Then
FileNameQueue.Enqueue(NewFileName)
End If
One feature that you might find helpful at times is the ability to copy the Queue to an Array
as seen here:
Dim MailList() As Net.Mail.MailMessage = MailQueue.ToArray()

9.4.2 Use of Queue


Queues are particularly useful for situations where you have longer operations to process,
such as parsing or converting a large data file. For example, if you have files arriving in a FTP
folder you would use FileSystemWatcher to detect the files as they arrived and place them in
the queue. Then, at some point, such as every 30 minutes, the current items in the queue would
be processed in the order they arrived and a new queue would be started.
Another example would be having a central order system prepare a queue of items for a remote
fulfilment centres. The fulfilment centre system would retrieve a serialized queue of orders via a
web service from the order locations web site and then work through the order objects within it.
The following VB.NET Source code shows some of commonly used functions:
Public Class Form1

190

Private Sub Button1_Click(ByVal sender As System.Object,_

ByVal e As System.EventArgs) Handles Button1.Click

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Dim queueList As New Queue

queueList.Enqueue(Sun)

queueList.Enqueue(Mon)

queueList.Enqueue(Tue)

queueList.Enqueue(Wed)

queueList.Enqueue(Thu)

queueList.Enqueue(Fri)

queueList.Enqueue(Sat)

MsgBox(queueList.Dequeue())

MsgBox(queueList.Peek())

If queueList.Contains(Sun) Then

Notes

MsgBox(Contains Sun )

Else

MsgBox(Not Contains Sun )

End If

End Sub

End Class
Example:
In this example, we explore how the Queue can be used to store help requests in a system. As
users request help for a program, the requests can be added to the Queue with Enqueue. Then,
those requests (represented by the RequestType Enum) can be read with Dequeue after testing
them with Peek.
Program that uses Enum Queue [VB.NET]
Module Module1

Enum RequestType As Integer

MouseProblem
TextProblem
ScreenProblem
ModemProblem
End Enum
Sub Main()

Dim help As Queue(Of RequestType) = New Queue(Of RequestType)()

Add some problems to the queue.

help.Enqueue(RequestType.TextProblem)
help.Enqueue(RequestType.ScreenProblem)

If first problem is not a mouse problem, handle it.

If help.Count > 0 Then

If Not help.Peek = RequestType.MouseProblem Then

LOVELY PROFESSIONAL UNIVERSITY

191

Modern Programming Tools & Techniques-III

Notes


This removes TextProblem.
help.Dequeue()

End If

End If

Add another problem.

help.Enqueue(RequestType.ModemProblem)

See all problems.

For Each element As RequestType In help

Console.WriteLine(element.ToString())

Next
End Sub
End Module
Output
ScreenProblem
ModemProblem
The Standard Template Library (STL), and the C++ 1998 standard, specifies
priority_queue as one of the STL container adaptor class templates.
If the queue is empty that the Dequeue function will return an
InvalidOperationException.

Self Assessment Questions


Multiple Choice Questions

1. A hashtable is a proven way of efficiently storing and retrieving values using the hash of
a ............

(a) value

(b) key value

(c) variable

(d) sorting value

2. The ArrayList class is found in the system collection namespace.



(b) False

3. The Hashtable class uses hash codes to provide efficient and ..............

(a) Fast lookups

(b) slow lookups

(c) Both (a) and (b)

(d) None of these

192

(a) True

4. ArrayList is dissimilar to an array because the number of its objects (elements) can grow
.................

(a) variable

(b) element

(c) data

(d) dynamically

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Notes

5. Arraylist is a...................

(a) .NET framework

(b) element

(c) .NET technology

(d) language

9.5 SortedList
The SortedList object contains items in key/value pairs. A SortedList object automatically sorts
the items in alphabetic or numeric order.
Items are added to the SortedList with the Add() method. A SortedList can be sized to its final
size with the TrimToSize() method.
SortedLists come in handy when developers need to maintain a collection of objects that is sorted
every time an item is added or removed. In the following example, you will look at a way of
implementing and utilizing SortedLists in VB.NET.
Example:
The following code creates a SortedList named mycountries and four elements are added:
<script runat= server>
sub Page_Load
if Not Page.IsPostBack then
dim mycountries=New SortedList
mycountries.Add(N, Norway)
mycountries.Add(S,Sweden)
mycountries.Add(F, France)
mycountries.Add(I, Italy)
end if
end sub
</script>

9.5.1 Advantages and Disadvantages of Using a SortedList


System.Collections.SortedList type is a key-based dictionary type that allows you to store items
in an ordered manner. This is advantageous whenever you need to be able to store sorted data
without going through a separate routine of sorting the contents of a collection. The convenience
of a SortedList comes at the price of slower additions and removals of items to the list. A
SortedList utilizes two arrays internally: one array stores keys, while another stores the data
or object reference.
When you work with SortedLists in VB.NET, keep in mind that objects are sorted based on
the key value and not an object itself; therefore, the key needs to be a type that supports
IComparableeither an integer or a string. Otherwise, you have to create a custom IComparer
as an argument to the SortedList when defining the SortedList.
Example:
This example first creates a List of three String instances. Then it invokes the Sort subroutine.
This subroutine does not return a value. Instead it changes the List to be sorted.
Program that uses Sort function on List [VB.NET]
Module Module1

LOVELY PROFESSIONAL UNIVERSITY

193

Modern Programming Tools & Techniques-III

Notes

Sub Main()
Dim l As List(Of String) = New List(Of String)
l.Add(tuna)
l.Add(velvetfish)
l.Add(angler)
Sort alphabetically.
l.Sort()
For Each element As String In l
Console.WriteLine(element)
Next
End Sub
End Module
Output
angler
tuna
velvetfish
Example:
This example shows the use of reverse function. The Reverse subroutine is very similar in some
ways to the Sort subroutine. It simply inverts the order of the elements in the List from their
original order. It does not do any sorting. As with Sort, you do not need to assign anything to
the result of Reverse.
Program that uses Reverse function [VB.NET]
Module Module1

Sub Main()
Dim l As List(Of String) = New List(Of String)

l.Add(anchovy)
l.Add(barracuda)
l.Add(bass)

l.Add(viperfish)

Reverse list.

l.Reverse()

For Each element As String In l

Console.WriteLine(element)

Next

End Sub

End Module
Output
viperfish

194

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

bass

Notes

barracuda
anchovy

9.6 BitArray
A BitArray object can hold a large number of Boolean values in a compact format, using a single
bit for each element. This class implements IEnumerable (and thus supports foreach), ICollection,
and ICloneable. You can create a BitArray object in many ways:
// Provide the number of elements (all initialized to false).
BitArray ba = new BitArray(1024);
// Provide the number of elements, and initialize them to a value.
BitArray ba2 = new BitArray(1024, true);
// Initialize the BitArray from an array of bool, byte, or int.
bool[] boolArr = new bool[1024];
// Initialize the boolArr array here.
BitArray ba3 = new BitArray(boolArr);
// Initialize the BitArray from another BitArray object.
BitArray ba4 = new BitArray(ba);
You can retrieve the number of elements in a BitArray by using either the Count property or
the Length property. The Get method reads and the Set method modifies the element at the
specified index:
// Set element at index 9, and read it back.
ba.Set(9, true);
Console.WriteLine(ba.Get(9)); // => True
The CopyTo method can move all elements back to an array of Booleans, or it can perform a
bitwise copy of the BitArray to a zero-based Byte or Integer array:
// Bitwise copy to an array of Integers
int[] intArr = new int[32]; // 32 elements * 32 bits each = 1,024 bits
// Second argument is the index in which the copy begins in target array.
ba.CopyTo(intArr, 0);
// Check that bit 9 of first element in intArr is set.
Console.WriteLine(intArr[0]); // => 512
The Not method complements all the bits in the BitArray object:
ba.Not(); // No arguments
The And, Or, and Xor methods enable you to perform the corresponding operation on pairs of
Boolean values stored in two BitArray objects:
// Perform an AND operation of all the bits in the first BitArray
// with the complement of all the bits in the second BitArray.
ba.And(ba2.Not);
Finally, you can set or reset all the bits in a BitArray class using the SetAll method:
// Set all the bits to true.
ba.SetAll(true);

LOVELY PROFESSIONAL UNIVERSITY

195

Modern Programming Tools & Techniques-III

Notes

The BitArray type does not expose any methods that enable you to quickly determine how many
true (or false) elements are in the array. You can take advantage of the IEnumerator support of
this class and use a foreach loop:
int bitCount = 0;
foreach ( bool b in ba )
{
if ( b )
{
bitCount += 1;
}
}
Console.WriteLine(Found {0} True values., bitCount);

Write a program to create a list and sort it.

9.7 BitVector32
The BitVector32 class (in the System.Collections.Specialized namespace) is similar to the BitArray
class in that it can hold a packed array of Boolean values, one per bit, but it is limited to 32
elements. However, a BitVector32 object can store a set of small integers that takes up to 32
consecutive bits and is therefore useful with bit-coded fields, such as those that you deal with
when passing data to and from hardware devices.
BitVector32 bv = new BitVector32();
// Set one element and read it back.
bv[1] = true;
Console.WriteLine(bv[1]); // => True
You can also pass a 32-bit integer to the constructor to initialize all the elements in one pass:
// Initialize all elements to true.
bv = new BitVector32(-1);
To define a BitVector32 that is subdivided into sections that are longer than 1 bit, you must create
one or more BitVector32.Section objects and use them when you later read and write individual
elements. You define a section by means of the BitVector32.CreateSection static method, which
takes the highest integer you want to store in that section and (for all sections after the first
one) the previous section.
Example:
bv = new BitVector32();
// Create three sections, of 4, 5, and 6 bits each.
BitVector32.Section se1 = BitVector32.CreateSection(15);
BitVector32.Section se2 = BitVector32.CreateSection(31, se1);
BitVector32.Section se3 = BitVector32.CreateSection(63, se2);
// Assign a given value to each section.
bv[se1] = 10;

196

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

bv[se2] = 20;

Notes

bv[se3] = 40;
// Read values back.
Console.WriteLine(bv[se1]); // => 10
Console.WriteLine(bv[se2]); // => 20
Console.WriteLine(bv[se3]); // => 40
The Data property sets or returns the internal 32-bit integer; you can use this property to save
the bit-coded value into a database field or to pass it to a hardware device:
// Read the entire field as a 32-bit value.
Console.WriteLine(bv.Data); // => 20810
Console.WriteLine(bv.Data.ToString(X)); // => 514A

Stack Overflow
Situation
Two prominent bloggers in the world of software development wanted to create a Question
and Answer Web site that would provide a central repository for accumulating programming
wisdom as developers posted questions and their peers posted replies.
Jeff Atwood, developer and author of the popular programming and human factors blog
Coding Horror; and Joel Spolsky, developer and the author of the software development
blog Joel on Software, and founder of Fog Creek Software, envisioned their Web site as a
community-run organization similar to Wikipedia. The two also saw the site as incorporating
aspects of blogging as well as community voting in the spirit of the Digg and Reddit social
news Web sites in which the prominence of information is based upon user ranking of its
relevance.
The mission of the site was summed up in a blog entry by Atwood that reads: None of Us
is as Dumb as All of Us.
Atwood and Spolsky wanted to create a site that behind the scenes was simple and fast, with
code that was lean and scalable. They were dissatisfied with traditional Web development
approaches that used an abstraction layer and that embedded code on Web pages to preserve
view states. In addition to potentially slowing response rates, they were concerned that
storing code on pages could adversely impact search engine optimization because view
state information at the top of a page could potentially lessen the relevance a search engine
accords to the actual page content found lower on the page.
The two developers wanted to create their new solution using a Model-View-Controller (MVC)
approach, which simplifies application programming. MVC architecture, first described by
Trygve Reekskaug in 1979, uses a design pattern based upon a model which provides a data
representation relevant to the needs of the application; a view, or interface, for interacting
with the data model; and a controller for mediating between the view and the model objects.
The three together are sometimes referred to as a triplet, and MVC-based applications can
be assembled as a series of triplets, each independent of the other.
The two wanted to create their site using the Microsoft Application Platform, but needed
an MVC solution. We were definitely sticking with the Microsoft stack because we like the
Microsoft stack, Atwood says. We are big fans of the language C#. Historically C# has
evolved rapidly, and in ways that we like. To stay within C# we were preparing to create
Contd...

LOVELY PROFESSIONAL UNIVERSITY

197

Modern Programming Tools & Techniques-III

Notes

our own MVC implementation, but then we heard about the beta version of the Microsoft
ASP.NET MVC Framework.
Solution
Atwood and Spolsky created their new siteStack Overflowusing the ASP.NET MVC
Framework, the Visual Studio 2008 development system, and the Microsoft .NET Framework
3.5, which are all part of the Microsoft Web Platform. The site, which was created within two
months, proved popular and was able to scale to support what turned out to be rapid growth.
Stack Overflow has grown incredibly fast, Spolsky says. After a year in business, it gets
over a million page views most weekdays and currently stands as the 817th largest site on
the Internet, according to Quantcast. It reaches 5.2 million people a month. At last count
the site hosted 500,000 questions along with the related answers and discussions, ranked
according to what the community felt were the best responses.
The two have repurposed the same code to broaden the scope beyond programmers,
launching sister sites including Server Fault, for system administrators, and Super User, for
computer power users.
A spin off of the software, called StackExchange, has been released by Fog Creek Software
to allow third parties to build Stack-Overflow communities around other topics. You can
use the same software to create a Q&A site about anything, Atwood says. Someone could
create a Stack Overflow Q&A community for airplanes, or stamp collecting, geology, or any
other area of interest.
Stack Overflow was created using the Microsoft Web Platform, which in addition to
development tools includes the Windows Server 2008 operating system, Internet Information
Services (IIS) 7, and Microsoft SQL Server 2008 database software.
The basic elements of Stack Overflow include:

Load Balancing. Users entering the stackoverflow.com site are first handled by a load
balancer, which assigns a user to one of several Web servers according to IP address.
Users continue to be assigned to the same server for as long as they have the same IP
address. Stack Overflow uses the open-source HAProxy for this load balancing.

Presentation. Customers browse pages served by Windows Server 2008 Standard,


through IIS 7.5. The Web servers are computers with Xeon quad core CPUs and 8
gigabytes (GB) RAM. When a user submits a question or an answer, their information
is written to the database using the lightweight LINQ to SQL database abstraction layer.

Database. The database is hosted on a dedicated server with 2 Intel Xeon quad core
CPUs and 48 GB of RAM, and runs Microsoft SQL Server 2008 Enterprise. Stack
Overflow takes advantage of the Online Indexing feature, introduced with SQL Server
2008 Enterprise, which enables table re-indexing while the database continues to run.
We designed this to be a next generation Q&A site, Atwood says. We tried to combine
aspects of Wikis, in that everybody can edit everything once the system learns to trust
them. Voting, as with DIGG and REDDIT, are an important component. Stack Overflow has
a reputation system which comes out of the voting, so as other people vote your content
up that increases your reputation score and it unlocks different abilities on the site as the
system learns to trust you. It has elements of blogging in that there is a strong sense of
ownership. When you create a question you are the owner of that question and you have
special privileges as you curate that question. And, like a blog, people can post comments.
We wanted to synthesize the best of what we saw in all of these types of communities and
bring them all together into one simple site.
Contd...

198

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Notes

Benefits
Building the Stack Overflow solution using the ASP.NET MVC Framework, the .NET
Framework 3.5, Visual Studio 2008, and other elements of the Microsoft Web Platform gave
the site the high performance and fast development that the developers had anticipated
they would gain from using an MVC approach. Developers found that testing and code
maintenance was easier using the ASP.NET MVC Framework. The company has also
benefited from the strong developer community that has emerged to support the ASP.NET
MVC Framework.
High Performance
The Stack Overflow team was impressed by the performance of the site they created using
the Microsoft Web Platform. Our site is definitely faster than if we had created it with a
more traditional abstraction-based Web architecture, Atwood says. The .NET Framework
is responsible for much of the speed we see, but ASP.NET MVC plays a role because it is
so lightweight. It enhances performance.
The high performance also contributes to the real-world scalability Stack Overflow has
enjoyed. I want to emphasize that MVC not only works from an architectural standpoint
of clean code and sensibility, but it also scales really well in the wild, Atwood says.
Fast Development
Stack Overflow developers credit the clean separation between presentation code, business
logic, and the data model they gained by using the ASP.NET MVC Framework with
enabling faster development than they could have achieved using abstraction-based Web
development models. The developers also praised the low-level HTTP control they gained
using ASP.NET MVC.
The first thing that saved us time was that Microsoft created an MVC framework so that we
did not have to create our own, Atwood says. ASP.NET MVC provides a simple framework
that enables developers to work very efficiently. It mapped very well to our mental model
of what Web development should be.
The developers liked the design of ASP.NET MVC. Microsofts MVC implementation is
well designed in the sense that it anticipates all the standard work a Web developer would
have to do, Atwood says. So there is great coverage for the basics, and a clean framework
that enables you to go far beyond the basics. We never felt that there was something that
we could not do within the MVC framework.
The openness of the framework was appreciated by the developers. ASP.NET MVC is very
pluggable, Atwood says. Microsoft allows you to use your own viewer, for example. One
of our developers loves jQuery [an open-source JavaScript library] and so we use jQuery,
which is supported by Microsofts implementation of MVC. We also like that Microsoft has
posted the source code for ASP.NET MVC on the CodePlex open-source site.
Easier Testing and Code Maintenance
The Stack Overflow team is enjoying the separation of concerns that is inherent to an MVC
approach to development, finding that code written with an MVC pattern is easier to test
and maintain because logic is not integrated into the view state.
With MVC you have a more logical structure for the code, Atwood says. By keeping
application logic in the controller or data model, it is easier to create, test, and maintain
the code. The more traditional method of embedding a lot of code into the view makes for
cumbersome development and can create difficult testing scenarios. MVC enables a more
Contd...

LOVELY PROFESSIONAL UNIVERSITY

199

Modern Programming Tools & Techniques-III

Notes

direct control of HTML than working through an abstraction layer, and this also makes it
easier to test and maintain the code.
Strong Community
Atwood says he enjoys the strong community he sees developing around the ASP.NET MVC
Framework. Developers are excited to have an MVC implementation designed to interoperate
with Visual Studio, the .NET Framework, and other elements of the Microsoft Web Platform.
He identified Microsofts posting of its MVC source code to CodePlex as representing a large
contribution to the sense of community that is developing around the product.
During the beta phase, some common bugs were identified by members of the developer
community, Atwood says. The difference was that this time we did not have to wait for
Microsoft to post the bug fixes. Someone in the community just posted their own fix, because
they had access to the code. The community is way faster than a company can be. We just
downloaded the fix and were on our merry way.
With Microsoft at the core of the community, Atwood likes the fact that Microsoft will
continue to enhance the MVC Framework.
A basic rule of programming is to never write what you can buy or get for free, Atwood
says. An MVC implementation was needed. Microsoft created one, and it is generally
accepted within the Microsoft developer community that they did a great job on this. It
is reassuring to know that Microsoft will continue to build upon and support its MVC
framework because we are huge fans of the .NET Framework, C#, and Visual Studio. We
love these tools. Part of the reason we built Stack Overflow was to show people: Look, you
can build really awesome stuff with this stack.
Questions

1. What is the problem of stack overflow?

2. What are the benefits to build the solution for stack overflow using ASP.NET MVC
Framework?

Self Assessment Questions


Multiple Choice Questions

6. Which of the following statements are correct about an ArrayList collection that implements
the IEnumerable interface?

(i) The ArrayList class contains an inner class that implements theIEnumerator interface.

(ii) An ArrayList Collection cannot be accessed simultaneously by different threads.

(iii) The inner class of ArrayList can access ArrayList classs members.

(iv) To access members of ArrayList from the inner class, it is necessary to pass ArrayList
classs reference to it.

(v) Enumerators of ArrayList Collection can manipulate the array.

(a) (i) and (ii)

(b) (i), (iii) and (iv)

(c) (ii) and (v)

(d) All of these.

7. Which of the following is NOT an interface declared in System.Collectionsnamespace?

200

(a) IComparer

(b) Enumerable.

(c) Enumerator

(d) IDictionaryComparer

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

8. Which of the following statements are correct about the Stack collection?

(i) It can be used for evaluation of expressions.

(ii) All elements in the Stack collection can be accessed using an enumerator.

(iii) It is used to maintain a FIFO list.

(iv) All elements stored in a Stack collection must be of similar type.

(v) Top-most element of the Stack collection can be accessed using the Peek()method.

(a) (i) and (ii)

(b) (iii) and (iv)

(c) (i), (ii) and (v)

(d) All of these.

Notes

9. How many enumerators will exist if four threads are simultaneously working on
anArrayList object?

(a) 1

(b) 3

(c) 2

(d) 4

10. In which of the following collections is the Input/Output index-based?


(i) Stack

(ii) Queue

(iii) BitArray

(iv) ArrayList

(a) (i) and (ii)

(b) (iii) and (iv)

(c) (iv)

(d) (i), (ii) and (v)

11. Which of the following is an ordered collection class?


(i) Map

(ii) Stack

(iii) Queue

(iv) BitArray

(a) (i)

(b) (ii) and (iii)

(c) (iii) and (iv)

(d) All of these

12. Which of the following statements are correct about the Collection Classes available in
Framework Class Library?

(a) Elements of a collection cannot be transmitted over a network.

(b) Elements stored in a collection can be retrieved but cannot be modified.

(c) It is not easy to adopt the existing Collection classes for newtype of objects.

(d) They use efficient algorithms to manage the collection, thereby improving the
performance of the program.

13. In which of the following collections is the Input/Output based on a key?


(i) Map

(ii) Stack

LOVELY PROFESSIONAL UNIVERSITY

201

Modern Programming Tools & Techniques-III

Notes

(iii) BitArray

(iv) HashTable

(v) SortedList

(a) (i) and (ii)

(b) (ii) and (iii)

(c) (i), (ii) and (iii)

(d) (iv) and (v)

14. Which of the following is the correct way to find out the number of elements currently
present in an ArrayList Collection called arr?

(a) arr.Count

(b) arr.GrowSize

(c) arr.MaxIndex

(d) arr.Capacity

15. In a HashTable Key cannot be null, but Value can be?


(a) True

(b) False

9.8 Summary

All the collection classes in the .NET Framework implement the ICollection interface.

ArrayList is dissimilar to an array because the number of its objects (elements) can grow
dynamically.

A stack is a data structure that allows to add and remove objects at the same position.

Once the stack is implemented, a program can consume it.

A queue is simply a First-In-First-Out (FIFO) buffer where new items are added to the
end of the list and the item at the front of the list is processed first.

Queues are particularly useful for situations where you have longer operations to process,
such as parsing or converting a large datafile.

SortedLists maintain a collection of objects that is sorted every time an item is added or
removed.

A BitArray object can hold a large number of Boolean values in a compact format, using
a single bit for each element.

A BitVector32 object can store a set of small integers that takes up to 32 consecutive bits
and is therefore useful with bit-coded fields.

9.9 Keywords
ArrayList Class: It implements the IList interface using an array whose size is dynamically
increased as required.
ICollection Interface: Defines size, enumerators and synchronization methods for all collections.
IDictionary Interface: Represents a nongeneric collection of key/value pairs.
IEnumerable Interface: Exposes the enumerator, which supports a simple iteration over a nongeneric collection.
IList Interface: Represents a non-generic collection of objects that can be individually accessed
by index.

202

LOVELY PROFESSIONAL UNIVERSITY

Unit 9: Using System.Collections

Queue Class: Represents a first-in, first-out collection of objects.

Notes

Stack Class: Represents a simple last-in-first-out (LIFO) non-generic collection of objects.


1. Write a program to implement stack and also implement Push and Pop
operation on its elements.
2. Write a program to implement a Hashtable.

9.10 Review Questions


11. Define Collections in .NET and briefly explain its types
12. Explain Interface inheritance for the core interfaces
13. The ArrayList is an extremely effective and helpful class in VB .NET. How?
14. What is the difference between Array and ArrayList? Explain briefly.
15. Explain AddRange and ReadOnly methods of Array List.
16. Discuss the common functions and uses of Stack class. How it is different from a Queue?
17. Discuss the advantages and disadvantages of using a SortedList.
18. Explain enqueue and dequeue.
19. Queue is a type-safe collection. Explain.
20. How is BitArray different from BitVector32?

Answers for Self Assessment Questions


1. (b)

2. (a)

3. (a)

4. (d)

5. (c)

6. (b)

7. (d)

8. (c)

9.

(d)

10.

(b)

11. (b)

12. (d)

13. (d)

14.

(a)

15.

(a)

9.11 Further Readings


.NET Gotchas, by Venkat Subramaniam.
Visual Studio .NET: The.NET Framework Black Book, by Julian Templeman.

http://visualbasic.about.com/od/usingvbnet/a/ienumble.htm

LOVELY PROFESSIONAL UNIVERSITY

203

Modern Programming Tools & Techniques-III

Unit 10: Windows Programming

Notes

CONTENTS
Objectives
Introduction
10.1 Controls

10.1.1

Control Tab Order

10.2

Button Control

10.2.1

Button Event

10.2.2

Working with Buttons

10.3

TextBox Control

10.3.1

10.4

RichTextBox

10.5

Label, Link Label

10.5.1 Label

10.5.2

Properties of Textbox Controls

Link Label

10.6 Checkbox
10.7

List Box

10.7.1

Properties of the List Box

10.8 ComboBox

10.8.1

Properties of the ComboBox

10.9

Tree View

10.9.1

Properties of TreeView

10.10

CheckedListBox

10.11 Panel, Group Box, Picture Box


10.11.1 Panel

10.11.2 GroupBox Control

10.11.3 PictureBox Control

10.12 ToolTip, Error Provider


10.12.1 ToolTip

10.12.2 Setting a ToolTip

10.12.3 ErrorProvider Component

10.12.4 Displaying an Error

10.13 Status Bar


10.14 RadioButton
10.15 Summary
10.16 Keywords
10.17 Review Questions
10.18 Further Reading

204

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Objectives

Notes

After studying this unit, you will be able to:


Explain the representation of textboxes and rich text boxes

Define box property

Understand the representation of date time picker

Discuss the combo boxes in VB

Explain the creation of buttons

Describes the creation of rich textbox

Explain the controls in VB.NET and its types

Introduction
Microsoft Visual Basic .NET is a programming environment used to create graphical user interface
(GUI) applications for the Microsoft Windows family of operating systems. It usually ships in
two types, either by itself or as part of Microsoft Visual Studio .NET. To use the chapter on
this site, you must have installed either Microsoft Visual Basic .NET or Microsoft Visual Studio
.NET. All instructions on this site will be based on an installation of Microsoft Visual Studio
.NET. From now on, unless specified otherwise, we will use the expressions Microsoft Visual
Basic or Visual Basic to refer to Microsoft Visual Basic .NET. If we want to refer to another
version, we will state it.
VB and Windows Programming
The VB language provides almost everything you need to create a computer application. To
create a typical program, you will use your knowledge of VB and additional new concepts we
will introduce.
A Windows application primarily appears as a rectangular object that occupies a portion of the
screen. This type of object is under the management of the operating system: Microsoft Windows.
Based on the functionality of Microsoft Windows, for an application to become useful, it must be
opened. An application must have an entry point. On a C/C++ application, this entry point is
a function called main. On a Win32 application, this entry point is a function called Win Main.
The VB language defines this entry point with a function called Main, as you should know
already from your learning VB.

10.1 Controls
A control is an object that can be drawn on to the Form to enable or enhance user interaction
with the application. An example of these controls, TextBoxes, Buttons, Labels, Radio Buttons,
etc. All these Windows Controls are based on the Control class, the base class for all controls.
Visual Basic allows us to work with controls in two ways: at design time and at runtime. Working
with controls at design time means, controls are visible to us and we can work with them by
dragging and dropping them from the Toolbox and setting their properties in the properties
window. Working at runtime means, controls are not visible while designing, are created and
assigned properties in code and are visible only when the application is executed. There are
many new controls added in Visual Basic .NET and we will be working with some of the most
popular controls in this section. You can select the controls from the menu towards the lefthand side of this page.

LOVELY PROFESSIONAL UNIVERSITY

205

Modern Programming Tools & Techniques-III

Notes

Properties of most of these Windows Controls which are based on the Control class itself are
summarized. You can always find the properties of the control with which you are working by
pressing F4 on the keyboard or by selecting View->Properties Window from the main menu.
The Control Class
The Control class is in the System.Windows.Forms namespace. It is a base class for the Windows
Controls. The class hierarchy is shown below:

Object

MarshalByRefObject

Component

Control

ButtonBase,Etc,Etc

Button, Etc, Etc

Main class is the Object class from which MarshalByRefObject class is derived and the Component
class is derived from the MarshalByRefObject class and so on.

10.1.1 Control Tab Order


To move focus from one control to other quickly using the keyboard we can use the Tab key.
We can set the order in which the focus is transferred by setting the tab order. The tab order
is the order in which controls on the form receive the focus and is specified by the Tab Index
property. To change the order in which a control receives focus we need to set the Tab Index
property to different value for each control on the form. Lower values receive the focus first
and proceed numerically through higher values. If there is a tie between Tab Index values, the
focus first goes to the control that is closest to the front of the form.
We can also set the tab order graphically with Visual Studio by selecting Tab Index from the
View menu. Boxes containing current tab order appear in each control when you select Tab
Index from View menu. Click each control to set the correct tab order in which you want the
controls to receive focus.
VB 1.0 was introduced in 1991.

10.2 Button Control


One of the most popular controls in Visual Basic is the Button Control (previously Command
Control). They are the controls which we click and release to perform some action. Buttons
are used mostly for handling events in code, say, for sending data entered in the form to the
database and so on. The default event of the Button is the Click event and the Button class is
based on the ButtonBase class which is based on the Control class.

10.2.1 Button Event


The default event of the Button is the Click event. When a Button is clicked it responds with
the Click Event. The Click event of Button looks like this in code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_System.EventArgs)
Handles
Button1.Click
You place the code here to perform action when Button is clicked
End Sub

206

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

10.2.2 Working with Buttons

Notes

Well, it is time to work with Buttons. Drag a Button from the toolbox onto the Form. The
default text on the Button is Button1. Click on Button1 and select its properties by pressing F4
on the keyboard View->Properties Window from the main menu. That displays the Properties
for Button1.
Appearance
Appearance section of the properties window allows us to make changes to the appearance of the
Button. With the help of BackColor and Background Image properties we can set a background
colour and a background image to the button. We set the font colour and font style for the text
that appears on button with ForeColor and the Font property. We change the appearance style
of the button with the FlatStyle property. We can change the text that appears on button with
the Text property and with the Text Align property we can set where on the button the text
should appear from a predefined set of options.
Behaviour
Notable Behaviour properties of the Button are the Enabled and Visible properties. The Enabled
property is set to true by default which makes the button enabled and setting its property to
False makes the button Disabled. With the Visible property we can make the Button Visible or
Invisible. The default value is set to true and to make the button Invisible set its property to False.
Layout
Layout properties are about the look of the Button A control can be docked to one edge of its
parent container or can be docked to all edges and fill the parent container. The default value is
set to none. If you want to dock the control towards the left, right, top, bottom and centre you
can do that by selecting from the button like image this property displays. With the Location
property you can change the location of the button. With the Size property you can set the size
of the button. Apart from the Dock property you can set its size and location by moving and
stretching the Button on the form itself. (See Figure 10.1)
Figure 10.1: Button Control

Creating a Button in Code


Below is the code to create a button.
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles_MyBase.Load

LOVELY PROFESSIONAL UNIVERSITY

207

Modern Programming Tools & Techniques-III

Notes

Dim Button1 as New Button()


declaring the button, Button1
Button1.Text=Creating a Button
setting the text to be displayed on the Button
Button1.Location=New Point(100,50)
setting the location for the Button where it should be created
Button1.Size=New Size(75,23)
setting the size of the Button
Me.Controls.Add(Button1)
adding the Button that is created to the form
the Me keyword is used to refer to the current object, in this case the Form
End Sub
End Class
Visual Basic 4.0 (August 1995) was the first version that could create 32-bit as
well as 16-bit Windows programs.

Create an employee information from using textboxes label and buttons.

10.3 TextBox Control


Windows users should be familiar with textboxes. This control looks like a box and accepts input
from the user. The TextBox is based on the Textbox Base class which is based on the Control
class. TextBoxes are used to accept input from the user or used to display text. By default we
can enter up to 2048 characters in a TextBox but if the Multiline property is set to True we can
enter up to 32KB of text. The Figure 10.2 below displays a Textbox.
Figure 10.2: Displays a Textbox

10.3.1 Properties of Textbox Controls


Some important properties in the behaviour section of the Properties Window for Textboxes.

208

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Enabled: Default value is true. To disable, set the property to False.

Notes

Multiline: Setting this property to True makes the Textbox multiline which allows to accept
multiple lines of text. Default value is False.
PasswordChar: Used to set the password character. The text displayed in the TextBox will be the
character set by the user. Say, if you enter *, the text that is entered in the TextBox is displayed as *
ReadOnly: Makes this TextBox readonly. It does not allow entering any text
Visible: Default value is true. To hide it set the property to False.
Textbox Event
The default event of the TextBox is the TextChanged Event which looks like this in code:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByValue As _
System.EventArgs) Handles TextBox1.TextChanged
End Sub
Working with Textboxes
Let us work with some examples to understand TextBoxes.
Drag two TextBoxes (TextBox1, TextBox2) and a Button (Button1) from the toolbox.
Code to Display some text in the TextBox
We want to display some text, say, Welcome to TextBoxes, in TextBox1 when the Button is
clicked. The code looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
TextBox1.Text = Welcome to TextBoxes
End Sub
Code to Work with Password Character
Set the Password Char property of TextBox2 to *. Setting that will make the text entered in
TextBox2 to be displayed as *. We want to display what is entered in TextBox2 in TextBox1.
The code for that looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
TextBox1.Text = TextBox2.Text
End Sub
When you run the program and enter some text in TextBox2, text will be displayed as *. When
you click the Button, the text you entered in TextBox2 will be displayed as plain text in TextBox1.
Code to Validate User Input
We can make sure that a TextBox can accept only characters or numbers which can restrict
accidental operations. For example, adding two numbers of the form 27+2J cannot return
anything. To avoid such kind of operations we use the Key Press event of the TextBox.
Code that allows you to enter only double digits in a TextBox looks like this:
Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As_
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If(e.KeyChar < 10 Or e.KeyChar > 100) Then
MessageBox.Show(Enter Double Digits)

LOVELY PROFESSIONAL UNIVERSITY

209

Modern Programming Tools & Techniques-III

Notes

End If
End Sub
Creating a TextBox in Code
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles MyBase.Load
Dim TextBox1 as New TextBox()
TextBox1.Text=Hello Mate
TextBox1.Location=New Point(100,50)
TextBox1.Size=New Size(75,23)
Me.Controls.Add(TextBox1)
End Sub
End Class
This control can be used to accept user input, which might include malicious
client script. Check any information that is sent from a client for executable
script, SQL statements, or other code before displaying it in your application.

10.4 RichTextBox
RichTextBoxes are similar to TextBoxes but they provide some advanced features over the
standard TextBox. RichTextBox allows formatting the text; say adding colors, displaying
particular font types and so on. The RichTextBox, like the TextBox is based on the TextBoxBase
class which is based on the Control class. These RichTextBoxes came into existence because
many word processors these days allow us to save text in a rich text format. With RichTextBoxes
we can also create our own word processors. We have two options when accessing text in a
RichTextBox, text and rtf (rich text format). Text holds text in normal text and rtf holds text in
rich text format. Figure 10.3 of a RichTextBox is shown below.
Figure 10.3: Rich Textbox

RichTextBox Event
The default event of RichtextBox is the TextChanged event which looks like this in code:

210

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, _ByVal e As System.


EventArgs) Handles RichTextBox1.TextChanged

Notes

End Sub
Code Samples
Code for creating bold and italic text in a RichTextBox
Drag a RichTextBox (RichTextBox1) and a Button (Button1) onto the form. Enter some text in
RichTextBox1, say, We are working with RichTextBoxes. Paste the following code in the click
event of Button1. The following code will search for text we mention in code and sets it to be
displayed as Bold or Italic based on what text is searched for.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
RichTextBox1.SelectionStart = RichTextBox1.Find(are)
using the Find method to find the text are and setting it is
return property to SelectionStart which selects the text to format
Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic)
creating a new font object to set the font style
RichTextBox1.SelectionFont = ifont
assigning the value selected from the RichTextBox the font style
RichTextBox1.SelectionStart = RichTextBox1.Find(working)
Dim bfont As New Font(RichTextBox1.Font, FontStyle.Bold)
RichTextBox1.SelectionFont = bfont
End Sub
When you run the above code and click Button1, the text are is displayed in Italic and the text
working is displayed in bold font. The image below displays the output.
Code for Setting the Colour of Text
Let us work with previous example. Code for setting the color for particular text looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click
RichTextBox1.SelectionStart = RichTextBox1.Find(are)
using the Find method to find the text are and setting its return
property to SelectionStart which selects the text
RichTextBox1.SelectionColor = Color.Blue
setting the color for the selected text with SelectionColor property
RichTextBox1.SelectionStart = RichTextBox1.Find(working)
RichTextBox1.SelectionColor = Color.Yellow
End Sub
The output when the Button is Clicked is the text are being displayed in Blue and the text
working in yellow as shown in the Figure 10.4.

LOVELY PROFESSIONAL UNIVERSITY

211

Modern Programming Tools & Techniques-III

Notes

Figure 10.4: Code for Saving Files to RTF

Drag two RichTextBoxes and two Buttons (Save, Load) onto the form. When you enter some
text in RichTextBox1 and click on Save button, the text from RichTextBox1 is saved into a rtf
(rich text format) file. When you click on Load button the text from the rtf file is displayed into
RichTextBox2. The code for that looks like this:
Private Sub Save_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Save.Click
RichTextBox1.SaveFile(hello.rtf)
using SaveFile method to save text in a rich text box to hard disk
End Sub
Private Sub Load_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Load.Click
RichTextBox2.LoadFile(hello.rtf)
using LoadFile method to read the saved file
End Sub

Create a program using rich textbox and Checkboxes.

10.5 Label, Link Label


Labels are those controls that are used to display text in other parts of the application. They are
based on the Control class.

10.5.1 Label
The property of the label control is the text property which is used to set the text for the label.
(See Figure 10.5)
212

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Notes

Label Event
The default event of Label is the Click event which looks like this in code:
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles Label1.Clic
End Sub
Creating a Label in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load Dim Label1 As New Label()
Label1.Text = Label
Label1.Location = New Point(135, 70)
Label1.Size = New Size(30, 30)
Me.Controls.Add(Label1)
End Sub
Figure 10.5: Label

10.5.2 Link Label


LinkLabel is similar to a Label but they display a hyperlink. Even multiple hyperlinks can be
specified in the text of the control and each hyperlink can perform a different task within the
application. They are based on the Label class which is based on the Control class.
Notable properties of the LinkLabel control are the ActiveLinkColor, LinkColor and LinkVisited
which are used to set the link colour.
LinkLabel Event
The default event of LinkLabel is the LinkClicked event which looks like this in code:
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked
End Sub
Working with LinkLabel
The code for that looks like this:
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal_

LOVELY PROFESSIONAL UNIVERSITY

213

Modern Programming Tools & Techniques-III

Notes

e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)_
Handles LinkLabel1.LinkClicked
System.Diagnostics.Process.Start(www.startvbdotnet.com)
using the start method of system.diagnostics.process class
process class gives access to local and remote processes
End Sub
Creating a LinkLabel in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
Dim LinkLabel1 As New LinkLabel()
LinkLabel1.Text = Label
LinkLabel1.Location = New Point(135, 70)
LinkLabel1.Size = New Size(30, 30)
Me.Controls.Add(LinkLabel1)
End Sub

Self Assessment Questions


Multiple choice questions
1. Text boxes are not used to accept input from the user or used to display text.
(a) True

(b) False

2. Labels are those controls that are used to display text in .............. of the application.
(a) single part

(b) other parts

(c) parts

(d) None of these

3. Checkboxes are those controls which gives us an option to select, say ....................
(a) Yes/No

(b) True/False

(c) No

(d) None of these

4. The label class which is based on the ................


(a) object class

(b) default class

(c) control class

(d) constructer class

5. Rich text boxes are similar to .............


(a) message box

(b) check box

(c) button box

(d) text box

10.6 Checkbox
Checkboxes are those controls which gives us an option to select, say, Yes/No or
True/False. A checkbox is clicked to select and clicked again to deselect some option.
When a checkbox is selected a check (a tick mark) appears indicating a selection. The
Checkbox control is based on the Textbox Base class which is based on the Control class.
The Figure 10.6 shows a Checkbox.

214

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Figure 10.6: Checkbox

Notes

Checkbox Properties
Important properties of the Checkbox in the Appearance section of the properties window are:
Appearance: Default value is Normal. Set the value to Button if you want the Checkbox to be
displayed as a Button.
BackgroundImage: Used to set a background image for the checkbox.
CheckAlign: Used to set the alignment for the CheckBox from a predefined list.
Checked: Default value is False, set it to True if you want the CheckBox to be displayed as Checked.
Checkstate: Default value is Unchecked. Set it to True if you want a check to appear. When set
to Indeterminate it displays a check in gray background.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of
the checkbox.
Important property in the Behaviour section of the properties window is the ThreeState property
which is set to False by default. Set it to True to specify if the Checkbox can allow three check
states than two.
Checkbox Event
The default event of the CheckBox is the CheckedChange event which looks like this in code:
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
End Sub
Code to display some text when the Checkbox is checked
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
TextBox1.Text = CheckBox Checked
End Sub
Code to check a CheckBoxs state
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click

LOVELY PROFESSIONAL UNIVERSITY

215

Modern Programming Tools & Techniques-III

Notes

If CheckBox1.Checked = True Then


TextBox1.Text = Checked
Else
TextBox1.Text = UnChecked
End If
End Sub
Creating a CheckBox in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles_ MyBase.Load
Dim CheckBox1 As New CheckBox()
CheckBox1.Text = Checkbox1
CheckBox1.Location = New Point(100, 50)
CheckBox1.Size = New Size(95, 45)
Me.Controls.Add(CheckBox1)
End Sub

10.7 List Box


The List Box control displays a list of items from which we can make a selection. We can select
one or more than one of the items from the list. The List Box control is based on the List Control
class which is based on the Control class. The Figure 10.7 below displays a List Box.
Figure 10.7: A Multicolumn List Box

10.7.1 Properties of the List Box


In the Behaviour Section
HorizontalScrollbar: Displays a horizontal scrollbar to the List Box. Works when the List Box has
MultipleColumns.

216

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

MultiColumn: The default value is set to False. Set it to true if you want the list box to display
multiple columns.

Notes

ScrollAlwaysVisible: Default value is set to False. Setting it to true will display both vertical and
Horizontal scrollbar always.
SelectionMode: Default value is set to one. Select option None if you do not any item to be selected.
Select it to MultiSimple if you want multiple items to be selected. Setting it to MultiExtended
allows you to select multiple items with the help of Shift, Control and arrow keys on the keyboard.
Sorted: Default value is set to False. Set it to true if you want the items displayed in the List Box
to be sorted by alphabetical order.
In the Data Section: Notable property in the Data section of the Properties window is the Items
property. The Items property allows us to add the items we want to be displayed in the list box.
Doing so is simple, click on the ellipses to open the String Collection Editor window and start
entering what you want to be displayed in the List Box. After entering the items click OK and
doing that adds all the items to the List Box.
Counting the number of Items in a List Box
Add a Button to the form and place the following code in it is click event.
Private Sub Button1_Click(ByVal sender As System.Object, ByValue _
As System.EventArgs) Handles Button1.Click
TextBox1.Text = ListBox1.Items.Count
counting the number of items in the ListBox with the Items.Count
End Sub
When you run the code and click the Button it will display the number of items available in
the ListBox.
Code to display the item selected from ListBox in a TextBox
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedItem
using the selected item property
End Sub
When you run the code and click an item in the ListBox that item will be displayed in the TextBox.

10.8 ComboBox
Combo Box is a combination of a Textbox and a List Box. The Combo Box displays an editing
field (Textbox) combined with a List Box allowing us to select from the list or to enter new text.
Combo Box displays data in a drop-down style format. The Combo Box class is derived from
the List Box class. See in the Figure 10.8 of a Combo Box.

10.8.1 Properties of the ComboBox


The DropDownStyle property in the Appearance section of the properties window allows us
to set the look of the ComboBox. The default value is set to DropDown which means that the
ComboBox displays the Text set by its Text property in the Textbox and displays it is items in
the DropDownListBox below. Setting it to simple makes the ComboBox to be displayed with
a TextBox and the list box which does not drop down. Setting it to DropDownList makes the

LOVELY PROFESSIONAL UNIVERSITY

217

Modern Programming Tools & Techniques-III

Notes

ComboBox to make selection only from the drop down list and restricts you from entering any
text in the textbox.
We can sort the ComboBox with its Sorted property which is set to False by Default.
We can add items to the ComboBox with its Items property.
Figure 10.8: Combo Box.

ComboBox Event
The default event of ComboBox is SelectedIndexChanged which looks like this in code:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
Working with ComboBoxes
Drag a ComboBox and a TextBox control onto the form. To display the selection made in the
ComboBox in the Textbox the code looks like this:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
selecting the item from the ComboBox with selected item property
End Sub
Removing items from a ComboBox
You can remove all items or one particular item from the list box part of the ComboxBox. Code
to remove a particular item by its Index number looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
ComboBox1.Items.RemoveAt(4)
removing an item by specifying its index
End Sub

218

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Code to remove all items from the ComboBox

Notes

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
ComboBox1.Items.Clear()
using the clear method to clear the list box
End Sub

10.9 Tree View


The tree view control is used to display a hierarchy of nodes (both parent, child). You can
expand and collapse these nodes by clicking them. This control is similar to Windows Explorer
which displays a tree view in its left pane to list all the folders on the hard disk. Below is the
Figure 10.9 of a Tree View control.
Figure 10 9: Tree View Control

10.9.1 Properties of TreeView


Bounds: Gets the actual bound of the tree node
Checked: Gets/Sets whether the tree node is checked
FirstNode: Gets the first child tree node
FullPath: Gets the path from the root node to the current node
ImageIndex: Gets/Sets the image list index of the image displayed for a node
Index: Gets the location of the node in the node collection
IsEditing: Gets whether the node can be edited
IsExpaned: Gets whether the node is expaned
IsSelected: Gets whether the node is selected
LastNode: Gets the last child node

LOVELY PROFESSIONAL UNIVERSITY

219

Modern Programming Tools & Techniques-III

Notes

NextNode: Gets the next sibling node


NextVisibleNode: Gets the next visible node
NodeFont: Gets/Sets the font for nodes
Parent: Gets the parent node of the current node
PrevNode: Gets the previous sibling node
PrevVisibleNode: Gets the previous visible node
TreeView: Gets the nodes parent tree view
TreeView Event
Default event of the Tree View control is the After Select event which looks like this in code:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As_
System.Windows.Forms.TreeViewEventArgs)Handles TreeView1.AfterSelect
End Sub
Working with Tree Views
Drag a Tree View control on to a form and to add nodes to it select the nodes property in the
properties window, which displays the TreeNode editor as shown below. (See Figure 10.10)
Figure 10.10: Tree Node Editor

To start adding nodes, you should click the Add Root button, which adds a top-level node. To
add child nodes to that node, you should select that node and use the Add Child button. To
set text for a node, select the node and set it is text in the textbox as shown in the image above.
Assuming you added some nodes to the tree view; drag two Labels (Label1, Label2) from the
toolbox on to the form. The following code displays the node you select on Label2 and the path
to that node on Label1. The code looks like this:
220

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Public Class Form 12 Inherits System.Windows.Forms.Form

Notes

#Region Windows Form Designer generated code


#End Region
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As_
System.Windows.Forms.TreeViewEventArgs)Handles TreeView1.AfterSelect
Label1.Text = You are here-> & & e.Node.FullPath
displaying the path of the selected node
Label2.Text = Current node selected: & & e.Node.Text
displaying the selected node
End Sub
End Class
The Figure 10.11 below displays sample output from above code.
Figure 10.11: Output

10.10 CheckedListBox
As the name says, CheckedList Box is a combination of a List Box and a Checkbox. It displays
a List Box with a Checkbox towards its left. The CheckedListBox class is derived from the List
Box class and is based on that class. Since the CheckedListBox is derived from the List Box it
shares all the members of List Box. Below is the Figure 10.12 of a CheckedListBox.
Properties of CheckedListBox
The notable property in the appearance section of the properties window is the Three Checkboxes
property which is set to False by default. Setting it to true makes the CheckedListBox to be
displayed in Flat or Normal style.

LOVELY PROFESSIONAL UNIVERSITY

221

Modern Programming Tools & Techniques-III

Notes

Notable property in the behaviour section is the CheckOnClick property which is set to False
by default. When set to False it means that to check or uncheck an item in the CheckedListBox
we need to double-click the item. Setting it to True makes an item in the CheckedListBox to be
checked or unchecked with a single click.
Notable property in the Data section is the Items property with which we add items to the
CheckedListBox.
Private Sub CheckedListBox1_SelectedIndexChanged(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged
End Sub
Figure 10.12: Checklist Box

10.11 Panel, Group Box, Picture Box


Panels are those controls which contain other controls, for example, a set of radio buttons,
checkboxes, etc.

10.11.1 Panel
Panels are similar to Groupboxes but the difference, Panels cannot display captions where as
GroupBoxes can and Panels can have scrollbars where as GroupBoxes cannot. If the Panels
Enabled property is set to False then the controls which the Panel contains are also disabled.
Panels are based on the ScrollableControl class.
Notable property of the Panel control in the appearance section is the BorderStyle property. The
default value of the BorderStyle property is set to none. You can select from the predefined list
to change a Panels BorderStyle.
Notable property in the layout section is the AutoScroll property. Default value is set to False.
Set it to true if you want a scrollbar with the Panel.

222

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Adding Controls to a Panel

Notes

On a from drag a Panel (Panel1) from the toolbox. We want to place some controls, say,
checkboxes on this Panel. Drag three checkboxes from the toolbox and place them on the
Panel. When that is done all the checkboxes in the Panel are together as in a group but they
can function independently.
Creating a Panel and adding a Label and a CheckBox to it in Code
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim Panel1 As New Panel()
Dim CheckBox1 As New CheckBox()
Dim Label1 As New Label()
Panel1.Location = New Point(30, 60)
Panel1.Size = New Size(200, 264)
Panel1.BorderStyle = BorderStyle.Fixed3D
setting the borderstyle of the panel
Me.Controls.Add(Panel1)
CheckBox1.Size = New Size(95, 45)
CheckBox1.Location = New Point(20, 30)
CheckBox1.Text = Checkbox1
Label1.Size = New Size(100, 50)
Label1.Location = New Point(20, 40)
Label1.Text = CheckMe
Panel1.Controls.Add(CheckBox1)
Panel1.Controls.Add(Label1)
adding the label and checkbox to the panel
End Sub
The Figure 10.13 displays a panel.
Figure 10.13: Panel

LOVELY PROFESSIONAL UNIVERSITY

223

Modern Programming Tools & Techniques-III

Notes

10.11.2 GroupBox Control


As said above, Groupboxes are used to Group controls. GroupBoxes display a frame around
them and also allows to display captions to them which is not possible with the Panel control.
The GroupBox class is based on the Control class.
Creating a GroupBox and adding a Label and a CheckBox to it in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim GroupBox1 As New GroupBox()
Dim CheckBox1 As New CheckBox()
Dim Label1 As New Label()
GroupBox1.Location = New Point(30, 60)
GroupBox1.Size = New Size(200, 264)
GroupBox1.Text = InGroupBox
setting the caption to the groupbox
Me.Controls.Add(GroupBox1)
CheckBox1.Size = New Size(95, 45)
CheckBox1.Location = New Point(20, 30)
CheckBox1.Text = Checkbox1
label1.Size = New Size(100, 50)
Label1.Location = New Point(20, 40)
Label1.Text = CheckMe
GroupBox1.Controls.Add(CheckBox1)
GroupBox1.Controls.Add(Label1)
adding the label and checkbox to the groupbox
End Sub

10.11.3 PictureBox Control


PictureBoxes are used to display images on them. The images displayed can be anything varying
from Bitmap, JPEG, GIF, PNG or any other image format files. The PictureBox control is based
on the Control class.
Notable property of the PictureBox Control in the Appearance section of the properties window
is the Image property which allows to add the image to be displayed on the PictureBox.
Adding Images to PictureBox
Images can be added to the PictureBox with the Image property from the Properties window
or by following lines of code.
Private Sub Button1_Click(ByVal sender As System.Object,_ByVal e As System.EventArgs)
Handles Button1.ClickPictureBox1.Image = Image.FromFile(C:\sample.gif)
loading the image into the picturebox using the FromFile method of the image class
assuming a GIF image named sample in C: drive
End Sub

10.12 ToolTip, Error Provider


ToolTips are those small windows which display some text when the mouse is over a control
giving a hint about what should be done with that control.

224

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

10.12.1 ToolTip

Notes

ToolTip is not a control but a component which means that when we drag a ToolTip from the
toolbox onto a form it will be displayed on the component tray. Tooltip is an Extender provider
component which means that when you place an instance of a ToolTipProvider on a form,
every control on that form receives a new property. This property can be viewed and set in the
properties window where it appears as Tooltip on n, where n is the name of the ToolTipProvider.
To assign ToolTips with controls we use it is SetToolTip method.
Notable property of the ToolTip is the Active property which is set to true by default and which
allows the tool tip to be displayed.

10.12.2 Setting a ToolTip


Assume that we have a TextBox on the form and we want to display some text when your
mouse is over the TextBox. Say the text that should appear is Do not leave this blank. The
code for that looks like this:
Private Sub Form1_Load(ByVal sender As System.Object, ByValue_
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, Do not leave this blank)
End Sub
The image below displays output from above code.

10.12.3 ErrorProvider Component


The ErrorProvider component provides an easy way to set validation errors. It allows us to
set an error message for any control on the form when the input is not valid. When an error
message is set, an icon indicating the error will appear next to the control and the error message
is displayed as Tool Tip when the mouse is over the control.
Notable property of ErrorProvider in the Appearance section is the Icon property which allows
us to set an icon that should be displayed. Notable property in Behavior section is the BlinkRate
property which allows setting the rate in milliseconds at which the icon blinks.

10.12.4 Displaying an Error


Lets work with an example. Assume we have a TextBox and a Button on a form. If the TextBox
on the form is left blank and if the Button is clicked, an icon will be displayed next to the TextBox
and the specified text will appear in the Tool Tip box when the mouse is over the control. The
code for that looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByValue_
As System.EventArgs) Handles Button1.Click
If TextBox1.Text = Then
ErrorProvider1.SetError(TextBox1, Cannot leave textbox blank)
Else
ErrorProvider1.SetError(TextBox1, )
End If
End Sub

10.13 Status Bar


Status Bars are used to display status messages at the bottom of the form. They are generally
used to provide additional information, such as page numbers, display a message, etc. There

LOVELY PROFESSIONAL UNIVERSITY

225

Modern Programming Tools & Techniques-III

Notes

are two kinds of status bars: simple status bars and status bars that display a panel. Simple
status bars display a single message on the status bar and a status bar with panels can display
multiple messages. Figure 10.14 shows a StatusBar control.
Figure 10.14: Status Bar

Notable properties of the Status bar:


Panels: Gets the collection of status bar panels in a status bar.
Show Panels: Default is True. You can set it to False if you do not want to show panels.
Text: Gets/Sets the text to be displayed.
StatusBar Event
Default event of the StatusBar control is the Panel Click event which looks like this in Code:
Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, ByVal e _
As System.Windows.Forms.StatusBarPanelClickEventArgs) Handles StatusBar1.PanelClick
End Sub
Sample code for a Simple Status Bar
From the toolbox add a status bar control to the form. The following code will display the
message Hello on the StatusBar when the form loads.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
StatusBar1.Text = Hello
End Sub
Status Bars with Panels
You can add panels to a status bar by opening its properties window and clicking the Panels
property. When you click the Panels property it opens the StatusBarPanel Collection Editor
which looks like the Figure 10.15.

226

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Figure 10.15: StatusBarPanel

Notes

You add panels by clicking the Add button found in the editor. While adding panels you can
set the Text to be displayed for each panel, an icon, tooltip, width for each panel you add.
To add panels to status bar in code we use the StatusBar.Panel.Add method and StatusBar.Panels.
Remove, StatusBar.Panels.RemoveAt to remove the panels. To access text in each panel you use
the text property of StatusbarPanel as: StatusBarPanels(0).Text=I am panel one.
To handle status bar panel clicks you use the PanelClick event as shown in the code below. To
work with this code, add a status bar control to the form, open it is properties window, select
the Panels property and add three status bar panels. For StatusBarPanel1 set the text More
VB .NET? Please Visit ->, for StatusBarPanel2 set the text MSDN and for StatusBarPanel3
Startvbdotnet.com.
Switch to code view and paste the following code:
Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, ByVal e As _
System.Windows.Forms.StatusBarPanelClickEventArgs)Handles StatusBar1.PanelClick
If e.StatusBarPanel Is StatusBar1.Panels(1) Then
checks if status bar panel2 is clicked and if true opens a webpage
System.Diagnostics.Process.Start(www.msdn.mcirosoft.com)
Else If e.StatusBarPanel Is StatusBar1.Panels(2) Then
checks if status bar panel3 is clicked and if true opens a webpage
System.Diagnostics.Process.Start(www.startvbdotnet.com)
End If
End Sub

10.14 RadioButton
RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded instead
of boxed as with a checkbox. Like CheckBoxes, RadioButtons are used to select and deselect

LOVELY PROFESSIONAL UNIVERSITY

227

Modern Programming Tools & Techniques-III

Notes

options but they allow us to choose from mutually exclusive options. The RadioButton control is
based on the Button Base class which is based on the Control class. A major difference between
CheckBoxes and RadioButtons is, RadioButtons are mostly used together in a group. Below is
the image of a RadioButton.(See Figure 10.15)
Figure 10.16: RadioButton

Important properties of the RadioButton in the Appearance section of the properties window are:
Appearance: Default value is Normal. Set the value to Button if you want the RadioButton to be
displayed as a Button.
BackgroundImage: Used to set a background image for the RadioButton.
CheckAlign: Used to set the alignment for the RadioButton from a predefined list.
Checked: Default value is False, set it to True if you want the RadioButton to be displayed as
checked.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of
the RadioButton.
RadioButton Event
The default event of the RadioButton is the CheckedChange event which looks like this in code:
Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
End Sub
Working with Examples
Drag a RadioButton (RadioButton1), TextBox (TextBox1) and a Button (Button1) from the Toolbox.
Code to display some text when the RadioButton is selected
Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
TextBox1.Text = RadioButton Selected
End Sub

228

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

Code to check a RadioButtons state

Notes

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_


System.EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
TextBox1.Text = Selected
Else
TextBox1.Text = Not Selected
End If
End Sub
Creating a RadioButton in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles_ MyBase.Load
Dim RadioButton1 As New RadioButton()
RadioButton1.Text = RadioButton1
RadioButton1.Location = New Point(120,60)
RadioButton1.Size = New Size(100, 50)
Me.Controls.Add(RadioButton1)
End Sub

VB6 into a .NET Framework


Client Situation
Since its inception, the client has been using a large-scale application developed with
VB6.0. The software was responsible for dealing with employees, payroll, insurance, and
Bonds. However, as the business grew, more functionalities needed to be added to existing
Application, adding to the continuous slowdown of system performance apart from rising
Maintenance cost and time.
Solution
The client decided to migrate from VB6 into a .NET framework. The main idea behind the
Migration was to enhance system performance and optimize workflow management. Using
the advanced functionalities offered by .NET, the client would be able to provide redefined
and high quality business solutions to serve its end users better.
Deliverables
Informatics Consultants were responsible for the complete migration from VB6.0 to VB.NET.
This involved business detailed requirement analysis, design, and deployment of the System
on the new server.
Deliverables by Informatics Consultants included:

Transplantation of the existing system on another framework

Optimization of business logic for the existing legacy system

Inclusion of additional functionalities to the existing legacy system


Contd...

LOVELY PROFESSIONAL UNIVERSITY

229

Modern Programming Tools & Techniques-III

Notes

The new application was built on a customized .NET framework in a three-tier model

Consisting of the business logic, presentation, and database. The advantage of the
three-tier

System was better scalability without hampering performance.


Approach
A team of developers, with a commendable experience in VB.NET was given total
responsibility of the migration. The project commenced with a comprehensive training of
developers to understand the current system. Although time-consuming, the training was
necessary to ensure a successful completion of the project System migration did not allow
the developers to shut down the existing legacy system, as this would affect the ongoing
business operations of the client.

The migration project was carried out by the client and Informatics Consultants
simultaneously. To enable this, Informatics Consultants set up a development server
on the client network so that coordination becomes easier and source codes remain
protected.

At the end of 90 man months of continuous efforts, the migration was successfully
implemented.
Benefits

The whole legacy system migration was made possible at a fraction of the cost, as
compared to onshore system migration, with the majority of the work carried out in
India.

With experienced personnel on the job, flexible implementation process was made
possible.

Extensive documentation created as a part of the migration project, for ease of future
development and maintenance effort.
Questions

1. How to open and edit word documents within a form with vb.net (windows application)?

2. Implement the registration form using VB.Net control.

Self Assessment Questions


Multiple Choice Questions
6. Entry point is a function called main. On application, this entry point is a
function called Win Main.
(a) win 32

(b) win 64

(c) win 128

(d) None of these

7. Visual Basic allows us to work with controls in two ways: at design time and ..

(a) at compile time

(b) at runtime

(c) Both

(d) None of these.

8. The Control class is in the System.Windows.Forms namespace. It is a for


the Windows Controls.

230

(a) derived class

(b) main class

(c) base class

(d) None of these

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

9. The tree view control is used to display a hierarchy of nodes for


(a) parent

(b) child

(c) Both

(d) None of these

Notes

10. CheckedListBox is a combination of ..


(a) ListBox and CheckBox

(b) ListBox and ComboBox

(c) ListBox and CheckedlistBox

(d) None of these

11. ToolTip is not a control but a . which means that when we drag a ToolTip from
the toolbox onto a form
(a) rich component

(b) component

(c) rich control

(d) None of these

12. The ErrorProvider component provides an easy way to set .


(a) compile errors

(b) runtime errors

(c) validation errors

(d) None of these

13. Open File Dialogs are supported by the class and they allow us to select a
file to be opened.
(a) FileDialog

(b) OpenFileDialog

(c) OpenFileDialoge

(d) None of these

14. Date TimePicker allows us to ..


(a) select date and time

(b) all date and time

(c) max date and time

(d) None of these

15. Status Bars are used to display status messages at the . of the form.
(a) bottom

(b) left

(c) top

(d) right
1. Write a program using Date TimePicker.
2. Write a program using treeview control.

10.15 Summary

Microsoft Visual Basic .NET is a programming environment used to create graphical user
interface (GUI) applications for the Microsoft Windows family of operating systems.

Windows Controls are based on the Control class, the base class for all controls.

RichTextBox allows formatting the text say adding colours, displaying particular font types
and so on. The RichTextBox, like the TextBox is based on the TextBoxBase class which is
based on the Control class.

The DropDownStyle property in the Appearance section of the properties window allows
us to set the look of the ComboBox.

GroupBoxes display a frame around them and also allows displaying captions to them
which is not possible with the Panel control.

LOVELY PROFESSIONAL UNIVERSITY

231

Modern Programming Tools & Techniques-III

Notes

PictureBoxes are used to display images on them. The images displayed can be anything
varying from Bitmap, JPEG, GIF, PNG or any other image format files.

Tooltip is an Extender provider component which means that when you place an instance
of a ToolTipProvider on a form, every control on that form receives a new property.

10.16 Keywords
CheckedListBox: CheckedListBox is a combination of a ListBox and a CheckBox. It displays a
ListBox with a CheckBox towards its left.
ComboBox: ComboBox displays data in a drop-down style format.
Control Class: The Control class is in the System.Windows.Forms namespace. It is a base class
for the Windows Controls.
Control: A control is an object that can be drawn on to the Form to enable or enhance user
interaction with the application.
ErrorProvider: The ErrorProvider component provides an easy way to set validation errors.
GroupBox: Groupboxes are used to Group controls. GroupBoxes display a frame around them
and also allows displaying captions to them which is not possible with the Panel control.
ListBox: The ListBox control displays a list of items from which we can make a selection.
PictureBox: PictureBoxes are used to display images on them. The images displayed can be
anything varying from Bitmap, JPEG, GIF, PNG or any other image format files.
SaveFileDialog: Save File Dialogs are supported by the SaveFileDialog class and they allow us
to save the file in a specified location. Below is the image of a SaveFileDialog.
StatusBar: Status Bars are used to display status messages at the bottom of the form.

10.17 Review Questions


1. Explain the representation of textboxes.

2. What are the properties of list box?

3. What do you understand by representation of date time picker?

4. Discuss the combo boxes in VB.


5. Explain the creation of buttons.
6. Explain the creation of rich textbox

7. Define controls in VB.NET and its types.

8. Define label and link label.

9. What is combo box? Explain with example

10. Explain tree view with example.

Answers for Self Assessment Questions

232

1. (b)

2. (b)

3. (c)

4.

(d)

5.

(d)

6. (a)

7. (b)

8. (c)

9.

(c)

10.

(a)

11. (b)

12. (c)

13. (b)

14.

(a)

15.

(a)

LOVELY PROFESSIONAL UNIVERSITY

Unit 10: Windows Programming

10.18 Further Reading

Notes

Windows Forms Programming in Visual Basic .Net, by Chris Sells, Justin Gehtlan.

http://books.google.co.in/books?id=ee_dZN3y6fAC&printsec=frontcov
er&dq=Windows+Programming+in+vb.net&hl=en&sa=X&ei=vEoGUK7
zMMnTrQfX1tyjBg&ved=0CD0Q6AEwAA#v=onepage&q=Windows%20
Programming%20in%20vb.net&f=false

LOVELY PROFESSIONAL UNIVERSITY

233

Modern Programming Tools & Techniques-III

Unit 11: Common Dialog Boxes

Notes

CONTENTS
Objectives
Introduction
11.1 Common Dialog Boxes

11.1.1 Using a Common Dialog Box

11.1.2 Common Dialog Box Library

11.1.3 The Common Dialog Control

11.2 Open File Dialog


11.2.1 Open File Dialog Box Creation

11.2.2 Characteristics of an Open Dialog Box

11.3 Save File Dialog


11.3.1 Creating a SaveFileDialog

11.4 The Color Dialog Box


11.4.1 Making a Color Dialog Box Available

11.5 Message Box Class


11.5.1 MessageBox( ) Function

11.5.2 The Input Box( ) Function

11.6 Dialog Result Class


11.6.1 Dialog Result Values

11.7 Summary
11.8 Keywords
11.9 Review Questions
11.10 Further Readings

Objectives
After studying this unit, you will be able to:
Define common dialog boxes

Describe the common dialog control


Understand save file dialog box
Explain the colour dialog box
Describes the possible dialog result values

Introduction
The common dialog box in visual basic is an insert able control that allows users to display a
number of common dialog boxes in their program. These include Open and Save As file dialog
boxes; the Find and Replace editing dialog boxes; the Print, Print Setup, Print Property Sheet,
and Page Setup printing dialog boxes;
The Print, Print Setup, Print Property Sheet, and Page Setup printing dialog boxes; and the
Colour and Font dialog boxes.
Common Dialog not only replaces three controls (Drive, Directory and FileList), but also is
easier to program. It is supported in Visual Basic and VBA as well. The new VB.NET has the
same functionality in the OpenFileDialog class

234

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Windows implements a variety of reusable dialog boxes that are common to all applications,
including dialog boxes for opening files, saving files, and printing. Since these dialog boxes are
implemented by the operating system, they can be shared among all the applications that run
on the operating system, which helps user experience consistency; when users are familiar with
the use of an operating system-provided dialog box in one application, they do not need to
learn how to use that dialog box in other applications. Because these dialog boxes are available
to all applications and because they help provide a consistent user experience, they are known
as common dialog boxes.
Many Windows programs have things in common, such as dialog boxes for opening files, selecting
colours, or starting a print job. When you need this kind of functionality in your VB6 program,
you may want to turn to the Common Dialog control instead of creating your own dialog box.
To use this control, you must select Microsoft Common Dialog Control 6.0 on the Controls tab
in the Components window (select Project | Components from the menu). Then, the control
icon will appear in your toolbox and you can add it as a form like any other control. At run
time, it is invisible until you need it.
The Common Dialog control is very flexiblein fact, it is five dialog boxes in one. You choose
the dialog box you need by the method you call on the control. Here are brief descriptions of
the dialog boxes:
ShowOpen: Shows a File Open dialog box.
ShowSave: Shows a File Save dialog box.
ShowColor: Shows a Select Color dialog box.
ShowFont: Shows a Font Selection dialog box.
ShowPrinter: Shows a Print/Print Options dialog box.
The control has a range of properties, many of which are relevant only for a specific type of
dialog box. For example, when using the Show Open method, you can set properties to specify
the starting folder and the types of files that are shown. Likewise, the Color dialog box has a
property that returns the color the user selects. A nice feature is that each dialog box automatically
provides context-sensitive help on its elements.
Windows Presentation Foundation (WPF) encapsulates the open file, save file, and print common
dialog boxes and exposes them as managed classes for you to use in standalone applications.

Notes

11.1 Common Dialog Boxes


A common dialog box is a window that is used to perform a specific but common type of userdriven operation. Examples of such operations include opening a file, saving a file, printing,
selecting a colour, etc. These objects are referred to as common dialog boxes, not because they
have anything in common (in most cases they do not), but because they are available as standard
objects in all versions of Microsoft Windows.
To set a mutual foundation to all common dialog boxes, the VCL provides a class named
TCommonDialog. The TCommonDialog class is derived from TComponent. (See Figure 11.1)
Figure 11.1: Dialog Boxes
TObject

TPersistent

TComponent

TApplication

TCommonDialog

TScreen

LOVELY PROFESSIONAL UNIVERSITY

235

Modern Programming Tools & Techniques-III

Notes

There are three types of dialog boxes:


System Modal
1. Modal: Modal dialog boxes are generally used inside a program, to display messages, and
to set program parameters. Modal dialog boxes come to the front of the screen, and you may
not use the program while the modal dialog box is open. To continue using the program, the
modal dialog box must be closed.
2. System Modal: System modal dialog boxes are like modal boxes, except that they supersede
the entire desktop area. When a system modal dialog box is open, nothing else on the screen
can be clicked or selected.
3. Modeless: Modeless dialog boxes are able to be deselected, and control can be taken away
from a modeless dialog box and transferred to some other window. Modeless dialog boxes are
frequently used as a fast and easy way to create a window, without having to register a window
class. Modeless dialog boxes are common in the Windows control panel.

11.1.1 Using a Common Dialog Box


The common dialog boxes used in the VCL are customized versions of their Win32 part. To help
give a transition to their parent, the TCommonDialog class is equipped with Handle property:
__property HWND__ * Handle = {read=FHandle};
As we will see, after creating a common dialog box, you must present it to the user. To make
this possible, the TCommonDialog class provides a method named Execute. It is available in
two versions whose syntaxes are:
virtual bool __fastcall Execute(void);
virtual bool __fastcall Execute(HWND__ * ParentWnd);
To display the dialog box, you can call this method without passing an argument. When this
method is called, the dialog box fires an OnShow event that is of type TNotifyEvent:
__property TNotifyEvent OnShow;
When it comes up, a common dialog box presents, among other options, a default button
(sometimes labels Print, Save, Open, or else) and a Cancel button. After using the dialog box, if
the user clicks the default button or presses Enter, you must collect the necessary information,
validate, and take appropriate actions. On the other hand, the user can click Cancel or press Esc
to ignore whatever was done on the dialog box (in some cases, there are exceptions; for example,
if the user creates a folder using the Save or the Open dialog box, if the user clicks Cancel, the
folder that was created will still exist). Either way, when the dialog box closes, the object fires
an OnClose event that is of type TNotifyEvent.
Common Dialog Example
This example shows you how to use the Common Dialog control to display the Open, Save,
Select Colour and Print dialog boxes.
First, add a Common Dialog control to your form (you will need to add the component to your
project first by going to Project | Components). Next, add a text box, and name it txtData. You
now need to add some buttons to display the different dialog boxes. Name them cmdOpen,
cmdSave, cmdColour, and cmdPrint, and set their captions appropriately. Finally, add the code
below.
Private Sub cmdColour_Click()
On Error GoTo errhandler
CommonDialog1.CancelError = True

236

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Notes

Display the Colour dialog box


CommonDialog1.ShowColor
Set the forms background colour to the one selected
Me.BackColor = CommonDialog1.Color
Exit Sub
errhandler:
Select Case Err
Case 32755 Dialog Cancelled
MsgBox you cancelled the dialog box
Case Else
MsgBox Unexpected error. Err & Err & : & Error
End Select
End Sub
Private Sub cmdOpen_Click()
On Error GoTo errhandler
CommonDialog1.CancelError = True
Set flags
CommonDialog1.Flags = cdlOFNHideReadOnly + cdlOFNPathMustExist + cdlOFNFileMustExist
Set filters
CommonDialog1.Filter = All Files (*.*)|*.*|RTF (*.rtf)|*.rtf|Text Files (*.txt)|*.txt
Display the Save dialog box
CommonDialog1.Filename =
CommonDialog1.ShowOpen
txtData.Text = File Selected:& CommonDialog1.Filename
Exit Sub
errhandler:
Select Case Err
Case 32755 Dialog Cancelled
MsgBox you cancelled the dialog box
Case Else
MsgBox Unexpected error. Err & Err & : & Error
End Select
End Sub
Private Sub cmdPrint_Click()
StopPrinting = False
Set CancelError is True
On Error GoTo errhandler
CommonDialog1.PrinterDefault = True
CommonDialog1.CancelError = True
Set flags
CommonDialog1.Flags = cdlPDReturnDC + cdlPDNoPageNums
CommonDialog1.ShowPrinter

LOVELY PROFESSIONAL UNIVERSITY

237

Modern Programming Tools & Techniques-III

Notes

Printer.Print txtData.Text
Printer.EndDoc
Exit Sub
errhandler:
Select Case Err
Case 32755 Dialog Cancelled
MsgBox you cancelled the dialog box
Case Else
MsgBox Unexpected error. Err & Err & & Error
End Select
End Sub
Private Sub cmdSave_Click()
On Error GoTo errhandler
CommonDialog1.CancelError = True
Set flags
CommonDialog1.Flags = cdlOFNHideReadOnly + cdlOFNOverwritePrompt +
cdlOFNPathMustExist
Set filters
CommonDialog1.Filter = All Files (*.*)|*.*|RTF (*.rtf)|*.rtf|Text Files
(*.txt)|*.txt
Specify default filter
Display the Save dialog box
CommonDialog1.Filename =
CommonDialog1.ShowSave
Set the label values
txtData.Text = File Selected: & CommonDialog1.Filename
Exit Sub
errhandler:
Select Case Err
Case 32755 Dialog Cancelled
MsgBox You cancelled the dialog box
Case Else
MsgBox Unexpected error Err & Err & : & Error
End Select
End Sub

11.1.2 Common Dialog Box Library


The Common Dialog Box Library contains a set of dialog boxes for performing common tasks,
such as opening files and printing documents. The common dialog boxes provide a uniform
user interface that lets users carry out these common tasks without being forced to learn new
techniques with each application.
The Common Dialog Box Library contains a set of dialog boxes for performing common
application tasks, such as opening files, choosing color values, and printing documents. The
238

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

common dialog boxes allow you to implement a consistent approach to your applications user
interface. This reduces the amount of effort that users spend in learning user interface behavior
for your application.

Notes

This section describes the common dialog boxes which include the Open and Save As file dialog
boxes; the Find and Replace editing dialog boxes; the Print, Print Setup, Print Property Sheet,
and Page Setup printing dialog boxes; and the Color and Font dialog boxes.
Common dialog boxes have been superseded by the Common Item Dialog.
You use the Common Item Dialog API instead of these dialog boxes from the Common Dialog
Box Library.
Common Dialog/Direct is a new DLL or class library which shows how to completely replace
COMDLG32.OCX through Visual Basic code. The main advantage of this is you no longer need
to put a control on a form to use common dialogs - just declare an instance of the class and you
have a straight replacement.
The Windows Common Dialog Box library the DLL, not the control (OCX) provides other
applications with the standard Windows dialog boxes for opening and saving files, and the
ability to choosing colors and fonts, etc. All these methods reside in the Comdlg32.dll library
file. It is grouped under the User Interface category of the API.
The following example will look at a trivial implementation of a path to a purchasing contract
with a vendor. The idea here is that we will retrieve the path to the file and store along with
our purchase order -- you may be thinking, why not use the OLE Container, hence a trivial in
its use not in its implementation.
We will start by opening Modifier and adding a String control for the path and a Push Button
control to the POP_PO_Entry form.
Save the changes and return to Dynamics GP. You will need to grant security to the modified
POP_PO_Entry window under Microsoft Dynamics GP > Tools > Setup > System > Alternate
Modified Forms/Reports.
Open the Purchase Order Entry screen to verify all changes have been successfully achieved
with Modifier. Now you can proceed to add the form to Visual Basic, by pressing CTRL+F11
on your keyboard.
You can now add the newly created controls to the Visual Basic project by pressing Shift+F11
on your computers keyboard. Make sure to add the sFilePath string control and the PB_File
push button control.
Proceed to open the Visual Basic Editor. You can press ALT+F11 on your keyboard to quickly
access the Editor or use the Tools menu on the Purchase Order Entry screen.
Copy and paste the following code into the editors window:
Private Declare Function GetOpenFileName Lib comdlg32.dll Alias GetOpenFileNameA
(pOpenfilename As OPENFILENAME) As Long
Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String

LOVELY PROFESSIONAL UNIVERSITY

239

Modern Programming Tools & Techniques-III

Notes

nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Private Sub PBFile_BeforeUserChanged (KeepFocus As Boolean, CancelLogic As Boolean)
Dim Open File As OPENFILENAME
Dim lReturn As Long
Dim sFilter As String
OpenFile.lStructSize = Len(OpenFile)
sFilter = All Files (*.*) & Chr(0) & *.* & Chr(0)
OpenFile.lpstrFilter = sFilter
OpenFile.nFilterIndex = 1
OpenFile.lpstrFile = String(257, 0)
OpenFile.nMaxFile = Len(OpenFile.lpstrFile) - 1
OpenFile.nMaxFileTitle = OpenFile.nMaxFile
OpenFile.lpstrInitialDir = C:\
OpenFile.lpstrTitle = Select File
OpenFile.flags = 0
l_return = GetOpenFileName(OpenFile)
If l_return = 0 Then
MsgBox Operation cancelled
Else
PathtoContract.Value = Trim(OpenFile.lpstrFile)
End If
End Sub
7 Compile the project and return to Microsoft Dynamics GP. Close and reopen the Purchase
Order Entry window. and press the file button. You will now get the File Open Common Dialog
Box and can now choose a file. Once selected, the file and its path will be returned to the string
control added to store its value after selected.

11.1.3 The Common Dialog Control


The Common Dialog control provides a standard set of dialog boxes for operations such as
opening, saving, and printing files, as well as selecting colors and fonts and displaying help.
Any six of the different dialog boxes can be displayed with just one Common Dialog control.
240

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

A particular dialog box is displayed by using one of the six Show... methods of the Common
Dialog control: ShowOpen, ShowSave, ShowPrinter, ShowColor, ShowFont, or ShowHelp.

Notes

The Common Dialog control not an intrinsic control; rather, it is an Active X control that must
be added to the toolbox via the Components dialog box, as shown below. This dialog box is
accessed via the Project menu, Components item. Once you check Microsoft Common Dialog
Control 6.0 and click OK, the control is added to your toolbox (also shown below, circled). Then
you can double-click it to make it appear on your form, as you would with any other control.
The Common Dialog control is not visible at run-time.
Adding the Common Dialog Box Control
Although the Common Dialog Box control is known as a standard control, the control does not
appear on your toolbox until you add it. Perform these steps to add the Common Dialog Box
control to your toolbox:
1. Select Project | Components (Ctrl+T is the equivalent shortcut key for this option) to display
the Components dialog box shown in Figure 11.2.
Figure: 11.2 Additional Tools to Add Toolbox Window

2. Scroll to the control named Microsoft Common Dialog Control 6.0 and select it.
3. Click OK. The Common Dialog Box control will now appear at the end of your Toolbox window.
4. Double-click the Common Dialog Box control to add the control to your Form window.

Search the Internet and Microsofts home pages for additional ActiveX controls you
can drop into your toolbox by selecting the tool from the Components dialog box. (You may
have to click the Browse button to locate controls found in places other than your Windows
System folder.) An ActiveX control is identical to the toolboxs intrinsic controls and performs
work when you set its properties and when you use methods and events related to the control.

LOVELY PROFESSIONAL UNIVERSITY

241

Modern Programming Tools & Techniques-III

Notes

You can add ActiveX controls to your Toolbox window. If a tool you need does not appear on
the toolbox, that tool might appear as an ActiveX control in the Components dialog box or even
as an add-on tool you can download from an online service.
When you add the Common Dialog Box control, you will see several other controls listed in the
Components dialog box. At any time you can add these other controls to your tool box if you
think you can use their help. For example, you can add the Microsoft Calendar control if you
need to display calendar information in a Visual Basic application. You can add any ActiveX
control to your toolbox, and Visual Basic comes with several that you see when you display the
Components dialog box. (See Table 11.1)
Controls in the Dialog Box
The following controls are displayed in the Move dialog box.
Table 11.1: Controls in Dialog Box
Column name

Displays

Table of artifacts

Click to specify that the table listing the artifacts you can
move appears on the Move dialog box by default.

Move destination

Click to specify that the Destination and Browse options


appear on the Move dialog box by default.

Activity

Click to specify that when you are using a UCM view,


the Select Activity, New, and Find options appear on the
Move dialog box by default.

Comment

Click to specify that the Comment option appears on the


Move dialog box by default.

Option to leave the parent


directory checked out

Click to specify that the Leave the parent directory


checked out option appears on the Move dialog box by
default.

Current activity

Click to specify that the Current Activity option appears


on the Move dialog box by default when you are using
a UCM view.

Keep parent directories


checked out after
modification

Click to specify that the Leave the parent directory


checked out option is selected by default on the Move
Dialog Preferences page.

Restore Defaults

Click to restore the default settings to the Move Dialog


Preferences page.

Apply

Click to apply any changes you have specified while


leaving open the Preferences dialog box.

OK

Confirms the operation and closes the Preferencesdialog


box.

Cancel

Cancels the operation.

Remove:
Use this option to set the following preferences for the Remove dialog box: (See Table 11.2)
Controls in the dialog box
The following controls are displayed in the Remove dialog box.
242

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Notes

Table 11.2: Remove Dialog Box


Column name

Displays

Table of artifacts

Click to specify that the table listing the artifacts that you
can remove appears on the Remove dialog box by default.

Activity

Click to specify that when you are using a UCM view,


the Select Activity, New, and Find options appear on the
Remove dialog box by default.

Comment

Click to specify that the Comment option appears on the


Remove dialog box by default.

Option to leave the parent


directory checked out

Click to specify that the Leave the parent directory checked


out option appears on the Remove dialog box by default.

Current activity

Click to specify that the Current Activity option appears


on the Remove dialog box by default when you are using
a UCM view.

Keep parent directories


checked out after
modification

Click to specify that the Leave the parent directory checked


out option is selected by default on the Remove Dialog
Preferences page.

Restore Defaults

Click to restore the default settings to the Remove Dialog


Preferences page.

Apply

Click to apply any changes you have specified while


leaving open the Preferences dialog box.

OK

Confirms the operation and closes the Preferences dialog


box.

Cancel

Cancels the operation.

Rename:
Use this option to set the following preferences for the Rename dialog box: (See Table 11.3)
Controls in the dialog box:
The following controls are displayed in the Rename dialog box.
Table 11.3: Rename Dialog Box
Column name

Displays

Table of artifacts

Click to specify that the table listing the artifacts you can
rename appears on the Rename dialog box by default.

Activity

Click to specify that when you are using a UCM view,


the Select Activity, New, and Find options appear on the
Rename dialog box by default.

Comment

Click to specify that the Comment option appears on the


Rename dialog box by default.

Option to leave the parent


directory checked out

Click to specify that the Leave the parent directory checked


out option appears on the Rename dialog box by default.
Contd...

LOVELY PROFESSIONAL UNIVERSITY

243

Modern Programming Tools & Techniques-III

Notes

Column name

Displays

Current activity

Click to specify that the Current Activity option appears


on the Rename dialog box by default when you are using
a UCM view.

Keep parent directories


checked out after
modification

Click to specify that the Leave the parent directory checked


out option is selected by default on the Rename Dialog
Preferences page.

Restore Defaults

Click to restore the default settings to the Rename Dialog


Preferences page.

Apply

Click to apply any changes you have specified while


leaving open the Preferences dialog box.

OK

Confirms the operation and closes the Preferences dialog


box.

Cancel

Cancels the operation.

Undo Checkout:
Use this option to set the following preferences for the Undo Checkout dialog box:
Controls in the dialog box: The following controls are displayed in the Undo Checkout dialog
box. (See Table 11.4)
Table 11.4: Checkout Dialog Box
Column name

Displays

Table of artifacts

Click to specify that the table listing the resources for an


undo checkout operation appears on the Undo Checkout
dialog box by default.

Keep copy

Click to specify that the Keep a copy of modified artifacts


option appears on the Undo Checkout dialog box by default.

Keep a copy of the


un-Checkedout file

Click to specify that the Keep a copy of modified artifacts


option is selected on the Undo Check out dialog box by
default.

Restore Defaults

Click to restore the default settings to the Undo Checkout


Dialog Preferences page.

Apply

Click to apply any changes you have specified while leaving


open the Preferences dialog box.

OK

Confirms the operation and closes the Preferences dialog box.

Cancel

Cancels the operation.

Undo Hijack:
Use this option to set the following preferences for the Undo Hijack dialog box:
Controls in the dialog box:
The following controls are displayed in the Undo Hijack dialog box. (See Table 11.5)

244

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Table 11.5: Undo Hijack Dialog Box


Column name

Displays

Table of artifacts

Click to specify that the table listing the resources for an


undo hijack operation appears on the Undo Hijack dialog
box by default.

Keep copy

Click to specify that the Keep a copy of hijacked artifacts


option appears on the Undo Hijack dialog box by default.

Keep a copy of the


un-Hijacked file

Click to specify that the Keep a copy of hijacked artifacts


option is selected by default on the Undo Hijack dialog box.

Restore Defaults

Click to restore the default settings to the Undo Hijack


Dialog Preferences page.

Apply

Click to apply any changes you have specified while leaving


open the Preferences dialog box.

OK

Confirms the operation and closes the Preferences dialog


box.

Cancel

Cancels the operation.

Notes

Write a program using dialog box.


Once you make your changes and exit the Keyword Selection dialog box, you
cannot return to make additional changes. Calling up the Keyword Selection
dialog box again re-initializes it, eliminating your previous choices. Additional
changes must be made in the Exclude and Include text boxes in the Qualifier
List dialog box.

11.2 Open File Dialog


The Windows Forms OpenFileDialog component is a pre-configured dialog box. It is the same
Open File dialog box exposed by the Windows operating system. It inherits from the Common
Dialog class. Besides saving files, another common operation performed by users consists of
opening files. This refers to existing files since a file must primarily exist. To support this operation,
Microsoft Windows provides a standard dialog box: the Open File dialog box:
The OpenFileDialog object interacts with the Computers API (Application Programming
Interface) to present available files to the user and retrieves the users file selection back to
the program. This object is part of the System.Windows.Forms library so no additional using
reference will be needed. This dialog can be customized to show the file type, beginning
directory, and the title to be displayed on the dialog itself. When you limit the file type to just
the extension .txt as we did in this sample code, only those particular file types will be visible
to the user although they do have the option to select All files (*) as well.

11.2.1 Open File Dialog Box Creation


To provide file opening support, the .NET Framework provides the you can use the
OpenFileDialog class which is derived from the FileDialog class that in fact provides most of its
functionality. The easiest way to use it is to click the OpenFileDialog button from the Toolbox

LOVELY PROFESSIONAL UNIVERSITY

245

Modern Programming Tools & Techniques-III

Notes

and click on the form. You can click anywhere on the form because it would not be seen at run
time. After placing it on the form, you can use the Properties window to configure it.
If you prefer to dynamically create an Open dialog box, declare a variable of type OpenFileDialog
and use the new operator to allocate it memory using its default constructor. H
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace WindowsApplication2
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
SaveFileDialog sfd;
OpenFileDialog ofd;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
sfd = new SaveFileDialog();
ofd = new OpenFileDialog();
}
}
}

11.2.2 Characteristics of an Open Dialog Box


One of the most important properties of an Open dialog box is the file it presents to the user.
This is represented by the FileName property. If you want a default file to be specified when the
dialog box comes up, you can specify this in the FileName property of the Properties window. If
you need to use this property, you should make sure the file can be found. If the file is located in
the same folder as the application, you can provide just its name. If the file is located somewhere
else in the hard drive, you should provide its complete path. Most of the time, you will not be
concerned with this property if you are creating an application that will allow the user to open
any file of his or her choice. Once a file is located, it can be accessed using the OpenFileDialog.
FileName property.
246

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

To make your application more effective, you should know what types of files your application
can open. This is taken care by specifying a list of extensions for the application. To control the
types of files that your application can open, specify their extensions using the Filter Property.
The Filter string is created exactly like that of a SaveFileDialog control as we saw earlier.

Notes

Like the SaveFileDialog control, the default extension is the one the dialog box would first
filter during file opening. If you want the Open dialog box to easily recognize a default type
of file when the dialog box opens, you can specify the extensions type using the Default Ext
property. You can also use the FilterIndex we saw earlier to indicate the default index of the
Files of Type combo box.
For convenience, or for security reasons, Open dialog boxes of applications are sometimes asked
to first look for files in a specific location when the Open File dialog box comes up. This default
folder is specified using the InitialDirectory property.
The essence of using the Open dialog box is to be able to open a file. This job is handled by
the ShowDialog() method. After opening the dialog box, if the user selects a file and clicks OK
presses Enter, the file is opened. Most of the time, users are interested in opening one file to
view or manipulate. It is also possible for a user to want to select various files and open them at
the same time. When the user clicks OK after using the Open dialog box, before taking the next
step, you may need to find out whether the user selected various files. To get this information,
you can check the value of the OpenFileDialog. Multselect Boolean property. If the user had
selected various files, this property produces a true result. If the user selected only one file, this
property renders a false result. The result of this checking process allows you either to agree
to open the files or to take some action of your choice. After a file has been opened, the user
may want to alter it.
Configure Open File Dialog Box
Dim dlg As New Microsoft.Win32.OpenFileDialog()
dlg.FileName = Document Default file name
dlg.DefaultExt = .txt Default file extension
dlg.Filter = Text documents (.txt)|*.txt Filter files by extension
Show Open File Dialog Box
Dim result? As Boolean = dlg.ShowDialog()
Process open file dialog box results :
If result = True Then
Open document :
Dim filename As String = dlg.FileName
End If

Write a program using SaveFileDialog control.

11.3 Save File Dialog


A SaveFileDialog control is used to save a file using Windows Save File Dialog. A typical Save
File Dialog where you can see Windows Explorer like features to navigate through folders and
save a file in a folder. Use the System.Windows.Forms.SaveFileDialog class. In VB.NET, you
should be able to find it in the toolbox. Just set its properties, then call ShowDialog at runtime.

LOVELY PROFESSIONAL UNIVERSITY

247

Modern Programming Tools & Techniques-III

Notes

A SaveFileDialog control is used to save a file using Windows Save File Dialog. A typical Save
File Dialog looks like( Figure 11.3) where you can see Windows Explorer like features to navigate
through folders and save a file in a folder.
Figure 11.3: SaveFileDialog

11.3.1 Creating a SaveFileDialog


We can create a SaveFileDialog control using a Forms designer at design-time or using the
SaveFileDialog class in code at run-time (also known as dynamically). Unlike other Windows
Forms controls, a SaveFileDialog does not have and not need visual properties like others. Even
though you can create a SaveFileDialog at design-time but it is easier to create a SaveFileDialog
at run-time.
Design-time: To create a SaveFileDialog control at design-time, you simply drag and drop a
SaveFileDialog control from Toolbox to a Form in Visual Studio. After you drag and drop a
SaveFileDialog on a Form, the SaveFileDialog looks like. (See Figure: 11.4).
Figure 11.4: SaveFileDialog

Adding a SaveFileDialog to a Form adds following two lines of code.Me.SaveFileDialog1 = New


System.Windows.Forms.SaveFileDialog()
Run-time
Creating a SaveFileDialog control at run-time is merely a work of creating an instance of
SaveFileDialog class, set its properties and add SaveFileDialog class to the Form controls.
First step to create a dynamic SaveFileDialog is to create an instance of SaveFileDialog class.
The following code snippet creates a SaveFileDialog control object.
Dim saveFileDialog1 As New SaveFileDialog
ShowDialog method displays the SaveFileDialog.

248

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Notes

saveFileDialog1.ShowDialog()
Once the ShowDialog method is called, you can browse and select a file.
Setting SaveFileDialog Properties
After you place a SaveFileDialog control on a Form, the next step is to set properties. The easiest
way to set properties is from the Properties Window. You can open Properties window by
pressing F4 or right click on a control and select Properties menu item. The Properties window
looks like (See Figure 11.5).
Figure 11.5: Properties Window

Initial and Restore Directories


InitialDirectory property represents the directory to be displayed when the open file dialog
appears first time.
SaveFileDialog1.InitialDirectory = @C:\
If RestoreDirectory property set to true that means the open file dialog box restores the current
directory before closingSaveFileDialog1.RestoreDirectory = True
Title:Title property is used to set or get the title of the open file dialog.
SaveFileDialog1.Title = Browse Text Files
Default Extension
DefaultExtn property: represents the default file name extension.
SaveFileDialog1.DefaultExt = txt
Filter and Filter Index:
Filter property represents the filter on an open file dialog that is used to filter the type of files
to be loaded during the browse option in an open file dialog. For example, if you need users to
restrict to image files only, we can set Filter property to load image files only.
SaveFileDialog1.Filter = txt files (*.txt)|*.txt|All files (*.*)|*.*
FilterIndex property: Represents the index of the filter currently selected in the file dialog box.
SaveFileDialog1.FilterIndex = 2
Check File Exists and Check Path Exists

LOVELY PROFESSIONAL UNIVERSITY

249

Modern Programming Tools & Techniques-III

Notes

CheckFileExists property: Indicates whether the dialog box displays a warning if the user specifies
a file name that does not exist. CheckPathExists property indicates whether the dialog box
displays a warning if the user specifies a path that does not exist.
SaveFileDialog1.CheckFileExists = True
SaveFileDialog1.CheckPathExists = True
File Name and File Names
FileName property represents the file name selected in the open file dialog.
textBox1.Text = SaveFileDialog1.FileName
If MultiSelect property is set to true that means the open file dialog box allows multiple file
selection. The FileNames property represents all the files selected in the selection.
this.SaveFileDialog1.Multiselect = True
SaveFileDialog1.FileNames
The following code snippet is the code for Save button click event handler.
Once a text file is selected, the name of the text file is displayed in the TextBox.

Private Sub SaveButton_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles SaveButton.Click

Dim saveFileDialog1 As New SaveFileDialog

saveFileDialog1.InitialDirectory = C:\

saveFileDialog1.Title = Save text Files

saveFileDialog1.CheckFileExists = True

saveFileDialog1.CheckPathExists = True

saveFileDialog1.DefaultExt = txt

saveFileDialog1.Filter = Text files (*.txt)|*.txt|All files

saveFileDialog1.FilterIndex = 2

saveFileDialog1.RestoreDirectory = True

If (saveFileDialog1.ShowDialog() = DialogResult.OK) Then

TextBox1.Text = saveFileDialog1.FileName

End If

End Sub

(*.*)|*.*

Visual Basic 3.0 was released in the summer of 1993 and came in Standard
and Professional versions. VB3 included version 1.1.

11.4 The Color Dialog Box


To provide the selection of colours on Microsoft Windows applications, the operating system
provides a common dialog box appropriate for such tasks. The Colour dialog box is used for
various reasons to let the user set or change a colour of an object such as the background colour
of a control or the colour used to paint an object. (See Figure 11.6) When it displays, by default,
the dialog box appears as follows
250

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Figure: 11.6: Colour Dialog Box

Notes

This displays a constant list of colors to the user. If none of the available colors is appropriate
for the task at hand, the user can click the Define Custom Colors >> button to expand the dialog
box (see figure 11.7)
Figure 11.7: Custom Colours

The expanded Color dialog box allows the user to either select one of the preset colours or to
custom create a color by specifying its red, green, and blue values.
The user can change the color in four different areas. The top left section displays a list of 48
predefined colors. If the desired color is not in that section, the user can click and drag the
mouse in the multi-colored palette. The user can also drag the right bar that displays a range
based on the color of the palette; the user can scroll up and down by dragging the arrow. For
more precision, the user can type the Red, Green and Blue values. Each uses an integral value
that ranges from 1 to 255.

11.4.1 Making a Color Dialog Box Available


To provide the Color dialog box to your application, on the Toolbox, you can click the ColorDialog
button and click anywhere on the form. The Color dialog box is implemented through the
ColorDialog class, which is based on the CommonDialog class that is the ancestor to all Windows
common dialog boxes of the .NET Framework. To display the dialog box to the user, call the
CommonDialog.ShowDialog() method. Here is an example:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Me.colorDialog1.ShowDialog()
End Sub

LOVELY PROFESSIONAL UNIVERSITY

251

Modern Programming Tools & Techniques-III

Notes

The most important and most obvious property of the Color dialog box is the selected color
once the user has made a choice. When the user opens the dialog box, you can set the default
color. At design time, in the Properties windows, you can select a color from the Color property
(See Figure 11.8)
Figure 11.8: Colour Properties Window

At run time, you can set the color programmatically by assigning it a valid known name of a color:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Me.ColorDialog1.Color = Color.Green
End Sub
When the user has finished using the Color dialog box and clicks OK, you can find out what
color was selected by using the ColorDialog::Color property.
By default, the Color dialog box comes up in its regular (small) size. This allows the user to select
one of the preset colors. If the desired color is not available, as mentioned already, the user can
click the Define Custom Colors >> button. If you want to control the users ability to expand the
dialog box, use the Boolean AllowFullOpen property. When this property is set to True, which
is its default value, the dialog box appears in its regular size but with the Define Custom Colors
>> button enabled. If you want the user to be able to select only one of the preset colors and
not have the ability to expand the dialog box, set the AllowFullOpen property to False. With
this value, when the Color dialog box comes up, it is in its regular size but the Define Custom
Colors >> button is disabled (see figure 11.9)
Figure 11.9: Custom Colour Dialog Box

252

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

As mentioned above, by default, the Colour dialog box displays in its regular size. You can
control the regular or full size of the dialog using the Boolean Full Open property. When its
value is False, which is the default, the dialog appears regularly. If you want it to appear in its
full size, set this property to True.

Notes

Visual Basic 9.0 was released together with the Microsoft .NET Framework
3.5 on 19 November 2007.

Self Assessment Questions


Multiple choice questions
1. Modal dialog boxes are generally used ............. a program, to display messages, and to
set program parameters.
(a) inside

(b) out side

(c) Both (a) and (b) (d) None of these


2. The Open File Dialog object interacts with the Computers ............... to present available
files to the user and retrieves the users file selection back to the program.
(a) Application language interface
(b) Application design interface
(c) Application programming interface
(d) Application based interface
3. The new VB.NET has the same functionality in the ................. class.
(a) Open File Dialog

(b) Close File Dialog

(c) both (a) and (b)

(d) None of these

4. Modeless dialog boxes are frequently used as a ............ way to create a window.
(a) slow and easy

(b) fast and easy

(c) fast and default

(d) None of these

True or Flase

5. Filter property represents the filter on an open file dialog that is used to filter the type of
files to be loaded during the browse option in an open file dialog.

(a) True

(b) False

11.5 Message Box Class


The message box dialog is one of the most common ways to display custom messages to the user
and accept their input regarding the choice that they have made. VB.NET provides two ways to
use message boxes: the first is the MsgBox function, which is part of the Microsoft.VisualBasic
namespace and is coded in a fashion very similar to pre-.NET versions of VB; the second is
the MessageBox class, which has a slightly different syntax, and is the native .NET way to use
message boxes. MessageBox.Show displays a dialog box (see Figure11.10). It interrupts the user
it immediately blocks further interaction. It requires only one Function call. We specify buttons,
default buttons, an icon, and some other properties of the dialog. To display a simple message
box, you can use the MsgBox() function with the following formula:

LOVELY PROFESSIONAL UNIVERSITY

253

Modern Programming Tools & Techniques-III

Notes

MsgBox(Message)
Inside the parentheses, pass a string. Here is an example:
Private Sub btnMessage_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnMessage.Click
MsgBox(Is Visual Basic is awesome)
End Sub
Figure 11.10: Message Box

An event handler in the VB.NET language that will show the message boxes in the screenshot
sequentially when the program executes. The MessageBox.Show function is a Public Shared
Function typeit can be called without an instance reference.
We explored the MessageBox.Show function in the VB.NET language. We saw a program text
in the VB.NET language that specifies an event handler method body and this called into the
MessageBox.Show overloads, demonstrating how its behavior differs based on the arguments.
MessageBox Class Syntax: public class MessageBox
Creating a custom messagebox class :
Public Class MyCustomMsgBox

Private MyForm As Form = New Form

Private lblHeadline As Label = New Label

Private lblMessageBody As Label = New Label

Private btnNo As Button = New Button

Private btnOk As Button = New Button

Private btnYes As Button = New Button

Public Sub New(ByVal Message As String)

With MyForm

Width = 438

Height = 214

Controls.AddRange(New Control()
lblMessageBody, btnNo, btnYes, btnOk})

End With

End Sub

{lblHeadline,

11.5.1 MessageBox( ) Function


The objective of MsgBox is to produce a pop-up message box and prompt the user to click on
a command button before you can continues. This format is as follows:
yourMsg=MsgBox(Prompt, Style Value, Title)

254

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, for types of command
button displayed. The Title argument will display the title of the message board. (See Table 11.6)

Notes

Table 11.6: Style Values


Style Value

Named Constant

Buttons Displayed

vbOkOnly

Ok button

vbOkCancel

Ok and Cancel buttons

vbAbortRetryIgnore

Abort, Retry and Ignore buttons.

vbYesNoCancel

Yes, No and Cancel buttons

vbYesNo

Yes and No buttons

vbRetryCancel

Retry and Cancel buttons

We can use named constant in place of integers for the second argument to make the programs
more readable. In fact, VB6 will automatically shows up a list of names constant where you
can select one of them.
yourMsg=MsgBox(Click OK to Proceed, 1, Startup Menu) and
yourMsg=Msg(Click OK to Proceed. vbOkCancel,Startup Menu) are the same.
yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values
are determined by the type of buttons being clicked by the users. It has to be declared as Integer
data type in the procedure or in the general declaration section. The values, the corresponding
named constant and buttons. (See Table 11.7)
Table 11.7: Return Values and Command Buttons
Value

Named Constant

Button Clicked

vbOk

Ok button

vbCancel

Cancel button

vbAbort

Abort button

vbRetry

Retry button

vbIgnore

Ignore button

vbYes

Yes button

vbNo

No button

11.5.2 The Input Box( ) Function


An InputBox( ) function will display a message box where the user can enter a value or a message
in the form of text. The format is:
myMessage=InputBox (Prompt, Title, default_text, x-position, y-position)
myMessage is a variant data type but typically it is declared as string, which accept the message
input by the users. The arguments are explained as follows:
Prompt: The message displayed normally as a question asked.
Title: The title of the Input Box.

LOVELY PROFESSIONAL UNIVERSITY

255

Modern Programming Tools & Techniques-III

Notes

Default Text: The default text that appears in the input field where users can use it as his intended
input or he may change to the message he wish to key in.
X-Position and Y-Position: the position or the coordinate of the input box.

11.6 Dialog Result Class


DialogResult is returned by dialogs after they are dismissed. It indicates which button was
clicked on the dialog by the user. It is used with the MessageBox.Show method. It is a valueit
can be switched upon and tested in an if-statement.DialogResult can be used from the code
that showed a dialog box to determine whether a user accepted (true) or cancelled (false) the
dialog box. If a dialog box was accepted, this signifies to the code that opened the dialog box
to retrieve the data that was collected by the user and process it. If a dialog box was cancelled,
however, this signifies that calling code should stop any further processing. We use a switch
selection statement on the DialogResult enum local variable. We change the Text property based
on what button was clicked in the MessageBox. If the Enter key was pressed, the OK button is
considered to be used.
By default, a dialog box is cancelled when a user does one of the following:

Presses ALT+F4.

Clicks the Close button.


Selects Close from the System menu.

In all of these cases, DialogResult is false by default.


A dialog box typically provides a special button to cancel a dialog, which is the button whose
IsCancel property is set to true. A button configured this way will automatically close a window
when either it is pressed, or when the ESC key is pressed. In either of these cases, DialogResult
remains false.
A dialog box also typically provides an accept button, which is the button whose IsDefault
property is set to true. A button configured this way will raise its Click event when either it or
the ENTER key is pressed. However, it would not automatically close the dialog box, nor will
it set DialogResult to true. You need to manually write this code, usually from the Click event
handler for the default button.
DialogResult is null when the dialog box is shown but neither accepted nor canceled.
After a dialog box closes, you can get the dialog result from the value returned by ShowDialog
method, or by inspecting the DialogResult property.
DialogResult can only be set when a Window is opened by calling its ShowDialog method.
The DialogResult property is defined on the Window class. Not all Windows are dialogs.
Therefore, the property is not relevant to all windows. A Window that has been shown via
Show() rather than ShowDialog() will (presumably, unless you set it for some reason) have
DialogResult = null.
The following example shows how to configure an OK button and a Cancel button to return
the appropriate DialogResult.

256

Imports System

Imports System.Windows

Imports System.Windows.Controls

Namespace VisualBasic

Partial Public Class DialogBox


LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

Inherits Window

Public Sub New()

Notes

InitializeComponent()

End Sub

The accept button is a button whose IsDefault property is set to true.

This event is raised whenever this button is clicked, or the ENTER key is
pressed.

Private Sub acceptButton_Click(ByVal sender As Object, ByVal e As


RoutedEventArgs)

Accept the dialog and return the dialog result

Me.DialogResult = True

End Sub

End Class

End Namespace

11.6.1 Dialog Result Values


The DialogResult enum contains many different values. Because this enum is not decorated
with the [Flags] attribute, you cannot combine multiple enum values.
Here are the possible values for DialogResult:
DialogResult.None
DialogResult.OK
DialogResult.Cancel
DialogResult.Abort
DialogResult.Retry
DialogResult.Ignore
DialogResult.Yes
DialogResult.No

Safeco

afeco, Microsoft and ArtinSoft Corporation partnered to convert a large scale, real
world application to Visual Basic .NET. Safeco looked towards a VB to .NET migration
to enhance performance and take advantage of .NETs improved development
environment.
Company Overview
Safeco is a Fortune 500 diversified financial services company based in Seattle, Washington.
Safeco has been in business since 1923 and has grown to be premier provider of insurance
and financial products. Its products include auto, home, life and business insurance,
investments such as mutual funds, annuities and stock purchase plans; retirement plans for
business, trust services and surety bonds. Safeco had more than 17,000 partners, including
independent insurance agents, brokers, investment advisors and wholesalers. For 2001, its
Contd...
annual revenue was $6.87 billion.

LOVELY PROFESSIONAL UNIVERSITY

257

Modern Programming Tools & Techniques-III

Notes

Business Challenge
All the independent agents who sell personal Auto and Home products used Safecos software,
Personal Lines Rating Software (PLRS), developed in VB 6.0. The company had maximized
the use of its software by having remote quote and sale of its Home and Auto products.
Even though the software permitted download and upload of the updated transactions using
standard internet connections, the new .NET framework offered additional benefits highly
desired for the superior client server services.
The PLRS software was provided to more than 10,000 agents back then. Thousands of
quotes were done on a daily basis using PLRS, and thousands of sales were uploaded to
Safeco monthly. More sales were received at Safeco through PLRS than any of its other sales
channels or technologies.
Agents applauded the PLRS software for its ease of use, automatic self-updating, and the
use of standard Internet technology. PLRS could also bridge information from a number
of the popular agency management software systems that were often used in an insurance
agency, making sales tracking and servicing even easier.
Recognizing the great value of the current application and the need to evolve to a higher
technological platform, the company decided to investigate migrating to .NET and leverage
the knowledge and capital embedded in its software.
The VB to .NET migration was a challenge. The PLRS software consisted of approximately
230,000 lines of code, 462 classes, and 580 designers. In addition it had approximately 258
reports. Safeco wished to migrate this application to VB .NET in order to take advantage of
anticipated performance enhancements on the server side, utilization of web services, better
change management vs. COM, and the ability to run multiple copies of code. On the client
side, SAFECO felt that .NET offered a more stable development environment than ActiveX.
These two benefits added would substantially reduce Total Cost of Ownership by simplifying
deployment and maintenance for more than 10,000 agents.
The challenge for Safeco was to determine the viability of migrating this strategic application
from VB to .NET to take advantage of the technological advantages this platform offers, while
retaining the valuable business logic and functionality of the PLRS software.
The Solution
Safeco, in conjunction with Microsoft, turned to ArtinSoft, the industry leading enterprise
software migration and upgrade specialist. ArtinSoft developed for Microsoft the Visual
Basic 6.0 to Visual Basic .NET Upgrade Wizard that is included with Visual Studio .NET
and has been working with Visual Studio .NET and the .NET framework even before its
official release.
ArtinSoft, in consultation with Safeco, developed a project plan to achieve full functional
equivalence of the PLRS software in Visual Studio .NET in 101 calendar days. The application
port was essentially completed with an effort of 4 man-months of work. This is just a fraction
of the estimated 4 man-years it would have taken to manually re-write the application from
scratch. In order to optimize performance, VB6 string manipulation functions were converted
to their equivalent functions in .NET, and COM interop for User Controls was eliminated. A
conversion project of this size (230,000 lines of code) shows the robustness of the ArtinSoft
automation, and the experience of ArtinSofts engineers to handle a real world application.
Benefits
For Safeco, the opportunity to migrate PLRS to the .NET platform provided several key
business benefits, including support for web services, more rapid response time, better

258

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

change control to enhance the development process, and a more productive development
environment. The elimination of DLL version conflicts and simplified deployment
substantially reduced TCO and downtime.

Notes

Utilizing ArtinSofts expertise and rapid migration methodology and technology allowed
significant savings in both dollars and time over new development of the PLRS functionality
in Visual Studio .NET.
Questions

1. Explain the situation of Safeco.

2. What are the advantages to migrating from Vb to VB .NET?

Self Assessment Questions


Multiple choice questions
6. Which of the following is the method for showing common dialog boxes?
(a) ShowDialog

(b) ShowOpen

(c) ShowPrint

(d) ShowColor

7. Which of the following is not a type of common dialog box?


(a) Colour

(b) Save

(c) Edit

(d) Open

8. Which of the following is NOT true about menu items in Visual Basic?
(a) Menus appear at the top of a window.
(b) Menus can contain keyboard access keys
(c) You can add a separator between menu items by using the Line control from the
toolbox
(d) Create a menu using the MenuStrip component
9. Which of the following is NOT true about using keyboard access with a menu item?
(a) The first menus Text property should be &File.
(b) Do not use the same access key on a main menu name as you use on a form control
(c) When the program is running, use the Alt key with the letter in the menu that is
underlined, in order to access that procedure
(d) Menu items will not function correctly if keyboard access is not assigned
10. Which property in a menu items property window is used to change the words that will
display in the menu?
(a) Name

(b) Text

(c) Visible

(d) Index

11. Which property of a menu must be set to True if you want an item to have a check mark
next to it when the project runs?
(a) Selected

(b) Enabled

(c) Visible

(d) Checked

LOVELY PROFESSIONAL UNIVERSITY

259

Modern Programming Tools & Techniques-III

Notes

12. Which of the following is NOT true about a menu item that has a check mark?
(a) It is currently selected
(b) It can be deselected by changing its Checked property to False
(c) It can be toggled on and off
(d) It is shown in gray
13. Common Dialog Boxes ...........................
(a) Allow Visual Basic programs to translate the text on the screen into another language
(b) Display the predefined Windows dialog boxes for open, save, fonts, and colors
(c) Can only be used on forms with menus
(d) Allow you to create message boxes that will pop up and prompt the user for text
input
14. Of the following choices, which cannot be done with common dialog boxes?
(a) Opening files

(b) Selecting fonts

(c) Selecting colours

(d) Resizing windows

15. Which of the following statements about menus is NOT true?


(a) Menu items are displayed in buttons at the top of the window
(b) Create a menu by adding a MenuStrip component to the form
(c) In a menu, submenus will be indicated by a filled triangle to the right of the command
(d) Each item in a menu can have keyboard access

11.7 Summary

260

The common dialog box in visual basic is an insert able control that allows users to display
a number of common dialog boxes in their program.

The Common Dialog Box Library contains a set of dialog boxes for performing common
tasks, such as opening files and printing documents.
The OpenFileDialog object interacts with the Computers API (Application Programming
Interface) to present available files to the user and retrieves the users file selection back
to the program.
A SaveFileDialog control is used to save a file using Windows Save File Dialog. A typical
Save File Dialog where you can see Windows Explorer like features to navigate through
folders and save a file in a folder.
To provide the Colour dialog box to your application, on the Toolbox, you can click the
ColorDialog button and click anywhere on the form.
The objective of MsgBox is to produce a pop-up message box and prompt the user to click
on a command button before you can continues.
A dialog box also typically provides an accept button, which is the button whose IsDefault
property is set to true. A button configured this way will raise its Click event when either
it or the ENTER key is pressed.

LOVELY PROFESSIONAL UNIVERSITY

Unit 11: Common Dialog Boxes

11.8 Keywords

Notes

Cancel Dialog Box: A dialog box typically provides a special button to cancel a dialog, which
is the button whose IsCancel property is set to true.
Common Dialog Boxes: A common dialog box is a window that is used to perform a specific
but common type of user-driven operation. Examples of such operations include opening a file,
saving a file, printing, selecting a colour, etc.
Common Dialog Control: The Common Dialog control provides a standard set of dialog boxes
for operations such as opening, saving, and printing files, as well as selecting colors and fonts
and displaying help.
Dialogresult Values: The DialogResult enum contains many different values. Because this enum
is not decorated with the [Flags] attribute, you cannot combine multiple enum values.
InputBox( ) Function: An InputBox( ) function will display a message box where the user can
enter a value or a message in the form of text.
1. Create a form using message box function.
2. Write a program using colour dialog box in VB.NET.

11.9 Review Questions


1. What do you mean by common dialog boxes?

2. Describe common dialog library in detail.

3. Describe in detail about savefiledialog box.

4. How we make colour dialog box available?

5. What are the possible dialog result values?

6. Write the characteristics of an openfile dialogbox.

7. What do you mean by message box function ()?

8. Write an example to create a custom message box class.

9. Explain in detail about dialog result class.

10. Write a program using common dialog library in VB .NET.

Answers for Self Assessment Questions


1 (a)

2 (b)

3 (a)

4 (a)

5 (a)

6. (a)

7. (c)

8. (c)

9. (c)

10. (b)

11. (d)

12. (d)

13. (b)

14. (d)

15. (a)

11.10 Further Readings


Visual Basic 6 Programming Black Book by Steven Holzner.
Microsoft Visual Basic 2010 Step by Step by Michael Halvorson.
http://books.google.co.in/books?id=e1MKMiwPJkcC&pg=PA198&dq=comm
on+dialog+box&hl=en&sa=X&ei=DK0DUMTpA8PJrAew2MGgBg&ved=0CD
MQ6AEwAA#v=onepage&q=common%20dialog%20box&f=false

LOVELY PROFESSIONAL UNIVERSITY

261

Modern Programming Tools & Techniques-III

Unit 12: File Input Output

Notes

CONTENTS
Objectives
Introduction
12.1 Working with Files

12.1.1 The File Class

12.1.2 Path

12.1.3 File Enumerations

12.1.4 Basic File Class Operations

12.2 Working with Directory


12.2.1 Using the Classic File System Object

12.2.2 Notify Filters

12.2.3 Streams

12.2.4 FileStream

12.2.5 BufferedStream

12.2.6 NetworkStream

12.2.7 CryptoStream

12.2.8 MemoryStream

12.2.9 Readers and Writers

12.3 System.IO Operations


12.4 Summary
12.5 Keywords
12.6 Review Questions
12.7 Further Readings

Objectives
After studying this unit, you will be able to:

Explain the working with files

Describe the working with directory

Discuss the system.IO operations

Introduction
For the beginning .NET developer, one of the single most important underlying concepts is
called streams. A stream can be written to and read from. Conceptually, a pipe has two ends
just like a network connection. In any event, the overall concept involves input and output.
Therefore meant for the beginner to gain a sharper focus on I/O as a whole, with the end goal
of approaching streams, encryption, remoting, and overall .NET network programming. The
System.IO namespace contains and defines the classes used to navigate and manipulate files,
directories, and drives. The file system classes are separated into two types of classes: information
and utility. Most of the informational classes drive from the FileSystemInfo base class. These
262

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

classes expose all the system information about file system objects, particularly files, directories
and drives. These classes are named FileInfo and DirectoryInfo. In addition, the DriveInfo class
represents a drive in the file system, but although it is still an informational class, it does derive
from the FileSystemInfo class because it does not share the common sorts of behavior (i.e., you
can delete folders, but not drives. The utility classes provide static methods to perform certain
operations on file system objects such as files, directories, and file system paths.

Notes

12.1 Working with Files


An application devoid of support for files and directories is like a vehicle without wheels or a
boat without a propeller. Simply put, it is not going anywhere. There are a lot of things in .NET in
general and Visual Basic .NET in particular that you do not need to have an initial grounding in.
There are two approaches to coding against the file and directory libraries that ship with the
.NET Framework. You can reference static operations classes (File, Directory, and Path), or you
can create file and directory objects using the FileInfo and DirectoryInfo classes.
For many operations, you can simply use the static or shared classes, but there will be many
reasons to work with file and folder objects. For starters, if you herald from the worldwide
sisterbrotherhood of classic VB programmer you will probably be very familiar with the File
System Object (FSO). Most established VB programmers use the FSO all the time. Both FileInfo
and DirectoryInfo let you code against a similar and thus familiar object model as the FSO.
If you are not familiar with file and directory object models, consider the objects as objects that
represent files or directories, or abstractions thereof. An operations class is somewhat disconnected
from the file or directory you intend to work on, but a file or directory object is more like a
programmable file or directory object, with a layer you can code against.
When IBM and Microsoft were co-developing OS/2, they realized that File
Allocation Tables, FATs, did not offer the features a modern OS would
require, and Microsoft began developing the High Performance File System,
codenamed Pinball.

12.1.1 The File Class


The File class provides the .NET Frameworks support for all manner of file handling. With
this class, you can create, copy, delete, move, and open files and much more. File is a static or
shared operations class and not a class for objects. You cannot instantiate File and it has no
constructor. To use File, simply reference it as follows:
File.Copy(c:\doh.txt, c:\ray.txt)
If you need to use file objects to do your file operations, use the FileInfo class, which contains
instance methods that work like the methods of the File class but live in objects. Static methods,
being shared, incur more security overhead, whereas instance methods do not always require
security checks. Table 12.1 lists the static (s) members of File.
You have the potential to raise exceptions if you provide malformed filenames and path
information. The following examples of paths will get processed by the File methods, but you
should consider using the Path class, discussed next, to help reduce path errors:
c:\doh\ray.txt
c:\doh
doh\ray.txt a relative path and file name
\\doh\ray\ A UNC path for a server and share name.

LOVELY PROFESSIONAL UNIVERSITY

263

Modern Programming Tools & Techniques-III

Notes

12.1.2 Path
Programming against the file and directory classes is not rocket science, but the potential for
problems in your code is increased because you need to pass complex arguments (such as the
various mode and access constants). One parameter that can be a minefield represents the path
information argument you need to pass to the various methods of the file and directory classes.
Table 12.1: The Static Methods of File
Member

Purpose

AppendText

Bridge to a StreamWriter that appends UTF8 encoded text


to an existing file

Copy

Copies a source file to a new target file

Create

Creates a file on a given fully qualified path

CreateText

Creates or opens a new file for writing UTF8 encoded text

Delete

Deletes the file on the given fully qualified path. An exception


is not thrown if the specified file dose not exist

Exists

Checks if a specific file exists

GetAttributes

Retrieves the FileAttributes on the file on a given fully


qualified path

GetCreationTime

Retrieves the creation date and time of the specified file or


directory

GetLastAccessTime

Retrieves the date and time that the file or directory was last
accessed

GetLastWriteTime

Retrieves the date and time that the file or directory was last
written to

Move

Moves the source file to a new folder. It also provides the


option of a new filename

Open

Opens a FileStream on the given path

OpenRead

Opens an existing file for reading

OpenText

Opens an existing UTF8 encoded text file for reading

OpenWrite

Opens an existing file for writing

SetAttributes

Sets the specified FileAttributes on the file on the given path

SetCreationTime

Sets the date and time that the file was created

SetLastAccessTime

Sets the date and time that the given file was last accessed

SetLastWriteTime

Sets the date and time that the given file was last written to

The other stickler in file and directory operations has to deal with the differences between the
various file systems on the Windows platformFAT, FAT32, and the mighty NTFS. The current
file system on the platform you are targeting your application to determines the exact format
of a path. You might not always have the pleasure of working with one file system, or even
accessing a file or directory on a system other than a version of FAT or NTFS. You thus need to
come up with a flexible design to accommodate changing file system conditions.

264

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Some paths start with drive or volume letters, while others do not. Some file systems maintain
file extensions, and some do not. Some systems maintain a threecharacter extension; others
let you maintain extensions of more than three characters. The separator characters of path
namespaces also differ from platform to platform. And you probably know that various TCP/
IP path elements are separated with forward slashes instead of the backslashes of the UNC.

Notes

Paths can also contain absolute or relative location information. Absolute paths specify physical
locations that can be uniquely identified. Relative paths specify a partial location that still
requires additional resolution.
File systems on the various platforms in use today are as different as humming birds are from
fruit beetles. To cater to these differences (remember we are living in the era of the Internet and
distributed functionality), .NET provides a class you can use to process path strings as platform
independently as possible.
The members of the Path class are not used to physically operate on files and folders. You will
use the aforementioned file and directory classes and objects for that. But Paths members are
used to verify and modify path strings before you submit them as arguments to methods that
do manipulate file systems objects.
When you use Path to verify a path string, it will throw an ArgumentException if your path string
characters do not evaluate correctly. You decide what is or is not correct. The invalid characters
get defined in an InvalidPathChars array, which gets looked at when you request verification.
Example:
Invalid path characters on some platforms include quote (), less than (<), greater than (>), pipe
(|), backspace (\b), null (\0), and Unicode characters 16 through 18 and 20 through 25. You
will thus insert these characters into the InvalidPathChars array and then use this construct to
filter out bad path strings.
The Path class is also very useful for other path operations, such as enabling you to quickly
and easily perform common operations like determining whether a filename extension is part
of a path, or the combining of two strings to make one pathname. Table 12.2 lists the members
of the Path class.
The following example uses several members of the Path class to work files and path names
and to determine if the paths passed to various file and directory methods are acceptable. Please
note that these properties have been extracted from a class that encapsulates the constructs of
the Path class. The first example calls the Combine method to make a full path name out of the
directory and file names:
Make a path
Public ReadOnly Property FilePath() As String
Get
Return PathChecker.Combine(pName, fName)
End Get
End Property
This FilePath property information returned is
C:\indexworks\noisefile.txt

LOVELY PROFESSIONAL UNIVERSITY

265

Modern Programming Tools & Techniques-III

Notes

Table 12.2: Members of the Path Operations Class


Member

Purpose

AtlDirectorySeparatorChar

Provides a platformspecific alternate character


used to separate directory levels in a path string
that reflects a hierarchical file system organization

DirectorySeparatorChar

Provides a platformspecific character used to


separate directory levels in a path string that reflects
a hierarchical file system organization

InvalidPathChars

Provides a platformspecific array of character that


cannot be specified in path string arguments passed
to members of the Path class

PathSeparator

A platformspecific separator character used to


separate path strings in environment variables

VolumeSeparatorChar

Provides a platformsspecific volume separator


character

ChangeExtension

Changes the extension of a path string

Combine

Combines two path strings

GetDirectoryName

Retrieves the directory information for the specified


path string

GetExtension

Retrieves the extension of the specified path string

GetFileName

Retrieves the filename and extension of the


specified path string

GetFileNameWithoutExtension

Retrieves the filename of the specified path string


without the extension

GetFullPath

Retrieves the absolute path for the specified path


string

GetPathRoot

Retrieves the root directory information of the


specified path

GetTempFileName

Retrieves a unique temporary filename and creates


a zerobyte file by that name on disk

GetTempPath

Retrieves the path of the current systems temporary


folder

HasExtension

Determines whether a path includes a filename


extension

IsPathRooted

Retrieves a value indicating whether the specified


path string contains absolute or relative path
information

The following example extracts the root from the abovespecified full path and file name:

Public ReadOnly Property PathRoot() As String

Get
Return PathChecker.GetPathRoot(FilePath)
End Get
End Property

266

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

The PathRoot information returned is

Notes

C:\
The following example tests to see if a logical root exists in a path string. It returns False when
the FilePath property passes indexwork\noisefile.txt to the IsPathRooted method.

Public ReadOnly Property CheckRooted() As Boolean

Get
Return PathChecker.IsPathRooted(FilePath)
End Get
End Property
Remember that Path is not privy to exactly whats cooking on the hard disks or devices, volatile
or built of silicone and metal. Just because a drive and file path check though the Paths string
gauntlet does not mean the actual drive, computer, and network actually exist at the time the
path checks out.

Search a file with the help FilePath property.

12.1.3 File Enumerations


Among the parameters required by various methods for file operations are certain values that
are represented by a collection of enumeration classes. These classes include constants for file
access, synchronous or asynchronous processing, and file attributes. Table 12.3 lists the file
enumeration classes.
Enumerations can apply to FileInfo and FileStream classes as well, so get
used to them now.
FileAccess
Various file handling methods require you to specify the level of file access enjoyed by the user
or process accessing the file. The default file access level is full read and write capability on a file.
A FlagsAttribute attribute decorates the class so that the CLR can evaluate bitwise combinations
of the members of the enumeration. Table 12.3 lists the three FileAccess attributes.
Here is an example that grants read only access to a file. This allows it to be opened by the File
operation while someone else is using the file, but only allows the other, latter users to read
the file. They cannot write to it until they get the chance to open the file with write access, as
demonstrated in the following code:
Dim noisefile As New FileStream(filePath, FileMode.Open,
FileAccess.Read, FileShare.Read)
Table 12.3: File Enumeration Classes
Enumeration

Purpose

FileAccess

Read and write access to file

FileShare

Level of access permitted for a file that is already in use

FileMode

Synchronous or asynchronous access to the file in use

LOVELY PROFESSIONAL UNIVERSITY

267

Modern Programming Tools & Techniques-III

Notes

Table 12.4: Constants for the FileAccess Attribute Parameter


Member

Purpose

Read

Read access to the file. Date can be read from the


file. Combine with Write for read/write access

ReadWrite

Read and write access to the file. Data can be written


to and read from the file

Write

Write access to the file. Data can be written to the


file. Combine with Read for read/write access

FileAttributes
This enumeration class provides additional attributes for files and directories. A FlagsAttribute
attribute also decorates the file. Table 12.5 lists the file and directory attributes that permeate
up from the WinNT.h wrapper. The table also indicates where the attributes are applicable to
files and where they are applicable to directories. The asterisk (*) denotes that the facility may
not be supported by all file systems.
Not all attributes can be accommodated by every file system in existence. For example, reparse
points and support for mounted folders and encryption only arrived with the Windows 2000
operating system.
Table 12.5: Constants for the FileAttributes Parameter
Member

Purpose

Archive

Use this attribute to mark a file backup or removal.

Compressed

Indicates the object is compressed.[*]

Device

Reserved for future use.

Directory

Indicates the object is a directory.

Encrypted

Indicates the object encrypted. At the file object level, all


data in the file is encrypted. At the directory level, this
attribute indicates that all newly created files and files in
subdirectories get encrypted.[*]

Hidden

The file is marked as hidden so that the file system does


not allow it to be shown in a directory listing. The user
can usually change this at the directory level to show
hidden files.

Normal

Normal here means no other attributes, other than


normal, are set.

NotContentIndexed

Files that are marked with this attribute do not get indexed
by Index Server or some other content indexing service.

Offline

When a file is marked offline, it means that its data in not


immediately available.

ReadOnly

The file is readonly. See also the file access attributes.

ReparsePoint

This means the file contains a reparse point, which is


a block of userdefined data associated with a file or a
directory.
Contd...

268

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Notes
SparseFile

A sparse file is typically a large file whose data is mostly


zeros.

System

This means your file is part of the operating system or it


is used exclusively by the operating system.

Temporary

A temporary file is usually a placeholder for a file currently


in volatile memory. Your application should delete
temporary files as soon as they are no longer needed.

[*]

The asterisk denotes that the facility may not be supported by all file systems.

FileMode
The FileMode parameter lets you specify the treatment of a file as it is accessed.
For example, you can specify if the file should be opened in Append mode, which causes the
opening object supporting a Seek method to seek to the end of the file, where the new data
gets appended. OpenCreate, for example, lets the opening object create and open the file in the
same pass.
These attributes can be specified in Files (and FileInfos) Open methods and the constructors
of FileStream and IsolatedStorageFileStream. They control whether the file can be overwritten,
created, or opened, or open in some combination modes. Table 12.6 lists the FileMode
enumerations constants.
Table 12.6: Constants for the FileMode Parameter
Member

Description

Append

Seeks to the end of the existing file when it is opened; if the


file does not exist, the file system creates a new file

Create

Forces the creation of a new file

CreateNew

Requests the file system to create a new file with the given
name

Open

Requests that the file system should open an existing file

OpenOrCreate

Requests that the file system should open a file if it exists;


otherwise, a new file should be created

Truncate

Requests that the file system should open an existing file

The following list demonstrates the use of these attributes in the File.Open methods:

Append: This attribute can only be used in conjunction with FileAccess.Write. Any attempt
to read in the same pass gets rebuked with ArgumentException. The following code
demonstrates FileMode.Append:
Dim noisefile As New FileStream(filePath, FileMode.Append, _
FileAccess.Read, FileShare.Read)

Create: If the file already exists, it will be overwritten. This requires PermissionAccess.Write
and FileIOPermissionAccess.Append. FileMode.Create is the equivalent of requesting that
if the file does not exist; use CreateNew; otherwise, use Truncate. The following code
checks use Files Exist method to choose either Create or CreateNew. There are various
techniques you can use to prevent inadvertent deletion of a file when trying to create a
new one. The following If. . .Then condition is one example:
LOVELY PROFESSIONAL UNIVERSITY

269

Modern Programming Tools & Techniques-III

Notes

If Not (File.Exists(FilePath)) Then


Dim noisefile As New FileStream(FilePath, FileMode.Create, _

FileAccess.Read, FileShare.Read)
End If

CreateNew: This attribute requires FileIOPermissionAccess.Read and FileIOPermissionAccess.


Append. This attribute provides better protection of existing files than the Create attribute
discussed earlier, because it will cause an IOException that prevents damage to the existing
file. The following examples illustrates its usage.
Dim noiseFile As New FileStream(filePath, FileMode.CreateNew,
FileAccess.Read, FileShare.Read)

Open: This attribute also requires FileIOPermissionAccess.Read. It will cause a


FileNotFoundException if the file does not exist. The following examples demonstrates
opening the file in Read mode:
Dim noiseFile As New FileStream(filePath, FileMode.Open,
FileAccess.Read, FileShare.Read)

OpenOrCreate: A useful attribute if you are creating a number of files. Use this attribute with
FileAccess.Read and FileIOPermissionAccess.Read. When you use FileAccess.ReadWrite
and the file exists, FileIOPermissionAccess.Write is required at the same time. But if the
file does not exist, FileIOPermissionAccess.Append is required in addition to Read and
Write. The following example shows this happening:
Dim noiseFile As New FileStream(filePath, FileMode.OpenOrCreate,
FileAccess.Read, FileShare.Read)

Truncate: This attribute will cause an existing file to be opened and cleared or flushed in
one pass. In other words, as soon as it is opened, the file size of the file is zero bytes. This
operation requires FileIOPermissionAccess.Write. Naturally, any attempts to read from a
truncated file will result in an exception. The following method opens a file and specifies
truncation:
Dim noiseFile As New FileStream(filePath, FileMode.Truncate,
FileAccess.Read, FileShare.Read)
If a file is already open when you try to open it using one of the Read, Write,
or None flags, the operation will fail. You can only gain access to the file once
the current owner has closed it. And even if the file is closed and you pass
one of the above flags, you may still need additional permissions to access it.

FileShare
The constants exposed in the FileShare enumeration map to constants that let you specify to the
file system exactly how a file should be opened when it opens it. These constants are typically
passed to the Open methods of File and FileInfo and in the constructors of FileStream and the
IsolateStorageFileStream. Table 12.7 lists the constants of this enumeration.
Must specify to the file system exactly how a file should be opened when it
opens it.

270

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Table 12.7: Constants for the FileShare Parameter


Member

Notes

Purpose

Inheritable

Allows the file handle to be inherited by child


processes. This feature is apparently not directly
supported by the Win32 API.

None

Rebukes attempts to share access to a file. Any request


to open the file by the current process or any another
process fails until the file is closed.

Read

Allows subsequent opening of the file for reading

ReadWrite

Allows subsequent opening of the file for reading or


writing.

Write

Allows subsequent opening of the file for writing.

12.1.4 Basic File Class Operations


Here we learn demonstrates how to create and work with files.
In the example code, we have created a class with various methods that call the File classs
static methods, and then allow other objects to delegate to this wrapper or bridge the objects
for file operations.
How to Create a File
The Create and CreateText methods let you create a file at the end of the fully qualified path. You
can choose to call the Create method that returns a reference to the created file, or you can call
CreateText to open a file for writing in UTF8 encoded data. The following code demonstrates
calling CreateText. Note also that the following code calls for a Boolean result from the Exists
method to prevent an existing file from being deleted as a result of a create process.

If Not (File.Exists(FilePath)) Then

If FileFile.CreateText(FilePath)

End If
How to Copy a File
The following code demonstrates the copying of an existing file to a new file:
File.Copy(SourceFile, TargetFile)
The arguments SourceFile and TargetFile provide the Copy method with source and target path
and file names. If you omit directory information Copy sources and targets the folder of the
application it is executed from.
How to Delete a File
The following code demonstrates the call to delete a file. Delete will throw an exception if it is
unable to delete the target file for any reason.
File.Delete(TargetFile)
The method also traps the exception that will be inevitable if you attempt to delete a file that is
not on the fully qualified path, or that simply does not exist.
Getting and Setting File Attributes and Access Information on Files
You will always have cause to peek at file attributes and use them in various file handling
scenarios. The following example demonstrates retrieving the attributes that adorn a given file
with the GetAttributes method.

LOVELY PROFESSIONAL UNIVERSITY

271

Modern Programming Tools & Techniques-III

Notes

Public Function GetFileAtts(ByVal fileandpath As String) _


As System.IO.FileAttributes

FilePath = c:\indexworks\noisefile.txt

Debug.WriteLine(File.GetAttributes(FilePath))
End Function
With the list of attributes in hand, we can write the code that sets and changes certain attributes.
This is achieved using the SetAttributes method in the following code:
File.SetAttributes(FilePath, FileAttributes.Hidden)
To report on the time a file was created, last accessed, and last written to, and to set these
attributes, you can use the methods GetCreationTime, GetLastAccessTime, GetLastWriteTime,
SetCreationTime, SetLastAccessTime, and SetLastWriteTime, respectively. The following code
extracts this information from all the files in a directory and writes the information to a file
that is stored in a directory. Then a process checks the last time the file directory activity status
file was written to and, if a certain number of hours have passed, recreates the status file and
then resets its creation time.
Moving Files Around
The Move method moves a file to a new location. The method also provides the option of
changing the filename, as demonstrated in the following code:
File.Move(SourceFile, TargetFile)
The arguments SourceFile and TargetFile provide File.Move with source and target path and
file names. The Move method throws exceptions if it cannot source the file or the destination
already contains a file of the same name as the one being moved.
UTF-8 was first officially presented at the USENIX conference in San Diego,
from January 2529, 1993.

Write a program for getting and setting file attributes and access information
on files.

Self Assessment Questions


Multiple Choice Questions

1. The file system classes are separated into types of classes.

(a) one

(b) two

(c) three

(d) four

2. The CLR also uses a streams model for encrypted data.

(a) reading

(b) writing

(c) reading and writing

(d) None of these

3. This class contains methods that provide the as the File class.

(a) large service

(b) same service

(c) different service

(d) same and different service

True or False
4. Decoders and encoders are obtained using the Get Decoder and Get Encoder methods.
(a) True

272

(b) False

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

5. Network Stream implements the standard .NET Framework stream mechanism to send
and receive data through network sockets.
(a) True

Notes

(b) False

12.2 Working with Directory


The Directory class contains static methods exposed for the purpose of creating, moving, and
enumerating through directories and subdirectories. As is the case with the File class, Directory
is a shared operations class. If you need to perform folder operations via an object, then you can
use the DirectoryInfo class, discussed shortly. Table 12.8 lists the members of the Directory class.
Table 12.8: The Static Members of the Directory Class
Member

Purpose

CreateDirectory

Creates directories and subdirectories on a given path

Delete

Deletes directory contents

Exists

Checks if given path exist

GetCreationTime

Retrieves creation dates and times of directories

GetCurrentDirectory

Retrieves current working directories of the applications

GetDirectories

Retrieves names of subdirectories in specified directories

GetDirectoryRoot

Retrieves volume information, root information, or both


for the specified paths

GetFiles

Retrieves the names of files in the specified directories

GetFilesSystem Entries

Retrieves the names of all files and subdirectories in the


specified directory

GetLastAccessTime

Retrieves the date and time the specified file or directory


was last accessed

GetLastWriteTime

Retrieves the date and time the specified file or directory


was last written to

GetLogicalDrives

Retrieves the names of the logical drives on this computer,


for example, c:\

GetParent

Retrieves the parent directory of the specified path,


including both absolute and relative paths

Move

Moves files or folders and directory contents to a new


location

SetCreationTime

Lets you set the creation date and time for files or directories

SetCurrentDirectory

Lets you create the current working directory

SetLastAccessTime

Lets you set the date and time the specified file or directory
was last accessed

SetLastWriteTime

Lets you set the date and time a directory was last written to

The static methods of Directory are straightforward, The following code, however, parses a
given directory and then reports what it finds to the console:

Public Shared Sub ProcessDirectory(ByVal targetDir As String)

Dim subdirectory As String


Dim fileName As String

LOVELY PROFESSIONAL UNIVERSITY

273

Modern Programming Tools & Techniques-III

Notes

Dim subdirectories As String() = Directory.GetDirectories(targetDir)

Dim files As String() = Directory.GetFiles(targetDir)

For Each fileName In files

Next fileName

PrintFileInfo(fileName)

For Each subdirectory In subdirectories


ProcessDirectory(subdirectory)

Next subdirectory

End Sub
The ProcessDirectory method starts off taking the path of a target directory passed to it and then
it recursively enumerates all subdirectories in the target directory. The full path is then written
to the console using the PrintFileInfo method in the following code:
Public Shared Sub PrintFileInfo(ByVal path As String)

Console.WriteLine(Found: {0}, path)

End Sub
The FileInfo Class
This class contains methods that provide the same service as the File class. The main difference
between the two classes is that FileInfos methods are instance methods and the class contains a
constructor that lets you create it as an object. What you get is a reference variable to an object
that represents or abstracts a file. The class also provides a handful of properties that make
reporting on a file easier. The members of FileInfo (sans methods inherited from Object) are
listed in Table 12.9.
Table 12.9: The Members of the FileInfo Class
Member

Purpose

Attributes (p)

Gets or sets the File Attributes of the current FileSystemInfo


object

CreationTime (p)

Gets or sets the creation time of the current FileSystemInfo


object

Directory (p)

Gets an instance of the parent directory

DirectoryName (p)

Gets a string representing the directorys full path

Exists (p)

Gets a value indicating whether a file exists

Extension (p)

Gets the string representing the extension part of the file

FullName (p)

Gets the full path of the directory or file

LastAccessTime (p)

Gets or sets the time the current file or directory was last
accessed

LastWriteTime (p)

Gets or sets the time when the current file or directory was
last written to

Length (p)

Gets the size of the current file or directory

Name (p)

Gets the name of the file

AppendText

Creates a StreamWriter that appends text to the file


represented by this instance of the FileInfo

CopyTo

Copies an existing file to a new file


Contd...

274

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Notes

Create

Creates a file

CreateText

Creates a StreamWriter that writes a new text file

Delete

Permanently deletes a file

MoveTo

Moves a specified file to a new location, providing the option


to specify a new filename

Open

Opens a file with various read/write and sharing privileges

OpenRead

Creates a readonly FileStream

OpenText

Creates a StreamReader with UTF8 encoding that reads


from an existing text file

OpenWrite

Creates a writeonly FileStream

Refresh

Refreshes the state of the object

Apart from the semantic differences, the reduction in security checks, and a few additional
members like Refresh and Length, this class provides the same operations on files as the File class,
if you get more utility out of a file system object and prefer to stick with a .NET file handling
class, then uses FileInfo over the legacy FSO.
Also, the same exception raised for File problems applies to FileInfo problems, especially
malformed paths and file information.
DirectoryInfo
Table 12.10 lists the methods and properties of the DirectoryInfo class. This class can be
instantiated and its members are instance members. Instantiation gets you access to a useful
collection of properties that provide information such as file extensions, parent directory names,
root folders, and so on.
Table 12.10: The Instance Members of the DirectoryInfo Object
Member

Purpose

Attributes (p)

Retrieves or changes the FileAttributes of the current


resource

CreationTime (p)

Retrieves or changes the creation time of the current resource

Exists (p)

Retrieves or changes a value indicating whether the directory


exists

Extension (p)

Retrieves or changes the string representing the extension


part of the file

FullName (p)

Retrieves the full path of the directory or file

LastAccessTime (p)

Retrieves or changes the time the current file or directory


was last accessed

LastWriteTime (p)

Retrieves or changes the time when the current file or


directory was last written to

Name Overridden (p)

Retrieves the name of this DirectoryInfo instance

Parent (p)

Retrieves the parent directory of a specified subdirectory

Root (p)

Retrieves the root portion of a path

Create

Creates a directory
Contd...

LOVELY PROFESSIONAL UNIVERSITY

275

Modern Programming Tools & Techniques-III

Notes

CreateSubdirectory

Creates a subdirectory of subdirectories on the given path.


The path can be relative to this instance

Delete

Deletes the resource directory and its contents from a path

GetDirectories

Retrieves the subdirectories of the current directory

GetFiles

Retrieves a file list from the current directory

GetFileSystemInfos

Retrieves an array of strongly typed FileSystemInfo objects

MoveTo

Move a directory and its contents to a new path

Refresh

Refreshes the state of the object

Instantiate a DirectoryInfo object passing in the directory path string (pName) to the method
as follows:
Dim dirinfo As New DirectoryInfo(pName)
You can then code against the object, as demonstrated in the following example, which maintains
a reference to a DirectoryInfo object for folder management:

Dim dirifo As New DirectoryInfo(pName)

If dirinfo.Exists = False Then

create the directory

dirinfo.Create()
End If
Creating a file and opening it are also quite simple with the DirectoryInfo class. Here is an
example:
Dim folders As New DirectoryInfo(C:\indexworks)
folders.CreateSubdirectory(noisefiles)
Notice in the above example the CreateSubdirectory method only needs the name of the
subdirectory. It will throw an exception if you try to pass it path information.

12.2.1 Using the Classic File System Object


The .NET Framework can wrap the classic File System Object (FSO) that many VB programmers
are familiar with. Bringing the FSO into .NET is a process that happens in less than ten mouse
clicks, so the only difficulty you may have in using it is deciding if you want to or have to. If
you know your way around the FSO model, you can continue to program against it, because the
interop layer that wraps this legacy object provides seamless access to the original objects in its
COM DLL (the Microsoft Scripting Runtime). If this support helps you with migration or porting,
then you need to consider it until you are ready to adopt the FileInfo and DirectoryInfo classes.
If, however, you do not care for the FSO or are not moving code from VB to Visual Basic .NET,
then stick with the native classes that do not need the additional overhead of the interop
layers (the FSO is still very fast, even in .NET).
For those of you who do not know about the FSO object model, it encapsulates the following
objects:

276

Drive: Lets you extract information about drives attached to the local computer or a remote
computer on the network. With it, you can determine how much space is available on the
drive, what share names it has, and so on. The Drive object lets you access other devices
as well, such as a CDROM drive, a RAM disk, and a DVD.

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Drives: Exposes Count and Item properties.

Folder: Lets you create, delete, or move folders. It also supports the ability to research
folder names, paths, and more

File: Lets you create, delete, or move files. It also supports the ability to research filenames,
paths, and other information.

TextStream: Lets you read and write text files

Notes

To use the FSO in your application, you need to create a reference to the Scripting type library
(Scrrun.dll) in which it resides. This is a COM object that typically lives in the operating systems
folders (such as C:\Winnt\System32). But you can access and reference it in your project by
adding the reference to it from the References Folder, Add Reference option, or from your
projects menus.
Click the COM tab in the Add Reference dialog box and scroll down to the item that reads
Microsoft Scripting Runtime. Doubleclick the item to select it and click OK. Presto, an interop
wrapper is spun around this legacy DLL, and you can start using it (just do not go interopping
every legacy DLL you have been using in your VB apps for the past ten years, or your apps
will start crawling to a halt in no time).
At the top of your class that you are going to use to code against the FSO add an Imports
statement and point it to the Scripting namespace created in the interop wrapper. You will see it
the second you type Imports. You can now start using the facilities in this namespace immediately.
The following code demonstrates how to instantiate a new FSO:
Dim fso As New FileSystemObject
Or you can call old faithful, the CreateObject method, and pass the FQNS (the legacy type library
and the object it encapsulates) to the FSO as an argument. This affects the bridge as well. The
latter option is demonstrated as follows:
Dim fso = CreateObject(Scripting.FileSystemObject)
Once you have referenced the Scripting DLL, you can browse the interop.Scripting assembly in
the Object Browser. You will notice that most of the objects, classes, and methods do not offer
anything special or different from the native File and FileInfo classes (we will also be covering
.NETs Directory and Path classes shortly, so sit tight). However, the Drive and Drives classes
are worth looking at.
Drive provides you with a neat collection of methods for accessing volume information, available
space, drive letters, share names, and so on. The properties listed in Table 12.11 provide disk
and volume information.
A Drives object that comes packaged into the FSO model also exposes a Count property and
an Item property. The following code demonstrates how to instantiate the objects via the FSO
interface and access its members.
Dim fso As New FileSystemObject()
DriveInfo.Add(fso.Drives.Count())
FileSystemWatcher
Objects of the FileSystemWatcher class watch the file system and report to you the moment a
file or folder changes. There are so many uses for this class that it would be pointless to try
and list them all.
The FileSystemWatcher class lets you also watch for changes in a specified directory on a
network drive, or a remote computer. But before you get caught up in the novelty of this

LOVELY PROFESSIONAL UNIVERSITY

277

Modern Programming Tools & Techniques-III

Notes

Table 12.11: The Properties of the Drive Class in the File System Object
Property

Purpose

TotalSize

Retrieves the total size of the drive, in bytes

AvailableSpace, FreeSpace

Retrieves the amount of space available on the drive,


in bytes

DriveLetter, Letter

Retrieves the drive letters assigned to the drive

DriveType

Retrieves the type of drive (removable, fixed, network,


CDROM, RAM disk)

SerialNumber

Retrieves the drives serial number

FileSystem

Retrieves the type of file system on the drive (FAT,


FAT32, or NTFS)

IsReady

Used to determine if the drive is available for use

ShareName, VolumeName

Provides the name of the share and/or volume

Path, RootFolder

Provides the path or root folder of the drive

class, remember that the watcher is platformdependent. FileSystemWatcher only works on


Windows XP, .NET Server, Windows 2000, and Windows NT 4.0. Your remote computers must
have one of these platforms installed for the component to function properly. You cannot watch
a remote Windows NT 4.0 computer from a Windows NT 4.0 computer.
FileSystemWatcher does not attempt to watch CDs and DVDs, which do not change. Its members
are listed in Table 12.12.
Table 12.12: The Members of the FileSystemWatcher Class
Member

Description

Container (p)

Retrieves the IContainer that contains the component

EnableRaisingEvents (p)

Retrieves or changes a value indicating whether the


component is enabled

Filter (p)

Retrieves or changes the filter string, used to


determine what files are monitored in a directory

IncludeSubdirectories (p)

Retrieves or changes a value indicating whether


subdirectories within the specified path should be
monitored

InternalBufferSize (p)

Retrieves or changes the size of the internal buffer

NotifyFilter (p)

Retrieves or changes the type of changes to watch for

Path (p)

Retrieves or changes the path of the directory to watch

Site (p)

See Component Site of the Component class

SynchronizingObject (p)

Retrieves or changes the object used to marshal the


event handler calls issued as a result of a directory
change

BeginInit

Begins the initialization of a FileSystemWatcher


used on a form or used by another component. The
initialization occurs at run time.
Contd...

278

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Notes
EndInit

Ends the initialization of a FileSystemWatcher


used on a form or used by another component. The
initialization occurs at run time.

Equals
(inherited from Object)

Determines whether two Object instances are equal

WaitForChanged

A synchronous method that returns a structure that


contains specific information on the change that
occurred

Changed (e)

Occurs when a file or directory in the specified Path


is changed

Created (e)

Occurs when a file or directory in the specified Path


is created

Deleted (e)

Occurs when a file or directory in the specified Path


is deleted

Disposed (e)
Adds an event handler to listen to the Disposed event
(inherited from Component) on the component
Error (e)

Occurs when the internal buffer overflows

Renamed (e)

Occurs when a file or directory in the specified Path


is renamed

The following example watches a folder for changes in files that will trigger the need to recreate
the files and folder status report. It creates a FileSystemWatcher to watch the directory specified
at run time. The component is set to watch for changes in LastWrite and LastAccess time, and
the creation, deletion, or renaming of text files in the directory. If a file is changed, created, or
deleted, the path to the file prints to the console. When a file is renamed, the old and new paths
print to the console.
Public Sub Watching()

declare a watcher

Dim Watcher As New FileSystemWatcher()

specify a path

Watcher.Path = c:\indexworks

specify the notify filters

Watcher.NotifyFilter = (NotifyFilters.LastAccess _

Or NotifyFilters.LastWrite _

Or NotifyFilters.FileName _

Or NotifyFilters.DirectoryName)

the file to watch

Watcher.Filter = noisefile.txt

Specify event handlers.

AddHandler watcher.Changed, AddressOf OnChanged


Start

Watcher.EnableRaisingEvents = True

End Sub

implement the event handler.

LOVELY PROFESSIONAL UNIVERSITY

279

Modern Programming Tools & Techniques-III

Notes

Public Shared Sub OnChanged(ByVal source As Object, _

ByVal eArgs As FileSystemEventArgs)


Reload the noisewords file after it has been changed

Indexworks.Reload(FilePath)

End Sub

12.2.2 Notify Filters


Changes to watch for in a file or folder are specified by constants of the NotifyFilters enumeration
and set to the NotifyFilter property. Like the constants of the file mode, access, and attributes
enumerations, this enumeration has a FlagsAttribute attribute that allows a bitwise combination
of its member values. In other words, you can combine constants to watch for more than one
kind of change.
For example, you can watch for changes in the size of a file or a folder, and for changes in security
settings. The combination raises an event anytime there is a change in size or security settings
of a file or folder. Table 12.13 lists the constants of the NotifyFilters enumeration.
Table 12.13: Members of the NotifyFilters Enumeration
Member

Purpose

Attributes

Represents the attributes of the file or folder

CreationTime

Represents the time the file of folder was created

DirectoryName

Represents the name of the directory

FileName

Represents the name of the file

LastAccess

Represents the date the file or folder was last opened

LastWrite

Represents the date the file or folder last had anything


written to it

Security

Represents the security settings of the file or folder

Size

Represents the size of the file or folder

Use these filter constants to specify the constant or constant combinations to watch. To watch
for changes in all files, set the Filter property in the object to an empty string (). If you are
watching for a specific file, then set the Filter property to the filename as follows:
Watcher.Filter = noisefile.txt
To watch for changes in all text files, simply set the Filter property as follows:
Watcher.Filter = *.txt
By the way, hidden files are not ignored.
WatcherChangeTypes
Changes to watch for that may occur to a file or folder are specified by constants of the
WatcherChangeTypes enumeration and set to the event hanlder. This enumeration also has a
FlagsAttribute attribute decorating it that allows the CLR to reference bitwise combinations of
its member values. Each of the WatcherChangeTypes constants is associated with an event in
FileSystemWatcher.
The constant members of this enumeration are listed in Table 12.14.

280

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Table 12.14: The Constants of the FileSystemWatcher Enumeration


Member

Notes

Description

All

Fires on the creation, deletion, change, or renaming of a


file or folder

Changed

Fires on the change of a file or folder. The types of changes


include: changes to size, attributes, security settings, last
write, and last access time.

Created

Fires on the creation of a file or folder

Deleted

Fires on the deletion of a file or folder

Renamed

Fires on the renaming of a file or folder

You also need to be careful not to create too many events in the FileSystemWatcher object, a
problem that can arise when a file you are watching is moved to another folder you are also
watching. You will get events for the departing files as well as the arrival files.
For example, moving a file from one location to another generates a delete event, OnDelete,
when the file departs. Then you get an OnCreated event when the file arrives at its new location.
You also need to be cognizant of the changes other applications make on your files. Backup
software changes the attributes of files. Virus software also has a stake in the file system because
it opens files, inspects them, and then closes them. Products like Open File Manager, which lets
backup software back up open files, may also conflict.
Too many changes in a short time may also cause the objects buffer to overflow. This will cause
the object to lose track of changes in the directory. Memory used by the object is also expensive,
because it comes from nonpaged memory that cannot be swapped out to disk. The key is to
keep the buffer as small as possible and avoid a buffer overflow by refining your operations.
This means dropping unnecessary or redundant filters and subdirectories.

12.2.3 Streams
.NET provides for getting data into files and getting it out again. This is the crux of I/O, and
.NET accomplishes it with streams.
The .NET Framework defines a base class called Stream that supports the reading and writing
of bytes. Any time that you implement stream I/O functionality, you will inherit, or directly
instantiate, objects from the classes inherited from Stream. The derivatives of Stream can be
found in Sytem.IO, System.Net, System.Security, and System.XML.
Stream is an abstract class and has been extended in a variety of specialized child classes. You
can derive from Stream and build your own classes to support streaming. But you would be
hardpressed to come up with something that is not already supported in the base class library
(other than soda streams), or that is not already earmarked for the next release of the .NET
Framework.
The Stream class and its children provide a facility for handling data, blocks of bytes, without
having to care about what happens down in the basement of the operating system. There is
no need for you to burden yourself with the myriad details of how data flows down to metal
and across the wire. The various layers beyond your method calls are dealt with by the CLR
and the file system. So perfectly aligned are these classes with the platform that writing and
reading to streams makes you feel guilty for what programmers in the Wild West days of C
and Assembly had to go through.

LOVELY PROFESSIONAL UNIVERSITY

281

Modern Programming Tools & Techniques-III

Notes

The following classes derive from Stream:


BufferedStream: Reads and writes to other Stream objects. This class can be derived from
and instantiated.

FileStream: Bridges a Stream object to a file for synchronous and asynchronous read and
write operations. This class can be derived from and instantiated.

MemoryStream: Creates a Stream in memory that can read a block of bytes from a current
stream and write the data to a buffer. This class can be derived from and instantiated.

CrytoStream: Defines a Stream that bridges data objects to cryptographic services. This
class can be derived from and instantiated.

NetworkStream: Defines a Stream that bridges data objects to network services. This class
can be derived from and instantiated.

The preceding classes provide data streaming operations. This data may be persisted by bridging
certain objects to various backing stores. However, the Stream objects do not necessarily need
to be saved. Your objects might stream volatile information, resident only in memory. For
algorithms not requiring backing stores and other output or input devices, you can simply use
MemoryStream objects.
MemoryStream objects support access to a nonbuffered stream that encapsulates data directly
accessible in memory. The object has no backing store and can thus be used as a temporary
buffer. On the other hand, when you need to write data to the network, you will use classes
like NetworkStream. Your standard text or binary streams can also be managed using the
FileStream class. Stream objects enable you to obtain random access to files through the use of
a Seek method, discussed shortly.
Another Stream derivative you will find yourself using on many occasions is the CryptoStream
class. This class is also not included in the System.IO namespace but has been added to the
System.Security.Cryptography namespace.
BufferedStream objects provide a buffering bridge for other Stream objects, such as the
NetworkStream object. The BufferedStream object stores the stream data in memory in a special
byte cache, which cuts down on the number of calls the object needs to be made to the OS.

12.2.4 FileStream
FileStream objects can be used to implement all of the standard input, output, and error stream
functionality. With these objects, you can read and write to file objects on the file system. With
it you can also bridge to various filerelated operating system handles, such as pipes, standard
input, and standard output. The input and output of data is buffered to facilitate performance.
The File class is typically used to create and bridge FileStream objects to files based on file paths
and the standard input, standard output, and standard error devices. MemoryStream similarly
bridges to a byte array.
The principal method in a FileStream object is Seek. It supports random access to files and allows
the read/write position to be moved to any position within a file. The location is obtained using
byte offset reference point parameters.
The following code demonstrates the creation and opening of a file and the subsequent bridge
to the FileStream object used to write to the file:
Dim aFile As New FileStream(source, IO.FileMode.Create)
In the preceding code, a file is opened, or created if it does not already exist, and information
is appended to the end of the file. The contents of the file are then written to standard output
for display.
282

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Byte offsets are relative to a seek reference point. A seek reference point can be the beginning
of the file, a position in the file, or the end of the file.

Notes

The three SeekOrigin constructs are the properties of the SeekOrigin class.
Disk files always support random access. At the time of construction, the CanSeek property
is set to true or false depending on the underlying file type. Specifically, if the underlying file
type is FILE_TYPE_DISK, as defined in winbase.h, the CanSeek property is true. Otherwise, the
CanSeek property is false. Table 12.15 lists the members of the FileStream class.
Table 12.15: The Members of FileStream

Member

Purpose

CanRead (p)

Retrieves a value indicating whether the current stream supports


reading

CanSeek (p)

Retrieves a value indicating whether the current stream supports


seeking

CanWrite (p)

Retrieves a value indicating whether the current stream supports


writing

Handle (p)

Retrieves the operating system file handle for the file that the current
FileStream object encapsulates

IsAsync (p)

Retrieves a value indication whether the FileStream was opened


asynchronously or synchronously

Length (p)

Retrieves the length, in bytes, of the stream

Name (p)

Retrieves the of the FileStream that was passed to the constructor

Position (p)

Retrieves or changes the current position of this stream

BeginRead

Begins an asynchronous read

BeginWrite

Begins an asynchronous write

Close

Closes the file and releases any resources associated with the current
file stream

EndRead

Waits for the pending asynchronous read to complete

EndWrite

Ends an asynchronous write, blocking until the I/O operation has


completed

Flush

Clears all buffers for this stream and causes any buffered data to be
written to the underlying device

Lock

Prevents access by other processes to all or part of a file

Read

Reads a block of bytes from the stream and writes the data in a given
buffer

ReadByte

Reads a byte from the file and advances the read position one byte

Seek

Changes the current position of this stream to the given value

SetLength

Changes the length of this stream to the given value

ToString

Returns a String that represents the current Object

Unlock

Allows access by other processes to all or part of a file that was


previously locked

Write

Overridden. Writes a block of bytes to this stream using data from


a buffer

WriteByte

Overridden. Writes a byte to the current position in the file stream

LOVELY PROFESSIONAL UNIVERSITY

283

Modern Programming Tools & Techniques-III

Notes

BeginRead, BeginWrite
When you get ready to open a file object using FileStream, you need to specify either synchronous
or asynchronous mode. The read and write methods support both modes but, depending on
your data and the algorithm, the modes provide significant performance consequences for
the synchronous methods (Read and Write) and the asynchronous methods (BeginRead and
BeginWrite).
Both sets of methods will work in either mode; however, the mode will affect the performance
of these methods. FileStream defaults to opening files synchronously, but the constructor is
overloaded and provides a version of New to open files asynchronously.
While either can be used, the underlying file system determines which resources might allow
access in only one of these modes. While FileStream opens the operating system handle
synchronously, this impacts asynchronous method calls, which are made independently of the
file systems. To use asynchronous methods, construct the object with a constructor that allows
you to specify an isAsync argument.
The signature of this BeginRead method is as follows:

Overrides Public Function BeginRead(ByVal array() As Byte, _

ByVal offset As Integer, _

ByVal numBytes As Integer, _

ByVal userCallback As AsyncCallback, _

ByVal stateObject As Object _

) As IAsyncResult
The following list describes its parameters:

Array: A buffer to read data into

Offset: The byte offset in the array at which to begin reading

numBytes: The maximum number of bytes to read

userCallback: The method to be called when the asynchronous read operation is completed

stateObject: A userprovided object that distinguishes this particular asynchronous read


request from other requests

Before you call BeginRead, issue a condition check on the CanRead property. This will let you
determine whether your object has the allclear to move into high gear. BeginRead will also choke
on invalid arguments and throws out exceptions immediately. Wrapping up the method calls
in exception handling code is thus critical. Exceptions are also raised during asynchronous read
requests. For example, a read may fail if the file reference dies through disk failure, corruption,
or some other file catastrophe.
By default, streams smaller than 64KB complete synchronously for better performance. The
additional effort required for asynchronous I/O on such small streams negates the advantages
of asynchronous I/O. Also, you need to call EndRead with IAsyncResult to find out how many
bytes were read. Table 12.16 lists the possible exceptions that can result from good read requests
that go bad.

284

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Table 12.16: Exceptions That Can Be Generated on a BeginRead Operation


Exception

Notes

Condition

ArgumentException

The array variables length minus offest is less


than numBytes

ArgumentNullException

The array variable references Nothing

ArgumentOutRangeException

The offset or numBytes is negative

IOException

An asynchronous read was attempted past the


end of the file

Seek
The Seek method changes the current position in the stream to the value passed as the argument.
Its signature is as follows:

Overrides Public Function Seek( _

ByVal offset As Long, _

ByVal origin As SeekOrigin _

) As Long
The following list describes its parameters:

Offset: A point relative to the origin from which to begin seeking.

Origin: A value that specifies the beginning, the end, or the current position as a reference
point for origin, using a value of type SeekOrigin.

Return Value: You get back the new position in the stream.

Seek can cause the exceptions listed in Table 12.17.


You can use the CanSeek property to determine whether the current instance supports seeking.
Also note that seeking to any location beyond the length of the stream is supported. Set the
position to one byte beyond the end of the stream, as recommended by the SDK documentation
to open a new file and write to it. This lets you append to the file. Just remember that the position
cannot be set to more than one byte beyond the end of the stream.
Table 12.17: Exceptions That Can Be Generated on a Seek Operation
Exception

Type Condition

IOException

An I/O error occurred

NotSupportedException

The stream does not support seeking. This can


happen if the FileStream is constructed from a pipe
or console Output

ArgumentException

Attempted seeking before the beginning of the


stream or more than one byte past the end of the
stream

ObjectDisposedException

Methods were called after the stream was closed

One of the classes you will find especially interesting is IsolatedStorageFileStream. This class
supports the streaming of data to isolated storage units, which are a form of private file systems
that can contain files and that can only be accessed by an owner, an application, or user.

LOVELY PROFESSIONAL UNIVERSITY

285

Modern Programming Tools & Techniques-III

Notes

Writing to a file stream object can be performed like the following examples which add words
to the top of the noisewords files. Existing words are pushed down:

Public Sub AddWords(ByVal fileandpath As String, ByVal neword As String)

Dim aFile As New FileStream(source, IO.FileMode.OpenOrCreate, _

FileAccess.Write)

Dim wordadder As StreamWriter = New StreamWriter(aFile)

Gets new words to add to the file.

wordadder.WriteLine(neword)
wordadder.Close()
End Sub
After the words are added, the file stream is closed and the information is automatically saved.
The following example appends to a file. Instead of the words inserted at the top of the file,
they are appended at the end of the text in the file:

Public Sub AddWords(ByVal source As String, ByVal neword As String)

Dim aFile As New FileStream(source, IO.FileMode.OpenOrCreate, _

FileAccess.Write)

Dim wordadder As StreamWriter = New StreamWriter(aFile)

Gets new words to append to the end of the file.

wordadder.BaseStream.Seek(0, SeekOrigin.End)

wordadder.WriteLine(neword)
wordadder.Close()
End Sub
In the preceding examples, there is a slight difference at the Seek calls. The change is the
BaseStream.Seek method of the StreamWriter object that we created. This means that the
subsequent executions of the second example will append the data to the file. You can easily
change the position by changing the SeekOrigin enumeration. This is demonstrated as follows:

Public Sub AddWords(ByVal source As String, ByVal neword As String)

Dim aFile As New FileStream(source, IO.FileMode.OpenOrCreate, _

FileAccess.Write)

Dim wordadder As StreamWriter = New StreamWriter(aFile)

Gets new words to append to the end of the file.

wordadder.BaseStream.Seek(0, SeekOrigin.Begin)

wordadder.WriteLine(neword)
wordadder.Close()
End Sub

12.2.5 BufferedStream
A buffered streams purpose in life is to read and write to another stream. BufferedStream is
essentially a block of bytes in memory used to cache data, thereby reducing the number of calls
to the operating system. You will use your buffers to improve read and write performance,
but you cannot use a buffer to read and write at the same time. Objects of the BufferedStream
work like the FileStream object, but the Read and Write methods of BufferedStream are used
to automatically maintain the buffer.

286

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

If you always read and write for sizes greater than the internal buffer size, then BufferedStream
might not even allocate the internal buffer. BufferedStream also buffers reads and writes in a
shared buffer. Usually, you do a series of reads or writes, but rarely alternate between reading
and writing.

Notes

The following method example demonstrates the creation of a BufferedStream object bridged
to the earlier

declared standard FileStream object:

Public Sub AddNoises(ByVal source As String, _

ByVal noiseword As String)


Dim fStream As New FileStream(source, FileMode.OpenOrCreate,
FileAccess.Write)
Dim bStream As New BufferedStream(fStream)

Create a StreamWriter to write the data into the file.

Dim sWriter As New StreamWriter(bStream)


sWriter.WriteLine(noiseword)

Update the StreamWriter.

sWriter.Flush()

Close the StreamWriter and FileStream.

sWriter.Close()
fStream.Close()
End Sub

12.2.6 NetworkStream
A NetworkStream object provides the underlying stream of data for network access.
NetworkStream implements the standard .NET Framework stream mechanism to send and
receive data through network sockets. It also supports both synchronous and asynchronous
access to the network data stream.

12.2.7 CryptoStream
The CLR also uses a streams model for reading and writing encrypted data. This service is
provided by the CryptoStream object. Any cryptographic objects that implement CryptoStream
can be chained together with any objects that implement Stream, so the streamed output from
one object can be bridged into the input of another object. The intermediate result (the output
from the first object) does not need to be stored separately.

12.2.8 MemoryStream
MemoryStream is no different from the previously mentioned streams except that volatile
memory is used as the so-called backing store rather than a disk or network sockets. This class
encapsulates data stored as an unsigned byte array that gets initialized upon the instantiation
of the MemoryStream object. However, the array can also be created empty. The encapsulated
data in the object is thus directly accessible in memory.
Memory streams can reduce the need for temporary buffers and files in an application, which
can improve performance by an order of magnitude.
GetBuffer
To create a MemoryStream object with a publicly visible buffer, simply call the default constructor.
A stream can be declared resizable, which resizes the array, but in that respect, multiple calls

LOVELY PROFESSIONAL UNIVERSITY

287

Modern Programming Tools & Techniques-III

Notes

to GetBuffer might not return the same array. You can also use the Capacity property, which
retrieves or changes the number of bytes allocated to the stream. This ensures consistent results.
GetBuffer also works when the MemoryStream is closed.
ToArray
The ToArray method is useful for translocating the contents of the MemoryStream to a formal
Byte array. If the current object was instantiated on a Byte array, then a copy of the section of
the array to which this instance has access is returned. MemoryStream also supports a WriteTo
method that lets you write the entire contents of the memory stream to another streamone that
has a persistent backing store.

12.2.9 Readers and Writers


So far we have looked at classes that let you work with Strings that also provide a facility for you
to retrieve or supply the String. We have also gone from manipulating String data to constructing
Strings and using them in various display fields. While capturing the values provided by the
various ToString methods is possible, the classes and utilities discussed earlier do not provide
much in the way of features that get data on the road.
The .NET Frameworks data streaming (I/O) support inherits from the abstract TextReader
and TextWriter classes that live in the System.IO namespace. These classes form the basis of
support for internationally viable and highly distributed software because they support Unicode
character streams.
Text Encoding
Before we look at the reader and writer classes, understand that methods are provided to convert
Arrays and Strings of Unicode characters to and from Arrays of Bytes encoded for a target code
page. A number of encoding implementations are thus provided in the System.Text namespace.
The following list presents these encoding classes:

ASCIIEncoding Class: Encodes Unicode characters as single 7bit ASCII characters. It only
supports character values between U+0000 and U+007F.

UnicodeEncoding: Encodes each Unicode character as two consecutive Bytes. Both little
endian and bigendian Byte orders are supported.

UTF7Encoding: Encodes Unicode characters using the UTF7 encoding (UTF7 stands for
UCS Transformation Format, 7bit form). This encoding supports all Unicode character
values.

UTF8Encoding: Encodes Unicode characters using the UTF8 encoding (UTF8 stands for
UCS Transformation Format, 8bit form). This encoding supports all Unicode character
values.

Other encoding can be accessed using the GetEncoding method that passes a code page or
name argument.
When the data to be converted is only available in sequential blocks (such as data read from
a stream), an application can use a decoder or an encoder to perform the conversion. This is
also useful when the amount of data is so large that it needs to be divided into smaller blocks.
Decoders and encoders are obtained using the GetDecoder and GetEncoder methods. An
application can use the properties of this class, such as ASCII, Default, Unicode, UTF7, and UTF8,
to obtain encodings. Applications can initialize new instances of encoding objects through the
ASCIIEncoding, UnicodeEncoding, UTF7Encoding, and UTF8Encoding classes.

288

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Through an encoding, the GetBytes method is used to convert arrays of Unicode characters

Notes

to Arrays of Bytes, and the GetChars method is used to convert Arrays of Bytes to Arrays of
Unicode characters. The GetBytes and GetChars methods maintain no state between conversions.
The core GetBytes and GetChars methods require you to provide the destination buffer and
ensure that the buffer is large enough to hold the entire result of the conversion. An application
can use one of the following methods to calculate the required size of the destination buffer.
The GetByteCount and GetCharCount methods can be used to compute the exact size of the
result of a particular conversion, and an appropriately sized buffer for that conversion can then
be allocated.
The GetMaxByteCount and GetMaxCharCount methods can be used to compute the maximum
possible size of a conversion of a given number of bytes or characters, and a buffer of that size
can then be reused for multiple conversions.
The GetMaxByteCount method generally uses less memory, whereas the second method
GetMaxCharCount generally executes faster. See the .NET Framework SDK documentation for
the various encoding and decoding methods.
StringReader/StringWriter
Besides the standard methods of the StringBuilder class, which make it useful on its own,
the framework bridges StringBuilder to both the StringWriter and StringReader classes. This
cooperation between the builder classes and the transport classes lets you stream characters
into and out of StringBuilder objects as a type of staging area where Strings get to go to be
manipulated. You can think of these classes as the instruments you can use to write and read
characters to the StringBuilder object.
Despite being the StringBuilders apprentices, these classes are located in the System.IO namespace
(while StringBuilder lives in System.Text), which has a lot to do with the fact that StringWriter
derives from TextWriter. Table 12.18 presents the important members of the StringReader class.
Table 12.18: The Members of the StringReader Class
Member

Purpose

Close

Closes the StringReader

Peek

Returns the next available character but does not consume it

Read

Reads the next character or next set of characters from the


input string

ReadBlock

Reads a maximum of counted characters from the current


stream and writes the data to the buffer, beginning at a
specified location

ReadLine

Reads a line from the underlying string

ReadToEnd

Reads to the end of the text stream

The syntax for creating a StringReader class is as follows:


Dim s as new StringReader(C:\MyFile.txt)

LOVELY PROFESSIONAL UNIVERSITY

289

Modern Programming Tools & Techniques-III

Notes

Table 12.19 lists the members of the StringWriter class.


Table 12.19: The Members of the StringWriter Class
Member

Purpose

Encoding (p)

Retrieves the encoding in which the output is written

FormatProvider (p)

Retrieves an object that controls formatting

NewLine (p)

Retrieves or changes the line terminator string used by the


current TextWriter

Close

Closes the current StringWriter and the underlying stream

CreateObjRef

Creates an object that contains all the relevant information


required to generate a proxy used to communicate with a
remote object

Flush

Clears all buffers for the current writer and causes any
buffered data to be written to the underlying device

GetLifetimeService

Retrieves the current lifetime service object that controls the


lifetime policy for this instance

GetStringBuilder

Returns the underlying StringBuilder object

Write

Writes to this instance of the StringWriter

WriteLine

Writes some data as specified by the overloaded parameters,


followed by a line terminator

Write
User the Write method to write data to an object that can receive a text input stream, such as
StringBuilder.
The following code illustrates writing to a StringBuilder object:

Public Sub AddWords(ByVal source As String, ByVal newword As String)

Dim sBuilder As New StringBuilder()


Dim strWriter As New StringWriter(sBuilder)
strWriter.Write(newword)

check if write worked

Console.WriteLine(sBuilder)
End Sub
Write does not force a new line, and new text is either appended to the existing text or, depending
on theobject, overwrites it.
WriteLine
The WriteLine method works exactly like Write, but adds a line terminator to the end of the
String, which forces a new line. This is demonstrated as follows:
Console.WriteLine(sBuilder)

290

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Notes

GetStringBuilder
The GetStringBuilder method will return an instance of StringBuilder that you can write to.
Append and insert your characters to the object as demonstrated in the earlier Building Strings
with StringBuilder section and then simply write the object to a line.
Public Sub AddChars()

Create a StringBuilder with 20 characters capacity and capped at 20

Dim sBuilder As New StringBuilder(20, 20)

Create a character array to hold characters that will be

fed into the StringBuilder.

Dim charArray As Char() = {Ic, c, lc, oc, vc, ec, _

c, Vc, Bc, c, .c, Nc, Ec, Tc, .c}

Create a StringWriter...

Dim strWriter As New StringWriter()


and bridge it to the StringBuilder object

sBuilder = strWriter.GetStringBuilder()

Write a bunch of characters from the array to the StringBuilder.

strWriter.Write(charArray, 0, 15)

Console.WriteLine(sBuilder)
End Sub
The code writes I Love VB .NET to the console. The technique shown here is useful for building
Strings that you can then simply write to a text output stream. The receiver picks up the object
and simply writes to the console or similar device.
Flush
Flush can also be used to write to the output device. But the method clears the writers buffer
in the process. The following example demonstrates flushing to a StringBuilder object:
sBuilder = strWriter.GetStringBuilder()
Write a bunch of characters from the array to the StringBuilder.
strWriter.Write(charArray, 0, 15)
strWriter.Flush(charArray, 0, 15)
Console.WriteLine(sBuilder)
Close
The Close method simply shuts down the writer and its underlying stream as follows:
strWriter.Close()
StreamReader/StreamWriter
While derivatives of the Stream class are intended for Byte I/O, the StreamReader and
StreamWriter classes are intended for writing to and reading from a standard text file. The
StreamReader and StreamWriter classes default to UTF8 encoding unless specified otherwise,
instead of defaulting to the ANSI code page for the current system. UTF8 handles Unicode

LOVELY PROFESSIONAL UNIVERSITY

291

Modern Programming Tools & Techniques-III

Notes

characters correctly and provides consistent results on localized versions of the operating system.
Table 12.20 lists the members of the StreamReader class; Table 12.21 lists the members of the
StreamWriter class.
The Read and Write methods read and write the number of characters specified by their Count
parameter. These are to be distinguished from BufferedStream.Read and BufferedStream.Write,
which read and write the number of bytes specified by a count parameter. Use the BufferedStream
methods only for reading and writing an integral number of byte array elements. For example:
Dim sReader As New StreamReader(FilePath)
The optional arguments are as follows:

Encoding Specified character encoding to use

BufferSize Suggested minimum buffer size

DetectEncodingFromByteOrderMarks Encoding type indicator


Table 12.20: The Members of the StreamReader Class
Member

Purpose

Null (p)

A StreamReader around an empty stream

BaseStream (p)

Returns the underlying stream

CurrentEncoding (p)

Retrieves the current character encoding that the current


StreamReader is using

Close

Closes the StreamReader and releases any system resources


associated with the reader

CreateObjRef

Creates an object that contains all the relevant information


required to generate a proxy used to communicate with
a remote object

DiscardBufferedData

Allows a StreamReader to discard its current data

Peek

Returns the next available character but does not consume


it

Read

Reads the next character or next set of characters from


the input stream

ReadBlock

Reads a maximum of counted characters from the current


stream and writes the data to a buffer, beginning at a
specified index

ReadLine

Reads a line of characters from the current stream and


returns the data as a string

ReadToEnd

Reads the stream from the current position to the end of


the stream

When you read data from the StreamReader for the first time, you can change the encoding by
changing the encoding flag.
The DetectEndcodingFromByteOrderMarks detects the encoding from the first three bytes of the
stream. The bigendian, littleendian, and UTF8 Unicode text is automatically recognized. If
the encoding cannot be determined, the userdefined encoding is implemented.

292

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Table 12.21: The Pertinent Members of StreamWriter


Member

Purpose

Null (Nothing) (p)

Provides a StreamWriter with a backing store that


can be written to, but not read from

AutoFlush (p)

Retrieves or changes a value indicating whether the


StreamWriter will flush its buffer to the underlying
stream after every call to Console.Write or Console.
WriteLine

BaseStream (p)

Retrieves the underlying stream that interfaces with


a backing store

Encoding (p)

Retrieves the encoding in which the output is


written

FormatProvider (p)

Retrieves an object that controls formatting

NewLine (p)

Retrieves or changes the line terminator string used


by the current TextWriter

Close

Closes the current StreamWriter and the underlying


stream

Flush

Clears all buffers for the current writer and causes


any buffered data to be written to the underlying
stream

Write

Writes to the stream

WriteLine

Writes some data as specified by the overloaded


parameters, followed by a line terminator

Notes

StreamWriter defaults to using an instance of the UTF8Encoding object unless specified


otherwise. This instance of UTF8Encoding is constructed such that the Encoding.GetPreamble
method returns the Unicode byte order mark written in UTF8. The preamble of the encoding
is added to a stream when you are not appending to an existing stream. This means any text
file you create with StreamWriter will have three byte order marks at its beginning. UTF8
handles all Unicode characters correctly and gives consistent results on localized versions of
the operating system. If we now create a StreamReader class, we can figure out what we wrote
to the StreamWriter with the following code:

Dim sReader As StreamReader = New StreamReader(fStream)

sReader.BaseStream.Seek(0, SeekOrigin.Begin)

For intX = 0 to 25

Console.Write cstr(rReader.Read)

Next intX

BinaryReader/BinaryWriter
The BinaryReader and BinaryWriter classes read and write primitive data types as binary values
in a specific encoding. The primary methods in these classes are Read and Write, which come
in a different flavor for every data type supported in the framework.

12.3 System.IO Operations


The System.IO namespaces contain types that support input and output, including the ability
to read and write data to streams either synchronously or asynchronously, to compress data in

LOVELY PROFESSIONAL UNIVERSITY

293

Modern Programming Tools & Techniques-III

Notes

streams, to create and use isolated stores, to map files to an applications logical address space,
to store multiple data objects in a single container, to communicate using anonymous or named
pipes, to implement custom logging, and to handle the flow of data to and from serial ports.
The .NET Framework provides an impressive range of IO namespaces that contain dozens of
classes used for writing, reading, and streaming all manner of text, characters, and binary data,
as well as file, folder, and path support. Many of them, such as those represented by the System.
IO, System.Text, and System.XML namespaces, let you code asynchronous and synchronous
reading and writing of data to streams and files. All these namespaces are currently partitioned
across the mscorlib, System, System.Text, and System.XML assemblies.
The files you work with in your programs are typically ordered collections of bytes, representing
characters on a file system. Files are static; they squat on your hard disks like chickens hatching
eggs. Streams, on the other hand, are continuous rivers of data, writing to and reading from
various devices. Streams are constantly on the move.
Streams typically originate from files on devices like hard disks, CDs, and DVDs, and other
devices for persistent storage such as tape drives and optical disks. Streaming data moves across
processes and workspaces on your workstation, and between computers on the vast networks of
the world. They move from persistent memory into volatile memory and back again in a constant
ebb and flow of data. Eventually, streams of data get fed to printers for physical representation
like annual reports or user manuals.
The following is a list of the key sections we will discuss that facilitate basic I/O for the .NET
Framework:

File and Directories: The classes that encapsulate the functionality of all known file
and directory processing operations. Files are opened, closed, and manipulated using
the classes enumerations, file mode enumerations, file information classes, directory
information classes, and so on. The principal classes discussed here are File, FileInfo,
Directory, DirectoryInfo, and Path. File, Directory, and Path descend directly from System.
Object while FileInfo and DirectoryInfo are descendants of FileSystemInfo. We also look at
BinaryReader and BinaryWriter, which also derive from System.Object.For the nostalgic,

Streams: The principal class discussed here is FileStream. Most of the stream utility classes
derive from System.IO.Stream.

Readers and Writers: They derive from System.IO.TextWriter and System.IO.TextReader.


We will also discuss how these readers and writers can be bridged to various classes and
objects like File and StringBuilder.

.NET data processing by discussing basic file operations first. You also need a good understanding
of how file processing works before working with the Stream objects, because streams objects
are bridged to file operations.
There is really only one way to perform an I/O action: bind it to Main.main in your program.
When your program is run, the I/O will be performed. It is not possible to perform I/O from
an arbitrary function, unless that function is itself in the IO monad and called at some point,
directly or indirectly, from Main.main.
IO is a monad, so IO actions can be combined using either the do-notation or the >> and >>=
operations from the Monad class.
Example:
Imports System.IO

Public Class Form1

294

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Private Sub Button1_Click(ByVal sender As System.Object, _

Notes

ByVal e As System.EventArgs) Handles Button1.Click


Try

Dim line As String

Dim readFile As System.IO.TextReader = New _

StreamReader(C:\TextReader.txt)
While True

line = readFile.ReadLine()

If line Is Nothing Then

Exit While
Else

MsgBox(line)
End If

End While

readFile.Close()

readFile = Nothing

Catch ex As IOException
MsgBox(ex.ToString)
End Try
End Sub
End Class
Example:
First, to begin using the FileInfo type, it helps to include the System.IO namespace at the top
using the Imports System.IO directive. In this example, we first construct the FileInfo instance
by passing a file name to its constructor.
Program that uses Length and FileInfo [VB.NET]
Imports System.IO
Module Module1
Sub Main()

Get file info for test.txt.


... Create this file in Visual Studio and select Copy If Newer
on its properties.

Dim info As New FileInfo(test.txt)

Get length of the file.

Dim length As Long = info.Length

Add more characters to the file.

File.AppendAllText(test.txt, More characters.)

Get another file info.

... Then get the length.

Dim info2 As New FileInfo(test.txt)

LOVELY PROFESSIONAL UNIVERSITY

295

Modern Programming Tools & Techniques-III

Notes

Dim length2 As Long = info2.Length

Show how the size changed.

Console.WriteLine(Before and after: {0}, {1}, length, length2)

Console.WriteLine(Size increase: {0}, length2 - length)


End Sub

End Module
Output
(Will change each run.)
Before and after: 3, 20
Size increase: 17

IO Virtualization Technology
The Atlantis Approach to IO Virtualization
Atlantis ILIO is an IO virtualization technology for VDI that front ends a traditional SAN/
NAS storage system to enable high performance IO, storage optimization/consolidation and
virtual desktop image composition.
Extracting IO state and creating Flocks
Flocks (File and Block IO) are Atlantis Computing patent pending format of virtualized
data storage that merges file and block data into a component. Flocks are block devices with
semantic knowledge of their contents. Flocks are aggregated and composited to form dynamic
volumes that host NTFS and Unix filesystems. The benefit of storing data in flocks is that a
common set of OS and application components can be used to create desktops and servers
that are fully customizable (including allowing users to install applications) yet allow the
underlying common OS and applications to be centrally changed (without the limitations
suffered by traditional block based Copy on Write approaches like linked clones) or resource
intensive instance-based file system based copy on write and kernel installed read write
redirection approaches which do not guarantee application compatibility.
Real time In-line De-duplication of Storage Objects
Traditional de-duplication is applied to a volume after duplicated data has been committed
to it. Traditional de-duplication processes a volume by calculating a unique check sum
for each block of data based on its contents and then sharing references to a single block
wherever blocks have the same checksum. De-duplication has been used with virtualization
as a means to reduce the physical storage requirements for virtual machine images where
the image content is highly repetitious. ILIO real time de-duplication works by marking and
identifying duplicate objects as they are virtualized into flocks before data is committed to the
storage volume. As a result the de-duplication process is more efficient and processes data
in real time rather than as a post process. In practice this means that if two users on a VDI
desktop pool install the same application, only one physical copy of the application is stored.
Contd...

296

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

Using a single common image of operating system and applications

Notes

ILIO allows the use of a single common physical copy of an operating system or application
to be used across all virtual desktops instances. In practice this means that in a 10,000 instance
Virtual Desktop implementation, there is just one copy of the OS and applications and all the
10,000 instances share the same base image. This typically results in a 20x storage reduction.
Caching Frequently used IOs and Offloading the Backend SAN/NAS
Latency between SAN/NAS storage and VDI servers is a critical parameter in determining
overall performance for a VDI deployment. As discussed previously, VDI is IO intensive
and needs low latencies coupled with large throughput to work well. On loaded SAN/NAS
systems latencies increase into the 10s of milliseconds and this can have negative consequences
on user experience in the case of virtual desktops. ILIO allows frequently accessed and
common IO to be cached close to the server. This serves two important purposes:
SAN/NAS Offload
ILIO can offload up to 95% of the IO on homogenous image deployment (as is the case with
VDI where most OS and application components are shared). This means that a SAN/NAS
system is no longer overwhelmed by many desktops making IO requests.
IO Acceleration
Atlantis ILIO allows important classes of IO such as Operating system virtual memory page
files and application swap files to be served from cache thus dramatically improving the
performance of IO intensive virtual workloads like virtual desktops.
Questions
1. Explain real time in-line de-duplication of storage objects.
2. Discuss the Atlantis approach to IO virtualization.

Self Assessment Questions


Multiple Choice Questions
6. The beginning .NET developer, one of the single most important underlying concepts is
called ..
(a) method

(b) streams

(c) function

(d) None of these

7. A stream can be ..

(a) written to and read from.

(b) written from and read to.

(c) Both (a) and (b) (d) None of these


8. System.IO namespace contains and defines the .

(a) property

(b) method

(c) function

(d) classes

9. You can simply use the static or shared classes, but there will be many reasons to work
with file and .
(a) programs

(b) classes

(c) folder objects

(d) None of these

LOVELY PROFESSIONAL UNIVERSITY

297

Modern Programming Tools & Techniques-III

Notes

10. File class provides the .NET Frameworks support for all manner of ..
(a) file handling

(b) exception handling

(c) class handling

(d) error handling

11. File is a static or .operations class and not a class for objects.
(a) shared

(b) open

(c) close

(d) altered

12. Other stickler in file and directory operations has to deal with the differences between the
various file systems on the ..
(a) dictionary

(b) data base

(c) program

(d) Windows

13. .. is a static or shared operations class and not a class for objects.
(a) File

(b) Class

(c) Object

(d) All of these

True or False
14. The constants exposed in the FileShare enumeration map to constants that let you specify
to the file system exactly how a file should be opened when it opens it.
(a) True

(b) False

15. All systems maintain a threecharacter extension.


(a) True

(b) False

12.4 Summary

298

The System.IO namespace contains and defines the classes used to navigate and manipulate
files, directories, and drives.

The file system classes are separated into two types of classes: information and utility.

An application devoid of support for files and directories is like a vehicle without wheels
or a boat without a propeller.

The File class provides the .NET Frameworks support for all manner of file handling.

Programming against the file and directory classes is not rocket science, but the potential
for problems in your code is increased because you need to pass complex arguments.

There are two approaches to coding against the file and directory libraries that ship with
the .NET Framework.

The classes that encapsulate the functionality of all known file and directory processing
operations.

The preamble of the encoding is added to a stream when you are not appending to an
existing stream

LOVELY PROFESSIONAL UNIVERSITY

Unit 12: File Input Output

12.5 Keywords

Notes

.NET Framework: It provides an impressive range of IO namespaces that contain dozens of


classes used for writing, reading, and streaming all manner of text, characters, and binary data,
as well as file, folder, and path support.
ASCIIEncoding Class: It encodes Unicode characters as single 7bit ASCII characters. It only
supports character values between U+0000 and U+007F.
Core GetBytes and GetChars: These are the methods require you to provide the destination
buffer and ensure that the buffer is large enough to hold the entire result of the conversion.
Despite Being the StringBuilders Apprentices: These classes are located in the System.IO
namespace
File Class: It provides the .NET Frameworks support for all manner of file handling.
Read and Write: These methods read and write the number of characters specified by their
Count parameter.
Streaming Data: It moves across processes and workspaces on your workstation, and between
computers on the vast networks of the world.
Streams: It is typically originate from files on devices like hard disks, CDs, and DVDs, and other
devices for persistent storage such as tape drives and optical disks.
WriteLine: This is a method works exactly like Write, but adds a line terminator to the end of
the String, which forces a new line.
1. W
 rite a path to calls the Combine method to make a full path name out of
the directory and file names.
2. Create a program to Constants for the FileAttributes Parameter.

12.6 Review Questions


1. Explain the file and directory.

2. What is outer stickler?


3. Define the Stream.

4. Explain the IO namespace working with file.

5. Describe the working with directories in IO namespace.


6. Define the BinaryReader/BinaryWriter

7. Describe the system.IO operations.


8. What is flush?

9. Define the text encoding.

10. Explain in brief The file stream.

LOVELY PROFESSIONAL UNIVERSITY

299

Modern Programming Tools & Techniques-III

Notes

Answers for Self Assessment Questions


1. (b)

2. (c)

3. (b)

4. (a)

6. (b)

7. (a)

8. (d)

9. (c)

11. (a)

12. (d)

13. (a)

14. (a)

5. (a)
10.

(a)

15. (b)

12.7 Further Readings


Programming in Visual Basic by E. Balagurusamy.
VB.Net Black Book by Wiley.

http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/src/
GHC-IO-Handle-Types.html#Handle

300

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

Unit 13: ADO.NET

Notes

CONTENTS
Objectives
Introduction
13.1 Accessing Database with ADO.NET

13.1.1 Display the Database Records

13.1.2 To Configure the Database

13.1.3 To Create the DataGrid Edit Column

13.1.4 To Edit the DataGrid

13.1.5 To update the DataGrid

13.1.6 To Add a Record to the DataGrid

13.1.7 To Delete a Row from the DataGrid

13.2 Executing Insertion


13.2.1 Inserting Data Using ADO.NET

13.3 Executing Deletion


13.3.1 Deleting Data Using ADO.NET

13.3.3 Records Affected by DELETE

13.4 Executing Updation


13.4.1 Updating Data Using ADO.NET

13.5 Select Command with Databases


13.6 Summary
13.7 Keywords
13.8 Review Questions
13.9 Further Reading

Objectives
After studying this unit, you will be able to:

Define the accessing database with ADO.NET

Describe in detail the executing insertion

Define the executing deletion, and updation

Discuss the select command with databases

Introduction
The ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.
Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet,
or an XML file. For the purposes of this chapter, we will look at ADO.NET as a way to interact
with a data base.

LOVELY PROFESSIONAL UNIVERSITY

301

Modern Programming Tools & Techniques-III

Notes

As we are probably aware, there are many different types of databases available.
For example, there is Microsoft SQL Server, Microsoft Access, Oracle, Borland Inter base, and
IBM DB2, just to name a few.
Though ADO was at its very infancy then, and was something of an offshoot of DAO and RDO,
nevertheless it represented a new bold direction. Each subsequent version of the technology leads
us one step closer to ADO 2.6, when development came to an end. At this point, emerging from
the shadows came the most revolutionary framework to date .NET, with it the very powerful
and mature ADO.NET.
This new data component, introduced with .NET, presented an exciting new approach to data
access. Though the techniques, and logic used to connect to databases with ADO.NET were not
startlingly different from those used with its predecessor, ADO.NET had a lot to offer. What
was unique about this technology was the architecture beneath it all; its powerful approach to
data management, and the flexibility in the next level of data-presenting devices.
ADO, for its time, was certainly successful. Although the re-releases of the technology had
not heralded dramatic change for ADO, it achieved what it had to within its own architecture.
However, it was continually plagued by problems that surrounded its handling of disconnected
data stores and functioning properly and concisely with XML. This is where ADO.NET stepped
in these are the two things the new technology easily manages, as XML is the core component
of the entire .NET Framework! ADO.NET was simply created to remedy all the deficiencies
found in ADO, and provides developers with the power to achieve more with less.
ADO.NET (ActiveX Data Objects .NET) is the primary data access API for the .NET Framework.
It provides the classes that you use as you develop database applications with Visual Basic .NET
as well as other .NET languages. In the two topics that follow, you will learn about how ADO.
NET uses these classes to provide access to the data in a database and the two ways you can
create ADO.NET objects in your Visual Basic programs. (See Figure 13.1)
Figure 13.1: How ADO.NET Works

13.1 Accessing Database with ADO.NET


The Jet database engine is provided by Microsoft Internet Information Services (IIS) for Microsoft
Access databases. This database engine is a popular alternative to Microsoft SQL Server and is
useful for low-volume Web applications. The Jet database engine is OLEDB-compliant and is
supported by classes in the Microsoft .NET Framework System Data OLEDB namespace.

302

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

The main objects you will use in this walkthrough are the OLEDB Connection, OLEDB Command,
and OLEDB Data Reader objects, and the Data Grid server control. (See Figure 13.2)

Notes

Figure 13.2: The ADO.NET Data Access Pipeline

The OLEDB Connection object handles the connection to the Jet database engine. The OLEDB
Command contains the Microsoft SQL statement that tells the database engine what to do.
The OLEDB Data Reader is a fast read-only forward-only database cursor that reads records
selected by the SQL statement. The Data Grid displays the records and fires events when you
add, delete, or edit a record. These events create new SQL statements that alter the database
and display the resulting records.
To Create the Database

Open Microsoft Access and create a blank database named Pets.mdb in the new folder
C:\Pets.

Create a new table in Designer view.

Add an AutoNumber field named ID and two Text fields named Pet Name and Pet Type.
Make ID the primary key and accept all defaults.
Figure 13.3: Designing the Data Table in Access

Switch to datasheet view and save the table as Pet Table.

Add a few entries to the table.


Figure 13.4: Adding Test Data

Save the table and close Access

13.1.1 Display the Database Records


The OLEDB Connection object holds the connection string that connects the Jet database engine
to the Pets.mdb database. When constructing the connection string, the location of the Pets.mdb

LOVELY PROFESSIONAL UNIVERSITY

303

Modern Programming Tools & Techniques-III

Notes

file is given relative to the root of the application. The relative path is changed to a physical
path by the Server .Map Path method. This lets you publish the Web application to a remote
server while still making it available to the Jet database engine.
The OLEDB Command object holds the SQL statement SELECT * FROM Pet Table, which selects
all the records in Pet Table. The OLEDB Command .Execute Reader method creates an OLEDB
Data Reader object to read these records. The Data Grid is connected to the data reader through
its Data Grid Data Source property.
When the Data Grid Data Bind method executes, database records are moved from the database
to the Data Grid, which displays them one record per row.
1. Open Visual Studio .NET.
2. Create a new Visual C# ASP.NET Web application at http://localhost/Pets.
3. Rename the file WebForm1.aspx to PetForm.aspx.
4. From the Solution Explorer, right-click the Pets project roots and select Add/New Folder.
Name the folder Pets. Leave the folder selected.
5. Right-click the Pets project and add the existing item C:\Pets\Pets.mdb to the Pets folder.
You will have to select All Files in the Files of Type dropdown list to see the Pets.mdb file
in the Existing Item browser window.
6. From the toolbox, drag a data grid to the Web form, renaming it to data grid.
7. Switch to code view by double-clicking the form.
8. Add this line to the using statements at the beginning of WebForm1.aspx.cs
9. Using System Data OLEDB;
10. Insert this code into the Page Load method:
Private void Page Load (object sender, System EventArgs e)
{
If (! IsPostBack) Read Records ();
}
11. Add the Read Records method to the Perform class just after the Page Load method:
Private void ReadRecords ()
{
OLEDBConnection conn = null;
OLEDBDataReader reader = null;
try
{
conn = new OLEDBConnection (
Provider=Microsoft.Jet.OLEDB.4.0; +
Data Source= + Server MapPath (Pets/Pets.mdb));
Conn.Open ();
OLEDBCommand cmd =
new OLEDBCommand (Select * FROM PetTable, conn);
reader = cmd.ExecuteReader ();
datagrid.DataSource = reader;

304

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

datagrid.DataBind ();

Notes

}
//catch (Exception e)
//{
//Response. Write (e.Message);
//Response. End ();
//}
finally
{
if (reader!=null) reader. Close ();
if (conn! = null) conn.Close ();
}
}
12. Press F5 to launch the Web application under the debugger. The contents of the database
should appear in the browser.
Figure 13.5: The Database as Seen in the Browser

12. Close the application, and then close Visual Studio.


The catch statement is commented out in the code above. By default, Visual Studio
creates a C# Web application project with the Generate Debugging Information
property set to true. This creates a Pets.pdb file in the bin directory. The default
ASP.NET error handler uses this information to create a detailed error page, which
shows the source line where the error occurred, as well as a stack trace and other error
information.
Once your project is debugged, you can set Generate Debugging Information to false, and
Pets.pdb will no longer be built. At this point, you can uncomment the catch statement and
substitute your own error handler.

The latest version ADO.NET Entity Framework is 4.3.1, which was released
on February 29, 2012.

13.1.2 To Configure the Database


The ASP.NET user, by default, does not have permission to write a record to a database or
create a locking file (.ldb) in the folder containing the database. You must give the ASP.NET
user these permissions. Normally, this is done in one of three ways:

You can add the ASP.NET user to the Administrators group.

You can enable impersonation for the application in the web.config file.

You can add ASP.NET write permission to both the database file and the folder that
contains it.

LOVELY PROFESSIONAL UNIVERSITY

305

Modern Programming Tools & Techniques-III

Notes

In this walkthrough you will use the third (and safest) method to grant write permission.

From the File Explorer, find the new Pets folder, normally located at C:\Inetpub\wwwroot\
Pets\Pets.

Right-click the Pets folder and select Properties.

Select the Security tab, and click the Add button.

Add the object name <YOURMACHINE>\ASPNET where <YOURMACHINE> is the


name of your machine. Click OK to return to the Security tab.

Select the ASP.NET account, and add Write permission. This account is named asp.net
wp account, ASP.NET MACHINE Account, or something similar.

From the File Explorer, right-click the file Pets.mdb, and select Properties.

Select the Security tab, and click the advanced button.

Check Inherit from parent the permissions entries that apply to child objects. Click OK
to accept the change.

For more information on ASP.NET security issues, see Authentication in ASP.NET: .NET Security
Guidance.

13.1.3 To Create the DataGrid Edit Column


You can use the Visual Studio Property Builder to add columns to a DataGrid. The Property
Builder has a choice of formats that can add colour and style to the DataGrid.

From Visual Studio Designer view, select the DataGrid. If you do not have the Property
window open, open it from the View menu.

At the very bottom of the Properties window you will see two links: Auto Format and
Property Builder. Select Property Builder.

Select Columns view.

Uncheck Create columns automatically at run time.

In the Available Columns list, expand the Button Column. Select the Edit, Update, Cancel
option. Click the > button to add it to the Selected Columns list.

In the Available Columns list, select Bound Column. Click the > button to add it to the
Selected Columns list. Give it the Header text Pet Name and the Data Field PetName.

Repeat the last step to add another Bound Column, giving it the Header text Pet Type
and the Data Field PetType.

Click OK to return to Designer view. The DataGrid will reflect the changes.

At the very bottom of the Properties window, select Auto Format.

Select a format, such as Colourful 1.

Click OK to return to Designer view. The DataGrid will reflect the changes. (See Figure
13.6)
Figure 13.6: The DataGrid with the Edit Links Added

306

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

Press F5 to launch the Web application under the debugger. The contents of the database should
appear in the browser. (See Figure 13.7)

Notes

Figure 13.7: Edit Links and Data in the Browser

13.1.4 To Edit the DataGrid


The DataGrid.EditItemIndex property selects a row for editing. When a row is selected for editing,
textboxes appear in each cell. The text in each textbox is set to the value of the corresponding
field in the data record.
You should also connect the Cancel link (not yet visible) to an event handler that restores the
DataGrid row without changing the corresponding record.

From Visual Studio Designer view, select the DataGrid, and click the Events tab in the
Properties window (the lightning bolt). Double-click Cancel Command to create the
datagrid_CancelCommand event handler. Return to the Events tab and double-click Edit
Command to create the datagrid_EditCommand event handler.

Insert the following code into the two event handlers:

Privatevoiddatagrid_CancelCommand
(objectsourceSystem.Web.UI.WebControls.
DataGridCommandEventArgs e)
{
datagrid.EditItemIndex = -1;
Read Records ();
}
Private void datagrid_EditCommand (object source, System.Web.UI.WebControls.
DataGridCommandEventArgs e)
{
datagrid.EditItemIndex = e.Item.ItemIndex;
Read Records ();
}

Press F5 to launch the Web application.

Click the Edit link to the left of the second row. The DataGrid displays the row with the
values for the fields PetName and PetType in textboxes. The Edit link changes to the
Update and Cancel links. (See Figure 13.8)
Figure 13.8: Editing Data in the Browser, Having Clicked the Edit Link

Edit

Pet Name Pet Type


Meow
cat

Update Cancel Barky

dog

You must connect the Edit link to an event handler that selects the row
containing the link for editing.

LOVELY PROFESSIONAL UNIVERSITY

307

Modern Programming Tools & Techniques-III

Notes

13.1.5 To update the DataGrid


When a row is selected for editing, the Update and Cancel links appear. Once you have used
the textboxes to enter new values for the fields in a database record, you must move these
changes back to the database.
You must connect the Update link to an event handler that reads each textbox and updates the
fields in the corresponding record. The DataGrid.DataKeyField uses the key field of the database
table to associate each row with its corresponding record. You build a SQL statement to update
the record with the new field values, and then call OLEDBCommand.ExecuteNonQuery to
perform the update.

From Visual Studio Designer view, select the DataGrid. In the Properties window, set the
DataKeyField property to ID.

Click the Events tab in the Properties view (the lightning bolt). Double-click Update
Command to create the datagrid_UpdateCommand event handler.

Insert the following code into the event handler:

Private void datagrid_UpdateCommand (object source,


System.Web.UI.WebControls.DataGridCommandEventArgs e)
{

int ID = (int)
ItemIndex];

datagrid.DataKeys

[(int)

e.Item.

String name = ((TextBox) e.Item.Cells [1].Controls[0]).


Text;

String type = ((TextBox) e.Item.Cells [2].Controls


[0]).Text;
String sql =

UPDATE PetTable SET PetName=\


PetType=\ + type +\ +

name

\,

WHERE ID= + ID; ExecuteNonQuery (sql);


datagrid.EditItemIndex = -1;
ReadRecords ();
}

Add the ExecuteNonQuery method to the PetForm class:


Private void ExecuteNonQuery (string sql)
{

OLEDBConnection conn = null;


try
{

Conn = new OLEDBConnection (Provider=Microsoft.Jet.


OLEDB.4.0; + Data Source= + Server.MapPath (Pets/
Pets.mdb));
conn. Open ();

OLEDBCommand cmd = new OLEDBCommand (sql, conn);


cmd.ExecuteNonQuery ();
}

//catch (Exception e)
308

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

//{

Notes

//Response. Write(e.Message);
//Response. End ();
//}

finally
{

if (conn!= null) conn.Close ();


}
}

13.1.6 To Add a Record to the DataGrid


The DataGrid does not support an Add column, but you can use a button click event
handler to add a record to the database. Create a SQL statement to add the record, then call
OLEDBCommand.ExecuteNonQuery to update the database.
From Visual Studio Designer view, drag a button from the toolbar to the form and name it
btnAddPet. Change its text to Add Pet. (See Figure 13.9)
Figure 13.9: Adding an Add Button to the DataGrid
Pet Name Pet Type
Edit Databound Databound
Edit Databound Databound
Add Pet

Double-click the button and insert this code in the btnAddPet_Click method:
Private void btnAddPet_Click (object sender, System.EventArgs e)
{
string sql = INSERT INTO PetTable (PetName, PetType)
+ VALUES (\ new\, \ new\);
ExecuteNonQuery (sql);
ReadRecords ();
}
Press F5 to launch the Web application.
Click the Add button. A new row is added to the database. (See Figure 13.10)
Figure 13.10: The New Row Added
Pet Type

Pet Name
Edit Meow
Edit Barky

cat
dawg

Edit new

new

13.1.7 To Delete a Row from the DataGrid


You can use the Property Builder to add a Delete column to the DataGrid. You must connect the
Delete link to an event handler that deletes the corresponding record in the database. You can
use the DataGrid.DataKeyField property to associate the row to be deleted with its corresponding

LOVELY PROFESSIONAL UNIVERSITY

309

Modern Programming Tools & Techniques-III

Notes

record. Create a SQL statement to delete the record, and then call OLEDBCommand.
ExecuteNonQuery to update the database.

From Visual Studio Designer view, select the DataGrid.

At the very bottom of the Properties window, select Property Builder.

Select Columns view.

In the Available Columns list, expand the Button column. Select the Delete option. Click
the > button to add it to the Selected Columns list. Click OK to return to Designer view.

Select the DataGrid, and click the Events tab in the Properties window (the lightning bolt).
Double-click the Delete Command to create the datagrid_DeleteCommand event handler.

Insert the following code into the event handler:


Private void datagrid_DeleteCommand (object source, System.Web.
UI.WebControls.DataGridCommandEventArgs e)
{
int ID = (int) datagrid.DataKeys [(int) e.Item.ItemIndex];
string sql = DELETE FROM PetTable WHERE ID= + ID;
ExecuteNonQuery (sql);
ReadRecords ();
}

Press F5 to launch the Web application.


Click the Delete button to the right of the last row. The row is deleted from the database.
The first version of Entity Framework (EFv1) was included with .NET
Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1, released
on 11 August 2008.

13.2 Executing Insertion


13.2.1 Inserting Data Using ADO.NET
Now that you know how to create and open a database connection, we can use this connection
to add new data to a database table. We will add the new data with the SQL INSERT command.
Here is the syntax for a basic INSERT command:
INSERT tablename (column1, column2.) VALUES (value1, value2)
You insert new records into a table by listing the table columns and listing the values that you
want to insert into the columns. For example, imagine that you have a table named Authors
that has both a First Name and a LastName column. The following statement inserts a new
author named Ralph Ellison:
INSERT Authors (First Name, LastName) VALUES (Ralph, Ellison)
Three steps are required for executing a SQL INSERT command in an ASP.NET

310

Create and open a database connection.

Create a database command that represents the SQL INSERT statement to execute.

Execute the command.

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

The ASP.NET page in example uses the classes from the System.Data.SqlClient namespace
to insert a new record into a SQL Server database table (this page is included on the CD
asSQLINSERTcommand.aspx).

Notes

Executing an INSERT Command


<%@ Import Namespace= System.Data


NameSpace= System.Data.SqlClient %>

%>

<%@

Import

<%

Dim myConnection As SqlConnection

Dim myCommand As SqlCommand

myConnection = New SqlConnection( server=localhost;uid=sa;


pwd=secret;database=myDataPubs )

myConnection.Open()

myCommand = New SqlCommand( Insert testTable ( col1 )

Values ( Hello ), myConnection )

myCommand.ExecuteNonQuery()
myConnection.Close()
%>

New Record Inserted!

An instance of the SqlConnection class is initialized with a connection string for the database
located on the local server. Next, the SqlConnection is opened with the Open () method.
In the statement that follows, an instance of the SqlCommand class is created. The SqlCommand
class is initialized with two parameters: the command to execute and the connection to use for
executing the command.In line a string containing an INSERT statement is passed to the instance
of the SqlCommand class. The INSERT statement inserts a new record into a table named testable
with a single column named col1.
Finally, the command is executed by calling the ExecuteNonQuery () method of the SqlCommand
class. The ExecuteNonQuery () method sends the SQL command to the database server. The
method is called theExecuteNonQuery () method because it is used to execute non-row-returning
SQL commands.
The code in example works only with Microsoft SQL Server (version 7.0 or greater). To work
with other databases, you would need to modify the code to use the classes from the System.
Data.OLEDB namespace rather than the System.Data.SqlClient namespace.
Adding a Record to Access

<%@ Import Namespace=System.Data %>


<%@ Import NameSpace= System.Data.OLEDB %>

<%

Dim myConnection As OLEDBConnection

Dim myCommand As OLEDBCommand

myConnection = New OLEDBConnection( PROVIDER=Microsoft.


Jet.OLEDB.4.0;DATA

Source=c:authors.mdb )

myConnection.Open()

LOVELY PROFESSIONAL UNIVERSITY

311

Modern Programming Tools & Techniques-III

Notes

myCommand = New OLEDBCommand( Insert INTO Authors (


Author ) Values

( Simpson ), myConnection )

myCommand.ExecuteNonQuery()
myConnection.Close()
%>

New Record Inserted!

The code in executes an INSERT statement that adds a new record to a Microsoft Access table
named authors.mdb. Notice that Microsoft Access requires you to use the keyword INTO with
the INSERT statement (you use INSERT INTO Authors rather than INSERT Authors).

Self Assessment Questions


True or False
1. The ADO.NET is an object-oriented set of libraries that allows you to interact with data
sources.
(a) True

(b) False

2. The Data Grid does not support an Add column.


(a) True

(b) False

Multiple Choice Questions


3. This database engine is a popular alternative to Microsoft SQL Server and is useful for
......................... web applications.
(a) low-volume

(b) high-volume

(c) medial -volume

(d) None of these

4. .................................... is the primary data access API for the .NET Framework.

(a) C#

(b) ASP.NET

(c) ADO.NET

(d) VB.NET

5. You can use the Visual Studio Property Builder to add columns to a ..........................
(a) SQL

(b) Data Grid

(c) Visual Basic

(d) ADO.NET

13.3 Executing Deletion


Deleting a data in database can be possible with using DELETE command.

13.3.1 Deleting Data Using ADO.NET


You can delete data from a database by using the SQL DELETE command.
The syntax for a basic DELETE command takes the following form:
DELETE tablename WHERE search condition
For example, if you want to delete all the rows from a table named Authors in which the
LastName column has the value Benet, use the following statement:
DELETE Authors WHERE LastName = Benet

312

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

To execute a DELETE command from within an ASP.NET page, you must complete the
following steps:

Notes

1. Create and open a database connection.


2. Create a database command that represents the SQL DELETE statement to execute.
3. Execute the command.
For example, the ASP.NET page in example demonstrates how you can delete a record from
a SQL Server database table (this page is included on the CD as SQLDELETEcommand.aspx).
Deleting a Record from SQL Server

<%@ Import Namespace= System. Data %>

<%@ Import Namespace= System.Data.SqlClient %>

<%

Dim my Connection As SqlConnection

my Connection
uid=sa;

Dim myCommand As SqlCommand


=

New

SqlConnection

(server=localhost;

pwd=secret; database=myDataPubs)
myConnection.Open ()

myCommand = New SqlCommand (DELETE testable WHERE col1=


fred, my Connection)
myCommand.ExecuteNonQuery ()
myConnection.Close ()

%>

Record Deleted!

The first two lines in example are used to import the necessary namespaces to work with
SQL Server. Next, a connection to the SQL Server running on the local machine is opened.
the SqlCommand class is initialized with two parameters: a SQL DELETE command and the
SqlConnection class. Next, the command is executed, and the connection is closed. If you need to
work with a database other than Microsoft SQL Server, you would use similar code. However,
you must use the classes from the System.Data.OLEDB namespace rather than the classes from
System.Data.SqlClient.
The example illustrates how you would delete a record from a Microsoft Access database table
named Authors
Deleting a Record from an Access Database

<%@ Import Namespace= System.Data %>

<%@ Import NameSpace= System.Data.OLEDB %>

<%

Dim myConnection As OLEDBConnection

Dim myCommand As OLEDBCommand

myConnection = New OLEDBConnection( PROVIDER=Microsoft.


Jet.OLEDB.4.0;DATA

Source=c:\authors.mdb )

myConnection.Open()

LOVELY PROFESSIONAL UNIVERSITY

313

Modern Programming Tools & Techniques-III

Notes

myCommand = New OLEDBCommand( DELETE FROM Authors

WHERE Author = Simpson, myConnection )

myCommand.ExecuteNonQuery()
myConnection.Close()
%>

Record Deleted!

Noticethat you must use DELETE FROM rather than just DELETE when working with

a Microsoft Access database.


A SQL DELETE command is similar to a SQL UPDATE command in that it might affect an
unknown number of records. A SQL DELETE command deletes all the records that match the
condition specified by the commands WHERE clause.
If you need to determine the number of records affected by a DELETE command, you can grab
the value returned by the ExecuteNonQuery () method. The page contained example illustrates
how you would do this (this page is included on the CD as SQLDELETERecordsAffected.aspx).

13.3.3 Records Affected by DELETE


<%@ Import Namespace= System. Data %>
<%@ Import Namespace= System.Data.SqlClient %>
<%
Dim my Connection as SQLConnection.
Dim my Command as SQLCommand.
Dim records Affected as Integer.
my Connection = New SqlConnection (server=localhost; uid=sa; pwd=secret;
database=myDataPubs)
myConnection.Open ()
myCommand = New SqlCommand (DELETE Authors2 WHERE LastName= Smith, my
Connection)
records Affected = myCommand.ExecuteNonQuery ()
Response.Write (The DELETE statement modified & recordsAffected.toString () & records!)
myConnection.Close
%>

13.4 Executing Updation


The updation of data is done by UPDATE command.

13.4.1 Updating Data Using ADO.NET


To update existing records in a database table, you use the SQL UPDATE command. Here is
the syntax for the basic UPDATE command:
UPDATE tablename SET column1 = value1, column2 = value2
WHERE search condition
You update a table by setting certain columns to certain values where a certain search condition
is true.

314

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

For example, imagine that you have a database table named Authors that has a column named
LastName. The following statement sets the value of the LastName column to Smith wherever
the column has a value of Benet;

Notes

UPDATE Authors SET LastName = Smith


WHERE LastName = Benet
You execute an UPDATE command within an ASP.NET page by completing the following steps:
1. Create and open a database connection.
2. Create a database command that represents the SQL UPDATE statement to execute.
3. Execute the command.
For example, the ASP.NET page contained in example updates a record in a SQL Server database
(this page is included on the CD as SQLUPDATEcommand.aspx).
Updating a SQL Database

<%@ Import Namespace= System.Data %>

<%@ Import NameSpace= System.Data.SqlClient %>

<%

Dim myConnection As SqlConnection

myConnection = New SqlConnection( server=localhost;


uid=sa;pwd=secret;database=myDataPubs )

Dim myCommand As SqlCommand

myConnection.Open()

myCommand = New SqlCommand( UPDATE Authors SET


LastName=Smith
WHERE LastName= Bennett, myConnection )

myCommand.ExecuteNonQuery()
myConnection.Close()
%>

Record Updated!

The first two statements in example import the necessary namespaces for working with the
SQL ADO.NET classes. a database connection is created and opened for the local server. In
the statement that follows, an instance of the SqlCommand class is created by passing a SQL
command and SqlConnection to the constructor for the class.
The SQL UPDATE command is executed when the ExecuteNonQuery () method of the
SqlCommand class is called. At this point, the UPDATE statement is transmitted to SQL Server
and executed.
The code in example will only works with Microsoft SQL Server (version 7.0 and greater). If you
want to update a record in another type of database, you will need to use the ADO.NET classes
from theSystem.Data.OLEDB namespace rather than the System.Data.SqlClient namespace.
The ASP.NET page contained in Listing 13.4.2 modifies a record in a Microsoft Access database
(the page is included on the CD as OLEDBUPDATEcommand.aspx)
Updating an Access Database

<%@ Import Namespace= System. Data %>

<%@ Import Namespace= System.Data.OLEDB %>

LOVELY PROFESSIONAL UNIVERSITY

315

Modern Programming Tools & Techniques-III

Notes

<%

Dim my Connection As OLEDBConnection

my Connection = New OLEDBConnection (PROVIDER=Microsoft.


Jet.OLEDB.4.0;DATA

Dim myCommand As OLEDBCommand

Source=c:\authors.mdb )
myConnection.Open ()

myCommand = New OLEDBCommand (UPDATE Authors SET Author=


Bennett
WHERE Author = Simpson, my Connection)
myCommand.ExecuteNonQuery ()

myConnection.Close
%>

Record Updated!

15:
One difference between the SQL UPDATE command and the SQL INSERT command is that
the SQL UPDATE command might affect more than one record at a time. When you execute
an UPDATE command, the command changes every record that satisfies the UPDATE
commands WHERE clause.
You can determine the number of records affected by an UPDATE command within an
ASP.NET page by grabbing the value returned by the ExecuteNonQuery () method. The
page contained in example illustrates this method (this page is included on the CD as
SQLUPDATERecordsAffected.aspx).
Records Affected by the UPDATE Command

<%@ Import Namespace= System. Data %>

<%@ Import Namespace= System.Data.SqlClient %>

<%

Dim my Connection As SqlConnection

Dim records Affected As Integer

Dim myCommand As SqlCommand


my Connection
uid=sa;

New

SqlConnection

(server=localhost;

pwd=secret; database=myDataPubs)
myConnection.Open ()

myCommand = New SqlCommand (UPDATE testable SET col1=


hello
WHERE col1= fred, my Connection)

records Affected = myCommand.ExecuteNonQuery ()

Response.Write (The UPDATE statement modified &


recordsAffected.toString () & records!)

myConnection.Close
%>

Write a program to connect and disconnect database from the SQL Server.
For (; ;);
Meke sure

316

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

13.5 Select Command with Databases

Notes

A database in the specified subdirectory. In a partitioned database environment, creates the


database on all database partitions listed in db2nodes.cfg, and creates a $DB2INSTANCE/
NODExxxx directory under the specified subdirectory at each database partition. In a single
partition database environment, creates a $DB2INSTANCE/NODE0000 directory under the
specified subdirectory.
Creates the system catalog tables and recovery log. Catalogs the database in the following
database directories:
Servers local database directory on the path indicated by path or, if the path is not specified,
the default database path defined in the database manager system configuration file by the
dftdbpath parameter. A local database directory resides on each file system that contains a
database. Servers system database directory for the attached instance. The resulting directory
entry will contain the database name and a database alias. If the command was issued from a
remote client, the clients system database directory is also updated with the database name
and an alias. Creates a system or a local database directory if neither exists. If specified, the
comment and code set values are placed in both directories.
Stores the specified code set, territory, and collating sequence. A flag is set in the database
configuration file if the collating sequence consists of unique weights, or if it is the identity
sequence. Creates the schemas called SYSCAT, SYSFUN, SYSIBM, and SYSSTAT with SYSIBM
as the owner. The database partition server on which this command is issued becomes the
catalog database partition for the new database. Two database partition groups are created
automatically: IBMDEFAULTGROUP and IBMCATGROUP.
Binds the previously defined database manager bind files to the database (these are listed in
the utilities bind file list, db2ubind.lst). If one or more of these files do not bind successfully,
CREATE DATABASE returns a warning in the SQLCA, and provides information about the
binds that failed. If a bind fails, the user can take corrective action and manually bind the failing
file. The database is created in any case. A schema called NULLID is implicitly created when
performing the binds with CREATEIN privilege granted to PUBLIC, if the RESTRICTIVE option
is not selected.
The utilities bind file list contains two bind files that cannot be bound against previous version
of the server:
db2ugtpi.bnd cannot be bound against DB2 Version 2 servers.
db2dropv.bnd cannot be bound against DB2 Parallel Edition Version 1 servers.
If db2ubind.lst is bound against a server which is not at the latest level, warnings pertaining to
these two files are returned, and can be disregarded.
Creates SYSCATSPACE, TEMPSPACE1, and USERSPACE1 table spaces. The SYSCATSPACE
table space is only created on the catalog database partition.
For information about privileges granted when creating a database, see: Default privileges
granted on creating a database.

If the RESTRICTIVE option is present it causes the restrict access database
configuration parameter to be set to YES and no privileges or authorities are
automatically granted to PUBLIC. For additional information, see the RESTRICTIVE
option of the CREATE DATABASE command.

Automatic storage is a collection of storage paths associated with a database on which table
spaces can be created without having to explicitly specify container definitions (see the CREATE

LOVELY PROFESSIONAL UNIVERSITY

317

Modern Programming Tools & Techniques-III

Notes

TABLESPACE statement for more information). Automatic storage is enabled by default, but
can be explicitly disabled for a database when it is created. Automatic storage can be disabled
at database creation time by specifying the AUTOMATIC STORAGE NO option.
It is important to note that automatic storage can only be enabled at database creation time; it
cannot be enabled after the database has been created. Also, automatic storage cannot be disabled
once a database has been defined to use it.
When free space is calculated for an automatic storage path for a given database partition, the
database manager will check for the existence of the following directories or mount points
within the storage path and will use the first one that is found. In doing this, file systems can
be mounted at a point beneath the storage path and the database manager will recognize that
the actual amount of free space available for table space containers may not be the same amount
that is associated with the storage path directory itself.
Storage_ path/instance name/NODE####/database name
Storage_ path/instance name/NODE####
Storage_ path/instance name
Storage_ path/
Where
storage path is a storage path associated with the database.
instance name is the instance under which the database resides.
NODE#### corresponds to the database partition number (for example NODE0000 or
NODE0001).
Database name is the name of the database.
Consider the example where two logical database partitions exist on one physical machine and
the database is being created with a single storage path: /db2data. Each database partition will
use this storage path but the user may want to isolate the data from each partition within its
own file system. In this case, a separate file system can be created for each partition and be
mounted at /db2data/instance/NODE####. When creating containers on the storage path and
determining free space, the database manager will know not to retrieve free space information for
/db2data, but instead retrieve it for the corresponding /db2data/instance/NODE#### directory.
In general, the same storage paths must be used for each partition in a multi-partition database
and they must all exist prior to executing the CREATE DATABASE command. One exception to
this is where database partition expressions are used within the storage path. Doing this allows
the database partition number to be reflected in the storage path such that the resulting path
name is different on each partition.
In an MPP environment, the database manager creates a subdirectory, $DB2INSTANCE/
NODExxxx, under the specified or default path on all database partitions. The xxxx is the
database partition number as defined in the db2nodes.cfg file (that is, database partition 0
becomes NODE0000). Subdirectories SQL00001 through SQLnnnnn will reside on this path.
This ensures that the database objects associated with different database partitions are stored
in different directories (even if the subdirectory $DB2INSTANCE under the specified or default
path is shared by all database partitions).
If LDAP (Lightweight Directory Access Protocol) support is enabled on the current machine,
the database will be automatically registered in the LDAP directory. If a database object of
the same name already exists in the LDAP directory, the database is still created on the local
machine, but a warning message is returned, indicating that there is a naming conflict. In this
case, the user can manually catalog an LDAP database entry by using the CATALOG LDAP
DATABASE command.

318

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

CREATE DATABASE will fail if the application is already connected to a database.

Notes

When a database is created, a detailed deadlocks event monitor is created. As with any monitor,
there is some overhead associated with this event monitor. You can drop the deadlocks event
monitor by issuing the DROP EVENT MONITOR command.
Use CATALOG DATABASE to define different alias names for the new database.
The combination of the code set and territory values must be valid. For a list of the supported
combinations, see Supported territory codes and code pages.
To specify a database path (instead of a drive) on a Windows operating system, you need to set
the DB2 registry variable: DB2_CREATE_DB_ON_PATH=YES.

Make an employee table for the organization.

Microsoft .NET Case Study

ataArt has developed an Open Investor Relationship Management System for a New
York-based asset management firm. The system provides classic CRM functions as
well as features specific to the operations of a financial services company.

The following functional areas are supported by the system:

Contact management

Investment tracking

Fund performance management

Front-office research support

Investor reporting
The system is entirely web-based, built on Microsofts .NET technology platform. It is
implemented in classic 3-tier architecture, providing good support for scalability and
maintainability. SQL Server 2000 is used as the data storage layer, which communicates with
the Data Management and Business Logic layers through ADO.NET.
Questions The data Management and Business Logic layers are organized as a set of
Class Libraries written in C#, operating under the control of Application Server (IIS+.NET
Framework). The top level, the User Interface, is based on the Microsoft IE 6.0/HTML/
JavaScript platform to combine mobility gained through fully web-based interface with
the advanced controls and user interaction methods provided by the IE 6.0 environment.
Communication between the User Interface and Application Server is organized in two ways:

Standard HTTP form-based data exchange is based on request-response roundtrips

A Web Services-based protocol, utilizing IEs Web Services scenarios (.HTC behavior
script). This options eliminates extra roundtrips to the server and thus intensifies the
user experience The system maintains Web Services-based interfaces with a number of
external systems, including the corporate website and the Microsoft Exchange server.

The .NET framework has brought a number of important technological benefits to the
solution:
Contd...

LOVELY PROFESSIONAL UNIVERSITY

319

Modern Programming Tools & Techniques-III

Notes

Web Server Controls are used to increase reusability of the code

Built-in support for caching is utilized extensively to minimize system response times
and optimize load
The .NET-based system proves to be exceptionally reliable and robust. Throughout a series
of intensive tests, the number of system failures, memory leaks and the like appeared to be
drastically less than in systems built on older platforms. Within this system, only safe code
is used, which has become possible only in the .NET environment.
.NETs control over Impersonation allows the system to utilize different approaches for
secure access rights control.
For example, application-level access rights are used for normal user operations, while
object-based restrictions, previously only typical for thick client architectures, are used for
system administration tasks.

1. Explain the functional areas which Microsoft .NET supported by the system.

2. Discuss the communication between the user interface and application server.

Self Assessment Questions


6. You can delete data from a by using the SQL DELETE command.
(a) SQL

(b) database

(c) Visual Basic

(d) None of these

7. You can use the Property Builder to add a Delete column to the
(a) XML

(b) ADO.NET

(c) Data Grid

(d) None of these

8. We will look at ADO.NET as a way to interact with a

(a) Data base.

(b) OLEDB

(d) None of these

(c) Data Grid.

9. Visual Basic .NET as well as other languages.


(a) NET

(b) ADO.NET

(c) ASP.NET

(d) All of these

10. The OLEDB Connection object handles the connection to the engine
(a) BLOB

(b) Jet database

(c) ASP.NET

(d) All of these

11. You can add the ASP.NET user to the


(a) administrators group

(b) database

(c) Jet database

(d) None of these

12. In the Available Columns list, expand the

320

(a) None

(b) database

(c) DataGrid

(d) Button Column

LOVELY PROFESSIONAL UNIVERSITY

Unit 13: ADO.NET

13. . is an object-oriented set of libraries that allows you to interact with data
sources.
(a) ADO.NET

(b) SQL

(c) ASP.NET

(d) XML

Notes

14. That you must use rather than just DELETE when working with a Microsoft
Access database.
(a) INSERT FROM

(b) administrators group

(c) DELETE FROM

(d) None of these

15. At this point, the UPDATE statement is to SQL Server and executed.
(a) Transmitted

(b) ADO.NET

(c) DataGrid

(d) None of these

13.6 Summary

The ASP.NET user, by default, does not have permission to write a record to a database
or create a locking file (.ldb) in the folder containing the database.

ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.

The Jet database engine is provided by Microsoft Internet Information Services (IIS) for
Microsoft Access databases.

The OLEDB Connection object holds the connection string that connects the Jet database
engine to the Pets.mdb database. When constructing the connection string, the location
of the Pets.mdb file is given relative to the root of the application.

The Property Builder has a choice of formats that can add color and style to the DataGrid.

13.7 Keywords
ADO.NET: ADO.NET is the new database technology of the .NET (Dot Net) platform, and it
builds on Microsoft ActiveX Data Objects (ADO).
DataGrid: The DataGridView class allows us to customization of cells, rows, columns, and
borders through the use of its properties.
ASP.NET: A Microsoft server-side Web technology. ASP.NET takes an object-oriented
programming approach to Web page execution.
BLOB: BLOB is a generic term that refers to the text, next, and image data types, which typically
contain documents and pictures.
XML: XML is one of the most fundamental of the core technologies in the Microsoft .NET
architecture.
1. Write a program to implement paging feature in the customer table.
2. Write a program to display the records from the database.

LOVELY PROFESSIONAL UNIVERSITY

321

Modern Programming Tools & Techniques-III

Notes

13.8 Review Questions


1. Explain the ADO.NET.

2. Define the accessing database with ADO.NET.

3. What is the DataGrid?


4. Define the Records Affected by the UPDATE Command.

5. What is XML?
6. What is the full form of ADO?
7. What are the two fundamental objects in ADO.NET?

8. Define the records affected by the UPDATE Command.

9. Define the updation a SQL Database.

10. Define database commands.

Answers for Self Assessment Questions


1. (a)

2. (a)

3. (a)

4. (c)

5. (b)

6. (b)

7. (c)

8. (a)

9. (a)

10. (b)

13. (a)

14. (c)

15. (a)

11. (d)

12. (d)

13.9 Further Reading


Pragmatic Ado.Net: Data Access for the Internet World, by Shawn Wildermuth.

http://books.google.co.in/books?id=IykBBnWqyugC&printsec=frontcover&
dq=ado.net+books&hl=en&sa=X&ei=flUBUMbTCYeurAfO292XBg&ved=0CE
AQ6AEwAQ#v=onepage&q=ado.net%20books&f=false

322

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Unit 14: XML

Notes

CONTENTS
Objectives
Introduction
14.1 Representation of the XML

14.1.1 XML Schemas

14.1.2 The Document Type Definition (DTD)

14.1.3 Characteristics of XML

14.2 Data Representation through XML


14.3 XML Reader and XML Writer Classes

14.3.1 XML Reader Classes

14.3.2 XML Writer Classes

14.3.3 The XML Advantages and Disadvantages

14.4 Summary
14.5 Keywords
14.6 Review Questions
14.7 Further Reading

Objectives
After studying this unit, you will be able to:

Explain the representation of the XML

Discuss data representation through XML

Working with XML Reader and XML Writer Classes

Write the advantages and disadvantages XML

Introduction
The XML is a computer language but this hardly does justice to something that has been at the
root of the social and economic revolution brought about by the World Wide Web. The Web
might still be just a collection of pages if it were not for XML. XML is the Esperanto of digital
communications, enabling disparate systems to talk a common language to one another. XML
is a key technology in the e-revolution in our schools and hospitals, in government, as well as
in many business sectors. XML is a key technology in a growing range of computer software
applications, including market leaders among office applications and accounting systems. Its
flexibility drives innovation. Its robust design drives consistency and reliability of implementation.
It is here to stay but normally. XML, the Extensible Mark-up Language has gone from the latest
buzzword to an entrenched e-business technology in record time.
The XML provides a basic syntax that can be used to share information between different kinds
of computers, different applications, and different organizations. XML data is stored in plain
text format. This software and hardware-independent way of storing data allows different

LOVELY PROFESSIONAL UNIVERSITY

323

Modern Programming Tools & Techniques-III

Notes

incompatible systems to share data without needing to pass them through many layers of
conversion. This also makes it easier to expand or upgrade to new operating systems, new
applications or new browsers without losing any data. With XML our data can be available to
all kinds of reading machines (Handheld computers, voice machines, news feeds, etc.) and
make it more available for blind people or people with other disabilities.
Three characteristics of XML seem to us to make it unlike other mark-up languages:

Its emphasis on descriptive rather than procedural mark-up.

Its document type concept.

Its independence of any one hardware or software system.

The mark-up language with which XML is most frequently compared. HTML the language
in which web pages had always been written until XML began to replace it. Compared with
HTML, XML has some other important characteristics:

XML is extensible: it does not contain a fixed set of tags

XML documents must be well-formed according to a defined syntax, and may be formally
validated

XML focuses on the meaning of data, not its presentation

The material in this section is based on the XML Specification. This is not an exhaustive list of
all the constructs which appear in XML it provides an introduction to the key constructs most
often encountered in day-to-day use.

14.1 Representation of the XML


There are the following ways to represent the XML:
Processor and Application
The specification places requirements on what an XML processor must do and not do but the
application is outside its scope. The processor (as the specification calls it) is often referred to
colloquially as an XML parser.
Mark-up and Content
Mark-up and content may be distinguished by the application of simple syntactic rules. All
strings which constitute mark-up either begin with the character < and end with a >, or begin
with the character and end with a Strings of characters which are not mark-up are content
Tag.
A mark-up construct that begins with < and ends with >. Tags come in three flavours:

start-tags; for example: <section>

end-tags; for example: </section>

empty-element tags; for example: <line-break/>

Comments
Comments may appear anywhere in a document outside other mark-up. Comments cannot appear
before the XML declaration. The string (double-hyphen) is not allowed inside comments.
Comments start with <! and end with -->. The ampersand has no special significance
within comments, so entity and character references are not recognized as such, and there is no
way to represent characters outside the character set of the document encoding.

324

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

<Note>
<to>satya</to>
<from>prakash</from>
<heading>Fine</heading>

<body>Do not forget me this weekend!</body>

</note>

14.1.1 XML Schemas


The XML schemas provide a much more powerful means by which to define our XML document
structure and limitations. XML schemas are themselves XML documents. They reference the XML
schema namespace and even have their own dtd.xml schemas do is provide an object oriented
approach to defining the format of an XML document. Xml schemas provide a set of basic
types. These types are much wider ranging than the basic PCDATA and CDATA of DTDs. they
include most basic programming types such as integer, byte, string and floating point numbers,
but they also expand into internet data types such as ISO country and language codes. Schemas
remained the province of philosophers for the next 200 years until, the word schema entered
computer science, probably through database theory schema originally meant any document that
described the permissible content of a database. More specifically, a schema was a description
of all the tables in a database and the fields in the table. A schema also described what type of
data each field could contain: char, int, char [32], blob, date, and so on. The word schema has
grown from that source definition to a more generic meaning of any document that describes
the permissible contents of other documents, especially if data typing is involved. Thus, we will
hear about different kinds of schemas from different technologies, including vocabulary schemas,
rdf schemas, organizational schemas, x.500 schemas and, of course, XML schemas. XML schema
then uses these core types, along with various operators and modifiers, to create complex types
of their own. These complex types are then used to define an element in the XML document.
Example:
Let us try to create a basic XML Schema for defining the bookstore that we used as an example
for DTDs. Firstly, we must declare this as an XSD Document and as we want this to be very
user friendly. We are going to add some basic documentation to it:
<xsd:schema xmlns:xsd= http://www.w3.org/2001/XMLSchema> <BR>
<xsd:annotation> <BR>
<xsd:documentation xlm:lang= en> <BR>
XML Schema for a Bookstore as an example. <BR>
</xsd:documentation> <BR>
</xsd:annotation>
Now, in the previous example, the bookstore consisted of the sequence
of a name and at least one topic. We can easily do that in an XML
Schema:
<xsd:element name= bookstore type= bookstoreType/> <BR>
<xsd:complexType name= bookstoreType> <BR>
<xsd:sequence> <BR>
<xsd:element name= name type= xsd:string/> <BR>

LOVELY PROFESSIONAL UNIVERSITY

325

Modern Programming Tools & Techniques-III

Notes

<xsd:element name= topic type= topicType minOccurs= 1/> <BR>


</xsd:sequence> <BR>
</xsd:complexType>
In this example, we have defined an element, bookstore that will equate to an XML element in
our document. We have defined it of type bookstore Type, which is not a standard type, and
so we provide a definition of that type next.
There is no undo command when working in schema view. Plan your work
carefully and save your files often.

14.1.2 The Document Type Definition (DTD)


The first method used to provide this definition was the DTD or Document Type Definition.
This defines the elements that may be included in our document what attributes these elements,
ordering and nesting of the elements. Traditionally, DTD has been the standard for XML schema
definition however XML usage has expanded dramatically in core application systems, being
tailored for a wide range of purposes for which DTD is not fully capable of supporting.XML
Schema as a schema definition language to replace DTD. The recommendation of XML Schema
has spurred its adoption as a standard schema definition language that DTD functions and
definitions have limitations when it comes to using XML for a variety of complex purposes.
Schema Data Type
There are 44 built-in simple types in the Schema language. These can be unofficially divided
into seven groups:

Numeric types

Time types

XML types

String types

The Boolean type

The binary types

Numeric Data Types


The most obvious data types, and the ones most familiar to programmers, are the numeric data
types. Among computer scientists, there is quite a bit of disagreement about how numbers should
be represented in computer systems. The W3C XML Schema language tries to make everyone
happy by providing almost every numeric type imaginable including:
Integer and floating point numbers
Finite size numbers similar to those in Java and C and infinitely precise, unlimited-size numbers
similar to those in Eiffel and Javas java.
Signed and unsigned numbers
We will probably only use a subset of these. For instance, we would not use both the arbitrarily
large xsd:integer type and the four-byte limited xsd:int type. Table1 summarizes the different
numeric types. (See Table 14.1)

326

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

Table 14.1 Schema Numeric Types


Name

Type

Examples

xsd:float

IEEE 754 32-bit floating -INF, -1E4, -0, 0, 12.78E-2, 12,


point number, or as close INF, NaN
as we can get using a base
10 representation; same
as Javas float type

xsd:double

IEEE 754 64-bit floating -INF, 1.401E-90, -1E4, -0,


point number, or as close 0, 12.78E-2, 12, INF, NaN,
as we can get using a base 3.4E42
10 representation; same
as Javas double type

xsd:decimal

A r b i t r a r y p r e c i s i o n , -2.7E400, 5.7E-444, -3.1415292,


decimal numbers; same 0, 7.8, 90200.76, 3.4E1024
as java.math.BigDecimal

xsd:integer

An arbitrarily large or -500000000000000000000000,


small integer; same as - 9 2 2 3 3 7 2 0 3 6 8 5 4 7 7 5 8 0 9 ,
java.math.BigInteger
-126789, -1, 0, 1, 5, 23, 42,
126789, 9223372036854775808,
4567349873249832649873624958

xsd:nonPositive
Integer

An integer less than or 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, . . .
equal to zero

xsd:negative
Integer

An integer strictly less -1, -2, -3, -4, -5, -6, -7, -8, -9,
than zero
...

xsd:long

An eight-byte twos - 9 2 2 3 3 7 2 0 3 6 8 5 4 7 7 5 8 0 8 ,
complement integer such -9223372036854775807, . . .
as Javas long type
-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
. . ., 2147483645, 2147483646,
2147483647, 2147483648,
. . .9223372036854775806,
9223372036854775807

xsd:int

An integer that can be


represented as a fourbyte, twos complement
number such as Javas
int type

-2147483648, -2147483647,
-2147483646, 2147483645, . . .
-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
. . ., 2147483645, 2147483646,
2147483647

xsd:short

An integer that can be


represented as a twobyte, twos complement
number such as Javas
short type

-32768, -32767, -32766, . . ., -6,


-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
. . . 32765, 32766, 32767

xsd:byte

An integer that can be


represented as a onebyte, twos complement
number such as Javas
byte type

-128, -127, -126, -125, . . ., -3,


-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16,
. . .121, 122, 123, 124, 125,
126, 127
Contd...

LOVELY PROFESSIONAL UNIVERSITY

327

Modern Programming Tools & Techniques-III

Notes

xsd:nonNegative
Integer

An integer greater than or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,


equal to zero
12, 13, 14, 15,...........

xsd:unsignedLong

An eight-byte unsigned 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,


integer
12, . . .18446744073709551614,
18446744073709551615

xsd:unsignedInt

A four-byte unsigned 0, 1, 2, 3, 4, 5, . . .4294967294,


integer
4294967295

xsd:unsignedShort

A two-byte unsigned 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,


integer
11, 12, 13, 14, . . .65533, 65534,
65535

xsd:unsignedByte

A one-byte unsigned 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,


integer
11, 12, 13, 14, . . . 252, 253,
254, 255

xsd:positiveInteger

An integer strictly greater 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,


than zero
12, 13, 14, . . .

Time Data Types


The next set of simple types the W3C XML Schema language provides are more familiar to
database designers than to procedural programmers; these are the time types. These can represent
times of day, dates, or durations of time. The formats shown in Table 2 are all based on the
ISO standard 8601, Representations of dates and times (http://www.iso.ch/markete/8601.pdf).
Time zones are given as offsets from Coordinated Universal Time (Greenwich Mean Time to
laypeople) or as the letter Z to indicate Coordinated Universal Time. (See Table 14.2)
Table14.2: XML Schema Time Types
Name

328

Type

Examples

xsd:dateTime

A particular moment in
Coordinated Universal Time,
up to an arbitrarily small
fraction of a second

1999-05-31T13:20:00.000-05:00,
1999-05-31T18:20:00.000Z, 199905-31T13:20:00.000, 1999-0531T13:20:00.000-05:00.321

xsd:date

A specific day in history

-0044-03-15, 0001-01-01, 1969-0627, 2000-10-31, 2001-11-17

xsd:time

A specific time of day that 14:30:00.000, 09:30:00.000-05:00,


recurs every day
14:30:00.000Z

xsd:gDay

A day in no particular month, --01, --02, . . . 09, --10, --11, --12,


or rather in every month
. . ., --28, --29, --30, --31

xsd:gMonth

A month in no particular year --01--, --02--, --03--, ---04--, . . .


--09--, --10--, --11--, --12--

xsd:gYear

A given year

xsd:gYearMonth

A specific month in a specific 1999-12, 2001-04, 1968-07


year

xsd:gMonthDay

A date in no particular year, --10-31, --02-28, --02-29


or rather in every year

xsd:duration

A length of time, without P2000Y10M31DT09H32M7.4312S


fixed endpoints, to an
arbitrary fraction of a second

LOVELY PROFESSIONAL UNIVERSITY

. . . -0002, -0001, 0001, 0002, 0003,


. . .1998, 1999, 2000, 2001, 2002, .
. .9997, 9998, 9999

Unit 14: XML

Notice in particular that in all the date formats the year comes first, followed by the month,
then the day, then the hour and so on. The largest unit of time is on the left and the smallest
unit is on the right. This helps avoid questions such as whether 20010211 is February 11, 2000
or November 2, 2001.

Notes

XML Data Types


The next batch of schema data types should be quite familiar. These are the types related to XML
constructs themselves. Most of these types match attribute types in DTDs such as NMTOKENS
or IDREF. The difference is that with schemas these types can be applied to both elements and
attributes. These also include four new types related to other XML constructs: xsd: language,
xsd: Name, xsd: QName, and xsd: NCName (See Table 14.3)
Table 14.3: XML Schema XML Types
Name

Type

Examples

xsd:ID

XML 1.0 ID attribute type; any XML p1, p2, ss124-45-6789,


name that is unique among ID type _92, red, green, NTattributes and elements
Decl, seventeen

xsd:IDREF

XML 1.0 IDREF attribute type; any XML p1, p2, ss124-45-6789,
name that is used as the value of an ID _92, p1, p2, red, green,
type attribute or element elsewhere in NT-Decl, seventeen
the document

xsd:ENTITY

XML 1.0 ENTITY attribute type; any PIC1, PIC2, PIC3, cow_
XML name that is declared as an m o v i e , M o n a L i s a ,
unparsed entity in the DTD
Warhol

xsd:NOTATION

XML 1.0 NOTATION attribute type; GIF, jpeg, TIF, pdf,


any XML name that is declared as a TeX
notation name in the schema using
xsd:notation

xsd:IDREFS

XML 1.0 IDREFS attribute type; a white p1, p2, ss124-45-6789


space-separated list of XML names that _92, red green NTare used as values of ID type attributes Decl seventeen
or elements elsewhere in the document

xsd:ENTITIES

XML 1.0 ENTITIES attribute type; a PIC1 PIC2 PIC3


white space-separated list of ENTITY
names

xsd:NMTOKEN

XML 1.0 NMTOKEN attribute type

12 are we ready 199

xsd:NMTOKENS XML 1.0 NMTOKENS attribute type, MI NY LA CA


a white space-separated list of name
p1 p2 p3 p4 p5 p6
tokens
123456

xsd:language

Valid values for xml:lang as defined en, en-GB, en-US, fr,


in XML 1.0
i-lux, ama, ara, araEG, x-choctaw

xsd:Name

An XML 1.0 Name, with or without set, title, rdf, math,


colons
math123, xlink:href,
song:title

xsd:QName

a prefixed name

song:title, math:set,
xsd:element

xsd:NCName

a local name without any colons

set, title, rdf, math,


tei.2, href

LOVELY PROFESSIONAL UNIVERSITY

329

Modern Programming Tools & Techniques-III

Notes

String Data Types


It is the most generic simple type. It requires a sequence of Unicode characters of any length but
this is what all XML element content and attribute values are. There are also two very closely
related types: xsd:token and xsd:CDATA. These are the same as xsd:string except that they limit
the amount, location, and type of white space that can be used. Table4 summarizes the string
data types. (See Table 14.4)
Table 14.4: XML Schema String Types
Name:

Type:

Examples:

xsd:string

A sequence of zero or more


Unicode characters that are
allowed in an XML document;
essentially the only forbidden
characters are most of the C0
controls, surrogates, and the
byte-order mark

p1, p2, 123 45 6789,


^*&^*&_92, red green
blue, NT-Decl, seventeen;
Mary had a little lamb,
The love of money is the
root of all Evil., Would we
paint the lily?

xsd:normalized
String

A string that does not contain PIC1, PIC2, PIC3, cow_


any tabs, carriage returns, or movie, MonaLisa, Hello
linefeeds
World , Warhol, red green

xsd:token

A string with no leading or


trailing white space, no tabs,
no linefeeds, and not more than
one consecutive space

Would we gild gold?

p1, p2, ss123 45 6789,


_92, red, green, NT Decl,
seventeenp1, p2, 123 45
6789, ^*&^*&_92, red
green blue, NT-Decl,
seventeen; Mary had a
little lamb, The love of
money is the root of all
Evil.

Boolean Types
The data type xs:boolean supports the mathematical concept of binary-valued logic: true or false.
Lexical form
The lexical form of the data type xs:boolean can be one of the literal values true, false, 1, or 0.
Constructor
Use the following syntax to construct an instance of xs:boolean:
>>-xs:boolean(value)-------------------------------------------><
Value
The value that is to be constructed . If this value is an empty sequence, the empty sequence is
returned.
If value type is illegal for the target data type, the constructor function returns
an error.

330

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Binary Types

Notes

It is impossible to include arbitrary binary files in XML documents because they might contain
illegal characters such as a form feed or a null that would make the XML document malformed.
Therefore, any such data must first be encoded in legal characters. The W3C XML Schema
Language supports two such encodings, xsd: base64Binary and xsd:hexBinary.
Hexadecimal binary encodes each byte of the input as two hexadecimal digits 00, 01, 02, 03,
04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 10, 11, 12, and so on. Thus, an entire file can be
encoded using only the digits 0 through 9 and the letters A through F. (Lowercase letters are
also allowed, but uppercase letters are customary.) On the other hand, each byte is replaced
by two bytes so this encoding doubles the size of the data. It is not a very efficient encoding.
Hexadecimal binary encoded data tends to look like this:
A4E345EC54CC8D52198000FFEA6C807F41F332127323432147A89979EEF3
Base64 encoding uses a more complex algorithm and a larger character set, 65 ASCII characters
chosen for their ability to pass through almost all gateways, mail relays, and terminal servers
intact, as well as their existence with the same code points in ASCII, EBCDIC, and most other
common character sets. Base64 encodes every three bytes as four characters, typically only
increasing file size by a third, so it is somewhat more efficient than xsd:hexBinary. Base64
encoded data tends to look something like this:
6jkpnnmkkwearsn5oeeg2njcz+nxdk0f9kzi892ddlr8lg1amhpeftyuoq3i6n
bjwzuktnzkixybfksstb8u09dtijo2ir3hjuy7ew/p89oskmfixpqsp9vqmgzph6qa
ly7j4mb7y5rojystr1/ffwmj/yhkhwpbpzed1le=
XML digital signatures use base64 encoding to encode the binary signatures before wrapping
them in an XML element.
The XML Declaration
All XML documents can optionally begin with an XML declaration. The XML declaration provides
at a minimum the number of the version of XML in use:
<? XML version= 1.0?>
Currently, 1.0 is the only approved version of XML, but others may appear in the future. The
XML declaration can also specify the character encoding used in the document:
<? XML version= 1.0 encoding= UTF-8?>
All XML parsers are required to support the Unicode UTF-8 and UTF-16 encodings; many
XML parsers support other encodings, such as ISO-8859-1, as well. There a few other important
rules to keep in mind about the XML declaration:

The XML declaration is case sensitive: it may not begin with <?XML or any other variant;

If the XML declaration appears at all, it must be the very first thing in the XML document:
not even whitespace or comments may appear before it; and

It is legal for a transfer protocol like HTTP to override the encoding value that we put
in the XML declaration, so we cannot guarantee that the document will actually use the
encoding provided in the XML declaration.

14.1.3 Characteristics of XML


XML provides the following features:

Administration tools to help we manage the integration of XML data in relational tables.

Storage and access methods for XML data within the database .

Location paths to specify the location of an element or attribute within an XML document.

LOVELY PROFESSIONAL UNIVERSITY

331

Modern Programming Tools & Techniques-III

Notes

Administration Tools
The XML administration tools help we enable our database and table columns for XML and
map XML data to DB2 relational structures.
We can use the following tools to complete administration tasks for the XML Extender:

The dxxadm command provides a command-line option for administration tasks.

The XML Extender administration stored procedures allow we to invoke administration


commands from a program.

Storage and Access Methods


The XML Extender provides two storage and access methods for integrating XML documents
XML column and XML collection. These methods have very different uses but can be used in
the same application.
XML Column Method
The XML column method works well for archiving documents. The documents are inserted into
columns enabled for XML and can be updated, retrieved, and searched.
XML Collection Method
This method helps we map XML so that we can either compose XML documents from existing
DB2 or decompose XML documents, storing the untagged data in DB2 tables. This method is
good for data interchange applications, particularly when the contents of XML documents are
frequently updated.
Location Paths
A location path specifies the location of an element or attribute within an XML document. The
XML Extender uses the location path to navigate the structure of the XML document and locate
elements and attributes.
There are two current versions of XML. The first (XML 1.0) was initially
defined in 1998.

14.2 Data Representation through XML


The XML document has both a logical and a physical structure. Physically, the document is
composed of units called entities. An entity may refer to other entities to cause their inclusion
in the document. A document begins in a root or document entity. Logically, the document is
composed of declarations, elements, comments, character references, and processing instructions,
all of which are indicated in the document by explicit up. A software module called an XML
processor is used to read XML documents and provide access to their content and structure.
It is assumed that an XML processor is doing its work on behalf of another module, called the
application. This specification describes the required behaviour of an XML processor in terms
of how it must read XML data and the information it must provide to the application. XML has
become a popular data interchange and storage format which in recent times has precipitated
the rise of XML-enabled relational databases as well as native XML databases. The language
proposed also provides the ability to perform queries, transformations and updates on the
documents in the XML repository either singly or across an entire collection. Syntax for the
language is presented as extensions to the W3Cs XML Query language (X-Query) and also as
a new language with syntax borrowed heavily from SQL for the relational model and DL/1 of
IBMs IMS system for the hierarchical model. A prototype implementation of the language has
been partially completed.

332

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

Basic XML-Data Representation


User/Student [tentative name alternatives] - Description of individual students, their


knowledge, their memory, their preferences etc.

Element - Individual pieces of knowledge, their content, children and their global parameters
(e.g. source, user count, global difficulty, global popularity, global reliability etc.)

Collection - Set of elements and its attributes (e.g. author, source, description, element
count etc.)

Learning Data - Description of learning parameters specific for a given Element for a given
User/Student.

Student Knowledge - A super-collection mastered by a single User/Student, its elements


Learning data, and other parameters (e.g. learning statistics).

Global Knowledge - Description and parameters of the global system of knowledge; all
Collections and all knowledge sets (mutually intersecting).

Accessory Elements

Student Memory - An attribute of User/Student with all data that helps characterize
his memory.

Element/Content - Located anywhere in the world on any device, possibly duplicated on


different devices, or dual (local copy of a remote resource). May include attributes such
as format (Q&A, HTML, Excel), date (e.g. for content updates), source, etc.

Student ID - Unique identifier (e.g. birth date, platform ID, registration number for platform,
random no) (e.g. 62.03.06.03.134213.392832)

ID - Unique identifier (author ID, number of element) (short form: AID.2321).

Student List - List of students using a given element (e.g. in on-line applications).

Same Elements may be organized in a different way. For example export from Windows could
result in the nested tree structure of Elements, their content and learning data, list of elements,
list of content and list of learning data in separate files, elements and the knowledge tree, etc.
Learning Data may link to Element/Content while Element may link to Learning Data.
Elements can be located anywhere in the world; learning data can also be remote or local.
Wherever possible Elements on the web must be index able by search engines!
Components

Anywhere in the world (remote or local).

Index able by search engines .

Text (HTML, plain, RTF, and others supported by web browsers), images (supported by
web browsers), sound (supported by web browsers), video (supported by web browsers),
OLE, executable, and others.

XML-Data Structures
The XML is now a widespread way of representing complex data structures serialised into text
format. It is used to describe documents such as Doc Book and XHTML. It is used in specialised
mark-up languages such as Math ML and CML (Chemistry Mark-up Language). It is used to
encode data as SOAP messages for Web Services, and the Web Service can be specified using
WSDL (Web Services Description Language).

LOVELY PROFESSIONAL UNIVERSITY

333

Modern Programming Tools & Techniques-III

Notes

At the simplest level, XML allows we to define our own tags for use in text documents. Tags
can be nested and can be interspersed with text. Each tag can also contain attributes with values.
For example:
<Person>
<Name>
<Family> New march </family>
<Personal> Jan </personal>
</name>
<email type= personal>
[email protected]
</email>
<email type= work>
[email protected]
</email>
</person>
The structure of any XML document can be described in a number of ways:

A document type definition DTD is good for describing structure

XML schema are good for describing the data types used by an XML document

RELAX NG is proposed as an alternative to both

There is argument over the relative value of each way of defining the structure of an XML
document. We would not buy into that, as Go does not support any of them. Go cannot check
for validity of any document against a schema, but only for well-formedness.
Structure of the Basic Node
The structure of the basic node has been divided into three sections content, data and lists. This
section explains why. But first, a word about the basic node attributes. Now, at last, we get to
the discussion of the nodes structure. The need for the separation into content and structure
arises from a major deficiency in XML, for our purposes. While XML is wonderful in many
ways, it has no mechanism for distinguishing tags which convey style information from
tags which represent structure. For example, consider the following hypothetical segment of
document mark-up:
<h2>An <I>Important</I> Heading
<p>an introductory paragraph</p>
<h3>A Subheading
<p>a paragraph under the subheading</p>
</h3>
</h2>
This segment represents the kind of thing we would like to do with XML. However, XMLs
validation mechanisms do not allow us to restrict an XML document to a form like this.
The note about this format is:

334

The <h2> tag contains the text of the heading and the substructure (paragraph and
subheadings) below it.

The text of the heading contains an italics style tag (<I>).

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

All content (text and style tags) occurs before any substructure tags. Once a substructure
tag occurs, no more content text or style tags occur.

Notes

It is the last observation in that list which is impossible to describe in XML. There is no way to
say text and style tags are allowed up until the first structure tag is seen, and no thereafter.
There is not, in fact, any way to distinguish style tags from structure tags at all. The inability
to make such restrictions means that the mixed content model (text plus tags) which can
be defined in XML would allow text and style tags to occur between the paragraph element
(<p>...</p>) and the <h3> element, for example. Since that text would not be enclosed in any
structure, it would be completely ambiguous. There is no way for a program to know what to
do with it. Although programs could be required to detect such errors, that requirement defeats
the automatic verification that constitutes one of XMLs major advantages.
Attributes
At a bare minimum, needs an ID attribute so that other nodes can link to it unambiguously: <node
type id= identifying-value>. The ID value must be unique within the system. Note, however,
that it is not globally unique. Since we intend to implement a distributed document object model
(DDOM) that value will be shared across every system that has a copy of the node.
Content Element
An unstated assumption in the foregoing analysis is that the CONTENT section will be able to
contain various style elements like bold and italic (<b>, <i>). Such tags are important because
they impart information, as well as formatting that make the text more readable.
Data Element
The data element provides a location for storing the data associated with a node. For a rating
node, for example, data elements would include the <average> and <number> elements;
containing the average rating value and the number of ratings it was constructed from. (More
sophisticated systems might include ratings of individuals, which would then weight the results
of their evaluations when constructing the average Data for a virtual node could include links
to the previous and following versions of the document. That information needs to be stored
somewhere the virtual node seems to be the natural place to put it.
Lists Element
The lists element contains the entire sub lists associated with a node. Those lists include:

The substructure under the node (subheadings and paragraphs).

Ratings.

Categories the node belongs to.

Relations the node participates in.

Data Models
In 1975 the American National Standards Institute (ANSI) published its 3-schema approach to
viewing data as they the Institute saw it, there were at least three different perspectives on data.
(Actually, in various drafts, they saw many more perspectives than but these have survived.)
Three Ways to Look at Data:
External
Everyone in an organization looks at its data slightly differently. Each person holds in mind a
schema or structure that is the representation of his/her surroundings from a particular point
of view. Each of these schemas describing the world as one person sees it is called by ANSI an

LOVELY PROFESSIONAL UNIVERSITY

335

Modern Programming Tools & Techniques-III

Notes

external schema. While, ideally these are similar for the many people working in a company,
as often as not they are in fact very different. Misunderstandings about what something means
are at the heart of many systems (and management) problems in companies today. Because of
their diversity it is not practical to draw a picture of each persons view of their data, but it is
appropriate when surveying these points of view to assemble an ontology or glossary of the
language used throughout the organization. Where terms have different meanings or there are
different terms for the same thing, these differences should be made explicit.
Conceptual
All of these participants in an organization are, after all, fundamentally looking at the same
business, even if their perspectives are different. The objective of a good systems analyst is to
integrate the set of external schemas to produce a single conceptual schema which represents
the fundamental structure of the organizations data. The data model that portrays a conceptual
schema consists of boxes representing the things of significance to it, along with lines describing
how they are related to each other. (This is often referred to as an entity/relationship or E/R
model.) These conceptual schemas can be rendered at various levels of abstraction.

An enterprise abstract conceptual data model is in terms of things that apply to the
organization as a whole. This presents a general structure for addressing people and
organizations, geography, physical assets, activities, and corporate objectives.

A purpose-oriented concrete conceptual data model is in terms of a language that is


relatively close to a particular area or function of the organization, such as contracting,
human relations, or manufacturing. It represents assertions that are true for anyone working
in that area, given the policies and procedures of the overall organization, but these are
usually about things that are specific to that part of it. The project concrete model is then
made up of: 1) sub-types of the enterprise entity classes, 2) views (analogous to SQL
views) of sets of entity classes and relationships, and 3) new entity classes.

Internal
ANSI originally described the internal schema as the way data are represented in a physical
storage medium. This included the use of random-access storage, tracks and cylinders, and so
forth. With the advent of database management systems, however, this was broken into two
schemas:

A logical schema described data in terms of a particular data management technology. In


the early days, this might have been a hierarchical database management system (DBMS),
or a networked one. In more recent times, this describes the tables and columns of a
relational DBMS, the classes of an object-oriented program, or XML tags.

Database technology has advanced to the point that a true physical schema describing
the physical architecture of a database is more important than ever. A set of tables and
columns in a logical database may be implemented in many pieces scattered all over the
world.

Note that along with relational database design, XML is one of several options for implementing
a conceptual data structure. XML scripts are examples of logical schemas. As with relational
database designs and object-oriented UML diagrams, these should be derived from a conceptual
data model not a replacement for it. Note that in each of these technologies, trade-offs must be
made in translating from the conceptual model. Relational database design does not recognize
super-/sub-type structures, so adjustments must be made. XML is fundamentally hierarchical,
so the translation from a two-dimensional data model will involve de-normalization that will
sacrifice some flexibility.

336

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

Logical Models
Note that the conceptual model describes a real situation, completely independent of any
technology that might be used to implement a system. (This particular example is a special case
because the subject of the model is a technology, but the point still holds. This model describes
that subject, without concern for how this descriptive information might be manipulated by
technology.) Indeed, the same conceptual model may be used to implement a multitude of
completely different kinds of systems: the entity classes can be rendered as either relational
tables or object-oriented classes. The relationships in a relational world become foreign keys;
in an object-oriented world, they become behaviours by which each of the classes gains access
to other classes. And in XML, entity classes become tags, while relationships become implied
in hierarchical tag structures.
XML: The Tree Structure
The great benefit about XML is that the document itself describes the structure of data. If any
of we have researched our family history, we have probably come across a family tree. At the
top of the tree is some early ancestor and at the bottom of the tree are the latest children. With
a tree structure we can see which children belong to which parents, which grandchildren belong
to which grandparents and many other relationships. The neat thing about XML is that it also
fits nicely into this tree structure, often referred to as an XML Tree. Before we even think about
matching up these tree terms with their XML counterparts, it might be helpful to see a real XML
document converted into a tree structure. (See Figure 14.1)
Figure 14.1: Tree Structure

inventory
drink

lemonade

price

amount

snack

chips

pop

price

amount

price

amount

As we can see from the XML document, inventory is the root element. When we convert the
document over to a tree format, we can see that the inventory element is at the top of the tree.
In other words, all other elements are a descendent of the inventory element.
XML Tree Features

Easy and intuitive graphics user interface

Support Elements, Comments, CDATA and Processing Instructions

Printing support

XML Tree Rules


We have written up a set of rules to use in figuring out if an element is a child or parent of
another element. With these basic rules, we can figure out the relationship of just about any
two elements in an XML document.
Descendants: If element A is contained by element B, then A is a descendant of B. In the lemonade.
xml example, every element is a descendant of inventory because inventory is the root element.

LOVELY PROFESSIONAL UNIVERSITY

337

Modern Programming Tools & Techniques-III

Notes

Ancestors: If an element B contains element A, then B is an ancestor of A. In the lemonade.xml


example, drink is the ancestor of lemonade and pop.
According to the 1933 edition of the Oxford English Dictionary Kant used the
word schema to mean, Any one of certain forms or rules of the productive
imagination through which the understanding is able to apply its categories
to the manifold of sense-perception in the process of realizing knowledge or
experience.

Self Assessment Questions


Multiple Choice Questions

1. XML digital signatures use base ................. to encode the binary signatures before wrapping
them in an XML element.

(a) 60 encoding

(b) 64 encoding

(c) 68 encoding

(d) 70 encoding

2. Which statement is true?


(a) All XML elements must have a closing tag

(b) All XML elements must be lower case

(c) All XML documents must have a DTD

(d) All the statements are true

3. XML uses the features of .


(a) HTML

(b) XHTML

(c) VML

(d) SGML

4. A . called an XML processor is used to read XML documents and provide


access to their content and structure.

(a) application module

(b) software model

(c) hardware module

(d) None of these

True or False

5. The XML column method not works well for archiving documents.
(a) True

(b) False

14.3 XML Reader and XML Writer Classes


XML reader and XML writer are defining below:

14.3.1 XML Reader Classes


The XML Reader data type allows the reading of XML files. The document XML offers an
introduction to that language. A variable of a new data type called XML Reader must be defined in
order to read the content of a XML file from a Gene Xus object. Then, the methods and properties
needed to obtain the information about the nodes that make it up must be invoked. XML Reader
reads XML data in inefficient way. With this System, XML type, we read in each element of an
XML file sequentially. This reduces memory usage and improves performance. We provide an
example for XML Reader. The basic idea is this: There is a Read() method that behaves like a
cursor moving forward through the file one node at a time. Using some properties, such as Name
and Value, it is possible to obtain the nodes data -in this case, its name and value. Therefore,

338

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

the method Read() is used to navigate through the document in a sequential way obtaining
its different nodes. We also recommend reading the document XML Writer. The Microsoft .NET
Framework XML Reader class provides a very easy pull model for traversing XML data. From
a more general point of view, though, XML is just one possible representation for hierarchical
information. Thus, an XML Reader can be viewed as a class encapsulating just some arbitrary
data structure. It maps this data structure/data format to the XML world with its nodes,
elements and attributes. Now, if handling hierarchical information with an XML Reader is so
easy, why not use XML Reader classes to access non-XML data? Why not, for example, transform
portions of the file system to HTML using XSLT? Why not query a CSV file with X-Path? With
custom XML Reader classes this is easy to do. When we are using an XML Text Reader or an
XML Document, do we really care if the data behind it actually is XML? Do we care if a file
containing text complying with the XML well-forkedness rules gets loaded and parsed? We
care mainly about the object model we are using to traverse or manipulate the data. The textual
notation of XML only is relevant to us as a persistence format for storing or exchanging data.
So if we do not care much about the data format when working with, for example, an XML
Reader, what is so good about it? It is the way it lets we access hierarchical data. Data that is
conformant with the XML Info set. To put it simply, we have come to like thinking in terms of
nested elements (the text bracketed by starting/ending tags in XML) that can have attributes
(the name/value pairs in an XML start tag) when describing/accessing data. We can create a
notation for any data structure using only elements and attributes. That means we could access
any (!) data structure with an XML Reader or XML Documentas long we can translate it to
XML, so to speak. (See Figure 14.2)

Notes

Figure 14.2: XML Reader


My Application
<xsd:schema ...>
<xsd:element name=...>
</xsd:element>
...
</xsd:schema>
XmlXYZReader

data
source

XmlReader

Features
There is a core set of features in XML support:

XML declarations

Elements

Attributes

Namespaces

Element prefixes (both global and local)

Attribute prefixes

LOVELY PROFESSIONAL UNIVERSITY

339

Modern Programming Tools & Techniques-III

Notes

CDATA blocks

Inner text

Processing instructions

Node graphs (element children)

Use XmlTextReader if we need performance without schema validation or X-Path/XSLT


services.

Use XML Document if we need X-Path services or need to update the XML.

Naturally, XmlTextReader is closer to the XML. It is a forward only reader, meaning that we
cannot go backwards. Contrast this with the Xml-Document class, which pulls in the entire
document and allows us to random-access the XML tree. The XmlTextReader supports streams,
and therefore should reduce memory requirements for very large documents.Another advantage
of the XmlTextReader is that it provides line and character position information, which can be
very useful diagnostic information when there is a problem with the XML.
Node Type
It returns the current node type obtained through the method Read or Read-Type.
The possible values are:

Element

End Tag

Text

Comment

White Space

Processing Instruction

Document Type

Element Type

End Tag Type

Text Type

Comment Type

Whitespace Type

Processing Instruction Type

These properties contain constant values which can be used to compare the Node Type property
result with the Read Type method.
Name
It returns the name of the current node obtained through the method Read or Read Type. It is
valid only for nodes of Element and End Tag type.
Value
It returns the value of the current node obtained through the method Read or Read Type. It is
valid only for nodes of Text, Comment, Processing Instruction, Document Type and Element type.

340

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

Attribute Count
It returns the amount of attributes in the current node, obtained through the method Read or
Read Type. It is valid only for nodes of Element type.
EOF
It returns whether the end of the document was reached.
Err Code
It returns a value greater than zero if an error occurred during the processing of a XML document.
Err Line Number
In case Err Code is different than zero, these properties return the line number and position
within it respectively.
Err Description
It returns the error description in case Err Code is different than zero.
Read External Entities
This Boolean (1/0) property indicates if the parsed external entities that make-up the XML
document being processed must be read (it includes the DTD external sub-set). If the reading
is enabled, the XML Reader object will read and process in a transparent way for the user all
references to external files or URLs included in the document. Otherwise, the references to
external entities are ignored.
Remove White Spaces
This Boolean(1/0) property indicates if the blank spaces, tabulations and end of lines at the
beginning and end of the value of a node of TEXT or ELEMENT type must be eliminated. The
value by default is TRUE (1).
Remove White Nodes
This Boolean (1/0) property indicates if the nodes of White Space type must be ignored when
processing a document. The value by default is TRUE (1).
Simple Elements
This property determines if the elements with a simple structure such as
<Element>value</element>
Or
<element/>
Are processed as a unique node of Element type.
The value by default is TRUE (1).
Validation Type (Only C# and Java)
This property determines how the read XML will be validated. The possible values are the
following:

validation is not carried out

automatic validation

validation by means of dtd

validation by means of a schema

validation by means of xdr (only c#)

LOVELY PROFESSIONAL UNIVERSITY

341

Modern Programming Tools & Techniques-III

Notes

When the automatic validation is selected, the behavior is the following (extracted form the .NET
documentation):if there is no dtd or schema, it will parse the XML without validation. if there is
a dtd defined in a <! doctype ...> declaration, it will load the dtd and process the dtd declarations
such that default attributes and general entities will be made available. general entities are only
loaded and parsed if they are used (expanded).if there is no <!doctype ...> declaration but there
is an xsd schema location attribute, it will load and process those xsd schemas and it will
return any default attributes defined in those schemas. if there is no <! doctype ...> declaration
and no xsd or xdr schema information then the parser is a non-validating parser (i.e. validation
type=validation type. none) if there is no <! doctype ...> declaration and no xsd schema location
attribute but there are some namespaces using the msxml x-schema: urn prefix, it will load
and process those schemas and it will return any default attributes defined in those schemas.
if there is no <! doctype ...> declaration but there is a schema declaration (<schema>); it will
validate using the in-line schema.
Stop on Invalid (only c#)
This Boolean property (1/0) indicates if the parser must stop when it detects a validation error,
but the XML is well formed. if the value is 0, the read() method will return 1 even if a validation
error has occurred, and the way of detecting the error is by controlling the value of the err code
property. The default value is true (1)
Example:
Imports System.Xml
Module Module1

Sub Main()

Dim reader As XmlTextReader = New XmlTextReader(books.xml)

Do While (reader.Read())

Select Case reader.NodeType

Case XmlNodeType.Element Display beginning of element.

Console.Write(< + reader.Name)

If reader.HasAttributes Then If attributes exist

While reader.MoveToNextAttribute()
Display attribute name and value.
Console.Write( {0}={1}, reader.Name, reader.Value)
End While
End If
Console.WriteLine(>)

Case XmlNodeType.Text Display the text in each element.

Console.WriteLine(reader.Value)

Case XmlNodeType.EndElement Display end of element.

Console.Write(</ + reader.Name)
Console.WriteLine(>)
End Select
Loop
Console.ReadLine()

342

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

End Sub

Notes

End Module
Output:
<bookstore>
<book>
<title>
The Autobiography of Benjamin Franklin
</title>
<author>
<first-name>
Benjamin
</first-name>
<last-name>
Franklin
</last-name>
</author>
<price>
8.99
</price>
</book>
<book>
<title>
The Confidence Man
</title>
<author>
<first-name>
Herman
</first-name>
<last-name>
Melville
</last-name>
</author>
<price>
11.99
</price>
</book>
<book>
<title>
The Gorgias

LOVELY PROFESSIONAL UNIVERSITY

343

Modern Programming Tools & Techniques-III

Notes

</title>
<author>
<name>
Plato
</name>
</author>
<price>
9.99
</price>
</book>
</bookstore>

14.3.2 XML Writer Classes


The XML writer is a simple class that can be used in our application to create/generate XML
output. All we need to do is include the XML writers and XML writer.cpp into us project The
implementation uses only standard CPP libraries and STLs; this can be used for applications
in Windows as well as Linux. Windows environment, Cygwin (Linux emulator), and in Linux
systems works fine in all the three states. This XML Writer class does not support all the features
of XML but surely satisfies the basic needs we will have in most of our applications. We can use
this code free of cost, but at our own risk. (Please test the application.)XML Writer writes XML
data from objects in memory. XML files are excellent for interoperability with other systems
and Internet sites. We use XML Writer in a C# program. We review each step required. We note
possible problems with this type. XML Writer uses less memory than XML Document, which is
only an issue if we write very big files though. Another important difference is that when using
XML Document, we can read an existing file, manipulate it and then write back the changes.
With XML Writer, we will have to write the entire document from scratch each time. This is
not necessarily a problem though, so as always, it really comes down to our situation as well
as our personal preferences. The XML Writer class contains the functionality to write to XML
documents. XML Writer is an abstract base class and is a super class of XML Text Writer and
XML Node Writer classes which are used to write the XML documents. This class has many
Write XXX methods to write paired, unpaired and empty XML elements. Some of these methods
are used in a start and end pair. For example, to write an element, we need to call Write Start
Element then write a string followed by Write End Element. (See Figure 14.3)
Figure 14.3: XML Writer Classes

XmlWriter

XmlTextWriter

XmlNodeWriter

Features
The XML Writer class contains three properties: Writer State, XML Lang, and XML Space. The
Write State property gets the current state of the XML Writer class. The values could be Attributes,

344

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Start, Element, Content, closed, or Prolog. The return value Write State. Start means the Write
method is not yet called. In other cases, it represents what is being written. For example, the
return value Write State. Attribute means the Attribute value has written. Write State. Close
represents that the stream has closed by calling Close method.

Easily creates nodes.

Easily creates elements.

Easily adds attributes.

Closes all the open tags with one simple command. (Stack to keep track of all the open
tags.)

Notes

No need to worry about file operations. (All handled internally.)


Features Missing
No verification and validation is done on the file. (Users responsibility to ensure that file is well
formed and valid.) Right now, provision to add processing instructions and CDATA sections
are missing. This can be easily added to the XML class (if we need it).
Basics of the XML Text Writer Class
The XML Text Writer class contains a number of methods that are useful for starting and
completing an XML document and for adding elements and attributes to the XML document.
The most important methods are:

Write Start Document - We should call this method to start creating an XML document.
This will create the first line in the XML document, specifying that the file is an XML
document and it is encoding.

Write Start Element (string) - This method creates a new element in the XML document
with the name specified by the string input parameter. (We can also specify a namespace
as a second, optional string parameter.)

Write Element String (name, text value) - If we want to create an XML element with nothing
but text content (i.e., no nested elements), we can use this method.

Write Attribute String (name, value) - This method writes an attribute name and value to
the current element.

Write End Element () - This method closes off the element created in the Write Start Element
(string) method call.

Write End Document () - This method completes the writing of the XML document.

Close () - This method closes the underlying stream, writing the contents of the XML
document to the specified file location.

To get started using the XML Text Writer class we need to specify the file and encoding in the
classs constructor. The encoding needs to be of the type System. Text Encoding; some example
encoding values are: System. Text Encoding ASCII, System. Text Encoding. Unicode and System.
Alternatively, we can specify in the constructor that the output of the XML Text Writer class
should be squirted out to a specified Stream.
XML Text Writer
XML Text Writer maintains a namespace stack corresponding to all the namespaces defined
in the current element stack. Using XML Text Writer we can declare namespaces manually.
This class maintains a namespace stack corresponding to all the namespaces defined in the

LOVELY PROFESSIONAL UNIVERSITY

345

Modern Programming Tools & Techniques-III

Notes

current element stack. Namespaces can be declared manually to override the current namespace
declaration. Prefixes can be specified to associate with a namespace. If there are multiple
namespace declarations mapping different prefixes to the same namespace URI, this class walks
the stack of namespace declarations backwards and picks the closest one.
Example:
[Visual Basic]
Public Class XMLTextWriter
Inherits XMLWriter
[C#]
Public class XMLTextWriter : XMLWriter
[C++]
Public __gc class XMLTextWriter : public XMLWriter
[Script]
Public class XMLTextWriter extends XMLWriter
XML Text Writer does not check for the following:

Invalid characters in attribute and element names.

Unicode characters that do not fit the specified encoding. If the Unicode characters do not
fit the specified encoding, the XML Text Writer does not escape the Unicode characters
into character entities.

Duplicate attributes.

Characters in the DOCTYPE public identifier or system identifier.

14.3.3 The XML Advantages and Disadvantages


The XML (extensible mark-up language) is a general-purpose specification for creating custom
mark-up languages. The term extensible is used to indicate that a mark-up-language designer
has significant freedom in the choice of mark-up elements. There are many advantages to using
XML for information exchange, and they offer many benefits to the user. The extensive mark-up
language uses human language, which is conversable, and not the language used by computers
which is binary and ASCII coded. XML is readable by even people who have had no formal
introduction to XML or have been coached on it. The extensive mark-up language is the way to
go for developing future web applications and it almost defines the future of web development.
There are no doubts about its performance in this arena. However, XML also has some drawbacks which need to be looked at and improved upon the reason it faces some resistance from
users is a result of these drawbacks. One of the biggest drawbacks of XML is that it is lacking in
the area of adequate applications for processing. XMLs goals emphasize representing documents
with simplicity, generality, and usability over the internet. XML has been used as the basis for
a large number (at least hundreds) of custom-designed languages. Some of these, for example
rss, atom, and xhtml, have become widely used on the internet. XML dialects (often packaged
in archive files) are becoming the default file format for office-productivity software packages,
including Microsoft office, openoffice.org, abi word, and apples iwork. Let us discuss advantages
and disadvantages of XML.

346

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

Advantages of XML
It is text-based. It supports Unicode, allowing almost any information in any written human
language to be communicated. The most important advantage of XML is that it is the most easily
readable format for other humans. A secondary advantage is that XML has been around for
quite a while and that many developers are already accustomed to it. It can represent the most
general computer science data structures: records, lists and trees. Its self-documenting format
describes structure and field names as well as specific values. the strict syntax and parsing
requirements make the necessary parsing algorithms extremely simple, efficient, and consistent
.XML is heavily used as format for document storage and processing, both online and offline. It
is based on international standards. It can be updated incrementally. It allows validation using
schema languages such as xsd and schematron, which makes effective unit-testing, firewalls,
acceptance testing, contractual specification and software construction easier. The hierarchical
structure is suitable for most (but not all) types of documents. it manifests as plain text files,
which are less restrictive than other proprietary document formats. It is platform-independent,
thus relatively immune to changes in technology. Forward and backward compatibility are
relatively easy to maintain despite changes in DTD or schema.

It is a simultaneously human- and machine-readable format.

It supports Unicode, allowing almost any information in any written human language to
be communicated.

It can represent the most general computer science data structures: records, lists and trees.

Its self-documenting format describes structure and field names as well as specific values.

The strict syntax and parsing requirements make the necessary parsing algorithms
extremely simple, efficient, and consistent.

XML is heavily used as a format for document storage and processing, both online and
offline.

It is based on international standards.

It allows validation using schema languages such as XSD and Schematron, which makes
effective unit-testing, firewalls, acceptance testing, contractual specification and software
construction easier.

The hierarchical structure is suitable for most (but not all) types of documents.

It manifests as plain text files, which are less restrictive than other proprietary document
formats.

It is platform-independent, thus relatively immune to changes in technology.

Forward and backward compatibility are relatively easy to maintain despite changes in
DTD or Schema.

Its predecessor, SGML, has been in use since 1986, so there is extensive experience and
software available.

The advantages of XML include that it can be used as an instrument to share data and application
models in wide networks like internet.
The Advantages of XML in Java
The XML uses the Common Component Architecture or CCA, and the Common Object Request
Broker Architecture, or CORBA. In other words, this means that it uses a common and standard
protocol which helps interoperability for programs. It also allows RMI or remote method

LOVELY PROFESSIONAL UNIVERSITY

347

Modern Programming Tools & Techniques-III

Notes

invocation in Java and invokes another java object. It also allows the clients to connect to the
program using the remote procedure calling, or RPC in short.
XML Advantages with Tags
The very first advantage with using tags in XML is that XML allows we to create our own tags,
and we are not limited to a standard set of tags that have to be used to program which are
predetermined by program vendors. If we use vendor declared tags in any program, there is
a limitation where the browsers and other programs associated with it will have to approve it
first and then get accustomed to usage, which will be quite a time consuming process. But in
XML we are creating our own tags and are already accepted by other languages so this becomes
a time saving process.
We can also have the freedom to develop at our own pace and moreover develop tools that will
be helpful for our programming needs without a lot of investment of time or money. Here by
defining our own tags we are widening our horizons. we can make the tags work for we and
develop anything the way we want it, compared to vendor declared tags where we will have to
fit our programming needs to suit the tags, which is a big limitation to creativity in programming.
Advantages of XML in Format
For example, escaping the tag limitations of html using XML is not even close to getting to
one of its best advantages. There is a lot more to it than just being able to give our own tags in
simple English. In html there are common problems that a user comes across while marking
up the data. However, there are three major problems that a user would come across and they
are; the graphic user interface, commonly known as the GUI is embedded with the data itself.
The disadvantage is that if we decide on some other format rather than the specified format in
the GUI, we will have to encode our entire html which means we might actually end up editing
volumes of data and lots of pages.
The second disadvantage the user might come across is it could be a very tedious process to
find information by navigating the data. Power searching is extremely difficult in html, and the
correlation of field does not exist. Only when the data is structured can we find similar data
or correlated data. The third disadvantage is that the data uses the same logic and language
that the html uses. if the user has the need to present the same data in some other format,
like say for example in a java applet, he will have to program that data using that individual
application, or the java applet has to parse the html document and string out information and
reformat the whole data. XML has advantages in all the above mentioned areas. It overcomes
all the limitations that html has whether it is with the language or the presentation of data or
the structure. XML is already known to be highly structured data which solves the problem for
users when it comes to correlation or identifying similar fields.
In XML the GUI can easily be extracted, and changes can be made without disturbing the
existing data in any way. If we want a table format we need to just create another style sheet
with the table format, and we do not have to erase the current data which is present in the file.
We can still retain the list format if we need to and also have the table format simultaneously.
Searching the data is all the more easy in XML document because any search engine can easily
parse through the data using the tags and locate the required data. It offers a freeway to navigate
through data. The XML data is structured and tree shaped depending on the way it has been
formatted. Even complex relationships in the tree structure and the parent child relationships
in a directory because it is clear in its format. The codes in XML are easily legible to a first
timer, and also because it is all written in simple plain text and in a human readable language.

348

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

XML from its Early Stages


XML has come a long way since it emerged, and it has been constantly improved and is still
undergoing a lot of changes as the internet technology is growing. But one factor which puts
XML in an advantageous position is that it is through the changes that it has been flexible,
and has been able to fit all the growing needs and functions as needed. It has its edge when
it comes to this in comparison to HTML or SGML, which have their own shortcomings. Even
though SGML has been used since the 1980s and is considered to be very powerful, it could not
cope with the fast changing technologies. And also as time moved forward SGML was proving
to be more expensive for its hunger for processor time and need of bigger processors. There
was a desperate need for a language that was low in cost and maintenance, but would not
compromise on efficiency and high level programming.HTML was some sort of an answer for
SGMLs in capabilities, but not in a very satisfactory way. HTML was hands free and simple. It
also had a wide acceptance. But it had defects, and it was not flexible, and changes within the
programmed document were almost impossible without disturbing the data in anyway. XML
provided the ultimate answer to all these capabilities. Over the years XML has evolved into a
completely functional tool which has made it easy for the internet in more than one way, and
users benefit from it in thousands of aspects.
Business Applications and Advantages of XML
XML accuracy when it comes to data has a proven track record. Airlines such as Jet blue depend
on XML for updating flight manuals and even flight plans because of its reliability. Business
documents are usually safe, not in one location but various locations. XML can be used to integrate
this data. Companies like General Motors are finding solutions in XML for their problems with
data in distributed environments. Many companies are now depending on the web services
which can provide them solutions for a centralized environment for their data which needs to
be safe and secure. Many applications come with a legacy and heavy price tag to pay. XML is
the simplest solution a user might have imagined in solving all these complex issues.
Disadvantages of XML
XML syntax is redundant or large relative to binary representations of similar data. the JavaScript
required to insert the data into the html page is quite verbose the redundancy may affect
application efficiency through higher storage, transmission and processing costs.XML syntax
is verbose relative to other alternative text-based data transmission formats. No intrinsic data
type support: XML provides a specific notion of integer , string, Boolean, date, and so on.
The hierarchical model for representation is limited in comparison to the relational model or
an object oriented graph. Expressing overlapping (non-hierarchical) node relationships requires
extra effort. XML namespaces are problematic to use and namespace support can be difficult
to correctly implement in an XML parser. XML needs an application processing system. There
are no browsers yet which can read XML. In the case of html, anyone can write up a program
and that can be read using any browser anywhere in the world. To be able to be read in a
browser, XML still depends on html, and is not independent of it. The XML documents have
to be converted to html before they are deployed. The most common method is to write the
parsing routes in either DHTML or java applications or parse through the XML document.
XML documents can be difficult and also expensive to setup. A freelancer for example can sit
at his home and at his own pace create, write and format a document or a manuscript using
any of the free software available. However, the moment he introduces XML or starts with it,
the whole process could get really painful to take the document further. The formatting rules
can be applied by the style sheet to convert the entire document into html. XML as a language
is very flexible, but its flexibility can potentially become one of its disadvantages, since there
may be disagreement in its tags. If an XML object has too many constraints, it might get very
difficult to construct the file. It is too verbal and sometimes this may be a problem for other

LOVELY PROFESSIONAL UNIVERSITY

349

Modern Programming Tools & Techniques-III

Notes

applications. While just describing tags and building a system sounds very easy, it may not be
that easy in reality. For example, a business or professional organization may have hundreds
of functions related with one set of documents. XML does not have the capability to synthesize
all the information related to the document.

XML syntax is redundant or large relative to binary representations of similar data.

The redundancy may affect application efficiency through higher storage, transmission
and processing costs.

XML syntax is too verbose relative to other alternative text-based data transmission
formats.

No intrinsic data type support: XML provides a specific notion of integer , string,
Boolean, date, and so on.

The hierarchical model for representation is limited in comparison to the relational model
or an object oriented graph.

Expressing overlapping (non-hierarchical) node relationships requires extra effort.

XML namespaces are problematic to use and namespace support can be difficult to correctly
implement in an XML parser.

XML is commonly depicted as self-documenting but this depiction ignores critical


ambiguities.

Lack of Applications Processing


Other disadvantages of XML include the fact that it is more difficult, more demanding and
more precise when compared to the html. XML does not have any browser support and does
not have anything to support the end user applications. it is still in the early experimental stage
and has not proved its mettle yet.
General Weaknesses of XML
Since XML is a verbose language, it is totally dependent on who is writing it. a verbose language
may pose problems for other users. XML is not specific to any platform, and has a neutral
platform requirement which may be a disadvantage in a few circumstances. all the standards
of XML are not yet fully compliant. They are not fully recognized to be used yet. Users have
reported problems with the parser and there are problems with XML and http which are still
being resolved.
XML and Unicode Disadvantages
While implementing programs which are multiple in number are incompatible, when XML is
split between these it may really turn out into a bad thing. When XML is tied closely to Unicode,
the Unicode changes XMLs attributes which might result in something which is totally different
from the original. The XML parsers when used along with the rss and the component called
next cannot disable the external entities. Instead they recognize them as their own which can
prove to be a major disadvantage. XML by itself cannot work along with netscape, which makes
it dependent on html. In certain instances like this, XML does have disadvantages and cannot
be called a super efficient model which is platform independent, and that can be deployed on
any operating system. The limitation here is also very basic since it cannot talk to the browsers.
There are a lot of sample codes which belong to html and XHTML which contain a DOCTYPE,
and which points it to a DTD. The common belief is that this actually works, but what very few
people do not realize is that the browsers do not actually retrieve these DTDs. Whenever the DTD
is unavailable for a various number of reasons then the entire application breaks down. This is
such a bad phenomenon because the DTD can be unavailable for reasons beyond comprehension,
and in some cases and it does not mean that the service itself has to become unavailable.
350

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

The XML creates an abundant amount of dependency on single factors which can let down the
program many times. DTD when available is totally not useful, and an outside program has to
be burdened to create a backup system, so users and developers might as well use the outside
program from scratch, which has the back up at intermediary levels. External entities again
pose a perennial problem, which again is a major disadvantage for XML. The best way to fix
the external entities problems with XML DTD is to not to use them at all, or if we have to use
them, then do not use them on the producer side, and moreover do not attempt to retrieve them
on the clients side. In case we are writing the specifications for an XML document, do not even
mention the specifications for DTD in the vocabulary, and there is also a need for the programs
to run their parsers for XML by disabling the external entity resolution. Otherwise the external
entities problem will invariably crop up, triggering a series of problems which cannot be solved
by the XML environment alone. While layering the specifications it can be considered against
the rules to disable or ban certain document types, which is allowed in soap. If our job is to
implement the web application which is based on XML, we may need to configure the parser
not to perform the DTD based validations, and also not to try and resolve the external entities.
This could be an answer to some of the future problems, so taking precautionary measures is
worthwhile. Publishing documents on the web requires the same precautions to be taken by
not including the document types.

Notes

The document may not be valid like the way XML describes it to be, and some people even
believe that the document validation in XML is overrated. Document data types are not known
to be very powerful when it comes to validation and it has been forgotten that the document
has its own language and grammar which can again not be efficient while getting validated.
There is also the problem of other programs not trusting the XML DTD. If there is an application
which exists that can handle multiple vocabularies of XML, and also knows to dispatch the
respective documents to the concerned handlers by checking the namespace at the root of
the element, then we can consider ourself lucky. If the vocabularies are not mentioned in the
namespace then we can look for them in the mime type. In some cases the vocabularies are not
present in the name space, nor are they specific to the mime, and then such language is certainly
a bad example and will create a lot of problems because we will have to use the root element
name. The XML specifications define three kinds of files processing. The first one is DTD based
validations which do not perform or retrieve external entities, and the second one is the DTD
based validations which do not performs or retrieve external entities so that the info set and
the reference library can be expanded. The third one is to perform the DTD based validation
by retrieving the external entities so that the info set and the entity reference can be expanded.
The point of having many profiles is so that the application has a choice and it chooses the
right one. It is a disadvantage because there will be a problem with the input and its editor. On
the World Wide Web there may be other options available when there is such a problem. The
situation need not be so unfortunate because there may be a solution which exists, and there
in fact is an input method which can solve the problem with the editor. If the XHTML entities
were pre defined then there would not have been much of these problems but that is going
back in time, and it cannot be changed.

Scheduled Data Exchange

he accounting and IT teams at Altova designed and developed a system that performs
automated currency exchange rate updates to the companys internal business
management application. This system works behind the scenes, ensuring that all
pricing information remains current for both the Euro and the US Dollar.
Contd...

LOVELY PROFESSIONAL UNIVERSITY

351

Modern Programming Tools & Techniques-III

Notes

Altova software tools are designed to solve real-world business challenges, and therefore,
projects such as this are generally done in-house, without requiring external services.
This project was assigned to an IT manager who worked with Altova tools and XML
technology, as well as with built-in Microsoft Windows functionality and the Foreign
Currency Exchange Rates & Indexes Table embedded within the companys SAP Business
One enterprise resource planning (ERP) system.
The Challenge
Altova needed to build and deploy a simple, lightweight application whereby its back-end,
SAP system would be automatically updated daily with the most current exchange rate
information for US Dollars (USD) and Euros (EURO). The application was to be created and
implemented by an Altova IT manager using Altova software tools. This way we would not
only avoid troubling our own software developers (who were busy working on enhancements
for our line of application development and data management tools) and save the cost of
using third-party services, but would also demonstrate the versatility and ease of use of our
tools to power users.
This project required the use of several different components, some pre-existing, and some
that needed to be created by the IT manager:
Existing Components
XML document The European Central Bank (ECB), which is responsible for regulating
international currency exchange, maintains a publicly available XML document that it updates
daily to provide current exchange rates. This file can be viewed at: http://www.ecb.int/
stats/eurofxref/eurofxref-hist.XML
Database table The Foreign Currency Exchange Rates & Indexes Table within our SAP
system enables the storage of current data from different currencies, based on exchange rates.
Altova XMLSpy XMLSpy is the industry leading XML editor and was used in this case to
generate an XML Schema based on the XML instance document mentioned above.
Microsoft Scheduler The Scheduled Tasks feature of the Windows operating system gives
users the ability to schedule recurring processes for any installed or accessible software
application.
Altova MapForce graphical user interface (GUI) MapForce is an application that can be used
for mapping to and from a wide variety of data formats. It provides a visual data mapping
interface, which allows the user to perform complex transformations using simple drag-anddrop functionality without writing any code.
MapForce Engine & command line interface (CLI) The MapForce Engine can be used within
custom-built data integration applications and has the ability to execute automated mappings.
The MapForce CLI launches the MapForce Engine, which in this application is called by the
Scheduled Task to execute an XML to database insert.
Using these available components, the IT manager set about developing a straightforward
system whereby internal pricing information would be automatically updated by referencing
an external resource (the ECB XML document).
The Solution
To complete this task, the IT manager devised a method for a variety of different components
to interact remotely on a regularly scheduled basis.
Contd...

352

LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

Notes

Created Components
XML Schema definition (XSD) XML Schema is the W3C recommended language for
describing the structure of an XML document. In this case, a schema for the ECBs XML
document was automatically generated using Altova XMLSpy.
MapForce design (.mfd) file A MapForce design file defines a data integration process
that can be represented visually and is used to generate and/or execute complex data
transformations.
Windows Scheduled Task file (.job) A Scheduled Task is a simple way to run any script,
program, or document at a pre-determined time and/or frequency.
In order to update the SAP database table with the constantly changing information from the
ECB XML document, a simple mapping was created using the MapForce GUI. The mapping
would take the data from the XML file and simply transform it to the database format for
use by the SAP system.
Altova MapForce utilizes an XSD to create a structural tree diagram of an XML instance for
mapping purposes. The XSD is essentially a bare bones representation of the XML document
structure without the associated content, and MapForce uses it as a sort of stub file or table
of contents to map the elements of the XML file. The ECB XML file is not supported by an
XSD, and, in order to reap the benefits that MapForce offers, one needed to be created so
that its components could be mapped to the database. XMLSpy offers the capability to infer
and automatically generate an XML Schema from an XML instance document, and this was
an ideal feature for this project because it only took a couple of seconds to use.
Questions
1. What was the challenge of Altova MapForce?
2. How XML helps to solve the problem?

Self Assessment Questions


Multiple Choice Questions

6. What is XML?

(a) Extensible Mark-up Language

(b) Extra Modern Link

(c) Example mark-up Language

(d) X-Mark-up Language

7. Which Statement about XML is true?


(a) Elements may have multiple attribute with the same name.

(b) Quoting attribute is optional

(c) Elements may nest but not overlap

(d) All of these

8. The term DTD stands for:

(a) Dynamic Type Definition

(b) Document Type Definition

(c) Do the Dance

(d) Direct Type Definition

LOVELY PROFESSIONAL UNIVERSITY

353

Modern Programming Tools & Techniques-III

Notes

9. XML Schema is designed to:

(a) Be self descriptive

(b) display only useful data

(c) Carrying request

(d) giving response

10. We can also use a DTD to verify our own ...............


(a) control

(b) description

(c) data

(d) None of these

11. With DTD, each of our XML files can carry a ........... of its own format with it.

(a) data

(b) control

(c) description

(d) and control

12. The XML schemas are the successors of ...........


(a) DTD

(b) XML

(c) XSL

(d) XSLT

13. Which statements are true? All XML documents must have:

(a) DTD

(b) All XML elements must be lower case

(c) All XML elements must be properly closed

(d) All of these

14. XML Schema is designed to be ...................


(a) self descriptive

(b) display only useful data

(c) carrying request

(d) giving response

15. Which syntax is used to insert comments into an XML document?


(a) <comment>this is a comment</comment>

(b) <?-This is a comment->

(c) <!-This is a comment->

(d) All of these

14.4 Summary

354

Mark-up and content may be distinguished by the application of simple syntactic rules.
All strings which constitute mark-up either begin with the character < and end with a >,
or begin with the character and end with a Strings of characters which are not mark-up
are content Tag.

XML schemas provide a much more powerful means by which to define our XML document
structure and limitations. XML schemas are themselves XML documents. they reference
the XML schema namespace and even have their own DTD.

All XML documents can optionally begin with an XML declaration. The XML declaration
provides at a minimum the number of the version of XML.
LOVELY PROFESSIONAL UNIVERSITY

Unit 14: XML

XML allows us to define our own tags for use in text documents tags can be nested and
can be interspersed with text.

The data element provides a location for storing the data associated with a node for a
rating node.

The XML reader data type allows the reading of XML files. The document XML offers an
introduction to that language. A variable of a new data type called XML reader must be
defined in order to read the content of an XML file.

Notes

14.5 Keywords
Data Element: The data element provides a location for storing the data associated with a node.
DTD: A Document Type Definition (DTD) is a set of markup declarations that define a document
type for an SGML-family markup language (SGML, XML, HTML).
Err Code: It returns a value greater than zero if an error occurred during the processing of a
XML document.
Read External Entities: This Boolean (1/0) property indicates if the parsed external entities that
make-up the XML document being processed must be read.
XML Text Writer: XML text writer maintains a namespace stack corresponding to all the
namespaces defined in the current element stack. Using XML text writer we can declare
namespaces manually.
1. Write an XML program to print Hello World.
2. Create a DTD for a college?

14.6 Review Questions


1. What is the Mark-up and Content?

2. Defined XML collection method.

3. Explain is Encoding detection.

4. What is Schema Data Type and Attribute?


5. Define Administration tools and hierarchical data.

6. What XML is a standard format?


7. Discuss Accessory elements and data models.

8. XML tree structure and XML tree features.

9. Define XML reader and writer classes.

10. Business applications and advantages of XML and format.

Answers for Self Assessment Questions


1. (a)

2. (a)

3. (d)

4.

(b)

5.

(b)

6. (a)

7. (c)

8. (b)

9.

(a)

10.

(c)

11. (c)

12. (a)

13. (c)

14.

(a)

15.

(c)

LOVELY PROFESSIONAL UNIVERSITY

355

Modern Programming Tools & Techniques-III

Notes

14.7 Further Reading


XML, by Kevin Howard Goldberg.

http://books.google.co.in/books?id=485Ol3iv2tAC&printsec=frontcover&d
q=xml&hl=en&sa=X&ei=GvsEUO_wEYyzrAec6sC9Bg&ved=0CEoQ6AEwB
A#v=onepage&q=xml&f=false

356

LOVELY PROFESSIONAL UNIVERSITY

You might also like