Modern Programming Tools - and Techniques III - Shrivastava - Ibrg
Modern Programming Tools - and Techniques III - Shrivastava - Ibrg
in
DIRECTORATE OF DISTANCE EDUCATION
SYLLABUS
Modern Programming Tools & Techniques-III
Objectives:
To enable the student to understand Database application development using dot net and data transmission
technology.
COURSE CONTENTS:
S. No.
Topics
1.
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.
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:
35
Unit 3:
55
Unit 4: Array
Unit 5:
In Built Functions
Unit 6:
Unit 7: Namespaces
74
89
110
135
Unit 8:
Exception Handling
163
Unit 9:
Using System.Collections
178
204
234
262
301
323
Notes
CONTENTS
Objectives
Introduction
1.1
1.1.1
1.1.2
1.2
1.3
Visual Basic.NET
1.3.1
1.3.2
Managed Execution
1.3.3
1.3.4
1.3.5
Executing Code
1.3.6 Assemblies
1.3.7
Assembly Manifest
1.3.8
1.3.9
1.4
1.4.1 Classes
1.4.2 Interfaces
1.4.3
1.4.4 Delegates
1.5
Feature of VB.NET
1.5.1
1.5.2
1.5.3
Simplified Deployment
1.5.4
1.5.5
Improved Coding
1.5.6
1.5.7
1.5.8
1.5.9
Mobile Applications
1.6
NET Framework
1.6.1
Value Types
Notes
1.7
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:
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.
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.
Notes
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
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
TextBox
Button
CheckBox
RadioButton
ListBox
ComboBox
Timer
PictureBox
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.
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.
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.
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.
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.
Locate classes
LOVELY PROFESSIONAL UNIVERSITY
Load classes
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.
11
Notes
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
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.
Assembly name
Version
Referenced assemblies
In addition, a developer can set custom attributes for an assembly, such as a title and a description.
13
Notes
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.
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
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.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.
15
Notes
(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
(a) languages
(b) program
(c) function
(d) variable
16
Notes
17
Notes
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
(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
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.
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.
19
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
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
End
EndIf
Enum
Erase
Error
Event
Explicit
False
Boolean Literal
For
Finally
For
Friend
Function
Get
GetType
GoTo
Handles
Call
Case
Catch
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
CInt
Data-conversion function
Class
CLng
Data-conversion function
CObj
Data-conversion function
Compare
CShort
Data-conversion function
CSng
Data-conversion function
Contd...
21
Notes
CStr
Data-conversion function
CType
Data-conversion function
Date
Decimal
Declare
Default
Delegate
Dim
Do
Double
Each
Else
ElseIf
End
EndIf
Enum
Erase
Error
Event
Explicit
False
Boolean literal
For
Finally
For
Friend
Function
Get
GetType
GoTo
Handles
If
Implements
Imports
In
Inherits
Input
Integer
Interface
Is
Let
Lib
Like
Lock
Function name
Long
22
Notes
Loop
Used in a Do loop
Me
Mid
Mod
Module
MustInherit
MustOverride
MyBase
MyClass
Namespace
New
Next
Not
Nothing
NotInheritable
NotOverridable
Object
Off
On
Option
Optional
Or
Boolean operator
OrElse
Boolean operator
Output
Overloads
Overridable
Overrides
ParamArray
Preserve
Private
Property
Protected
Public
RaiseEvent
Random
Read
ReadOnly
ReDim
Rem
RemoveHandler
Resume
Return
Seek
Select
23
Notes
Set
Shadows
Shared
Short
Single
Static
Step
Stop
String
Structure
Sub
SyncLock
Text
Then
Throw
To
True
Boolean literal
Try
TypeOf
Unicode
Until
Variant
When
While
With
WithEvents
WriteOnly
XOr
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
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.
25
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:
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.
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
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
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.
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.
27
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
col.Add(Some value)
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
col.Add(Some value)
Dim i As Integer
For i = 1 To col.Count
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
29
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.
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
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
Label Text
Auto Sales
Service Center
Detail Shop
Employment Opportunities
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...
31
Notes
Sci-Fi
Aisle 4
Horror
Aisle 5
New Releases
Back Wall
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.
(b) 2005
(c) 1991
(d) 1980
7. Select is a
(a) condition
(b) loop
(d) statement
8. Visual Basic is a high level programming language which was evolved from the earlier
DOS version called .
(a) BASIC
(b) FORTRAN
(d) Perl
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
(b) example
(c) class
(d) object
Notes
(b) object
(c) framework
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
Assembly represents the unit of deployment, version control, reuse, and security.
XML Web services enable we to call components running on any platform using open
Internet protocols.
Visual Basic .NET source code is saved in files with a .vb extension.
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.
33
Notes
Event Driven
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)
http://media.visual-paradigm.com/media/documents/dbva40npg/pdf/
dbva_dotnet_programmer_guide
34
Notes
CONTENTS
Objectives
Introduction
2.1 Variables
2.1.1
2.1.2
2.2 Operators
2.2.1
Mathematical Expressions
2.2.2
Event-Driven Programming
2.2.3
2.3
Data Types
2.3.1
2.4 Summary
2.5 Keywords
2.6
Review Questions
2.7
Further Reading
Objectives
After studying this unit, you will be able to:
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.
35
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
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
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.
37
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
Procedure only
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
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:
Once you define a variable, that variable always retains its original data type. The Dim statement
defines variables. Using Dim, you tell Visual Basic
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:
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
39
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.
40
Notes
(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) 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:
41
Notes
Example
Description
Net + Disc
Price 4.00
Total * Fact
Tax / Adjust
Adjust ^ 3
& or +
Operator Precedence
The order in which mathematical operators used when formula is solved.
Operators
Order of Precedence
()
*/
Mod
Change
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
Click
The user clicks and object with the primary mouse button
(usually the left button).
Dbclick
DragDrop
42
DragOver
GotFocus
KeyDown
KeyPress
KeyUp
LostFocus
MouseDown
MouseMove
MouseUp
Notes
Usage
Description
>
<
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
>=
FirstName >=
Mike
<=
Num <=
lblAmt Cap ion
<>
txtAns.Text <>
Yes
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)
Or
If (A > B) OD)
Not
If Not (Ans =
43
Notes
Visual Basic supports the use of six operators that produce true or false results
based on data values.
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
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
String
Boolean
2 bytes
True or False
Date
8 bytes
Object
4 bytes
Variant
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.
45
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
your main concern, declare it using the Single data type. Here is an example:
Notes
47
Notes
48
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
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
922,337,203,685,477.5808 to
922,337,203,685,477.5807
String
String of characters
8-byte date/time
value
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
49
Notes
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:
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:
50
Notes
o Unit-tests.
(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
(b) double
(c) string
(d) database
51
Notes
9. Database data type allows you to get a to the database you are using.
(a) tool
(c) reference
(d) 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
(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.
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.
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.
53
Notes
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)
http://ftp.ku.ac.th/pub/manual/VB.NET%20-%20(OReilly)%20
Programming%20Visual%20Basic%20%20NET.
54
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
Objectives
After studying this unit, you will be able to:
Define looping
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.
55
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
No
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
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
Dim b As Integer
a = 3
b = 4
If a > b Then
Else
57
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.
(a) loop
(b) data
(c) structure
(a) PHP
(b) Java
True or False
4. If uses comparison operator results to test data.
(a) True
(b) False
(b) False
58
Notes
Else
End If
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.
59
Notes
Examination Grades
Dim grade As String
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
comment.Caption = Excellence
Case Is >= 70
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
61
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.
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
Notes
System.IO.File.
Debug.WriteLine(sr.ReadLine())
End While
sr.Close()
End If
End Sub
STATEMENT 1
OF
LOOP BODY
STATEMENT 2
OF
LOOP BODY
T
CONDITION?
F
SOME STATEMENT
AFTER
LOOP FINISHES
63
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.
Loop
counter =counter+1
STATEMENT 1
OF
LOOP BODY
STATEMENT 2
OF
LOOP BODY
F
CONDITION?
T
SOME STATEMENT
AFTER
LOOP FINISHES
64
Notes
Do Until (condition)
Block of one or more Visual Basic statements
Loop
65
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
Negative
A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.
An Object.
A type T that has the following operators, where B is a type that can be used in a Boolean
expression.
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
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.
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.
Debug.Write(number.ToString & )
Next
Debug.WriteLine()
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
67
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
End If
Debug.Write(index.ToString & )
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
Debug.Write(mammal.ToString & )
Debug.WriteLine()
End Sub
In the following example, the statement parameters use a class that has operator overloads for
the +, , >=, and <= operators.
68
Notes
End Sub
End Operator
End Operator
End Operator
End Operator
End Class
Debug.Write(dist.Number.ToString & )
Debug.WriteLine()
Output: 10 14 18 22
End Sub
Conditional Structures
1. Program FindAverage;
Contd...
69
Notes
4. begin
5. Count := 0;
6. Sum := 0;
7. repeat
9. readln(Num);
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:
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;
4. begin
5. Count := 0;
Contd...
70
Notes
6. Sum := 0;
7. repeat
9. readln(Num);
No number is inputted!
Questions
(b) Then
(c) Else
71
Notes
(a) IfThen
(c) DoLoop
(d) ForNext
10. How many times is the test expression of a Select Case evaluated?
(a) 0
(b) 1
(c) 2
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
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.
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.
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.
9. You can also nest different kinds of control structures within one another. How?
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
73
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
4.4.1
4.5
Multidimensional Arrays
4.6
4.7
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:
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
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
75
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.
76
Unit 4: Array
Notes
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.)
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.
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
77
Notes
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 .
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
(b) fixed-size
(c) fixed-dynamic
(d) dynamic
Unit 4: Array
(b) 31
(c) 32
(d) 33
Notes
4. Arrays are declared using Dim, ReDim, and Static, Private, Public and Protected .............. .
(a) variables
(b) keywords
79
Notes
80
Unit 4: Array
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.
81
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:
Class Test
Console.WriteLine(x)
Next
End Sub
Console.WriteLine(myArray(x))
Next
End Sub
Dim i As Integer = 0
Else
Console.WriteLine()
i = 1
End If
Console.WriteLine(myEnumerator.Current)
End While
End Sub
TestForEach(myIntArray)
82
Unit 4: Array
Notes
an Object array
TestForWithLength(myObjArray)
To
myObjArray2.SetValue(i * i, i)
Next
TestForEnum(myObjArray2)
Console.ReadLine()
End Sub
End Class
C
reates and initializes a new integer array and a new
Object array.
Console.Write(integer array:)
Console.Write(Object array: )
PrintValues(myObjArray)
83
Notes
C
opies the first two elements from the integer array
to the Object array.
System.Array.Copy(myIntArray, myObjArray, 2)
Prints the values of the modified arrays.
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)
PrintValues(myIntArray)
Console.Write(integer array:)
Console.Write(Object array: )
PrintValues(myObjArray)
End Sub
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
Console.Write(ControlChars.Tab + {0}, i)
Next i
Console.WriteLine()
End Sub
End Class
Output
Initially,
84
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
85
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.
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
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
Unit 4: Array
(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
12. Which method will arrange the elements of an array in alphabetical order?
(a) Arrange
(b) Assemble
(c) Order
(d) Sort
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.
87
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.
9. Define snippet.
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)
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
Notes
CONTENTS
Objectives
Introduction
5.1
5.2
String Class
5.2.1
5.3
Conversion Functions
5.3.1
5.3.2
Val Function
5.4
Miscellaneous Functions
5.5
5.5.1 Subroutine
5.6 Summary
5.7 Keywords
5.8
Review Questions
5.9
Further Reading
Objectives
After studying this unit, you will be able to:
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.
89
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.
Named constant
Buttons displayed
0 vbOkOnly
Ok
vbOkCancel
Ok and Cancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
Yes and No
vbRetryCancel
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
Buttons clicked
1 vbOk
Ok
2 vbCancel
Cancel
3 vbAbort
Abort
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.
91
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:
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;
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:
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
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
93
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.
94
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.
95
Notes
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.
96
CByte
Notes
CDbl
CDec
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)
97
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
CLng
CSng
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.
blnTest = False
sngTest = 123.456
CVar
98
lngX = 1615198
intX = Val(2457)
intX = 2457
intX = Val(2457)
intX = 2457
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
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:
99
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
Sub Main()
Console.WriteLine(The
c.DisplayName)
CultureInfo
Console.ReadLine()
End Sub
End Module
Output:
100
is
set
to:
{0},
Notes
Imports System.Collections.Generic
Imports System.Linq
Sub Main()
End Sub.
End Module.
1. The Val function is a more generic (and less efficient) way to convert a string to a ..............
(a) variable
(c) number
2. The Input Box() function displays a .............. input box into which the user can type a
message.
(a) push-up
(b) pop-up
3. The expression must be a number (or a string representation of a number) that is within
the ....................
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
Notes
(c) True
(d) False
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.
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
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
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
Functions
A function is a self contained section of code, that:
Has Inputs: Generally Yes
Has Output: Always
1
Return x * x
End Function
Subroutines and Functions may contain calls to other Functions and Subroutines.
01
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
103
Notes
10
11
Return SquareOfNumber(Factorial(x))
12
End Function
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
2 A+=2
3 B+=2
4
End Sub
Tb. Text =
End Sub
104
To avoid from error in the program, do not call a subroutine from within
another program.
Notes
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:
li $t1, 0 # i = 0
LOOP:
105
Notes
INCR:
END:
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
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:
INCR:
END:
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.
6. Visual Basic .NET has built-in functions for manipulating text and carrying
out mathematical operations.
(a) single
(b) many
(c) double
(a) push-up
(b) pop-up
(c) both
(a) constructor
(b) destructor
(c) reflector
107
Notes
9. VB would perform the necessary conversions in these cases wherever it could. Such
conversions are called ..
(a) Int
(b) Float
(c) Double
(d) String
(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) Currency
(b) Int
(c) Float
(d) String
(a) Object
(b) Class
(c) both
5.6 Summary
108
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.
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.
7. Define CBool.
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)
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
109
Notes
CONTENTS
Objectives
Introduction
6.1
6.1.1
6.1.2
Create a Class
6.1.3
6.1.4
Create a Method
6.2 Constructor
6.3
6.3.1
Creating Properties
6.3.2
Creating Indexer
6.4
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:
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
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
111
Notes
Dim a As Integer = 5
Dim b As Integer = 6
Dim c As Integer
Sub add()
c=
a+b
Console.WriteLine(c)
End Sub
End Class
Sub Main()
End Sub
End Module
In this example test define the Class and obj defines the objects of class test.
112
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
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.
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.
113
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
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
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
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
115
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.
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
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.
5. ByVal e As System.EventArgs)
6.
8.
9. oLine.Line = txtLine.Text
117
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
Notes
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.
119
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.
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.
(a) variable
(c) value
(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
(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
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]
121
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.
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.
GetStarts a Get property procedure used to return the value of a property. Get blocks
are optional unless the property is ReadOnly.
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.
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
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)
123
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
124
Notes
Indexer Example
Imports System
Imports System.Net
Class GetDNSaliases
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
Return m_arrAlias.GetUpperBound(0)
End Get
End Property
End Class
Class MyApp
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)
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
125
Notes
Console.WriteLine(Exception occurred!{0} & vbCr & vbLf,
e.ToString())
Finally
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.
126
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
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
127
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
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()
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
Inherits Employee
128
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
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
129
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.
130
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...
131
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
2. Which one is the first version of Visual Basic could create 16 bit as well as 32 bit windows
program?
(b) VB 6
(c) C++
(d) C#
(a) debugging
(b) methods
(c) events
132
(a) asp
(b) aspx
(c) asp.vb
(d) aspx.vb
(b) Properties
(c) Instances
Notes
(b) classes
(c) data
(d) events
6.5 Summary
Visual Basic controls (i.e. those found in the Toolbox) are predefined objects, and include
Labels, Textboxes, Buttons and other controls.
Objects are instance of the class. Fields and Properties represent information that an object
contains.
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.
133
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.
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)
http://www.codeproject.com/Articles/8825/Object-Oriented-ProgrammingIn-VB-NET
134
Unit 7: Namespaces
Unit 7: Namespaces
Notes
CONTENTS
Objectives
Introduction
7.1
7.1.1
Declaring a Namespace
7.1.2
7.1.3
Nesting a Namespace
7.1.4
7.1.5 Assemblies
7.2
7.3
7.3.1
7.3.2
Creating Properties
7.3.3
7.3.4
7.3.5
Parameterized Properties
7.3.6
Default Properties
7.3.7
7.3.8
7.3.9
7.4
Creation of Namespaces
7.4.1
7.4 Summary
7.5 Keywords
7.6
Review Questions
7.7
Further Readings
Objectives
After studying this unit, you will be able to:
Define namespaces
135
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:
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 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
As Integer
Return a - b
End Function
As Long
Return a * b
End Function
End Class
End Namespace
Class GrupOp
136
Unit 7: Namespaces
As Integer
Notes
Return a + b
End Function
As Double
Return a / b
End Function
End Class
End Namespace
Module Module1
Sub Main()
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()
137
Notes
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.
138
Unit 7: Namespaces
System.Diagnostics: Includes classes that allow to debug our application and to step through
our code
Notes
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.
139
Notes
Namespace <Namespace_name>
End Namespace
Example
Namespace MyNamespace
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.
P
ublic Shared Function color() color is another function in
parrot class
Console.WriteLine(normally Parrots are green)
End Function
C
onsole.WriteLine(Different type of parrot are found around
the world)
End Function
End Class
End Namespace
140
Unit 7: Namespaces
Module Module1
Notes
another
way
to
myfunction()
End Sub
End Module
Output:
P
ublic Shared Function disp() create a function inside a
outer namespace
Console.WriteLine(hi this is outer name space)
End Function
End Class
141
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
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 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.
143
Notes
Namespace innerscope
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
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 the assembly version (each assembly has a specific version number).
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.
145
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
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.
(b) proc
(c) prod
(d) proe
147
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
(b) double
(c) multiple
(d) more
True or False
5. Nesting a Namespace means create a namespace inside a namespace.
(a) True
(b) False
148
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
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.
149
Notes
150
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
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
151
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:
Get
152
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.
153
Notes
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
Get
Return miPatientID
End Get
Set
miPatientID = Value
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.
155
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.
156
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
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)
157
Notes
158
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
(a) Objects
(b) Classes
(c) files
(d) folders
159
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
(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
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
(b) event
(c) Method
(d) Namespace
(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
(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
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.
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.
161
Notes
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.
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)
162
5. (a)
Notes
CONTENTS
Objectives
Introduction
8.1
8.1.1
8.1.2
8.1.3
8.1.4
8.1.5
8.2
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
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.
163
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.
164
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- 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.
165
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.
166
Notes
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.
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
167
Notes
Try
prcTextFile.Start ()
Catch
Finally
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.
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
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
MessageBox.Show(ex. Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
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
Try
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.
169
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
Notes
Click the View Details links under Actions to see the following:
Figure 8.3: View Details
171
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.
(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....................
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
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
173
In the context of IEEE 754 floating point hardware the term exception is used
Notes
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
Notes
(a) If....EndElse
(b) End...Else...If
(c) If...Else...End
(a) HelpLink
(b) StackTrace
(c) InnerException
(b) overflow
(b) ExecuteStream
(c) Open
(d) ExecuteReader
(b) .asp
(c) .aspx
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
175
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
Notes
10. Write a statement between the try and catch keywords is called protected code because
any runtime errors resulting?
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)
http://www.codeproject.com/Articles/13658/VB-NET-Error-Handling
177
Notes
CONTENTS
Objectives
Introduction
9.1 ArrayList
9.1.1
Use of ArrayList
9.1.2
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
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:
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
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 IList and IDictionary interfaces derive from the ICollection interface, which in turn
derives from IEnumerable.
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.
179
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.
Description
Capacity
Count
IsFixedSize
IsReadOnly
IsSynchronized
Item
SyncRoot
Description
Add
AddRange
BinarySearch
Clear
Clone
Contains
CopyTo
Equals
FixedSize
GetRange
GetType
IndexOf
180
Insert
InsertRange
LastIndexOf
ReadOnly
Remove
RemoveAt
RemoveRange
Reverse
SetRange
Notes
List.
Sort
ToArray
ToString
TrimToSize
3 Module Module1
5 Sub Main()
9 myArrayList.Add(Bit)
10 myArrayList.Add(Byte)
11 myArrayList.Add(Kilobyte)
12
181
Notes
16 Console.WriteLine(------------------)
17
18 MyArrayList.Add(Megabyte)
19 MyArrayList.Add(Gigabyte)
20
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
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
ArrayList
(thread safe)
ArrayList
(thread safe)
ArrayList
(sync root)
Array
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.
183
Notes
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.
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.
184
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)
185
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
Namespace DotNetTreats.DataStructures
Friend Class stackconsumer
Public Sub New()
End Sub
<STAThread> _
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(stack.Peek().ToString())
Expression validator
As
Boolean
New
eval.Validate(Console.
If result Then
186
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.
The following sample code validates expressions that use the following characters: ( ), { },
and [ ].
Imports System
Namespace DotNetTreats.DataStructures
Public Class ExpressionValidator
If stack.IsEmpty() Then
187
Return False
Notes
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()
188
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)
189
Notes
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()
190
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
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
MouseProblem
TextProblem
ScreenProblem
ModemProblem
End Enum
Sub Main()
help.Enqueue(RequestType.TextProblem)
help.Enqueue(RequestType.ScreenProblem)
191
Notes
This removes TextProblem.
help.Dequeue()
End If
End If
help.Enqueue(RequestType.ModemProblem)
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.
1. A hashtable is a proven way of efficiently storing and retrieving values using the hash of
a ............
(a) value
(c) variable
(b) False
3. The Hashtable class uses hash codes to provide efficient and ..............
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
Notes
5. Arraylist is a...................
(b) element
(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>
193
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()
Console.WriteLine(element)
Next
End Sub
End Module
Output
viperfish
194
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);
195
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);
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
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...
197
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.
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
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...
199
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
2. What are the benefits to build the solution for stack overflow using ASP.NET MVC
Framework?
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.
(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.
200
(a) IComparer
(b) Enumerable.
(c) Enumerator
(d) IDictionaryComparer
8. Which of the following statements are correct about the Stack collection?
(ii) All elements in the Stack collection can be accessed using an enumerator.
(v) Top-most element of the Stack collection can be accessed using the Peek()method.
Notes
9. How many enumerators will exist if four threads are simultaneously working on
anArrayList object?
(a) 1
(b) 3
(c) 2
(d) 4
(i) Stack
(ii) Queue
(iii) BitArray
(iv) ArrayList
(c) (iv)
(i) Map
(ii) Stack
(iii) Queue
(iv) BitArray
(a) (i)
12. Which of the following statements are correct about the Collection Classes available in
Framework Class Library?
(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.
(i) Map
(ii) Stack
201
Notes
(iii) BitArray
(iv) HashTable
(v) SortedList
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
(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.
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
Notes
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)
http://visualbasic.about.com/od/usingvbnet/a/ienumble.htm
203
Notes
CONTENTS
Objectives
Introduction
10.1 Controls
10.1.1
10.2
Button Control
10.2.1
Button Event
10.2.2
10.3
TextBox Control
10.3.1
10.4
RichTextBox
10.5
10.5.1 Label
10.5.2
Link Label
10.6 Checkbox
10.7
List Box
10.7.1
10.8 ComboBox
10.8.1
10.9
Tree View
10.9.1
Properties of TreeView
10.10
CheckedListBox
10.11.1 Panel
10.12.1 ToolTip
204
Objectives
Notes
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.
205
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
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.
206
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
207
Notes
208
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)
209
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
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.
211
Notes
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
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
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
213
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
(b) False
2. Labels are those controls that are used to display text in .............. of the application.
(a) single part
(c) parts
3. Checkboxes are those controls which gives us an option to select, say ....................
(a) Yes/No
(b) True/False
(c) No
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
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
215
Notes
216
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.
217
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
Notes
219
Notes
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
Notes
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.
221
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.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
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
223
Notes
224
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.
225
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
226
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
227
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
Notes
229
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
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)?
(b) win 64
7. Visual Basic allows us to work with controls in two ways: at design time and ..
(b) at runtime
(c) Both
230
(b) child
(c) Both
Notes
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
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
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.
231
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.
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)
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
233
Notes
CONTENTS
Objectives
Introduction
11.1 Common Dialog Boxes
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
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
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
TPersistent
TComponent
TApplication
TCommonDialog
TScreen
235
Notes
236
Notes
237
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
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
239
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.
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.
241
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
Activity
Comment
Current activity
Restore Defaults
Apply
OK
Cancel
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
Notes
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
Comment
Current activity
Restore Defaults
Apply
OK
Cancel
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
Comment
243
Notes
Column name
Displays
Current activity
Restore Defaults
Apply
OK
Cancel
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
Keep copy
Restore Defaults
Apply
OK
Cancel
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
Displays
Table of artifacts
Keep copy
Restore Defaults
Apply
OK
Cancel
Notes
245
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();
}
}
}
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
247
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
248
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
249
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.
saveFileDialog1.InitialDirectory = C:\
saveFileDialog1.CheckFileExists = True
saveFileDialog1.CheckPathExists = True
saveFileDialog1.DefaultExt = txt
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
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.
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.
251
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
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.
4. Modeless dialog boxes are frequently used as a ............ way to create a window.
(a) slow and easy
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
253
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
With MyForm
Width = 438
Height = 214
Controls.AddRange(New Control()
lblMessageBody, btnNo, btnYes, btnOk})
End With
End Sub
{lblHeadline,
254
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
Named Constant
Buttons Displayed
vbOkOnly
Ok button
vbOkCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
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
255
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.
Presses ALT+F4.
256
Imports System
Imports System.Windows
Imports System.Windows.Controls
Namespace VisualBasic
Inherits Window
Notes
InitializeComponent()
End Sub
This event is raised whenever this button is clicked, or the ENTER key is
pressed.
Me.DialogResult = True
End Sub
End Class
End Namespace
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.
257
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
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
(b) ShowOpen
(c) ShowPrint
(d) ShowColor
(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
259
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
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.
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.
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)
261
Notes
CONTENTS
Objectives
Introduction
12.1 Working with Files
12.1.2 Path
12.2.3 Streams
12.2.4 FileStream
12.2.5 BufferedStream
12.2.6 NetworkStream
12.2.7 CryptoStream
12.2.8 MemoryStream
Objectives
After studying this unit, you will be able to:
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
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
263
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
Copy
Create
CreateText
Delete
Exists
GetAttributes
GetCreationTime
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
Open
OpenRead
OpenText
OpenWrite
SetAttributes
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
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
265
Notes
Purpose
AtlDirectorySeparatorChar
DirectorySeparatorChar
InvalidPathChars
PathSeparator
VolumeSeparatorChar
ChangeExtension
Combine
GetDirectoryName
GetExtension
GetFileName
GetFileNameWithoutExtension
GetFullPath
GetPathRoot
GetTempFileName
GetTempPath
HasExtension
IsPathRooted
The following example extracts the root from the abovespecified full path and file name:
Get
Return PathChecker.GetPathRoot(FilePath)
End Get
End Property
266
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.
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.
Purpose
FileAccess
FileShare
FileMode
267
Notes
Purpose
Read
ReadWrite
Write
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
Compressed
Device
Directory
Encrypted
Hidden
Normal
NotContentIndexed
Files that are marked with this attribute do not get indexed
by Index Server or some other content indexing service.
Offline
ReadOnly
ReparsePoint
268
Notes
SparseFile
System
Temporary
[*]
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
Create
CreateNew
Requests the file system to create a new file with the given
name
Open
OpenOrCreate
Truncate
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
Notes
FileAccess.Read, FileShare.Read)
End If
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
Notes
Purpose
Inheritable
None
Read
ReadWrite
Write
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.
271
Notes
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.
(a) one
(b) two
(c) three
(d) four
(a) reading
(b) writing
3. This class contains methods that provide the as the File class.
True or False
4. Decoders and encoders are obtained using the Get Decoder and Get Encoder methods.
(a) True
272
(b) False
5. Network Stream implements the standard .NET Framework stream mechanism to send
and receive data through network sockets.
(a) True
Notes
(b) False
Purpose
CreateDirectory
Delete
Exists
GetCreationTime
GetCurrentDirectory
GetDirectories
GetDirectoryRoot
GetFiles
GetFilesSystem Entries
GetLastAccessTime
GetLastWriteTime
GetLogicalDrives
GetParent
Move
SetCreationTime
Lets you set the creation date and time for files or directories
SetCurrentDirectory
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:
273
Notes
Next fileName
PrintFileInfo(fileName)
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)
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)
CreationTime (p)
Directory (p)
DirectoryName (p)
Exists (p)
Extension (p)
FullName (p)
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)
Name (p)
AppendText
CopyTo
274
Notes
Create
Creates a file
CreateText
Delete
MoveTo
Open
OpenRead
OpenText
OpenWrite
Refresh
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)
CreationTime (p)
Exists (p)
Extension (p)
FullName (p)
LastAccessTime (p)
LastWriteTime (p)
Parent (p)
Root (p)
Create
Creates a directory
Contd...
275
Notes
CreateSubdirectory
Delete
GetDirectories
GetFiles
GetFileSystemInfos
MoveTo
Refresh
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:
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.
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.
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.
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
277
Notes
Table 12.11: The Properties of the Drive Class in the File System Object
Property
Purpose
TotalSize
AvailableSpace, FreeSpace
DriveLetter, Letter
DriveType
SerialNumber
FileSystem
IsReady
ShareName, VolumeName
Path, RootFolder
Description
Container (p)
EnableRaisingEvents (p)
Filter (p)
IncludeSubdirectories (p)
InternalBufferSize (p)
NotifyFilter (p)
Path (p)
Site (p)
SynchronizingObject (p)
BeginInit
278
Notes
EndInit
Equals
(inherited from Object)
WaitForChanged
Changed (e)
Created (e)
Deleted (e)
Disposed (e)
Adds an event handler to listen to the Disposed event
(inherited from Component) on the component
Error (e)
Renamed (e)
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
specify a path
Watcher.Path = c:\indexworks
Watcher.NotifyFilter = (NotifyFilters.LastAccess _
Or NotifyFilters.LastWrite _
Or NotifyFilters.FileName _
Or NotifyFilters.DirectoryName)
Watcher.Filter = noisefile.txt
Start
Watcher.EnableRaisingEvents = True
End Sub
279
Notes
Indexworks.Reload(FilePath)
End Sub
Purpose
Attributes
CreationTime
DirectoryName
FileName
LastAccess
LastWrite
Security
Size
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
Notes
Description
All
Changed
Created
Deleted
Renamed
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.
281
Notes
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
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)
CanSeek (p)
CanWrite (p)
Handle (p)
Retrieves the operating system file handle for the file that the current
FileStream object encapsulates
IsAsync (p)
Length (p)
Name (p)
Position (p)
BeginRead
BeginWrite
Close
Closes the file and releases any resources associated with the current
file stream
EndRead
EndWrite
Flush
Clears all buffers for this stream and causes any buffered data to be
written to the underlying device
Lock
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
SetLength
ToString
Unlock
Write
WriteByte
283
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:
) As IAsyncResult
The following list describes its parameters:
userCallback: The method to be called when the asynchronous read operation is completed
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
Notes
Condition
ArgumentException
ArgumentNullException
ArgumentOutRangeException
IOException
Seek
The Seek method changes the current position in the stream to the value passed as the argument.
Its signature is as follows:
) As Long
The following list describes its parameters:
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.
Type Condition
IOException
NotSupportedException
ArgumentException
ObjectDisposedException
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.
285
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:
FileAccess.Write)
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:
FileAccess.Write)
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:
FileAccess.Write)
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
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
sWriter.Flush()
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
287
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.
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
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
Peek
Read
ReadBlock
ReadLine
ReadToEnd
289
Notes
Purpose
Encoding (p)
FormatProvider (p)
NewLine (p)
Close
CreateObjRef
Flush
Clears all buffers for the current writer and causes any
buffered data to be written to the underlying device
GetLifetimeService
GetStringBuilder
Write
WriteLine
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:
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
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 StringWriter...
sBuilder = strWriter.GetStringBuilder()
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
291
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:
Purpose
Null (p)
BaseStream (p)
CurrentEncoding (p)
Close
CreateObjRef
DiscardBufferedData
Peek
Read
ReadBlock
ReadLine
ReadToEnd
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
Purpose
AutoFlush (p)
BaseStream (p)
Encoding (p)
FormatProvider (p)
NewLine (p)
Close
Flush
Write
WriteLine
Notes
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.
293
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.
.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
294
Notes
StreamReader(C:\TextReader.txt)
While True
line = readFile.ReadLine()
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()
... Create this file in Visual Studio and select Copy If Newer
on its properties.
295
Notes
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
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.
(b) streams
(c) function
7. A stream can be ..
(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
297
Notes
10. File class provides the .NET Frameworks support for all manner of ..
(a) file 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
(c) program
(d) Windows
13. .. is a static or shared operations class and not a class for objects.
(a) File
(b) Class
(c) Object
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
(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
12.5 Keywords
Notes
8. What is flush?
299
Notes
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)
http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/src/
GHC-IO-Handle-Types.html#Handle
300
Notes
CONTENTS
Objectives
Introduction
13.1 Accessing Database with ADO.NET
Objectives
After studying this unit, you will be able to:
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.
301
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
302
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
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.
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
303
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
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
The latest version ADO.NET Entity Framework is 4.3.1, which was released
on February 29, 2012.
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.
305
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.
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.
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.
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.
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.
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
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
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.
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 ();
}
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
dog
You must connect the Edit link to an event handler that selects the row
containing the link for editing.
307
Notes
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.
int ID = (int)
ItemIndex];
datagrid.DataKeys
[(int)
e.Item.
name
\,
//catch (Exception e)
308
//{
Notes
//Response. Write(e.Message);
//Response. End ();
//}
finally
{
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
309
Notes
record. Create a SQL statement to delete the record, and then call OLEDBCommand.
ExecuteNonQuery to update the database.
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.
310
Create a database command that represents the SQL INSERT statement to execute.
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
%>
<%@
Import
<%
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
%>
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
<%
Source=c:authors.mdb )
myConnection.Open()
311
Notes
( Simpson ), myConnection )
myCommand.ExecuteNonQuery()
myConnection.Close()
%>
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).
(b) False
(b) False
(b) high-volume
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
(d) ADO.NET
312
To execute a DELETE command from within an ASP.NET page, you must complete the
following steps:
Notes
<%
my Connection
uid=sa;
New
SqlConnection
(server=localhost;
pwd=secret; database=myDataPubs)
myConnection.Open ()
%>
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
<%
Source=c:\authors.mdb )
myConnection.Open()
313
Notes
myCommand.ExecuteNonQuery()
myConnection.Close()
%>
Record Deleted!
Noticethat you must use DELETE FROM rather than just DELETE when working with
314
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
<%
myConnection.Open()
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
315
Notes
<%
Source=c:\authors.mdb )
myConnection.Open ()
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
<%
New
SqlConnection
(server=localhost;
pwd=secret; database=myDataPubs)
myConnection.Open ()
myConnection.Close
%>
Write a program to connect and disconnect database from the SQL Server.
For (; ;);
Meke sure
316
Notes
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
317
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
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.
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.
Contact management
Investment tracking
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:
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...
319
Notes
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.
(b) database
7. You can use the Property Builder to add a Delete column to the
(a) XML
(b) ADO.NET
(b) OLEDB
(b) ADO.NET
(c) ASP.NET
10. The OLEDB Connection object handles the connection to the engine
(a) BLOB
(c) ASP.NET
(b) database
320
(a) None
(b) database
(c) DataGrid
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
15. At this point, the UPDATE statement is to SQL Server and executed.
(a) Transmitted
(b) ADO.NET
(c) DataGrid
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.
321
Notes
5. What is XML?
6. What is the full form of ADO?
7. What are the two fundamental objects in ADO.NET?
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)
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
Notes
CONTENTS
Objectives
Introduction
14.1 Representation of the XML
14.4 Summary
14.5 Keywords
14.6 Review Questions
14.7 Further Reading
Objectives
After studying this unit, you will be able to:
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
323
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:
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 documents must be well-formed according to a defined syntax, and may be formally
validated
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.
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
Notes
<Note>
<to>satya</to>
<from>prakash</from>
<heading>Fine</heading>
</note>
325
Notes
Numeric types
Time types
XML types
String types
326
Notes
Type
Examples
xsd:float
xsd:double
xsd:decimal
xsd:integer
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
-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
xsd:byte
327
Notes
xsd:nonNegative
Integer
xsd:unsignedLong
xsd:unsignedInt
xsd:unsignedShort
xsd:unsignedByte
xsd:positiveInteger
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
xsd:time
xsd:gDay
xsd:gMonth
xsd:gYear
A given year
xsd:gYearMonth
xsd:gMonthDay
xsd:duration
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
Type
Examples
xsd:ID
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
xsd:IDREFS
xsd:ENTITIES
xsd:NMTOKEN
xsd:language
xsd:Name
xsd:QName
a prefixed name
song:title, math:set,
xsd:element
xsd:NCName
329
Notes
Type:
Examples:
xsd:string
xsd:normalized
String
xsd:token
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
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.
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.
331
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:
332
Notes
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.
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.
Student ID - Unique identifier (e.g. birth date, platform ID, registration number for platform,
random no) (e.g. 62.03.06.03.134213.392832)
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
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).
333
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:
XML schema are good for describing the data types used by an XML document
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.
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:
Ratings.
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
335
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.
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:
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
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
Printing support
337
Notes
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
(a) HTML
(b) XHTML
(c) VML
(d) SGML
True or False
5. The XML column method not works well for archiving documents.
(a) True
(b) False
338
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
data
source
XmlReader
Features
There is a core set of features in XML support:
XML declarations
Elements
Attributes
Namespaces
Attribute prefixes
339
Notes
CDATA blocks
Inner text
Processing instructions
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
Text Type
Comment Type
Whitespace 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
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:
automatic validation
341
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()
Do While (reader.Read())
Console.Write(< + reader.Name)
While reader.MoveToNextAttribute()
Display attribute name and value.
Console.Write( {0}={1}, reader.Name, reader.Value)
End While
End If
Console.WriteLine(>)
Console.WriteLine(reader.Value)
Console.Write(</ + reader.Name)
Console.WriteLine(>)
End Select
Loop
Console.ReadLine()
342
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
343
Notes
</title>
<author>
<name>
Plato
</name>
</author>
<price>
9.99
</price>
</book>
</bookstore>
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
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.
Closes all the open tags with one simple command. (Stack to keep track of all the open
tags.)
Notes
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
345
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:
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.
346
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 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 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.
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
347
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
Notes
349
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.
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.
XML namespaces are problematic to use and namespace support can be difficult to correctly
implement in an XML parser.
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.
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...
351
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
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?
6. What is XML?
(a) Elements may have multiple attribute with the same name.
353
Notes
(a) control
(b) description
(c) data
11. With DTD, each of our XML files can carry a ........... of its own format with it.
(a) data
(b) control
(c) description
(a) DTD
(b) XML
(c) XSL
(d) XSLT
13. Which statements are true? All XML documents must have:
(a) DTD
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
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?
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)
355
Notes
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