Professional Documents
Culture Documents
NET NOTES
PREPARED BY
MRS.S.JASMINE PONMARY
2
SYLLABUS
UNIT I
VB.NET 2005 Training: The .NET Framework Architecture Part
2-Introducing Windows Forms- Implementing Class Library Object in
VB.NET 2005 -Introduction and Implementing Inheritance in VB.NET
2005- Visual Studio.NET Namespaces.
UNIT II
Windows Designing a Form using Forms Designer Window-Exploring
the Forms Designer generated code-Using Application Class and
Message Class-Setting and Adding Properties to a Windows Form -
Event Handling
In Visual Basic .NET 2005.
UNIT III
Building graphical interface elements-Adding Controls -Common
Controls and Handling Control Events-Dialog Boxes in Visual Basic
.NET 2005 -Common Windows Forms Controls
Section-DomainUpDown and NumericUpDown -Creating Menu and
Menu Items-Creating Multiple-Document Interface (MDI) Applications
Validation-Exceptions.
UNIT IV
Creating and Managing Components Section-Creating and Managing
.NET Assemblies-Simple Data Binding-Complex Data Binding-Using
the Data Form Wizard-Access and Manipulate Data - The ADO .NET
Object Model-Access and Manipulate Data - Using DataSets-Using
XML Data.
UNIT V
Finding and Sorting Data in DataSets-Editing Data With ADO .NET-Web
Services - SOAP, WSDL, Disco and UDDI-Instantiating - Invoking Web
Services, Creating Proxy Classes with WSDL-Creating Web Service
Project.
.Net framework has been built in a way that makes it easy for programmers to
build new features into their programs. It has also been built in a way that
makes it easy to extend the program with new features.
console. It’s possible to run any other programming language from the
CLI with the help of a package.
Visual Basic Form is the container for all the controls that make up the user
interface. Every window you see in a running visual basic application is a form, thus
the terms form and window describe the same entity. Visual Studio creates a
default form for you when you create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will
be buttons to close, maximize and minimize the form shown below
12
If you click the icon on the top left corner, it opens the control menu, which
contains the various commands to control the form like to move control from one
place to another place, to maximize or minimize the form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These
properties can be set or read during application execution. You can refer to
Microsoft documentation for a complete list of properties associated with a Form
control −
S.N Properties Description
Form Methods
The following are some of the commonly used methods of the Form class. You can
refer to Microsoft documentation for a complete list of methods associated with
forms control −
Sr.No. Method Name & Description
1 Activate
Activates the form and gives it focus.
2 ActivateMdiChild
Activates the MDI child of a form.
3 AddOwnedForm
Adds an owned form to this form.
4 BringToFront
Brings the control to the front of the z-order.
5 CenterToParent
Centers the position of the form within the bounds of the parent
form.
6 CenterToScreen
Centers the form on the current screen.
7 Close
Closes the form.
8 Contains
Retrieves a value indicating whether the specified control is a child
of the control.
9 Focus
Sets input focus to the control.
17
10 Hide
Conceals the control from the user.
11 Refresh
Forces the control to invalidate its client area and immediately
redraw itself and any child controls.
12 Scale(SizeF)
Scales the control and all child controls by the specified scaling
factor.
13 ScaleControl
Scales the location, size, padding, and margin of a control.
14 ScaleCore
Performs scaling of the form.
15 Select
Activates the control.
16 SendToBack
Sends the control to the back of the z-order.
17 SetAutoScrollMargin
Sets the size of the auto-scroll margins.
18 SetDesktopBounds
Sets the bounds of the form in desktop coordinates.
19 SetDesktopLocation
Sets the location of the form in desktop coordinates.
20 SetDisplayRectLocation
Positions the display window to the specified value.
21 Show
Displays the control to the user.
22 ShowDialog
Shows the form as a modal dialog box.
Form Events
Following table lists down various important events related to a form. You can refer
to Microsoft documentation for a complete list of events associated with forms
control −
Sr.No. Event Description
18
Class: Classical Object Oriented Concepts explain a class as a cookie cutter. A class allows
you to create objects of the class. As a programmer you define a class with data fields,
properties, methods and events. Then you can create objects based on that class that have
state (fields, properties) and behavior (methods, events). A class can be considered as a
specification of how the object of the class should look like and behave.
Creating a Class Library project
1. On the File menu, select New Project.
2. On the Templates pane, in the New Project dialog box, click Class Library.
3. In the Name box, type DemoClass1 and then click OK.
4. A new Class Library project opens, and the Code Editor displays the Class module
Class1.vb.
5. In the Solution Explorer, right-click Class1.vb and select Rename, and then change the
name to DemoClass1.vb.
6. Note that the name in the Code Editor also changed to DemoClass.vb.
7. On the File menu, select Save All.
8. In the Save Project dialog box, click Save.
class library defines types and methods that are called by an application. If the library
targets .NET Standard 2.0, it can be called by any .NET implementation (including .NET
Framework) that supports .NET Standard 2.0. If the library targets .NET 8, it can be
called by any application that targets .NET 8. This tutorial shows how to target .NET 8.
Create a class library project
1. Add a new .NET class library project named "StringLibrary" to the solution.
a. Right-click on the solution in Solution Explorer and select Add >
New Project.
21
b. On the Add a new project page, enter library in the search box.
Choose C# or Visual Basic from the Language list, and then
choose All platforms from the Platform list. Choose the Class
Library template, and then choose Next.
c. On the Configure your new project page, enter StringLibrary in the
Project name box, and then choose Next.
d. On the Additional information page, select .NET 8 (Preview), and
then choose Create.
2. Check to make sure that the library targets the correct version of .NET.
Right-click on the library project in Solution Explorer, and then select
Properties. The Target Framework text box shows that the project targets
.NET 7.0.
3. If you're using Visual Basic, clear the text in the Root namespace text box.
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class. Base & Derived
Classes: A class can be derived from more than one class or interface, which
means that it can inherit data and functions from multiple base classes or
interfaces.
The concept of inheritance is a common feature of an object-oriented
programming language. Inheritance allows a programmer to define a general
class, and then later define more specific classes that share or inherit all of the
properties of the more general class. This allows the programmer to save time
and energy that might otherwise be spent writing duplicate code. Related to
inheritance is the concept of polymorphism. Polymorphism allows us to define
different methods with the same name, but have those methods do different
things with different objects. This is related to method overloading, but as we will
see is different in that the position of the object in the inheritance hierarchy
determines what method gets invoked.
Visual studio.net namespaces.
All namespaces in your project are based on the root namespace for the
project. Visual Studio assigns your project name as the default root
namespace for all code in your project. For example, if your project is
named ConsoleApplication1 , its programming elements belong to the
namespace ConsoleApplication1.
Namespaces organize the objects defined in an assembly. Assemblies can contain
multiple namespaces, which can in turn contain other namespaces. Namespaces
prevent ambiguity and simplify references when using large groups of objects such as
class libraries.
For example, the .NET Framework defines the ListBox class in the
System.Windows.Forms namespace. The following code fragment shows how to
declare a variable using the fully qualified name for this class:
Dim LBox As System.Windows.Forms.ListBox
Avoiding Name Collisions
.NET Framework namespaces address a problem sometimes called namespace
pollution, in which the developer of a class library is hampered by the use of similar
names in another library. These conflicts with existing components are sometimes
called name collisions.
For example, if you create a new class named ListBox, you can use it inside your
project without qualification. However, if you want to use the .NET Framework ListBox
class in the same project, you must use a fully qualified reference to make the reference
unique. If the reference is not unique, Visual Basic produces an error stating that the
name is ambiguous. The following code example demonstrates how to declare these
objects:
' Define a new object based on your ListBox class.
Dim LBC As New ListBox
' Define a new Windows.Forms ListBox control.
23
By default, every executable file you create with Visual Basic contains a
namespace with the same name as your project. For example, if you define an
object within a project named ListBoxProject, the executable file
ListBoxProject.exe contains a namespace called ListBoxProject.
Multiple assemblies can use the same namespace. Visual Basic treats them as a
single set of names. For example, you can define classes for a namespace called
SomeNameSpace in an assembly named Assemb1, and define additional classes for
the same namespace from an assembly named Assemb2.
Fully Qualified Names
Fully qualified names are object references that are prefixed with the name of the
namespace in which the object is defined. You can use objects defined in other
projects if you create a reference to the class (by choosing Add Reference from
the Project menu) and then use the fully qualified name for the object in your
code. The following code fragment shows how to use the fully qualified name for
an object from another project's namespace.
Fully qualified names prevent naming conflicts because they make it possible for
the compiler to determine which object is being used. However, the names
themselves can get long and cumbersome. To get around this, you can use the
Imports statement to define an alias—an abbreviated name you can use in place
of a fully qualified name. For example, the following code example creates aliases
for two fully qualified names, and uses these aliases to define two objects.
Imports LBControl = System.Windows.Forms.ListBox
Imports MyListBox = ListBoxProject.Form1.ListBox
If you use the Imports statement without an alias, you can use all the names in that
namespace without qualification, provided they are unique to the project. If your project
contains Imports statements for namespaces that contain items with the same name,
you must fully qualify that name when you use it.
Namespace Level Statements
Within a namespace, you can define items such as modules, interfaces, classes,
delegates, enumerations, structures, and other namespaces. You cannot define items
such as properties, procedures, variables and events at the namespace level. These
items must be declared within containers such as modules, structures, or classes.
Global Keyword in Fully Qualified Names
If you have defined a nested hierarchy of namespaces, code inside that hierarchy might
be blocked from accessing the System namespace of the .NET Framework. The
following example illustrates a hierarchy in which the SpecialSpace.System namespace
blocks access to System.
24
Namespace SpecialSpace
Namespace System
Class abc
Function getValue() As System.Int32
Dim n As System.Int32
Return n
End Function
End Class
End Namespace
End Namespace
25
UNIT II
Windows Designing a Form using Forms Designer Window
The Windows Forms Designer provides many tools for building Windows Forms
applications. This article illustrates how to build an app by using the various tools
provided by the designer, including the following tasks:
● Arrange controls by using snaplines.
● Accomplish designer tasks by using smart tags.
● Set margins and padding for controls.
● Arrange controls by using a TableLayoutPanel control.
● Partition your control’s layout by using a SplitContainer control.
● Navigate your layout with the Document Outline window.
● Position controls with the size and location information display.
● Set property values by using the Properties window.
When you're finished, you'll have a custom control that's been assembled by using
many of the layout features available in the Windows Forms Designer. This control
implements the user interface (UI) for a simple calculator. The following image shows
the general layout of the calculator control:
17. Select Add until five rows are displayed. Select all five rows, and the select
Percent in the Size Type box. Set the Percent value to 20. This action sets
each row to the same height.
18. Select OK to accept your changes, and then select the smart tag glyph to close
the smart tag panel.
19. In the Properties window, change the value of the Dock property to Fill.
Populate the control
Now that the layout of the control is set up, you can populate the DemoCalculator
control with buttons and a display.
1. In the Toolbox, select the TextBox control icon.
A TextBox control is placed in the first cell of the TableLayoutPanel control.
2. In the Properties window, change the value of the TextBox control's
ColumnSpan property to 5.
The TextBox control moves to a position that is centered in its row.
3. Change the value of the TextBox control's Anchor property to Left, Right.
The TextBox control expands horizontally to span all five columns.
4. Change the value of the TextBox control's TextAlign property to Right.
5. In the Properties window, expand the Font property node. Set Size to 14,
and set Bold to true for the TextBox control.
6. Select the TableLayoutPanel control.
7. In the Toolbox, select the Button icon.
A Button control is placed in the next open cell of the TableLayoutPanel
control.
8. In Toolbox, select the Button icon four more times to populate the second
row of the TableLayoutPanel control.
9. Select all five Button controls by selecting them while holding down the
Shift key. Press Ctrl+C to copy the Button controls to the clipboard.
10. Press Ctrl+V three times to paste copies of the Button controls into the
remaining rows of the TableLayoutPanel control.
11. Select all 20 Button controls by selecting them while holding down the Shift
key.
12. In the Properties window, change the value of the Dock property to Fill.
All the Button controls dock to fill their containing cells.
13. In the Properties window, expand the Margin property node. Set the value of
All to 5.
All the Button controls are sized smaller to create a larger margin between
them.
14. Select button10 and button20, and then press Delete to remove them from
the layout.
15. Select button5 and button15, and then change the value of their RowSpan
property to 2. These buttons represent the Clear and = buttons for the
DemoCalculator control.
Use the Document Outline window
When your control or form is populated with several controls, you may find it easier to
navigate your layout with the Document Outline window.
28
1. On the menu bar, choose View > Other Windows > Document Outline.
The Document Outline window shows a tree view of the DemoCalculator
control and its constituent controls. Container controls like the
SplitContainer show their child controls as subnodes in the tree. You can
also rename controls in place by using the Document Outline window.
2. In the Document Outline window, right-click button1, and then select
Rename. Change its name to sevenButton.
Implement event handlers
The buttons on the DemoCalculator control have event handlers that can be used to
implement much of the calculator logic. The Windows Forms Designer enables you to
implement the stubs of all the event handlers for all the buttons with one selection.
1. On the designer surface, select all the Button controls by selecting them
while holding down the Shift key.
2. Select one of the Button controls.
The Code Editor opens to the event handlers generated by the designer.
Test the control
Because the DemoCalculator control inherits from the UserControl class, you can test
its behavior with the UserControl Test Container. For more information, see How to: Test
the run-time behavior of a UserControl.
1. Press F5 to build and run the DemoCalculator control in the UserControl
TestContainer.
2. Select the border between the SplitContainer panels and drag it left and
right. The TableLayoutPanel and all its child controls resize themselves to fit
in the available space.
3. When you're finished testing the control, select Close.
Use the control on a form
The DemoCalculator control can be used in other composite controls or on a form. The
following procedure describes how to use it.
Create the project
The first step is to create the application project. You'll use this project to build the
application that shows your custom control.
1. Create a new Windows Forms Application project and name it
DemoCalculatorTest.
2. In Solution Explorer, right-click the DemoCalculatorTest project, and then
select Add > Project Reference to open the Reference Manager dialog box.
3. Go to the Projects tab, and then select the DemoCalculatorLib project to
add the reference to the test project.
4. In Solution Explorer, right-click DemoCalculatorTest, and then select Set as
StartUp Project.
5. In the Windows Forms Designer, increase the size of the form to about 700
x 500.
Use the control in the form's layout
To use the DemoCalculator control in an application, you need to place it on a form.
1. In Toolbox, expand the DemoCalculatorLib Components node.
29
2. Drag the DemoCalculator control from Toolbox onto your form. Move the
control to the upper-left corner of the form. When the control is close to
the form's borders, snap lines appear. Snap Lines indicate the distance of
the form's Padding property and the control's Margin property. Position the
control at the location indicated by the snaplines.
Drag a Button control from Toolbox and drop it onto the form.
3. Move the Button control around the DemoCalculator control and observe
where the snaplines appear. You can align your controls precisely and
easily by using this feature. Delete the Button control when you're finished.
4. Right-click the DemoCalculator control, and then select Properties.
5. Change the value of the Dock property to Fill.
6. Select the form, and then expand the Padding property node. Change the
value of All to 20.
The size of the DemoCalculator control is reduced to accommodate the
new Padding value of the form.
7. Resize the form by dragging the various sizing handles to different
positions. Observe how the DemoCalculator control is resized to fit.
InitializeComponent: This method helps to persist the property values that you have set in
the Designer.The .NET Framework security system determines whether such requests are
honored. Requests are honored after verifying the code’s evidence and only relevant requests
are granted those permissions. The permission given to the code never exceeds the current
security settings. However, code will be granted less permission based upon a request.
The identity of the code forms the basis for granting the runtime permissions, also the level of
trust the code is granted is determined by the security policy.Code can demand that its callers
have specific permissions. If you place a demand for certain permission on your code, all code
that uses your code must have that permission to run.
There are three kinds of permissions, each with a specific purpose
● Code access permissions, which represent access to a protected resource or the ability
to perform a protected operation.
● Identity permissions, which indicate that code has credentials that support a particular
kind of identity.
● Role-based security permissions, which provide a mechanism for discovering whether a
user has a particular identity or is a member of a specified role. Thus a very robust and
well managed security is provided in the .NET Framework.
In Visual Basic .NET 2005
Discover some of the new features in Visual Basic.NET 2005 such as partial classes, generics,
operator overloading and using block
New features in Visual Basic.NET 2005
build on platform’s power and efficiency
Although Microsoft.NET languages have more or less the same facilities and power, one must
be aware of the syntax and capabilities of a language to take full advantage of it. This article
introduces new features of the upcoming Visual Basic.NET language that is part of Visual
Studio.NET 2005.
Visual Basic is one of the most popular languages used in the software development industry.
Its popularity comes from simplicity and efficiency. The new version of Visual Basic.NET builds
upon these attributes and introduces the following useful new features:
● my namespace
● partial classes
● generics
● operator overloading
● using block
My namespace
The My namespace feature includes functions and properties to do a lot of complex things in a
rapid manner. Think of this as shortcut syntax to get things done with less code. It groups
commonly required information and functionalities for easier access. The examples below show
how My namespace retrieves the current culture of the application compared to VB.NET 2003:
VB.NET 2003 Code:
stem.Threading.Thread.CurrentThread.CurrentCulture
VB.NET 2005 Code:
.Application.CurrentCulture
Even actions such as accessing various properties of the computer can be done easily and
quickly with My namespace. The following code, for example, will return a boolean indicating
the availability of the network:
.Computer.Network.IsAvailable
Partial classes
31
Partial classes define a class in multiple files. This separation is useful when you want to
have functionality of a class coded with different concerns and using inheritance might not
be appropriate.
Partial classes are used in Visual Studio.NET 2005 for auto-generated code. When you create a
windows form, for example, the Visual Studio.NET 2005 IDE creates a lot of auto-generated
code. In previous versions, this code is wrapped in regions in the same source file as
event-handling code. In Visual Studio.NET 2005, auto-generated code is separated from
event-handling code by defining it in a separate source file as a partial class. Here’s an example
of how a partial class can be defined:
rtial Public Class PersonPrivate pName As StringPrivate pAge As IntegerEnd Class
The above definition defines a class with the keyword “Partial” indicating that the definition of
the class is split into multiple source files.
rtial Public Class PersonPublic Property Name() As StringGetReturn Me.pNameEnd
tSet(ByVal value As String)Me.pName = valueEnd SetEnd PropertyPublic Property Age() As
egerGetReturn Me.pAgeEnd GetSet(ByVal value As Integer)Me.pAge = valueEnd SetEnd
opertyEnd Class
Now we are providing more definition of our Person class in a separate source file, providing
properties to expose our private fields.
Partial class can also be used to make your datasets more intelligent. The typed datasets you
create in Visual Studio.NET have the partial class definition for the generated source. This
enables you to add value to your typed dataset by providing functionality such as business logic
by defining a partial class definition for the generated class.
Generics
Generics enable your program to adapt itself to different types. The concept of generics is used
in the implementation of collections in the new framework. Let’s define a simple customer class
as follows:
Public Class CustomerPrivate name As StringSub New(ByVal value As String)Me.name =
ueEnd SubEnd Class
If we want to manipulate a collection of customer objects, a typical implementation in VB.NET
2003 would be:
Dim col As New Collections.ArrayListcol.Add(New Customer("John"))col.Add(New
stomer("Smith"))col.Add("A String")
The problem with this implementation is even though you wanted your collection to only handle
customers, there is no way of enforcing this. To restrict your collection to handle only
customers, you will need to implement a custom collection class by extending the facilities
provided by the collection framework. But what if you want to implement different collections to
handle different types of objects? You might end up with a lot of custom collections to handle
different types of objects even though the functionality you require from these collections is the
same.
32
This is where generics come in. They give you a way to implement a placeholder for the type
and then specify what the type is. An ideal solution to the previous problem would be to
provide the implementation of the collection with the type of the collection as a variable; when
creating a collection we would specify what the collection should manipulate. That’s exactly the
functionality of the collections provided by the System.Collections.Generic namespace in Visual
Basic.NET 2005:If you try to add a string or anything other than customer objects, the compiler
will detect it as a syntax error. You can also define your own generic functionality to program to
types that are not known in advance or to enable your program to work with multiple types.The
above class is defined by using the variable “T” as a placeholder. When you create an instance
of GenericClass you replace the placeholder type with a real type. Once we do this, our Accept
method will accept only arguments of the real type defined while instantiating GenericClass. For
example:Operator overloading
Operator overloading enables you to specify what operators such as + or – should do when
invoked with objects of classes you define. For example :
Dim val As New Boxval.Area = value1.Area + value2.Areaval.Weight = value1.Weight +
ue2.WeightReturn val
The above class definition is a simple box with an area and weight as properties. We wanted to
provide functionality to add two box objects and return a box with the area and weight as the
total of added boxes. We have overloaded the meaning of the + operator to work with Box
objects by defining how it should work. We could have defined a new method with a name to
achieve this, but using operators for similar operations makes the code more readable and easy
to use. To add two box objects, we simply use the + operator in a way similar to adding two
numbers:
m b As Box = New Box(12, 32) + New Box(15, 19)
Using block
Some objects you create are very resource intensive. So a good practice is to release the
resource as soon as you are finished with it. Generally when you create an object inside a
method, the object will not be released until the method terminates. But what if you want an
easy way to define an object as well as specify the scope of it inside a method? The using block
helps you to achieve this:
Using con As New System.Data.SqlClient.SqlConnection'Other statements using conEnd
ng
In the above code, the scope of the defined con object will be limited within the using block and
will be released as soon as it exits that block.
Rich and rapid
Visual Basic.NET is one of the popular languages in the .NET platform and future versions are
making it richer without losing the rapid development approach for which it’s renowned. This
article should help users take immediate advantage of new features that will be an integral part
of Visual Studio.NET 2005 and the Microsoft.NET 2.0 platform.
33
Message Class
Encapsulation:
The Message class uses encapsulation to bundle the properties (Sender, Recipient, Subject,
Body) together.
The properties are declared as Public to allow access from outside the class. You can choose to
make them private and provide public methods to access or modify them if you want stricter
encapsulation.
Constructors:
The class has two constructors: a default constructor with no parameters and a parameterized
constructor that allows you to initialize the properties during object creation.
Constructors are used to set initial values for the properties of the class.
Initialization:
The properties can be set individually after creating an instance of the class or during the object
creation using the constructor.
Usage:
You can create instances of the Message class and set their properties to represent different
messages.
The provided example in the Module1 demonstrates creating instances of the Message class,
setting their properties, and displaying the message details.
Methods (if needed):
You can add methods to the Message class if you need specific functionality associated with
messages. For example, you might want to add a method to send the message or perform
some validation on the message content.
Access Modifiers:
In this example, properties are declared as Public. Depending on your needs, you might want to
use different access modifiers like Private, Protected, or Friend to control the visibility of
properties outside the class.
Default Values:
The default constructor doesn't set any default values for the properties. You may modify it to
set default values if needed.
ToString Method (Optional):
You might consider overriding the ToString method in the Message class to provide a
human-readable representation of the message. This can be useful for debugging or logging
purposes.
Remember that this is a basic example, and as your application grows, you might need to
enhance the Message class based on your specific requirements and best practices.
34
' Constructors
Public Sub New()
' Default constructor
End Sub
Public Sub New(sender As String, recipient As String, subject As String, body As String)
' Parameterized constructor
Me.Sender = sender
Me.Recipient = recipient
Me.Subject = subject
Me.Body = body
End Sub
End Class
Application Class
In VB.NET, an application class is typically a class that serves as the entry point for your
application. It is where you define the application's main method, which is executed
when the application starts. The application class contains the Main method, and it can
be used to set up the application, handle command-line arguments, and initiate the
application's main functionality.
The Application object provides a diverse range of functionality, including support for
multithreaded programming, access to the system registry, and support for subclassing
(intercepting messages sent to application windows). It also includes a variety of
informational functions, such as properties to retrieve the company name, to retrieve
the application’s executable path, and to retrieve the application’s name and version.
However, because all of the Application object’s members are shared, you do not
need to instantiate the Application object to access its properties and methods.
Hence, you can retrieve the executable path of your application, for instance, with the
code fragment:
Application class members marked with a plus sign (+) are discussed in detail in their
own entries.
Public Properties
AllowQuit
CommonAppDataPath
CommonAppDataRegistry
CompanyName +
CurrentCulture
CurrentInputLanguage
ExecutablePath +
LocalUserAppDataPath
MessageLoop
ProductName +
ProductVersion +
SafeTopLevelCaptionFormat
StartupPath
UserAppDataPath
36
UserAppDataRegistry
AddMessageFilter
DoEvents +
Exit
ExitThread
OleRequired
OnThreadException
RemoveMessageFilter
Run
ApplicationExit
Idle
ThreadException
ThreadExit
Imports System.Collections.Generic
End Function
End Class
UNIT III
Building graphical interface elements
Graphics handling in Visual Basic .NET is based on GDI+ (Graphics Device Interface). A graphics
device interface allows you to display graphics on a screen or a printer without having to handle
the details of a specific display device. All that you need to do is to make calls to methods
supported by the GDI+ classes and those methods make the corresponding calls to individual
device drivers as needed to handle the screen or printer.
To create a graphics object
Receive a reference to a graphics object as part of the System.Windows.Forms.PaintEventArgs
in the System.Windows.Forms.Control.Paint event of a form or control. This is usually how you
obtain a reference to a graphics object when creating painting code for a control.
Call the System.Windows.Forms.Control.CreateGraphics method of a control or form to obtain a
reference to a System.Drawing.Graphics object that represents the drawing surface of that
control or form. Use this method if you want to draw on a form or control that already exists.
Create a System.Drawing.Graphics object from any object that inherits from
System.Drawing.Image. This approach is useful when you want to alter an already existing
image.
Suppose you want to work with a coordinate system that has its origin in the body of the
client area rather than the upper-left corner. Say, for example, that you want the origin to be
100 pixels from the left edge of the client area and 50 pixels from the top of the client area. The
following illustration shows such a coordinate system.
When you make the call myGraphics.DrawLine(myPen, 0, 0, 160, 80), you get the line shown in
the following illustration.
The coordinates of the endpoints of your line in the three coordinate spaces are as follows:
World
(0, 0) to (160, 80)
Page
(100, 50) to (260, 130)
Device
(100, 50) to (260, 130)
The code snippet to draw the line shown in the above picture is given below:
myGraphics.TranslateTransform(100, 50)
Drawing text on a Form can be achieved by the following method. You can use the
System.Drawing.Graphics.Drawstring method of the System.Drawing.Graphics class to draw
text. This example will be using the System.Windows.Forms.PaintEventArgs e, which is a
parameter of System.Windows.Forms.PaintEventHandler. Let us see a demo for this task. In a
new project add the following codes:
You have to add a button and set the value for the text property to “Exit”.
We declare a variable myText and assign it a value also. We also declare a fontFamily as an
object of type FontFamily Which sets the name for the font family. We also declare a font object
of the type Font and set values for its properties like FontFamily, Size, Style and Graphics Unit.
This defines the visual properties of the Font that we want to display. The DrawString method
which takes four parameters is used to draw Text. Here you can choose the type of brush by
declaring your own brush. The output is given below for the above project.
Adding Controls
Most forms are designed by adding controls to the surface of the form to define a user
interface (UI). A control is a component on a form used to display information or accept
user input.
The primary way a control is added to a form is through the Visual Studio Designer, but
you can also manage the controls on a form at run time through code.
Add with Designer
Visual Studio uses the Forms Designer to design forms. There is a Controls pane which
lists all the controls available to your app. You can add controls from the pane in two
ways:
Add the control by double-clicking
When a control is double-clicked, it is automatically added to the current open form with
default settings.
41
we will be learning how to use common control like Control Hierarchy, Label and LinkLabel,
TextBox and RichTextBox, PictureBox, GroupBox and Panel, Button, CheckBox and
RadioButton, ListBox, CheckedListBox and ComboBox, DomainUpDown and NumericUpDown,
MonthCalendar and DateTimePicker, TreeView and ListView, Timer, TrackBar and ProgressBar,
HScrollBar, VScrollBar, TabControl and Handling Control Events.All controls are governed by the
Control Class “System.Windows.Forms” Namespace. This class handles the entire basic
window handle (HWND) functionality such as the creation and destruction of window handles.
When Control and Rich Control are integrated VB.NET provides for greater functionality.A
number of properties are shared by all controls in a class. Any change in such shared properties
impacts on all controls in the class. Some of the shared properties are listed below.
DefaultBackColor: Read-only. Returns what the background color of the control would be if the
background color were set explicitly
DefaultFont: Read-only. Returns what the font of the control would be if the font were set
explicitly
DefaultForeColor: Read-only. Returns what the foreground color of the control would be if the
foreground color is changed.
Public Shared Properties
Public shared properties are distinct from properties that are shared by controls
of a class in that the value of the property is not shared across the controls in a
class. Any change in the property of a control does not result in a change in the
properties of the controls in the class. Even when two instances of an object are
created, each can have a distinct value assigned to a property. Examples of
public instance properties are listed below for your understanding.
Cursor Specifies the cursor that is displayed when the mouse pointer
moves over the control
Anchor Specifies which edges of the control are bound to the edges of its
container
Name Specifies the name of the control. This value is typically used to
refer to the control in code
TabIndex Specifies this control’s place in the tab order for all controls within
the same container
TabStop Specifies whether the control can receive focus via the tab key
Enabled Specifies whether the control is enabled. This also covers items
such as receiving focus
Execute the project by pressing F5. This example illustrates the purpose of the properties and
also the method used to assign the properties at run time. Please note that the property
TabStop is not available to all properties. For example the controls like Label and LinkLabel do
not expose this property.
Handling Control Events
Controls are used as a primary medium of handling events. Rich sets of events are specified for
controls and their nature can be easily understood by reading their names. For example OnClick,
MouseEnter, MouseLeave etc. describe the nature of the event they handle. Some of the events
and their descriptions are given below:
Event Name Description
KeyUp Occurs when a key is released while the control has focus
————
————
End Sub
The event handler takes two parameters in the above instance. The first is the sender as
System.Object and the other is the valued ‘e’ as System.EventArgs. The Sender defines the
object that has raised the event and the EventArg contains all the event specific data that the
event sender passes.
There are other types of arguments that are accepted, such as FileSystemEventArgs,
ImageClickEventArgs, KeyEventArgs and CommandEventArgs. Using the SenderObject could be
particularly useful if any action from out of a set of grouped actions is to be performed. Let us
look at an example of this.
Start a new Visual Basic Windows Application Project in the Visual Studio IDE.
Add seven buttons and four labels and rename the buttons as shown as shown in the following
screenshot.
46
Here, we have used a CommonHandler that does some action based on the output of the
various events. This is a simple code that changes the text of the labels. You can also write
complex codes using loops that perform some action based on the event of the object that has
sent the event. This facility is very useful in solving complex problems with simple solutions
quickly.
SaveFileDialog Class
The SaveFileDialog class offers you the standard window that we see while saving the file. The methods and
properties of this dialog box are given below:
perty or Method cription
erIndex ermine the index of the filter selected in the dialog box
wFullOpen cifies if the user can add custom colors to the box
Me.ColorDialog1.ShowDialog()
Label1.ForeColor = Me.ColorDialog1.Color
End Sub
Me.Close()
End Sub
End Class
Press F5 to execute the program
49
The three screenshots below illustrate how different common dialog boxes are displayed..
“Change Color” button opens the ColorDialog box. You can choose any color from the palette and click Ok.
(The codes for event handling of Ok and Cancel button in the ColorDialogBox are not given in this program.
You may however write it as shown earlier, if you want to see the impact of your program.) The next
screenshot will show the changed fore color of the label1:
The following screenshot shows the custom dialog box opened with the new text typed in the text box:
50
51
Windows Forms offers controls and components that perform a number of functions.
The following table lists the Windows Forms controls and components according to
general function. In addition, where multiple controls exist that serve the same function,
the recommended control is listed with a note regarding the control it superseded. In a
separate subsequent table, the superseded controls are listed with their recommended
replacements.
Text editing TextBox control Displays text entered at design time that can
be edited by users at run time, or changed
programmatically.
Information Label control Displays text that users cannot directly edit.
display
(read-only)
Web page WebBrowser control Enables the user to navigate Web pages
display inside your form.
Dialog ColorDialog control Displays the color picker dialog box that
boxes allows users to set the color of an interface
element.
User Help HelpProvider component Provides pop-up or online Help for controls.
Audio SoundPlayer control Plays sound files in the .wav format. Sounds
can be loaded or played asynchronously.
MainMenu MenuStrip
StatusBar StatusStrip
A visual basic NumericUpDown control is said to be a pair of a TextBox Control and the Up
Down arrows. The NumericUpDown Control generally works as a counter in which a user can
input a numeric value. It is also called a Spin box. The arrow in the NumericUpDown Control
works to increase or decrease the value. Up arrow is for increasing the value and the down
arrow is for decreasing the value. If you hold the mouse on the up arrow it will increase the value
till the maximum value in the list and then stop. Its reverse condition works with the down arrow;
the Specific range is also defined for the values. The example for the NumericUpDown Control is
the Volume control in any Music Player.
Output:-
DomainUpDown Control:-
Output:-
61
62
Let's create a MenuBar by dragging a MenuStrip control from the toolbox and dropping it to the
Windows form.
Step 1. Drag the MenuStrip control from the toolbox and drop it on to the Form.
Step 2: Once the MenuStrip is added to the form, we can set various properties of the
Menu by clicking on the MenuStrip control.
Properties Description
MenuStrip control.
63
control.
GripStyle The GripStyle property obtains or sets the visibility of the grip that
ShowItemToolTi It is used to obtain or set the value that determines if the ToolTips
DefaultSize The DefaultSize property is used to get the default horizontal and
Method Description
MenuStrip control.
64
MenuStrip control.
Events Description
MenuActivate When a user uses a menu bar control with a mouse or keyboard, a
Let's create a program to display the menu bar in the Windows form.
In this image, we have created the menu and sub-items of the menu bar in the form.
Now, we write the Shortcut keys for the File subitems, such as New -> Ctrl + N, Open ->
Ctrl + O, etc.
65
After that, we can see the subitems of the Files with their Shortcut keys, as shown
below.
Menus.vb
66
Output:
Click on the File menu that shows the multiple options related to files.
67
The MDI applications act as the parent and child relationship in a form. A parent form is a
container that contains child forms, while child forms can be multiple to display different
modules in a parent form.
1. MidParent: The MidParent property is used to set a parent form to a child form.
2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference of the current
child form.
4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms in the parent or
main form.
5. Controls: It is used to get the reference of control from the child form.
68
Let's create a program to display the multiple windows in the VB.NET Windows Forms.
Step 1: First, we have to open the Windows form and create the Menu bar with the use of
MenuStrip control, as shown below.
Step 2: After creating the Menu, add the Subitems into the Menu bar, as shown below.
69
In the above image, we have defined two Subitems, First is the Feedback Form, and the
Second is VB.NET.
Step 3: In the third step, we will create two Forms: The Child Form of the Main Form or Parent
Form.
Here, we have created the first Child Form with the name Form2.
Form2.vb
Form3.vb
6. Label2.BackColor = Color.SkyBlue
7. End Sub
8. End Class
Step 4: Now we write the programming code for the Main or Parent Form, and here is the code
for our Main Form.
MDI_form.vb
Output:
After that, click on the Menu button, it shows two sub-items of the Menu as Feedback Form and
VB.NET. We have clicked on the Feedback Form that displays the following form on the window.
72
When we click on the Menu item, it shows the following image on the screen.
73
Applications Validation
Validating user input can be quite a pain, especially if you do not know what techniques and
what namespaces are at your disposal. Because everyone has a different way of doing things,
my methods might not be 100% the same as your methods. This is why I decided to make use
of Regular Expressions here within this article. Today you will learn how to use regular
Expressions to validate user input.
In simple terms, validation refers to ensuring entered data is well valid. Determining whether or
not data is valid can sometimes be a painstaking process as there are numerous tests that need
to be thought of. These tests include:
1. Format test – This test determines if the entered string is in the correct format.
2. Type test – This test checks if the input is the correct type. For example: Integers of
dates that do not need conversion afterwards.
74
3. Permitted Character test – This test ensures that no illegal characters are
entered. For example: If a user is supposed to enter a name, numbers and some
special symbols must not be allowed.
4. Range test – This tests checks to see if entered values are within a specified range.
For example : If you are only supposed to type in 50 characters, you must not be able
to enter more than fifty.
Field-level validation means validating each field as it receives focus. Form-level validation is the
process where you validate all data on a form before the form is submitted.
Exceptions
An exception is a problem that arises during the execution of a program. An
exception is a response to an exceptional circumstance that arises while a program
is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another.
VB.Net exception handling is built upon four keywords - Try, Catch, Finally and
Throw.
Try − A Try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more Catch blocks.
Catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem. The Catch
keyword indicates the catching of an exception.
Finally − The Finally block is used to execute a given set of statements,
whether an exception is thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is raised or not.
Throw − A program throws an exception when a problem shows up. This is
done using a Throw keyword.
Syntax
Try
75
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.
The System.SystemException class is the base class for all predefined system
exception.
The following table provides some of the predefined exception classes derived from
the Sytem.SystemException class −
Handling Exceptions
These error handling blocks are implemented using the Try, Catch and Finally
keywords. Following is an example of throwing an exception when dividing by zero
condition occurs −
Live Demo
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
You can also define your own exception. User-defined exception classes are derived
from the ApplicationException class. The following example demonstrates this −
Live Demo
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
You can use a throw statement in the catch block to throw the present object as −
Throw [ expression ]
78
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _ is
being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
UNIT IV
Creating and Managing Components Section
A component is a class that implements the System.ComponentModel.IComponent interface or
that derives directly or indirectly from a class that implements IComponent. A .NET component
is an object that is reusable, can interact with other objects, and provides control over external
resources and design-time support.
An important feature of components is that they are designable, which means that a class that
is a component can be used in the Visual Studio Integrated Development Environment. A
component can be added to the Toolbox, dragged and dropped onto a form, and manipulated on
a design surface. Base design-time support for components is built into .NET. A component
developer does not have to do any additional work to take advantage of the base design-time
functionality.
A control is similar to a component, as both are designable. However, a control provides a user
interface, while a component does not. A control must derive from one of the base control
classes: Control or Control.
If your class will be used on a design surface (such as the Windows Forms or Web Forms
Designer) but has no user interface, it should be a component and implement IComponent, or
derive from a class that directly or indirectly implements IComponent.
Component Classes
The System.ComponentModel namespace provides classes that are used to implement the
run-time and design-time behavior of components and controls. This namespace includes the
base classes and interfaces for implementing attributes and type converters, binding to data
sources, and licensing components.
● License. The abstract base class for all licenses. A license is granted to a specific
instance of a component.
● LicenseManager. Provides properties and methods to add a license to a
component and to manage a LicenseProvider.
● LicenseProvider. The abstract base class for implementing a license provider.
● LicenseProviderAttribute. Specifies the LicenseProvider class to use with a class.
Creating Components by extending the UserControl Class, Testing the Control, Creating and
implementing Events, Extending a control through Visual Inheritance and Inheriting from a
UserControl.
A component is a reusable piece of code in binary form. This code can be reused by inheritance. No
class is being inherited. It follows that a containment relationship is defined between the application
using the component and the component that is being used. This is different from the relationship
that exists between a derived class and a base class.
Components have to interact with each other. They need information about each other. This is
achieved by loading the components within self-contained packages called assembly. An assembly
contains information about the files on which the component depends and the location of these
files. The CLR can use this information to determine the dependencies of a component. The
assemblies that are required during the execution of an application are called dependencies.
A class becomes a component when it follows defined standards of interaction. These standards
are provided by the IComponent interface. All components derive from Component class. The
Component class in turn implements IComponent interface.
Open the Visual Studio IDE and select the menu File, Choose New – Project to open a new project
Dialog Box
Choose Windows Control Library from the items displayed. Type the name of the project as
InterestCalculator. Click on OK.
In the solution Explorer window, right-click UserControl1 and select View Code
82
You can also change the default name UserControl1 to any name of your choice
The class inherits from the UserControl class by default. If you need to inherit from another existing
control, edit the statement Inherits System.Windows.Forms.UserControl to refer to your class.
In the solution explorer window of the new project, right –click the Reference node. Select Add
reference to open the Add reference dialog box.
Add the project with your custom control to the selected Components section in the AddReference
DialogBox. To close the Add Reference dialog box.
In the dialog box that you have opened select the .NET Framework Component tab from the Add
Reference Dialog Box.
83
An assembly can be a single file or it may consist of multiple files. In the case of multi-file,
there is one master module containing the manifest while other assemblies exist as
non-manifest modules. A module in .NET is a subpart of a multi-file .NET assembly. Assembly is
one of the most interesting and extremely useful areas of .NET architecture along with
reflections and attributes.
Private assembly requires us to copy separately in all application folders where we want to use
that assembly’s functionalities; without copying, we cannot access the private assembly
features and power. Private assembly means every time we have one, we exclusively copy into
the BIN folder of each application folder.
Public Assembly
Public assembly is not required to copy separately into all application folders. Public assembly
is also called Shared Assembly. Only one copy is required at the system level, there is no need to
copy the assembly into the application folder.
Shared assemblies (also called strong named assemblies) are copied to a single location
(usually the Global assembly cache). For all calling assemblies within the same application, the
same copy of the shared assembly is used from its original location. Hence, shared assemblies
are not copied in the private folders of each calling assembly. Each shared assembly has a
four-part name including its face name, version, public key token, and culture information. The
public key token and version information makes it almost impossible for two different
assemblies with the same name or for two similar assemblies with a different version to mix
with each other.
When the assembly is required for more than one project or application, we need to make the
assembly with a strong name and keep it in GAC or in the Assembly folder by installing the
assembly with the GACUtil command.
Satellite Assembly
Satellite assemblies are used for deploying language and culture-specific resources for an
application.
85
Assemblies are the core building blocks of .NET applications. In simple terms, assembly is
the .dll or .exe file that is created while building any .NET application. You can find many
definitions for assembly over the internet also. In my point of view, assembly is the building
block that is created after a successful build operation of your application.
After the compilation of each project, a .exe or .dll file is generated, known as Assembly. The
name of an assembly file is the same as the project name. The assembly of a project present
under the bin\Debug folder of that project folder. After the successful build of each project, an
assembly is generated inside that folder. We can use assembly files by our requirement. We may
directly take the assembly file and install it into the client machine if it is .exe type or we can
consume the file in another project if the assembly is dll type.
Class Library and Windows Forms Control Library projects generate a .dll assembly whereas
Windows Forms Applications, Console Applications, WPF Applications, and Windows Services
projects generate a .exe assembly.
.Exe type assembly is run by their own as well as they provide support to others in their
execution process so these assemblies are known as an in-process component whereas .dll
type assembly is called as out process component because they are only developed for the
purpose to consume inside .exe type of application.
Types of Assembly:
When we build any project we find a corresponding assembly inside the bin/Debug folder; so by
default, this assembly is a private type. It's private because when we add that assembly
reference to another project then a copy of that assembly is created inside that project. Below
figure is an example of Private assembly.
86
Start a new project inside Visual studio of type Class Library and name it as “PAssembly”,we
take the class library because we can consume this project dll file inside another project. Here I
am using VS2012 for my project creation.
in this project, you find a file called Class1.cs. Now, write the following code under the class:
Now, compile the project by opening the Solution Explorer, right-clicking on the project, and
selecting “Build” or Press "Ctrl+shift+B" which will build + compile your project and generate an
assembly with the name PAssembly.dll.
Open a new project of type Windows, name it as “TestPAssembly”, place a button on the Form,
and set its text as “Call TestHello method of Class1 in PAssembly.dll”. Now, add the reference of
PAssembly.dll from its physical location and write the following code under the click of a button:
87
Run the project to test it. Then, go and verify under the bin/debug folder of the current project
where we can find a copy of PAssembly.dll as it is a private assembly.
Note: The advantage of a private assembly is faster execution because it is available in the local
folder, whereas its drawback is that multiple copies get created when multiple projects add the
reference to consuming it.
Shared Assemblies
As we saw above while consuming a private assembly it always created a copy of that file inside
the project bin/debug folder; so if we want to use that assembly in several applications then we
are required to put that assembly inside a shared folder. That shared folder in .Net is called a
Global Assembly Cache folder. We can add a number of assemblies inside that folder and
consume that assembly for any project.
A good understanding of the dataflow from the control to the datasource is very
important. The diagram below gives an overview of the dataflow and the objects
involved.
In .NET, controls can have many properties that can be bound to a DataSource.
Each databound property has an associated Binding object. Since a control can
have many Binding objects, the control has a collection (instance of
ControlBindingsCollection class) of all the Binding objects. Also remember that
different properties of the same control can be bound to different datasource's.
89
As a rule of thumb if you want your class to be a datasource, you should use
CurrencyManager when your class is a data container. However, if you are
interested in binding a control to properties exposed by your own class, then using
a PropertyManager is easier, since you do not have to implement the IList
Interface.
Since a form can contain many controls each binding to a different datasource, a
class is needed to manage the CurrencyManager and PropertyManager objects.
Therefore, each windows form in .NET has a default BindingContext object
associated with it. But, you can always create more BindingContext objects on the
form. The BindingContext object is a collection of CurrencyManager and
PropertyManager objects.
90
The form exists as Form1 in the DataFormWizSamples project. The code behind this form works
identically to the code behind the switchboard form in the preceding section, except that this
form's code references four samples instead of five. The most significant point of the samples
referenced from this switchboard is that the Data Form Wizard generated all their forms. I did
not have to code any of them. However, these forms do typical database chores in a database
form. The first sample enables data access and manipulation via text boxes. The second
sample enables data manipulation via a DataGrid control. The third sample presents two
DataGrid controls in a main/subform configuration. The fourth sample takes this main/subform
to a higher level by showing aggregated data in the sub form.
VB developers scoff at the concept of bound controls, they are very useful for quickly building a
prototype or proof-of-concept. In addition, bound controls work well to demonstrate some of the
functionality in VB.NET.
To start the DataForm Wizard, right-click the LearningVBData project node, select Add, and then
Add New Item. Double-click the DataForm Wizard icon. This starts the DataForm Wizard. The
first screen is just information, so after reading it, click the Next button.
Step 2 of the DataForm Wizard asks you to choose whether to use a new DataSet or to use one
you've already created. Because you have already created the DataSet you will be using, select
the Existing radio button. If you drop down the list, you should see only one DataSet, which is the
one you just finished creating: dsProducts. The DataSet is listed as LearningVBdata.dsProducts,
and the list of available tables is shown in the list box on the right side. Figure 6.8 shows what
your form should look like. Click the Next button after choosing your DataSet.
Step 3 of the wizard asks you what method you want to use to load the data store. Earlier, when
you added the controls and set the SQL statement, a FillDataSet method was created in
Component1. Choose the FillDataSet method for the first box.
91
If you want, you can check the Include Update Method box, but be aware that doing so enables
you to manipulate the data as you work with it, and this might not be something you want to do.
However, if this is just a test machine, feel free to check this box and then select
UpdateDataSource as the method to use to update the data store. Figure 6.9 shows what this
screen should look like when you are done. Click Next to move forward.
Finally, Step 5 asks whether you want to display all the records (which will show them in a grid)
or just a single record (which will show the record in text boxes).
If you choose the grid display, the generated form displays the DataSet in a Datagrid. A Datagrid
has the functionality to navigate, add, and remove records already built into it. Thus, choosing to
view the records in a grid removes the options for adding navigation controls, as well as buttons
for Add, Delete, and Cancel. Select the Single Record radio button and leave all the buttons
enabled, as shown in Figure 6.10. Click the Finish button to exit the wizard, have it create a form,
and work its magic.
After the form is loaded, click the Load button. This actually fills the DataSet and then
displays the first record on the form. Use the navigation buttons to walk through the records.
Figure 6.11 shows how your form should look.
button, ProductID 9 shows a UnitsInStock of 28. "Aha!" you think. "I've updated that record." And
you have. But you haven't.
ADO.NET uses a disconnected paradigm. That means that the data in the DataSet is not
connected to the underlying database in real-time. The data you have changed is in the DataSet,
and not in the SQL Server table. You can verify this by opening SQL Server's Query Analyzer and
running the following SQL statement against the Northwind database:
This disconnected mode of working is why the DataForm Wizard adds an Update button. The
Update button calls the UpdateDataSource procedure that you selected in the DataForm Wizard.
As soon as you click the Update button, the data is updated in SQL Server. Using this
disconnected model, you could make multiple inserts, updates, and deletes, and then send them
to the underlying database all at once.
Some of you might have used disconnected recordsets in ADO. If so, this sounds familiar to you.
For those of you who didn't use ADO's disconnected recordsets, this might sound strange. Just
be aware that this is the default behavior in ADO.NET.
You can also see the data in the form of a grid. Select Add New Item from the Project menu.
Double-click the DataForm Wizard icon to start the DataForm Wizard. Choose the dsProducts
DataSet that you created earlier. In the method you want to use to load the data store, pick the
FillDataSet in Component1. Select the Products table and all the fields. Finally, choose to display
All Records (grid) on Step 5 of the wizard.
VB.NET adds a DataGrid control to the form, along with a Load button. Don't start the project yet;
if you do, you will see only Form1. To see DataForm2 at startup, right-click the project in the
Solution Explorer window and choose Properties. In the Startup Object box, choose
LearningVBdata.DataForm2. Now, start the project and click the Load button.
93
The data residing in a data store or database is retrieved through the data
provider. Various components of the data provider retrieve data for the application
and update data.
Data Provider
A data provider is used for connecting to a database, executing commands and
retrieving data, storing it in a dataset, reading the retrieved data and updating the
database.
1 Connection
This component is used to set up a connection with a
data source.
2 Command
A command is a SQL statement or a stored procedure
used to retrieve, insert, delete or modify data in a data
source.
3 DataReader
Data reader is used to retrieve data from a data source in
a read-only and forward-only mode.
4 DataAdapter
This is integral to the working of ADO.Net since data is
transferred to and from a database through a data
adapter. It retrieves data from a database into a dataset
and updates the database. When changes are made to
the dataset, the changes in the database are actually
done by the data adapter.
The .Net Framework data provider for SQL Server - provides access to
Microsoft SQL Server.
The .Net Framework data provider for OLE DB - provides access to data
sources exposed by using OLE DB.
The .Net Framework data provider for ODBC - provides access to data
sources exposed by ODBC.
The .Net Framework data provider for Oracle - provides access to Oracle data
source.
The EntityClient provider - enables accessing data through Entity Data Model
(EDM) applications.
95
DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of
records that are retrieved from a database. When a connection is established with
the database, the data adapter creates a dataset and stores data in it. After the
data is retrieved and stored in a dataset, the connection with the database is
closed. This is called the 'disconnected architecture'. The dataset works as a virtual
database containing tables, rows, and columns.
The DataSet class is present in the System.Data namespace. The following table
describes all the components of DataSet −
1 DataTableCollection
It contains all the tables retrieved from the data source.
2 DataRelationCollection
It contains relationships and the links between tables in a
data set.
96
3 ExtendedProperties
It contains additional information, like the SQL statement
for retrieving data, time of retrieval, etc.
4 DataTable
It represents a table in the DataTableCollection of a
dataset. It consists of the DataRow and DataColumn
objects. The DataTable objects are case-sensitive.
5 DataRelation
It represents a relationship in the
DataRelationshipCollection of the dataset. It is used to
relate two DataTable objects to each other through the
DataColumn objects.
6 DataRowCollection
It contains all the rows in a DataTable.
7 DataView
It represents a fixed customized view of a DataTable for
sorting, filtering, searching, editing and navigation.
8 PrimaryKey
It represents the column that uniquely identifies a row in
a DataTable.
9 DataRow
It represents a row in the DataTable. The DataRow object
and its properties and methods are used to retrieve,
evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new
row and the Add method adds a row to the table.
10 DataColumnCollection
It represents all the columns in a DataTable.
11 DataColumn
It consists of the number of columns that comprise a
DataTable.
Connecting to a Database
The .Net Framework provides two types of Connection classes −
Example
We have a table stored in Microsoft SQL Server, named Customers, in a database
named testDB. Please consult the 'SQL Server' tutorial for creating databases and
database tables in SQL Server.
Select a server name and the database name in the Add Connection dialog
box.
98
Choose the database object, Customers table in our example, and click the
Finish button.
102
Select the Preview Data link to see the data in the Results grid −
When the application is run using Start button available at the Microsoft Visual
Studio toolbar, it will show the following window −
103
.NET offers numerous XML-related classes for reading and writing XML documents.
Although the documentation states that any class conforms to the W3C XML 1.0
standard, there are trade-offs in respect to performance, efficiency, productivity, and
XML compliance between the different implementations.
So we first investigated these different access methods and then selected the most
appropriate for our application. This step also addresses important issues that must be
considered when dealing with legacy valid and well-formed XML data in .NET.
The VB.NET developer can use any of the following five methods to access XML data:
● XmlTextReader
● XmlValidatingReader
● XmlDocument (and the rest of the DOM API),
● XPathNavigator.
● ADO.NET DataSets
104
The detailed description of these methods would go beyond the scope of this article.
Thus the following table summarizes very briefly the characteristics of each method and
shows when to use which technology.
When dealing with complex XML Schemas, then ADO.NET DataSet offers greatest
support and flexibility. The DataSet, which can be used either relational databases or
XML data files, is an in-memory cache of retrieved data. It is the major component for
data handling in the ADO.NET architecture.
Considering all these features and the fact that this VB.NET application will need to be
WebService interoperable with a server application in future we decided to go for
DataSet's.
Going with DataSets, ReadXML and ReadXMLSchema are the methods of choice to
read the XML data, and the corresponding XML schema.
However doing so with the given valid and well-formed XML data file, raised the
following runtime error:
"The same table {description} cannot be the child table in two nested relations".
Looking deeper into the file shows that the valid and well-formed (and thus fully W3C
compliant) XML file had a child table called "description" which had more than one
parent table. This part of the XML Schema is shown in Figure 1 .
106
This is a valid and allowed design according to the W3C XML schema specification.
(Refer: W3C definition of Parent child Relationship). Also the XMLSpy tool validated this
XML schema as valid and well-formed.
More investigation showed that the .NET XML framework does not (yet?) support the
full XML 1.0 standard. It does not support recursive schemas or designs where a child
node type is beneath more than one parent node type. Of course, also all classes based
on DataSets, like the System.Windows.Forms.DataGrid, which we were going to use,
have the same restriction. In other words:
XML Design Issue 1: ".NET Datasets require that a table can only be a child of one
other table."
Microsoft has identified this as a bug (Q325695) and their knowledge base article
[MS-Q325695] gives more information.
There are essentially three ways to solve this problem:
If you can't change the existing XML Schema (for example because you are not the
owner of the file), there are two ways to solve the problem: you customize all your ode,
or you write a converter.
Customizing all your code means you write special methods for the XmlReader class
and add records to a table with a hierarchical type design. You also have to implement a
custom filtering mechanism if you want to display this data in bound controls, and a
custom writing mechanism to write to the type of hierarchical format you are reading
from. Even worse, any change in the schema file will cause changes in all of your
The second option, if you can't change the given XML Schema, is to write a converter.
That means you define a new .NET compliant XML Schema for the given XML file and
make use of the given DataSet capabilities. Then you write a bi-directional converter to
convert the data from one XML Schema into the other before you use it. Although this
still causes additional effort, it causes the least additional effort.
If you are the owner of the XML Schema file, then the solution is to change the given
XML Schema and make it also .NET compliant. In our situation, this meant, to define
three different description type structures (Idescription, Description, Description), for the
three occurrences of the description.
To avoid multiple definitions of the same structure (which can cause maintenance errors
in the future), we made use of the inheritance capabilities of XML Schema. We derived
the three description types from the still existing base structure "description". The details
are shown in figure 2.
108
Because a typed DataSet class inherits from the base DataSet class, the typed class
assumes all of the functionality of the DataSet class and can be used with methods that
take an instance of a DataSet class as a parameter.
You can use either type of DataSet in your application. However, Visual Studio has
more tool support for typed DataSets, and they make programming with the DataSet
much easier and less error-prone. So having considered all these options the decision
was to go with ADO.NET typed DataSets.
Typed Datasets can be generated with the XSD.EXE tool, which is part of the VS.NET
environment. The tool accepts a valid XML Schema file as input, as well as the
language to use (C#, VB). The following line shows a typical command line of the tool
which uses the XML Schema file XSDSchemaFileName.xsd.
The /d directive tells the tool to generate DataSets, /l specifies the language to use, the
optional /n defines the namespace to generate. The generated DataSet classes will be
saved in the source file XSDSchemaFileName.vb.
Once the Typed DataSet classes are generated, the further procedure is almost a
child's play. The provided methods and properties guarantee data access in a type safe
manner.
So the next step was to populate the Typed DataSet at runtime from the XML file. The
ReadXml() and the WriteXml() methods of the typed DataSet class do this very easily
without any difficulty as the following to lines of code show:
myDS.ReadXml("input.xml", XmlReadMode.ReadSchema).
Having created and populated the DataSet the next step was to bind the data to the
windows controls for user interaction. Since we were going to implement a grid view,
this involved binding DataTables to DataGrids with user navigation facilities and
providing parent-child relationships in the grid view so when a user selects a parent row,
the corresponding child rows are to be shown automatically for editing purposes.
The DataTable is the primary building block of ADO.NET. The DataTable is made up of
DataColumn and DataRow collections. The columns define the schema of the
DataTable and the rows make up the actual data in the DataTable. A DataView is a
bindable, customized view of a DataTable. You can create multiple Data Views of the
same DataTable, each one can contain different data sorted in different order.
Additionally, you can add, delete, or edit information in each DataView.
DataTable and DataView use the same instances of DataColumns, i.e. they share the
common structure. However DataTable and DataView each have its own row
collections. The DataTable is consists of DataRow's while the DataView is made up
DataRowView. Figure 3 shows the relationship between DataSet, DataTable and
DataView.
The data binding of typed DataSets is very smooth in VB.NET. You can bind the data
sources to the WindowsForms controls at design time or runtime without any difficulty.
For example, you can specify which data column to be bound to a ComboBox in a
WindowsForm by setting the DataSource and DataMember property of that control so
that it gets automatically bound at runtime.
We used the .NET DataView class to bind DataTables to the DataGrid. DataView
supports data filtering and data sorting at design time or at runtime. For convenience a
default DataView is generated for the developer for customization.
In the analysis part, the application needs to display some statistical information, which
is calculated from several columns and which is shown in some dynamically generated
extra columns as shown in Figure 4 .
Some of the data columns needed for these calculations were in different parent and
child tables. Unfortunately it was not possible join two tables in the dataset to show up
in a single DataGrid.(for example, by using the DataSet.Relations property).To further
clarify the situation say I have two Parent & child tables Table1(id,columnA,columnB)
and Table2(id,columnC,columnD) and I want resulting datagrid columns to be view like
(columnA , columnB , columnC , columnD). It is similar to the situation if I had wrote a
sql query like
The other way to do it (most developers seems to suggest) is to simply create a new
datatable
That is typed the way you want it and manually moved the data from both datatables to
the new one. Also any data manipulation has to copy over to the original tables using
nested loops. This is a brute force method. It would be nice to hear if anyone comes up
with something else.
Finally more references were added to the schema file. But that is not the best
workaround. The reason that the columns could not be merged is found in the relational
programming model of the DataSets. The existing XML file uses nested child tables
instead of references. This is not (yet?) resolved by the .NET DataSets, so that
references are missing to cross-reference tables and to establish relationships.
XML Design Issue 2: "Use references in XML data files instead of nested child tables
to show up a joined table in a single DataGrid".
In our application we use the Date column as a filter criteria for the generated graphs in
the Crystal Report Engine. Thus in Figure 5 a Date column has been added to the
session table, which is a direct reference of the date column of the day table.
Having completed the data binding to Windows forms the next task was to generate the
summarized reports in both graphical and tabular forms. We have chosen the Crystal
Reports Engine (which is delivered with the VS.NET environment) with its powerful
dynamic reporting capabilities.
Crystal Reports for Visual Studio .NET offers the following three object models:
The top level Engine object model is the report document object. The report document
object offers sophisticated control over your object. It contains all the properties and
methods needed to interface with and customize a report. However it does not provide
the display of the reports.
114
This is where viewer objects and the report document objects come together. The
Windows Forms viewer allows you to view a report in a Windows application and the
Web Forms viewer does it for a Web application.
So we selected the Engine Object model together with the Windows Object Model to
accomplish the requirements. The Vb.NET CrystalDecisions.Windows.Forms
namespace in the CrystalDecisions.Windows.Forms.dll assembly provides support for
the Windows Forms Viewer control and its associated classes. It can also dynamically
update the report being hosted and interact with controls within a windows application.
When using the Crystal Report Engine you basically have two options for the selection
of data sources. The first one is passing the raw XML file, and the second is passing the
populated DataSet to the Crystal Report Engine.
When using the first approach you have to verify on every usage, that the XML file
contains correct data types (data validation). Otherwise Crystal Report Engine would
interpret the data types in the XML files differently (e.g. floats are used as strings),
which prevents the data from being processed further within Crystal Reports.
The second, recommended option is passing the already populated typed DataSets to
the Crystal Report Engine. This saves the runtime verification of data types. The content
and the scope of the report is determined at runtime according to the user selection of
the required report format. Crystal Reports provides template files for this. Figure 6
shows a sample report.
115
UNIT V
A common use for filters is to specify only the current versions of records in the data table. If records
have been changed, there are two versions of a record–the current version reflecting the change and the
original version representing the record before any changes were made. Records are also flagged
according to their status: new, unchanged, deleted, or modified. A deleted record, for example, still exists
in the data table, but its raw-state flag has been set to delete.
Sorting
Sorting is similar to filtering, in that you specify a sort expression. A typical sort expression is simply the
name of the column to sort by. For example, to sort by the OrderDate column, the user msut specify the
sort expression OrderDate. However, the user can sort by the value of any expression, including calculated
values. If table’s Select method is called, the sort expression is passed as a parameter. If DataViews are
being used, the sort expression is to be specified as the value of the view’s Sort property.
The following project will illustrate the filtering and sorting of the data.
In the same way table data can be filtered. In this case all the instructions given for the above case holds
good. The only change is in the EventHandler for the ComboBox. Instead of writing code for sorting, the
activity for filtering will be defined. The Additional lines of code for this demo is given below:
118
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ComboBox2.SelectedIndexChanged
filtStr = Me.ComboBox2.Text
Label3.Text = "The Data is Filtered for all Names starting with alphabet " & filtStr
End Sub
Now press F5 to execute the program. The screenshot given below shows the initial Screen.
The DataView provides several ways of sorting and filtering data in a DataTable:
● You can use the Sort property to specify single or multiple column sort
orders and include ASC (ascending) and DESC (descending) parameters.
● You can use the ApplyDefaultSort property to automatically create a sort
order, in ascending order, based on the primary key column or columns of
the table. ApplyDefaultSort only applies when the Sort property is a null
reference or an empty string, and when the table has a primary key defined.
● You can use the RowFilter property to specify subsets of rows based on
their column values. For details about valid expressions for the RowFilter
property, see the reference information for the Expression property of the
DataColumn class.
If you want to return the results of a particular query on the data, as
opposed to providing a dynamic view of a subset of the data, use the Find
or FindRows methods of the DataView to achieve best performance rather
than setting the RowFilter property. Setting the RowFilter property rebuilds
the index for the data, adding overhead to your application and decreasing
performance. The RowFilter property is best used in a data-bound
application where a bound control displays filtered results. The Find and
FindRows methods leverage the current index without requiring the index to
be rebuilt. For more information about the Find and FindRows methods,
see Finding Rows.
● You can use the RowStateFilter property to specify which row versions to view.
The DataView implicitly manages which row version to expose depending upon the
RowState of the underlying row. For example, if the RowStateFilter is set to
DataViewRowState.Deleted, the DataView exposes the Original row version of all
Deleted rows because there is no Current row version. You can determine which row
version of a row is being exposed by using the RowVersion property of the
DataRowView.
The following table shows the options for DataViewRowState.
DataViewRowState Description
options
None No rows.
● Discovery: First, you need to locate the Web service. You locate Web
service through the Discovery Service Protocol. The *.disco file stores
the protocol in your Visual studio (VS) .NET project. This file contains
reference to all the Web services under your Web site's virtual directory.
VS can automatically generate this file for you. The discovery file
(.vsdisco), an XML file, is used to identify searchable paths on the web
server used by the discovery process.
● Description: Once you have discovered your service, you need a way to
tell the client what methods, classes, and so on the web service has and
what wiring protocol (SOAP, HTTP, and so on) the services are using. You
do this through WSDL, an XML format. VS provides tools for generating
WSDL files automatically from your services.
121
● Wiring Protocol: Web services under .NET use two main protocols,
HTTP-post /HTTP-get and SOAP. HTTP-post and HTTP-get enable you
to send and receive information via a URL by passing and receiving
name value pair strings. Unfortunately, HTTP can only pass strings that
represent different data types. SOAP allows you to pass a richer type of
information, such as datasets.
Exploring Web Services and the .NET Framework Library
The .Net framework class library provides four namespaces that contain web service
classes. These namespaces are
System.Web.Services,System.Web.Services.Description,
System.Web.Services.Discovery, and System.Web.Services.Protocol.
The System.Web.Services namespace provides classes that enable you to build and
use web services. It has four classes. The WebService class defines the optional
base class for Web services, which provides direct access to an ASP.NET application.
Server, Session, User, and Context are some of its properties. WebMethodAttribute,
WebServiceAttribute, and WebServiceBindingAttribute are other classes of this
namespaces.
To understand Web services better, I'll show you to build a simple Web service. The
Web service will receive an order ID and then query the Northwind database's
Orders table for the correct order. It'll then return the order in a DataSet.
The first step in creating the web service is to select File > New > Project and
choose the ASP.NET Web service template, as shown in Figure 8-1.
122
This creates a Web service project on the MCB server. By default, local-host is
available as a Web server on your development machine. After the server name,
you give it a project name. In this sample, the project name is
OrderRetrievalService. VS .NET creates a new folder with the project name on the
Web server and keeps all project files under that folder. Clicking the OK button
creates the project.
If you look at the solution explorer, you'll notice a list of files created automatically
for the project, as shown in Figure 8-2. You won't be able to see some code and
resources files by default; they are hidden. You need to click on the show All Files
button of the Solution Explorer to view all the files (see Figure 8-2).
123
First, the Web.config file is an XML file containing information on how to run the
service under ASP.NET. Second, the Global.asax and Global.asax.cs files enable you
to handle application-level events for the service. These event handlers include
event-handling pairs such as Application_Start-Application_End,
Session_start-Session_End, and Begin_Request-End_Request. You can view
Global.asax.cs by right clicking on the Global.asax file in the Solution Explorer and
choosing view code. Next, OrderRetrievalServices.vsdisco is an XML file containing
information for discovery of the service. You will actually need to generate an
OrderRetrievalService.disco file for your client to see the service (more on this
later).
Finally, the Service1.asmx file serves as the entry point into the service. The code
behind the service, Service1.asmx.cs is where you will place the method for
retrieving the order. Right-click on the Service1.asmx file in the Solution Explorer
and choose View Code from the pop-up menu, as shown in Figure 8-3.
See Listing 8-1 for the Web service code. Note that it looks like any other C#
component; it has a constructor, an InitializeComponent method, and a Dispose
method.
Now I'll add database support to the Web service. Actually adding database
support to a web service is quite easy using ADO.NET. You can add ADO.NET
data components to a web service by just dragging the ADO.NET component from
the toolbox's Data tab to Web Forms. Similar to windows forms, you can also use
the Server Explorer to add database components to a Web service.
You can access different kinds of data sources in a similar fashion. The only thing
you change is the data provider and the connection string.
In this example, I'll use the Access 2000 Northwind database. I simply create a
connection and a data adapter to the Orders table in the Northwind database. You
can do this automatically through the .NET framework by simply dragging the
orders table from the server explorer onto the Service1.asmx.cs Design view, as
shown in Figure 8-4. In fact, as you can see from the figure, you can drag any
database table to the Web page.
Drag the orders table to the page. This action adds a connection, data adapter, and
four command objects as follows:
Figure 8-5 Results of dragging the orders table from the Server Explorer
If you drag the Orders table from SQL server database, the result will look like
Figure 8-6. The only difference is that SQL server uses the Sql data provider instead
of the OleDb data provider.
Figure 8-6 Results of dragging the SQL server orders table from the Server
Explorer
127
Now, the next step is to add a Web method to the project. You can use the Class
Wizard to add a method, or you can also add a method manually. For this
example, I'll use the Class Wizard to add a method.
To add a method to the project, open the class view from the main menu's View >
Class View option and right-click on the Service1 class and select Add > Add
Method, as shown in Figure 8-7.
The Add Method option opens the C# Method Wizard, which lets you add a method.
As you can see from Figure 8-8, I added a GetOrderFromDatabase method, which
returns a DataSet (type "DataSet" in the Return Type text box). This method also
takes one argument of integer type. You type the parameter name "OrderId" of
integer type and use the Add button to add the parameter. Now click Finish. This
process adds a method to the class, which looks like following:
Wait, this method is not a Web method yet. Before you write any code, you need to
add the [WebMethod] attribute at the beginning of this method to recognize it a
Web method.
Now you're going to add some code to the method. This method returns a DataSet
that will have records from the Orders table corresponding to an OrderId. Listing
8-2 shows the GetOrderFromDatabase method.
Listing 8-2. The Web Service method for obtaining an order from an
OrderId
[WebMethod]
public DataSet GetOrderFromDatabase(int OrderId)
{
DataSet ds = new DataSet("OrderSet");
oleDbDataAdapter1.SelectCommand.CommandText = "Select * from
Orders WHERE OrderID = " + OrderId.ToString();
oleDbDataAdapter1.Fill(ds, "Orders");
return ds;
}
129
As you can see from Listing 8-2, the method receives an OrderId from a client
and returns a DataSet to the client. It uses the DataAdapter to fill a DataSet with
the row containing that OrderId.
Note: You have to add a WHERE clause onto SelectCommand to filter the single
row of data. Also, you must make all exposed methods in the Web service public,
and they must contain a [WebMethod] attribute; otherwise, the client won't use
them.
Now you are ready to build and test your web service. First, build the service using
the Build menu option and then start it in Debug mode. This will bring up the Web
service in your browser, as shown in Figure 8-9.
You can make this screen a bit more descriptive by adding a WebService
attribute to the top of the class and then adding descriptions to both the
WebService attribute and the WebMethod attribute. As you can see from listing 8-3,
I added a description to both.
If you click on the link for the GetOrderFromDatabase method, you see the screen
on figure 8-11. This browser screen enables you to test the method by entering an
OrderID.
131
After you click the invoke button, the browser returns the XML data representing
the DataSet, which contains the order with the order ID of 10248. Figure 8-12
shows a piece of the XML data representing the order and displayed by the browser.
132
Figure 8-12 The Order DataSet displayed by the browser in XML format
Note that because you're using a complex structure such as a DataSet for the
return parameter, you need to use SOAP with an XSD schema (which happens to be
the default wiring protocol) to transfer the data back to the client. The encoding of
the SOAP format is beyond the scope of this article, but if you're interested, you can
visit the World Wide Web Consortium (http://www.w3.org).
As you can see from figure 8-12, the default namespace for the DataSet xmlns is
http://tempuri.org. You can use the WebService attribute to specify the namespace
and description text for the XML Web service. As you can see, VS .Net doesn't
generate this attribute by default. You have to write it manually. If you are
specifying more than one property, you can separate them with a comma. For
example, the following code sets the namespace and the description properties of
the WebService attribute:
[WebService(Namespace = "http://servername/xmlwebservices/",
Description = "My Web Service")]
133
XML is used for structuring the data, SOAP is used to transfer the data, WSDL is used
for describing the services and UDDI is used to get a list of services available. Web
service allows applications to communicate with each other without worrying about their
hardware systems, operating systems and programming languages.
Unlike the older model, web service does not provide a user interface but exposes the
business logic, which can be programmed, and hence the user is free to add his own
interface to the application.
Google is one of the websites which has provided a public web service allowing
applications to use features like search and spell checks. We shall now see how we can
use this service in our application using Visual Basic.NET.
But before we could access Google web APIs service we will have to create a Google
account and obtain a license key which shall allow us to run about 1000 automated
queries a day.
Getting Started
Now that you have received your license key, we shall create an application in Visual
Basic .NET to create a customized search and a spelling checker using Google Web
APIs Service.
Open your Visual Studio .NET, create a new Windows Application Project, which we
shall call googleapi, click OK.
136
We shall now add a Web Reference to Google Web APIs Service, well this is almost like
adding a reference to a COM/ActiveX object, but when we add a Web Reference we
now have access to all the XML web service on Google server. Open your Solution
Explorer, right click the References and click Add Web Reference, alternatively you
could select Project menu and click Add Web Reference.
After you enter the URL and press Enter and the Google Web Service is loaded you
should see a screen like Figure 2 also the Add Reference button is enabled, click Add
Reference button to add this web reference to our project.
In the Solution Explorer Window click on the Web Reference to see a Google Web
Reference, which we have added, lets rename that to Google by right clicking on it and
clicking Rename.
138
Create a User Interface as shown below with the flowing controls and given names
Source Code
Private Sub btn_Search_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btn_Search.Click
Finally
Now we have finished coding our application, run the application now and type some
text to search in the text box and click the Google Search button to see the number of
results found. Also try Google spell check.
139
Now you must have realized how simple it is to incorporate Google Web APIs Service in
your application, here are few things you could do with this service
● Issuing regularly scheduled search requests to monitor the web for new
information on a subject.
● Performing market research by analyzing differences in the amount of
information available on different subjects over time.
● Searching via non-HTML interfaces, such as the command line, pagers, or
visualization applications.
● Creating innovative games that play with information on the web.
● Add Google spell-checking to an application.
1. Open the Visual Studio .NET Command Prompt and navigate to the folder that
contains the WSDL file you created in the previous section using disco.exe.
2. Enter the following command to create a proxy class to call the AirportWeather Web
service: wsdl /language:CS /out:AirportWeatherProxy.cs AirportWeather.wsdl.
The tool reads the WSDL file and creates a new file named AirportWeatherProxy.cs.
3. Create a new Visual C# ASP.NET Web Application project (Example5_3). Add a
reference to System.Web.Services.dll.
4. Add the AirportWeatherProxy.cs file to the project by selecting File, Add Existing
Item.
140
The difference between this project and Example5_1 is that this code explicitly defines the
objects it uses rather than discovering them at runtime. The AirportWeather and
WeatherSummary objects are proxy objects that pass calls to the Web service and return
results from the Web service.
Table 5.2 shows some of the command-line options you can use with wsdl.exe. You can use
either the path to a local WSDL or Disco file, or the URL of a remote WSDL or Disco file
with this tool.
Option Meaning
/n:Namespace
/d:DomainName
In fact, the end result is no different when using the tools to create a proxy class and adding
a Web reference because, behind the scenes, the Web reference creates its own proxy
class. To see this, click the Show All Files toolbar button in Solution Explorer for the project
Example5_1, and then expand the Web References node. You'll see a set of files similar to
those in Figure 5.3.
Figure 5.3. When you add a Web reference, the proxy file is automatically generated.
142
The .wsdl file is the same file that is generated by running the Web Services Discovery
tool on the URL of the Web reference, and the .map file is the same as the .discomap
file generated by the Web Services Discovery tool. As you can see by opening this file, the
.cs file defines the proxy objects to be used with the Web service that is represented by this
Web reference. The major difference between this file and the proxy you generated with the
WSDL tool is that the autogenerated file uses a namespace based on the name of the Web
reference.
Use the WSDL proxy class tool (WseWsdl3.exe) to generate proxy code for a web service client
from a WSDL file. The .NET Framework SDK 2.0 WSDL.exe tool must be installed and
accessible.
In this exercise, we will build a simple web service �Hello World'. Most articles teach
about web services using the Hello World example. But few explain the technology
behind this web services example in detail. In this article we will learn both.
Let us start by creating the Hello world web service. We will create the web service using
asp.net and visual basic language. The IDE we will use is Visual Studio. Net. We can also create
a ASP.NET Web Service in C# programming language using visual studio. Net IDE.
To create the web service, open Visual Studio and select File-> New Web site from the menu.
Make sure Visual Basic is selected in the language box and HTTP in the location box. Select
ASP.NET Web service from the template list. Enter the name as http://localhost/HelloService as
shown in above figure and click OK.
Visual Studio 2005 will create a new web service project. A new virtual directory - HelloService -
will be created on your computer's Web server. This action also creates two files called
Service.asmx and service.vb. Please note that Visual Studio creates the entry point file with
.asmx extension and the other code behind the file with .vb extension. These files are
automatically added to the project, which we can see in a solution explorer.
The service.asmx and service.vb files represent a single web service. WebServices do not have a
visible interface and so, the design interface is empty. When we open the Service.asmx file, only
the following code is seen.
The service.asmx file serves as the entry point into the web service.
The other file, service.vb, is the code-behind file for the web service. We can write the
functionality of the web service in this file. The code-behind file imports the
System.Web.Services namespace. This namespace contains the classes that are required to
144
build and use Web services. We can view this file by switching to the code view for the
service.asmx file.
Note that a single project can contain multiple WebServices, each web service implemented by a
different class.
If we open the service.vb code-behind page, we can see the default code which is created by
vs.NET automatically, as listed below.
From the above code, we see that service is the class that contains all the code that implements
the web service methods. This is actually the name of the WebService; it's named after the class
and not after the project. The .vb and .asmx files together form the Code model for the web
services.
As we have already seen a web service is basically a class that sits on the server. Building a Web
Service with Visual Studio is as simple as writing a class. The class inherits from System. Web.
Services, and this base class includes all that is necessary to make the functions (methods) of
the class available on the Web. The Web Service class belongs to the system.Web.Services
namespace. This class provides direct access to built-in ASP.NET objects, such as Application
and Session. If an application does not require these objects, we can create a Web service
without deriving it from the Web Service class. So, Note that deriving from a web service base
class is optional.
Service.asmx file
In the above line of code, @ WebService is the web processing directive that specifies a class
name, here service for a web service and the language used to create the web service is visual
basic.
Service.vb file
145
The WebService attribute is an optional attribute that can be used to provide additional
information about the Web service. We can also use the WebService attribute to provide a
unique namespace for the web service. This namespace can be used by client applications to
resolve conflicts that may arise due to different Web services having methods with the same
name. The Webservice attribute can be provided before the Web service class declarations as
shown below.
The description of the Web service appears in the browser window when we try to access the
web service directly by providing the path.
The methods that we want to expose to web service are marked with Webmethod attribute.
The Webmethod attribute enables us to call the web service methods remotely over the internet.
The syntax for applying the Webmethod attribute to a method is given below.
The methods of this class don't return an HTML page, instead, they return one or more values,
packaged as XML documents.
Basically, if you can write a function, you can write a web method; it's that simple. The difference
between a class and a WebService class, is that the members of the WebService can be called
remotely.
VB.NET uses less than and greater than symbols to the <WebMethod> attribute to appear on the
line before the function definition.
From the above code, we note that class name is Service and method is HelloWorld.
If we want to change its name, we must rename the Service item in the Solution Explorer's
window, as well as the name of the class in the code.
146
Note that we can also create methods without preceding them with the WebMethod
attribute. However, these methods cannot be used to expose some functionalities to
applications. They can only be used by the other methods within the Web service class. We can
also write web services as plain text files with an extension of .asmx. We can use notepad to
develop the web service. The code is listed below. We will use this code example in our articles
on deployment and consuming a web service.