Dot Net Programming Notes
Dot Net Programming Notes
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
.NET is a software framework which is designed and developed by Microsoft. The first version
of the .Net framework was 1.0 which came in the year 2002. In easy words, it is a virtual
machine for compiling and executing programs written in different languages like C#, VB.Net
etc.
It is used to develop Form-based applications, Web-based applications, and Web services. There
is a variety of programming languages available on the .Net platform, VB.Net and C# being the
most common ones. It is used to build applications for Windows, phone, web, etc. It provides a
lot of functionalities and also supports industry standards.
Common Language Runtime(CLR): CLR is the basic and Virtual Machine component of the
.NET Framework. It is the run-time environment in the .NET Framework that runs the codes and
helps in making the development process easier by providing the various services such as
remoting, thread management, type-safety, memory management, robustness, etc.. Basically, it is
responsible for managing the execution of .NET programs regardless of any .NET programming
language. It also helps in the management of code, as code that targets the runtime is known as
the Managed Code and code doesn’t target to runtime is known as Unmanaged code.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
The combination of Operating System Architecture and CPU Architecture is known as the
platform. Platform dependent means the programming language code will run only on particular
Operating System. A .NET application is platform dependent because of the .NET framework
which is only able to run on the Windows-based operating system. The .Net application is
platform independent also because of Mono framework. Using Mono framework the .Net
application can run on any Operating System including windows. Mono framework is a third
party software developed by Novell Company which is now a part of Micro Focus Company. It
is a paid framework
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Event-driven programming focuses on events. Eventually, the flow of program depends upon
events. Until now, we were dealing with either sequential or parallel execution model but the
model having the concept of event-driven programming is called asynchronous model. Event-
driven programming depends upon an event loop that is always listening for the new incoming
events. The working of event-driven programming is dependent upon events. Once an event
loops, then events decide what to execute and in what order. Following flowchart will help you
understand how this works −
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
.NET Components
The architecture of the .Net framework is based on the following key components;
The "Common Language Infrastructure" or CLI is a platform on which the .Net programs are
executed.
Exception Handling - Exceptions are errors which occur when the application is executed.
If an application tries to open a file on the local machine, but the file is not present.
If the application tries to fetch some records from a database, but the connection to the database
is not valid.
Garbage Collection - Garbage collection is the process of removing unwanted resources when
they are no longer required.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
A File handle which is no longer required. If the application has finished all operations on a file,
then the file handle may no longer be required.
The database connection is no longer required. If the application has finished all operations on a
database, then the database connection may no longer be required.
Language - The first level is the programming language itself, the most common ones are
VB.Net and C#.
Compiler – There is a compiler which will be separate for each programming language. So
underlying the VB.Net language, there will be a separate VB.Net compiler. Similarly, for C#,
you will have another compiler.
Common Language Interpreter – This is the final layer in .Net which would be used to run a .net
program developed in any programming language. So the subsequent compiler will send the
program to the CLI layer to run the .Net application.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
2. Class Library
The .NET Framework includes a set of standard class libraries. A class library is a collection of
methods and functions that can be used for the core purpose.
For example, there is a class library with methods to handle all file-level operations. So there is a
method which can be used to read the text from a file. Similarly, there is a method to write text to
a file.
Most of the methods are split into either the System.* or Microsoft.* namespaces. (The asterisk *
just means a reference to all of the methods that fall under the System or Microsoft namespace)
A namespace is a logical separation of methods. We will learn these namespaces more in detail
in the subsequent chapters.
3. Languages
The types of applications that can be built in the .Net framework is classified broadly into the
following categories.
WinForms – This is used for developing Forms-based applications, which would run on an end
user machine. Notepad is an example of a client-based application.
ASP.Net – This is used for developing web-based applications, which are made to run on any
browser such as Internet Explorer, Chrome or Firefox.
The Web application would be processed on a server, which would have Internet Information
Services Installed.
The result of the execution is then sent to the client machines, and the output is shown in the
browser.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
ADO.Net – This technology is used to develop applications to interact with Databases such as
Oracle or Microsoft SQL Server.
Microsoft always ensures that .Net frameworks are in compliance with all the supported
Windows operating systems.
The following design principles of the .Net framework are what make it very relevant to create
.Net based applications.
Interoperability - The .Net framework provides a lot of backward support. Suppose if you had
an application built on an older version of the .Net framework, say 2.0. And if you tried to run
the same application on a machine which had the higher version of the .Net framework, say 3.5.
The application would still work. This is because with every release, Microsoft ensures that older
framework versions gel well with the latest version.
Portability- Applications built on the .Net framework can be made to work on any Windows
platform. And now in recent times, Microsoft is also envisioning to make Microsoft products
work on other platforms, such as iOS and Linux.
Security - The .NET Framework has a good security mechanism. The inbuilt security
mechanism helps in both validation and verification of applications. Every application can
explicitly define their security mechanism. Each security mechanism is used to grant the user
access to the code or to the running program.
Memory management - The Common Language runtime does all the work or memory
management. The .Net framework has all the capability to see those resources, which are not
used by a running program. It would then release those resources accordingly. This is done via a
program called the "Garbage Collector" which runs as part of the .Net framework.
The garbage collector runs at regular intervals and keeps on checking which system resources are
not utilized, and frees them accordingly.
Simplified deployment - The .Net framework also have tools, which can be used to package
applications built on the .Net framework. These packages can then be distributed to client
machines. The packages would then automatically install the application.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
In this chapter, we will understand the execution process of .NET Core and compare it with the
.NET Framework. The managed execution process includes the following steps.
Choosing a compiler
Compiling your code to MSIL
Compiling MSIL to native code
Running code
Choosing a Compiler
Compiling translates your source code into Microsoft Intermediate Language (MSIL) and
generates the required metadata.
Metadata describes the types in your code, including the definition of each type, the
signatures of each type's members, the members that your code references, and other data
that the runtime uses at execution time.
The runtime locates and extracts the metadata from the file as well as from framework
class libraries (FCL) as needed during execution.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
At execution time, a just-in-time (JIT) compiler translates the MSIL into native code.
During this compilation, code must pass a verification process that examines the MSIL
and metadata to find out whether the code can be determined to be type safe.
Running Code
The common language runtime provides the infrastructure that enables the execution to
take place and services that can be used during execution.
During execution, managed code receives services such as garbage collection, security,
interoperability with unmanaged code, cross-language debugging support, and enhanced
deployment and
Interoperability
Asynchronous Programming
Portability
High Performance
Memory Management
Security
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
In general IDE is a graphical user interface based workbench which helps the developer in
building software applications by providing tools like a source code editor; build automation
tools, a debugger etc
In the context of .NET based applications, visual studio is the most commonly used IDE.
VS.Net is just an editor, provided by Microsoft to help developers to write .NET programs
easily.VS.Net provides:
Changing the state of an object is known as an event. For example click on button,
dragging mouse etc. Event handling is the mechanism that controls the event and decides
what should happen if an event occurs.
Event driven programming is a paradigm in which the flow of the program is determined
by events (mouse clicks, key presses), sensor outputs, or messages from other
programs/threads.
In in fig a simple event driven programming paradigm where each and every event go
through a scheduler. Scheduler passes the code written inside the events to a particular
event handler.
Events
Scheduler
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
A Visual studio IDE provides toolbox which is a window that gives us access to all
controls, components, etc. User can easily drag and drop controls or tools on forms.
A Visual studio IDE also provides editor which automatically generates codes for
different events like click or press events. The programmer therefore concentrate on
issues such as interface design, which involves adding controls such as command buttons,
text boxes, and labels to standard forms
Once the user interface is substantially complete, the programmer can add event-handling
code to each control as required.
Each event-handler is usually bound to a specific object or control on a form. Any
additional subroutines, methods, or function procedures required are usually placed in a
separate code module, and can be called from other parts of the program as and when
needed.
NET Framework:
Assemblies and namespaces are basic building blocks of the .net framework, They form
the fundamental unit of deployment, version control, reuse , security permissions and
more.
Assemblies:
An assembly is a collection of types and resources that are built to work together and
form a logical unit of functionality.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Manifest:
Manifest is the most important part of an Assembly. Manifest contains useful information, about
an assembly which makes an assembly: self-describing,
The specifications in an assembly are collectively referred to as the assembly’s the manifest
contains:
7. Custom information, such as user-friendly assembly title, description and product information,
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
2. System Namespaces:
Namespace plays a fundamental role in the .Net framework. You cannot build a vb.net
application without using classes from the .net system namespace.
The .net framework class library consists of several thousand classes and other types,
(such as interfaces, structures and enumerations) that are divided into several namespaces
Most commonly used namespaces are as follows:
1. System.Data:
ADO.net is an entirely new model for data access that is based on the disconnected dataset.
2.System.IO:
The system.IO namespace contains classes that provide a variety of input/output functionality,
such as
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
3. System.Text.RegularExpressions:
4.System.windows.forms
This namespace is the mother of all namespaces and is used for creating windows
applications.
The system.Window.Forms namesqace contains classes for creating windows based
applications that take full advantage of the rich user interface features available in the
Microsoft windows operating system.
In this namespace you will find the form class and many other controls that can be added
to forms to create user interfaces.
In fact each new form added to a vb.net Project contains the following line:
Imports System.Window.Forms
Fortunately visual studio provides the functionality of the system.window.forms
namespace to us as vb programmers, so we do not need to program directly against this
namespace.
.NET Framework
٭Microsoft .NET (pronounced “dot net”) is a software component that runs on the
Windows operating system.
٭.NET provides tools and libraries that enable developers to create Windows software
much faster and easier.
٭The .NET Framework must be installed on a user’s PC to run .NET applications.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
NET Framework
.Net Framework
It is used to develop applications for web, Windows, phone. Moreover, it provides a broad range
of functionalities and support.
This framework contains a large number of class libraries known as Framework Class Library
(FCL). The software programs written in .NET are executed in the execution environment, which
is called CLR (Common Language Runtime). These are the core and essential parts of the .NET
framework.
This framework provides various services like memory management, networking, security,
memory management, and type-safety.
The .Net Framework supports more than 60 programming languages such as C#, F#, VB.NET,
J#, VC++, JScript.NET, APL, COBOL, Perl, Oberon, ML, Pascal, Eiffel, Smalltalk, Python,
Cobra, ADA, etc.
Following is the .NET framework Stack that shows the modules and components of the
Framework.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Other Modules (WCF, WPF, WF, Card Space, LINQ, Entity Framework, Parallel LINQ, Task
Parallel Library, etc.)
It is a program execution engine that loads and executes the program. It converts the program
into native code. It acts as an interface between the framework and operating system. It does
exception handling, memory management, and garbage collection. Moreover, it provides
security, type-safety, interoperability, and portablility. A list of CLR components are given
below:
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
WinForms
Windows Forms is a smart client technology for the .NET Framework, a set of managed libraries
that simplify common application tasks such as reading and writing to the file system.
ASP.NET
ADO.NET
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
It is a framework for building service-oriented applications. Using WCF, you can send data as
asynchronous messages from one service endpoint to another.
WF (Workflow Foundation)
Windows Workflow Foundation (WF) is a Microsoft technology that provides an API, an in-
process workflow engine, and a rehostable designer to implement long-running processes as
workflows within .NET applications.
It is a query language, introduced in .NET 3.5 framework. It is used to make the query for data
sources with C# or Visual Basics programming languages.
Entity Framework
It is an ORM based open source framework which is used to work with a database using .NET
objects. It eliminates a lot of developers effort to handle the database. It is Microsoft's
recommended technology to deal with the database.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Parallel LINQ
It can improve and provide fast speed to execute the LINQ query by using all available computer
capabilities.
Apart from the above features and libraries, .NET includes other APIs and Model to improve and
enhance the .NET framework.
In 2015, Task parallel and Task parallel libraries were added. In .NET 4.5, a task-based
asynchronous model was added.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
What is VB.Net?
VB.NET stands for Visual Basic.NET, and it is a computer programming language developed by
Microsoft. It was first released in 2002 to replace Visual Basic 6. VB.NET is an object-oriented
programming language. This means that it supports the features of object-oriented programming
which include encapsulation, polymorphism, abstraction, and inheritance.
VB.NET Features
VB.NET comes loaded with numerous features that have made it a popular programming
language amongst programmers worldwide. These features include the following:
VB.NET is not case sensitive like other languages such as C++ and Java.
It is an object-oriented programming language. It treats everything as an object.
Automatic code formatting, XML designer, improved object browser etc.
Garbage collection is automated.
Support for Boolean conditions for decision making.
Simple multithreading, allowing your apps to deal with multiple tasks simultaneously.
Simple generics.
A standard library.
Events management.
References. You should reference an external object that is to be used in a VB.NET
application.
Attributes, which are tags for providing additional information regarding elements that
have been defined within a program.
Windows Forms- you can inherit your form from an already existing form.
Advantages of VB.NET
The following are the pros/benefits you will enjoy for coding in VB.NET:
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
You can connect your applications to other applications created in languages that run on
the .NET framework.
You will enjoy features like docking, automatic control anchoring, and in-place menu
editor all good for developing web applications.
Disadvantages of VB.NET
VB.NET cannot handle pointers directly. This is a significant disadvantage since pointers
are much necessary for programming. Any additional coding will lead to many CPU
cycles, requiring more processing time. Your application will become slow.
VB.NET is easy to learn. This has led to a large talent pool. Hence, it may be challenging
to secure a job as a VB.NET programmer.
Data types
Data types refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
VB.Net provides a wide range of data types. The following table shows all the data types
available −
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
User-Defined Depends on implementing platform Each member of the structure has a range
determined by its data type and independent of the
ranges of the other members
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
For example, let us consider a Rectangle object. It has attributes like length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating area and displaying details.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the
basis of our observations in it −
Live Demo
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
'Public methods
Public Sub AcceptDetails()
length = 4.5
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
width = 3.5
End Sub
End Sub
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined
item. The basic rules for naming classes in VB.Net are as follows −
A name must begin with a letter that could be followed by a sequence of letters, digits (0
- 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; :
" ' / and \. However, an underscore ( _ ) can be used.
It should not be a reserved keyword.
VB.Net Keywords
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Namespace
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
/ Divides one operand by another and returns a floating point result B / A will give
3.5
\ Divides one operand by another and returns an integer result B \ A will give
3
MOD Modulus Operator and remainder of after an integer division B MOD A will
give 1
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. VB.Net is rich in built-in operators and provides following types of commonly
used operators −
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
Bit Shift Operators
Assignment Operators
Miscellaneous Operators
This tutorial will explain the most commonly used operators.
Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then −
Show Examples
Comparison Operators
Following table shows all the comparison operators supported by VB.Net. Assume
variable A holds 10 and variable B holds 20, then −
Show Examples
= Checks if the values of two operands are equal or not; if yes, then (A = B)
condition becomes true. is not
true.
<> Checks if the values of two operands are equal or not; if values are not (A <> B)
equal, then condition becomes true. is true.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
> Checks if the value of left operand is greater than the value of right (A > B)
operand; if yes, then condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand; (A < B)
if yes, then condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand; if yes, then condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B)
right operand; if yes, then condition becomes true. is true.
Apart from the above, VB.Net provides three more comparison operators, which we will be
using in forthcoming chapters; however, we give a brief description here.
Is Operator − It compares two object reference variables and determines if two object
references refer to the same object without performing value comparisons. If object1 and
object2 both refer to the exact same object instance, result is True; otherwise, result is
False.
IsNot Operator − It also compares two object reference variables and determines if two
object references refer to different objects. If object1 and object2 both refer to the exact
same object instance, result is False; otherwise, result is True.
Like Operator − It compares a string against a pattern.
Logical/Bitwise Operators
Following table shows all the logical operators supported by VB.Net. Assume variable A holds
Boolean value True and variable B holds Boolean value False, then −
Show Examples
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
And It is the logical as well as bitwise AND operator. If both the operands are true, then (A And
condition becomes true. This operator does not perform short-circuiting, i.e., it B) is
evaluates both the expressions. False.
Or It is the logical as well as bitwise OR operator. If any of the two operands is true, (A Or B)
then condition becomes true. This operator does not perform short-circuiting, i.e., it is True.
evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Use to reverses the logical state of Not(A
its operand. If a condition is true, then Logical NOT operator will make false. And B)
is True.
Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns True if A Xor B
both expressions are True or both expressions are False; otherwise it returns False. is True.
This operator does not perform short-circuiting, it always evaluates both expressions
and there is no short-circuiting counterpart of this operator.
AndAlso It is the logical AND operator. It works only on Boolean data. It performs short- (A
circuiting. AndAlso
B) is
False.
OrElse It is the logical OR operator. It works only on Boolean data. It performs short- (A
circuiting. OrElse
B) is
True.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
We have already discussed the bitwise operators. The bit shift operators perform the shift
operations on binary values. Before coming into the bit shift operators, let us understand the bit
operations.
Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^
are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The
Bit shift operators are >> and << for left shift and right shift, respectively.
Assume that the variable A holds 60 and variable B holds 13, then −
Show Examples
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
And Bitwise AND Operator copies a bit to the result if it exists in both operands. (A AND B)
will give
12, which is
0000 1100
Xor Binary XOR Operator copies the bit if it is set in one operand but not both. (A Xor B)
will give
49, which is
0011 0001
Not Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (Not A )
will give -
61, which is
1100 0011
in 2's
complement
form due to
a signed
binary
number.
<< Binary Left Shift Operator. The left operands value is moved left by the number A << 2 will
of bits specified by the right operand. give 240,
which is
1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the A >> 2 will
number of bits specified by the right operand. give 15,
which is
0000 1111
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Assignment Operators
= Simple assignment operator, Assigns values from right side operands to left side C=A+
operand B will
assign
value of
A+B
into C
+= Add AND assignment operator, It adds right operand to the left operand and C += A is
assigns the result to left operand equivalent
to C = C
+A
-= Subtract AND assignment operator, It subtracts right operand from the left operand C -= A is
and assigns the result to left operand equivalent
to C = C -
A
*= Multiply AND assignment operator, It multiplies right operand with the left C *= A is
operand and assigns the result to left operand equivalent
to C = C
*A
/= Divide AND assignment operator, It divides left operand with the right operand C /= A is
and assigns the result to left operand (floating point division) equivalent
to C = C /
A
\= Divide AND assignment operator, It divides left operand with the right operand C \= A is
equivalent
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
^= Exponentiation and assignment operator. It raises the left operand to the power of C^=A is
the right operand and assigns the result to left operand. equivalent
to C = C ^
A
&= Concatenates a String expression to a String variable or property and assigns the Str1 &=
result to the variable or property. Str2 is
same as
Str1 =
Str1 &
Str2
Miscellaneous Operators
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Function It declares the parameters and code that Dim add5 = Function(num As
Expression define a function lambda expression. Integer) num + 5
'prints 10
Console.WriteLine(add5(5))
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Operator Precedence
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Await Highest
Exponentiation (^)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Negation (Not)
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Following is the general form of a typical decision making structure found in most of the
programming languages −
VB.Net provides the following types of decision making statements. Click the following links to
check their details.
Statement Description
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
nested If statements You can use one If or Else if statement inside another If or Else
if statement(s).
Select Case statement A Select Case statement allows a variable to be tested for
equality against a list of values.
nested Select Case statements You can use one select case statement inside another select
case statement(s).
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.
Do Loop It repeats the enclosed block of statements while a Boolean condition is True
or until the condition becomes True. It could be terminated at any time with
the Exit Do statement.
For...Next It repeats a group of statements a specified number of times and a loop index
counts the number of loop iterations as the loop executes.
For Each...Next It repeats a group of statements for each element in a collection. This loop is
used for accessing and manipulating all elements in an array or a VB.Net
collection.
While... End While It executes a series of statements as long as a given condition is True.
With... End With It is not exactly a looping construct. It executes a series of statements that
repeatedly refer to a single object or structure.
Nested loops You can use one or more loops inside any another While, For or Do loop.
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Exit statement Terminates the loop or select case statement and transfers execution to the
statement immediately following the loop or select case.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Continue statement Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
GoTo statement Transfers control to the labeled statement. Though it is not advised to use
GoTo statement in your program.
VB.Net provides the following control statements. Click the following links to check their
details.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Introduction
Vb.net is an object oriented programming (OOP) language which supports various OOP
concepts such as class, objects, methods, Procedure, functions, inheritance constructors and so
on.
Visual basic comes with thousands of built in classes and we knew that a form which we design
is also an object, windows forms are objects
Which derived form the system.Windows.Form.Formclass and that our code is part of that class.
For example
Inherits system.Windows.Forms.Form
--------------------
---------------------
End sub
End class.
For example
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Me.controls.add(Textbox)
End sub
A class is a user defined data type used to define new data types.
A class is a group of different data members or objects with the same properties, processes,
events of an object, and general relationships to other member functions. Furthermore, we can
say that it is like a template or architect that tells what data and function will appear when it is
included in a class object. For example, it represents the method and variable that will work on
the object of the class.
Objects are the basic run-time units of a class. Once a class is defined, we can create any number
of objects related to the class to access the defined properties and methods. For example, the Car
is the Class name, and the speed, mileage, and wheels are attributes of the Class that can be
accessed by the Object.
We can create a class using the Class keyword, followed by the class name. And the body of the
class ended with the statement End Class. Following is the general syntax for creating classes
and objects in the VB.NET programming language.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Where,
o Access_Specifier: It defines the access levels of the class, such as Public, Private or
Friend, Protected, Protected Friend, etc. to use the method. (It is an optional parameter).
o Shadows: It is an optional parameter. It represents the re-declaration of variables and
hides an identical element name or set of overloaded elements in a base class.
o MustInherit: It is an optional parameter that specifies that the class can only be used as a
base class, and the object will not directly access the base class or the abstract class.
o NotInheritable: It is also an optional parameter that representing the class not being used
as a base class.
o Partial: As the name defines, a Partial represents the partial definition of the class
(optional).
o Implements: It is used to specify interfaces from which the class inherits (optional).
My_program.vb
In the above syntax, we have created a class with the name 'My_program' using the Class
keyword.
In the above syntax, we have created an instance (Obj_Name) for the class Class_Name. By
using the object name 'Obj_Name' to access all the data members and the method name
of Class_Name.
Let's create a program to find the Area and Parameter of a rectangle using the class and object in
VB.NET.
My_program.vb
1. Imports System
2. Module My_program
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
3. Sub Main()
4. Dim rect As Rectangle = New Rectangle() 'create an object
5. Dim rect2 As Rectangle = New Rectangle() 'create an object
6. Dim area, para As Integer
7.
8. 'rect specification
9. rect.setLength = (5)
10. rect.setBreadth= (6)
11.
12. 'rect2 specification
13. rect2.setLength = (5)
14. rect2.setBreadth = (10)
15.
16. 'Area of rectangle
17. area = rect.length * rect.Breadth
18. 'area = rect.GetArea()
19. Console.WriteLine(" Area of Rectangle is {0}", area)
20.
21. 'Parameter of rectangle
22. 'para = rect.GetParameter()
23. para = 2 (rect2.length + rect.Breadth)
24. Console.WriteLine(" Parameter of Rectangle is {0}", para)
25. Console.WriteLine(" Press any key to exit...")
26. Console.ReadKey()
27. End Sub
28. Public Class Rectangle
29. Public length As Integer
30. Public Breadth As Integer
31.
32. Public Sub setLength(ByVal len As Integer)
33. length = len
34. End Sub
35.
36. Public Sub setBreadth(ByVal bre As Integer)
37. Breadth = bre
38. End Sub
39. Public Function GetArea() As Integer
40. Return length * Breadth
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
Member Function
The member function of a class is used to define the structure of member inside the definition of
the class. It can be accessed by all defined objects of the class and operated on the data member.
Furthermore, member variables are the attributes of an object to be implemented to a member
function. And we can access member variables using the public member function.
When we create a class without defining a constructor, the compiler automatically creates a
default constructor. In this way, there is a constructor that is always available in every class.
Furthermore, we can create more than one constructor in a class with the use of New keyword
but with the different parameters, and it does not return anything.
The following is the syntax for creating a constructor using the New keyword in VB.NET.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Let's create a program to define the default constructor in a VB.NET programming language.
Default_Const.vb
1. Imports System
2. Module Default_Const
3. Class Tutor
4. Public name As String
5. Public topic As String
6. ' Create a default constructor
7. Public Sub New()
8. name = "JavaTpoint"
9. topic = "VB.NET Tutorial"
10. End Sub
11. End Class
12. Sub Main()
13. ' The constructor will automatically call when the instance of the class is created
14. Dim tutor As Tutor = New Tutor() ' Create an object as a tutor
15. Console.WriteLine(" Your Site Name is : {0}", tutor.name)
16. Console.WriteLine(" Your Topic Name is : {0}", tutor.topic)
17. Console.WriteLine(" Press any key to exit...")
18. Console.ReadKey()
19. End Sub
20. End Module
Output:
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
In the above example, we created a class 'Tutor' and defined a default constructor method
with New() keyword without passing any arguments. When the object (tutor) is created, the
default constructor is called into the class.
Parameterized Constructor
In VB.NET, when we pass one or more arguments to a constructor, the constructor is known as a
parameterized constructor. And the object of the class should be initialized with arguments when
it is created.
Let's create a program to use the parameterized constructor to pass the argument in a class.
Para_Const.vb
1. Imports System
2. Module Para_Const
3. Class Tutor
4. Public name As String
5. Public topic As String
6. ' Create a parameterized constructor to pass parameter
7. Public Sub New(ByVal a As String, ByVal b As String)
8. name = a
9. topic = b
10. Console.WriteLine(" We are using a parameterized constructor to pass the parameter")
11. End Sub
12. End Class
13. Sub Main()
14. ' The constructor will automatically call when the instance of the class is created
15. Dim tutor As Tutor = New Tutor("JavaTpoint", "VB.NET Constructor")
16. Console.WriteLine(" Your Site Name is : {0}", tutor.name)
17. Console.WriteLine(" Your Topic Name is : {0}", tutor.topic)
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadKey()
20. End Sub
21. End Module
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
VB.NET Destructor
In VB.NET, Destructor is a special function that is used to destroy a class object when the object
of the class goes out of scope. It can be represented as the Finalize() method and does not accept
any parameter nor return any value. Furthermore, it can be called automatically when a class
object is not needed.
1. Class My_Destructor
2. ' define the destructor
3. Protected Overrides Sub Finalize()
4. ' Statement or code to be executed
5. End Sub
6. End Class
Destruct.vb
1. Imports System
2. Module Destruct
3. Class Get_Destroy
4. Public Sub New()
5. Console.WriteLine(" An Object of the class is being created")
6. End Sub
7. ' Use Finalize() method of Destructor
8. Protected Overrides Sub Finalize()
9. Console.WriteLine(" An Object of the class is being destroyed")
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
Constructor Overloading
Const_Over.vb
1. Imports System
2. Module Const_Over
3. Class Details
4. Public name As String
5. Public course As String
6. ' Define Default Constructor
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
24. Console.WriteLine(" Your Overloaded Details are: Name : {0} and Course :{1}", det1.nam
e, det1.course)
25. Console.WriteLine(" Press any key to exit...")
26. Console.ReadKey()
27. End Sub
28. End Module
Output:
Inheritance
In VB.NET, Inheritance is the process of creating a new class by inheriting properties and
functions from the old class and extending the functionality of the existing class. It also provides
a reusable and faster implementation time of the code. When we create a derived or inherited
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
class, inheritance allows us to inherit all the properties of the existing class. The old class is
known as the base class, and the inherited class is known as the derived class.
Inheritance Syntax
Simple_Inherit.vb
1. Imports System
2. Module Simple_Inherit
3. Public Class Vehicle
4. Public Sub speed()
5. Console.WriteLine(" 4 Wheeler cars are more luxurious than 2 Wheeler")
6. End Sub
7.
8. Public Overridable Sub perform()
9. Console.WriteLine(" Both Vehicles are good, but in a narrow lane, two-
wheeler are more comfortable than 4-Wheeler")
10. End Sub
11. End Class
12.
13. Class Bike
14. Inherits Vehicle
15. Public Overrides Sub perform()
16. Console.WriteLine(" Two-wheeler are lesser weight as compared to 4 wheeler")
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
Inherit_class.vb
1. Module Inherit_class
2. Class Circle 'base class
3. Protected radius As Integer
4. Public Const PI As Double = 3.14
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
Multi-Level Inheritance
VB.NET only supports single inheritance that means a class can be inherited from the base class.
However, VB.NET uses hierarchical inheritance to extend one class to another class, which is
called Multi-Level Inheritance. For example, Class C extends Class B, and Class B extends
Class A, Class C will inherit the member of both class B and Class A. The process of extending
one class to another is known as multilevel inheritance.
1. Public Class A
2. ' implementation of code
3. End Class
4.
5. Public Class B
6. Inherits A
7. ' Implementation of Code
8. End Class
9.
10. Public Class C
11. Inherits A
12. ' Implementation of code
13. End Class
Multi_inherit1.vb
1. Module Multi_inherit1
2. Public Class A
3. Public SName As String
4. Public Sub Display()
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
Interface
In VB.NET, the interface is similar to a class for inheriting all properties, methods, and events
that a class or structure can implement. Using the interface in VB.NET, we can use multiple
inheritances of classes. It uses the Implements keyword to implement the interfaces, and the
Interface keyword is used to create the interface. All interfaces in VB.NET starts with i.
1. Class MyClass
2. Inherits IClass
3. Private Sub FetchDetails() Implements IClass.FetchDetails
4. ' Method Implementation
5. End Sub
6. End Class
In the above snippets, we inherited an interface (IClass) in the Class MyClass that implemented
to the interface method defined in a class.
Get_Interface.vb
1. Module Get_Interface
2. Interface IStudent
3. Sub Details(ByVal y As String)
4. End Interface
5. Class Student
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
6. Implements IStudent
7. Public Sub Details(ByVal a As String) Implements IStudent.Details
8. ' Throw New NotImplementedException()
9. Console.WriteLine(" Name of Student: {0}", a)
10. End Sub
11. End Class
12.
13. Class Student1
14. Implements IStudent
15. Public Sub Details(ByVal a As String) Implements IStudent.Details
16. 'Throw New NotImplementedException()
17. Console.WriteLine(" Course: {0}", a)
18. End Sub
19. End Class
20. Sub Main(ByVal args As String())
21. Dim stud As IStudent = New Student()
22. stud.Details(" James Watt")
23. Dim stud1 As IStudent = New Student1()
24. stud1.Details("Computer Science")
25. Console.WriteLine(" Press any key to exit...")
26. Console.ReadKey()
27. End Sub
28. End Module
Output:
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
VB.NET Multithreading
When two or more processes execute simultaneously in a program, the process is known as
multithreading. And the execution of each process is known as the thread. A single thread is
used to execute a single logic or task in an application. By default, each application has one or
more threads to execute each process, and that thread is known as the main thread.
To create and access a new thread in the Thread class, we need to import
the System.Threading namespace. When the execution of a program begins in VB.NET, the
Main thread is automatically called to handle the program logic. And if we create another thread
to execute the process in Thread class, the new thread will become the child thread for
the main thread.
In VB.NET, we can create a thread by extending the Thread class and pass the ThreadStart
delegate as an argument to the Thread constructor. A ThreadStart() is a method executed by the
new thread. We need to call the Start() method to start the execution of the new thread because
it is initially in the unstart state. And the PrintInfo parameter contains an executable statement
that is executed when creating a new thread.
Let's write a program to create and access the thread in Thread class.
create_Thread.vb
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Method Description
Equals() It is used to check whether the current and defined thread object are
equal.
Interrupt() It is used to interrupt a thread from the Wait, sleep, and join thread
state.
Join() It is a synchronization method that stops the calling thread until the
execution thread completes.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
ongoing instance.
Output:
In the above program, the main and child threads begin their execution simultaneously. The
execution of the main thread is stopped after completing its function, but the child thread will
continue to execute until its task is finished.
The following are the most commonly used methods of Thread class.
In VB.NET Multithreading, each thread has a life cycle that starts when a new object is created
using the Thread Class. Once the task defined by the thread class is complete, the life cycle of a
thread will get the end.
State Description
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Runnable When we call a Start() method to prepare a thread for running, the runnable
situation occurs.
Not It indicates that the thread is not in a runnable state, which means that the
Runnable thread in sleep() or wait() or suspend() or is blocked by the I/O operation.
Dead If the thread is in a dead state, either the thread has been completed its work
or aborted.
Let's create a program to manage a thread by using various methods of Thread Class.
Thread_cycle.vb
1. Imports System.Threading
2. Module Thread_cycle
3. Sub Main(ByVal args As String())
4. Dim s As Stopwatch = New Stopwatch()
5. s.Start()
6. Dim t As Thread = New Thread(New ThreadStart(AddressOf PrintInfo))
7. t.Start()
8. ' Halt another thread execution until the thread execution completed
9. t.Join()
10. s.[Stop]()
11. Dim t1 As TimeSpan = s.Elapsed
12. Dim ft As String = String.Format("{0}: {1} : {2}", t1.Hours, t1.Minutes, t1.Seconds)
13. Console.WriteLine(" Total Elapsed Time : {0}", ft)
14. Console.WriteLine("Completion of Thread Execution ")
15. Console.WriteLine("Press any key to exit...")
16. Console.ReadKey()
17. End Sub
18. Private Sub PrintInfo()
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Output:
In the above example, we used a different method of the Thread class such as
the Start() method to start execution of the thread, the Join() method is used to stop the
execution of the thread until the execution of the thread was completed. The Sleep() method is
used to pause the execution of threads for 5 seconds.
Multithreading
When two or more processes are executed in a program to simultaneously perform multiple
tasks, the process is known as multithreading.
When we execute an application, the Main thread will automatically be called to execute the
programming logic synchronously, which means it executes one process after another. In this
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
way, the second process has to wait until the first process is completed, and it takes time. To
overcome that situation, VB.NET introduces a new concept Multithreading to execute multiple
tasks at the same time by creating multiple threads in a program.
Let's write a program of multiple threads to execute the multiple tasks at the same time in the
VB.NET application.
Multi_thread.vb
1. Imports System.Threading
2. Module Multi_thread
3. Sub Main(ByVal arg As String())
4. Dim th As Thread = New Thread(New ThreadStart(AddressOf PrintInfo))
5. Dim th2 As Thread = New Thread(New ThreadStart(AddressOf PrintInfo2))
6. th.Start()
7. th2.Start()
8. Console.ReadKey()
9. End Sub
10. Private Sub PrintInfo()
11. For j As Integer = 1 To 5
12. Console.WriteLine(" value of j is {0}", j)
13. Thread.Sleep(1000)
14. Next
15. Console.WriteLine(" Completion of First Thread")
16. End Sub
17. Private Sub PrintInfo2()
18. For k As Integer = 1 To 5
19. Console.WriteLine(" value of k is {0}", k)
20. Next
21. Console.WriteLine(" Completion of First Thread")
22. End Sub
23. End Module
Output:
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Constructor
Imports system
Class student
Dim name as string
Public sub New()
Name= “unknown”
Console.writeline(“Constructor called…..”)
End sub
End sub
End class
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
What is an Exception?
An exception is an unwanted error that occurs during the execution of a program and can be a
system exception or application exception. Exceptions are nothing but some abnormal and
typically an event or condition that arises during the execution, which may interrupt the normal
flow of the program.
A user has entered incorrect data or performs a division operator, such as an attempt to divide by
zero.
A connection has been lost in the middle of communication, or system memory has run out.
Exception Handling
When an error occurred during the execution of a program, the exception provides a way to
transfer control from one part of the program to another using exception handling to handle the
error. VB.NET exception has four built-in keywords such as Try, Catch, Finally, and Throw to
handle and move controls from one part of the program to another.
Keyword Description
Try A try block is used to monitor a particular exception that may throw an
exception within the application. And to handle these exceptions, it
always follows one or more catch blocks.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
In VB.net, there are various types of exceptions represented by classes. And these exception
classes originate from their parent's class 'System.Exception'.
The following are the two exception classes used primarily in VB.NET.
1. System.SystemException
2. System.ApplicationException
System.SystemException: It is a base class that includes all predefined exception classes, and
some system-generated exception classes that have been generated during a run time such
as DivideByZeroException, IndexOutOfRangeException, StackOverflowExpression, and so
on.
1. Try
2. ' code or statement to be executed
3. [ Exit Try block]
4. ' catch statement followed by Try block
5. Catch [ Exception name] As [ Exception Type]
6. [Catch1 Statements] Catch [Exception name] As [Exception Type]
7. [ Exit Try ]
8. [ Finally
9. [ Finally Statements ] ]
10. End Try
In the above syntax, the Try/Catch block is always surrounded by a code that can throw an
exception. And the code is known as a protected code. Furthermore, we can also use multiple
catch statements to catch various types of exceptions in a program, as shown in the syntax.
Let's create a program to handle an exception using the Try, Catch, and Finally keywords for
Dividing a number by zero in VB.NET programming.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
TryException.vb
1. Module TryException
2. Sub divExcept(ByVal a As Integer, ByVal b As Integer)
3. Dim res As Integer
4. Try
5. res = a \ b
6. ' Catch block followed by Try block
7. Catch ex As DivideByZeroException
8. Console.WriteLine(" These exceptions were found in the program {0}", ex)
9. ' Finally block will be executed whether there is an exception or not.
10. Finally
11. Console.WriteLine(" Division result is {0}", res)
12. End Try
13. End Sub
14. Sub Main()
15. divExcept(5, 0) ' pass the parameters value
16. Console.WriteLine(" Press any key to exit...")
17. Console.ReadKey()
18. End Sub
19. End Module
Output:
Let's create a program to understand the uses of User-Defined Exceptions in VB.NET Exception
Handling.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
User_Exception.vb
1. Module User_Exception
2. Public Class StudentIsZeroException : Inherits Exception
3.
4. Public Sub New(ByVal stdetails As String)
5. MyBase.New(stdetails)
6. End Sub
7. End Class
8. Public Class StudentManagement
9. Dim stud As Integer = 0
10. Sub ShowDetail()
11. If (stud = 0) Then
12. Throw (New StudentIsZeroException(" Student roll no 'zero' does not exist"))
13. Else
14. Console.WriteLine(" Student is {0}", stud)
15. End If
16. End Sub
17. End Class
18. Sub Main()
19. Dim stdmg As StudentManagement = New StudentManagement()
20. Try
21. stdmg.ShowDetail()
22. Catch ex As StudentIsZeroException
23. Console.WriteLine(" StudentIsZeroException {0}", ex.message)
24. End Try
25. Console.ReadKey()
26. End Sub
27. End Module
Output:
Lets' create a program using the Try-Catch statement in VB.NET to handle the exceptions.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Try_catch.vb
1. Imports System
2. Module Try_catch
3. Sub Main(ByVal args As String())
4. Dim strName As String = Nothing
5. Try
6. If strName.Length > 0 Then ' it thows and exception
7. Console.WriteLine(" Name of String is {0}", strName)
8. End If
9. Catch ex As Exception ' it cacthes an exception
10. Console.WriteLine(" Catch exception in a proram {0}", ex.Message)
11. End Try
12. Console.WriteLine(" Press any key to exit...")
13. Console.ReadKey()
14. End Sub
15. End Module
Output:
Throwing Objects
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
In VB.NET exception handling, we can throw an object exception directly or indirectly derived
from the System.Exception class. To throw an object using the throw statement in a catch block,
such as:
1. Throw [ expression ]
throwexcept.vb
1. Imports System
2. Module thowexcept
3. Sub Main()
4. Try
5. Throw New ApplicationException("It will throw a custom object exception")
6. Catch ex As Exception
7. Console.WriteLine(" Custom Exception is: {0}", ex.Message)
8. Finally
9. Console.WriteLine("Finally block statement executes whether there is an exception or no
t.")
10. End Try
11. Console.WriteLine(" Press any key to exit")
12. Console.ReadKey()
13. End Sub
14. End Module
Output:
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
ADO.NET Architecture
ADO.NET
ADO.NET consist of a set of Objects that expose data access services to the .NET environment.
It is a data access technology from Microsoft .Net Framework , which provides communication
between relational and non relational systems through a common set of components .
System.Data namespace is the core of ADO.NET and it contains classes used by all data
providers. ADO.NET is designed to be easy to use, and Visual Studio provides several wizards
and other features that you can use to generate ADO.NET data access code.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
The two key components of ADO.NET are Data Providers and DataSet . The Data Provider
classes are meant to work with different kinds of data sources. They are used to perform all data-
management operations on specific databases. DataSet class provides mechanisms for managing
data when it is disconnected from the data source.
Data Providers
The .Net Framework includes mainly three Data Providers for ADO.NET. They are the
Microsoft SQL Server Data Provider , OLEDB Data Provider and ODBC Data Provider . SQL
Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC
uses OdbcConnection Object respectively.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
A data provider contains Connection, Command, DataAdapter, and DataReader objects. These
four objects provides the functionality of Data Providers in the ADO.NET.
Connection
The Connection Object provides physical connection to the Data Source. Connection object
needs the necessary information to recognize the data source and to log on to it properly, this
information is provided through a connection string.
ASP.NET Connection
Command
The Command Object uses to perform SQL statement or stored procedure to be executed at the
Data Source. The command object provides a number of Execute methods that can be used to
perform the SQL queries in a variety of fashions.
ASP.NET Command
DataReader
ASP.NET DataReader
DataAdapter
DataAdapter Object populate a Dataset Object with results from a Data Source . It is a special
class whose purpose is to bridge the gap between the disconnected Dataset objects and the
physical data source.
ASP.NET DataAdapter
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
DataSet
DataSet provides a disconnected representation of result sets from the Data Source, and it is
completely independent from the Data Source. DataSet provides much greater flexibility when
dealing with related Result Sets.
DataSet contains rows, columns,primary keys, constraints, and relations with other DataTable
objects. It consists of a collection of DataTable objects that you can relate to each other with
DataRelation objects. The DataAdapter Object provides a bridge between the DataSet and the
Data Source.
ADO.NET Introduction
It is a module of .Net Framework which is used to establish connection between application and
data sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes
that can be used to connect, retrieve, insert and delete data.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes
located into System.Xml.dll.
ADO.NET has two main components that are used for accessing and manipulating data are the
.NET Framework data provider and the DataSet.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
These are the components that are designed for data manipulation and fast access to data. It
provides various objects such as Connection, Command, DataReader and DataAdapter that
are used to perform database operations. We will have a detailed discussion about Data
Providers in new topic.
The DataSet
It is used to access data independently from any data resource. DataSet contains a collection of
one or more DataTable objects of data. The following diagram shows the relationship between
.NET Framework data provider and DataSet.
ADO.NET DataTable
DataTable represents relational data into tabular form. ADO.NET provides a DataTable class to
create and use data table independently. It can also be used with DataSet also. Initially, when we
create DataTable, it does not have table schema. We can create table schema by adding columns
and constraints to the table. After defining table schema, we can add rows to the table.
DataTable Properties
The following table contains the DataTable class properties.
DataTable Methods
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
If we required some other functionality mentioned above, we can use DataReader to improve
performance of our application.
Data provider for SQL Server is a lightweight component. It provides better performance
because it directly access SQL Server without any middle connectivity layer. In early versions, it
interacts with ODBC layer before connecting to the SQL Server that created performance issues.
The .NET Framework Data Provider for SQL Server classes is located in
the System.Data.SqlClient namespace. We can include this namespace in our C# application by
using the following syntax.
1. using System.Data.SqlClient;
ADO.NET Tutorial provides basic and advanced concepts of ADO.NET. Our ADO.NET
Tutorial is designed for beginners and professionals both.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Our ADO.NET Tutorial includes all topics of ADO.NET Tutorial such as ADO Net Tutorial
with introduction, data providers, sql server connectivity, connection, command, datareader,
dataset, data adapter, data tables, web form examples, mvc examples etc.
ADO.NET Architecture
ADO.NET
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
The two key components of ADO.NET are Data Providers and DataSet .
The Data Provider classes are meant to work with different kinds of data
sources. They are used to perform all data-management operations on
specific databases. DataSet class provides mechanisms for managing
data when it is disconnected from the data source.
Data Providers
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Connection
ASP.NET Connection
Command
ASP.NET Command
DataReader
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
ASP.NET DataReader
DataAdapter
ASP.NET DataAdapter
DataSet
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
DataAdapter Object provides a bridge between the DataSet and the Data
Source.
Advantages of ADO.Net
There are some similarities and differences between ADO and ADO.NET, but the
way they operate and their foundations are quite different.
ADO stands for ActiveX Data Objects and it relies on COM whereas ADO.NET
relies on managed providers defined by the .NET Common Language Runtime.
Both models require a connection to a data store to fetch data, and the code for
getting a connection is similar for both.
A major difference in creating connections with ADO and ADO.NET is that ADO
fits all connections to all types of data sources into a single Connection object.
ADO.NET can have separate Objects that represent connections to different data
sources.
VB.Net
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
connectionString = ConfigurationManager.ConnectionStrings("SQLDbConnection").ToString
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Open Visual Studio .NET and select a new Visual Basic .NET Project.
Create a new Crystal Reports for Product table from the above database crystalDB. The Product
Table has three fields (Product_id,Product_name,Product_price) and we are showing the whole
table data in the Crystal Reports.
From main menu in Visual Studio select PROJECT-->Add New Item . Then Add New Item
dialogue will appear and select Crystal Reports from the dialogue box.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Next step is to select the appropriate connection to your database. Here we are going to select OLEDB
connection for SQL Server
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Next screen is the SQL Server authentication screen . Select your Sql Server name , enter userid ,
password and select your Database Name . Click next , Then the screen shows OLE DB Property
values , leave it as it is , and click finish.
Then you will get your Server name under OLEDB Connection from there select database name
(Crystaldb) and click the tables , then you can see all your tables from your database.
From the tables list select Product table to the right side list .
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Click Finish Button. Then you can see the Crystal Reports designer window . You can arrange
the design according your requirements. Your screen look like the following picture.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET
through Crystal Reports Viewer control .
Select the default form (Form1.vb) you created in VB.NET and drag a button and
CrystalReportViewer control to your form.
Imports CrystalDecisions.CrystalReports.Engine
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class
NOTES:
The Crystal Reports is in your project location, there you can see CrystalReport1.rpt . So give the
full path name of report here.
After you run the source code you will get the report like this.
Subject: 503 : Dot Net Programming CLASS: TYBBA(CA) V SEM (2013 PATTERN)
Reference Books:
3· Murach’s VB.NET database programming with ADO.NET -Anne Prince and Doug
Lowe
Link
1.http://vb.net-informations.com/crystal-report/vb.net_crystal_report_step_by_step.html
2.http://vb.net-informations.com/