0% found this document useful (0 votes)
9 views109 pages

NET All Units

The document provides an overview of the Microsoft .NET Framework, detailing its components such as the Common Language Runtime (CLR), Microsoft Intermediate Language (MSIL), and the Framework Class Library (FCL). It explains the architecture of the .NET Framework, including memory management, threading, and the role of assemblies and namespaces. Additionally, it highlights the interoperability of different programming languages through the Common Language Specification (CLS) and the Common Type System (CTS).

Uploaded by

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

NET All Units

The document provides an overview of the Microsoft .NET Framework, detailing its components such as the Common Language Runtime (CLR), Microsoft Intermediate Language (MSIL), and the Framework Class Library (FCL). It explains the architecture of the .NET Framework, including memory management, threading, and the role of assemblies and namespaces. Additionally, it highlights the interoperability of different programming languages through the Common Language Specification (CLS) and the Common Type System (CTS).

Uploaded by

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

Unit 1. Overview of Microsoft .

NET Framework

1.1. The .NET Framework


1.1.1.Managed Code MSIL, Metadata and JIT Compilation - Automatic Memory
Management.
1.2. The Common Language Runtime (CLR)
1.3. The .NET Framework class Library

1.1 What is .Net Framework?


 Net Framework is a software development platform developed by Microsoft for
developing Windows based applications and web based application. It consists of
developer tools, programming languages, and libraries to build desktop and web
applications.
 It is also used to build websites, web services, and games.

Narrow view of .NET Application

Architecture of .Net Framework

Page 1
Unit 1. Overview of Microsoft .NET Framework

Page 2
Unit 1. Overview of Microsoft .NET Framework

The .NET Framework consists of:

(1) Common Language Runtime (CLR)


 .NET Framework provides runtime environment called Common Language Runtime
(CLR).
 It is the heart of .net framework. It is the engine that compiles and run the application.
It uses MSIL code which is language independent for execution. The MSIL code is
translated by JIT compiler.
 It provides an environment to run all the .NET Programs.
 The code which runs under the CLR is called as Managed Code.
 Programmers need not to worry on managing the memory if the programs are running
under the CLR as it provides memory management and thread management.

Execution In CLR

Page 3
Unit 1. Overview of Microsoft .NET Framework

Microsoft Intermediate Language

 MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate


Language (IL) or Common Intermediate Language (CIL).
 The .NET Compiler will create MSIL while you run your program and JIT (Just in Time
compiler) will convert your Intermediate Language to machine code (Native Code).
 Microsoft Intermediate Language (MSIL) is a CPU-independent set of instructions that
can be efficiently converted to the native code.
 Microsoft Intermediate Language is also called Manage Code.
 When a compiler produces Microsoft Intermediate Language (MSIL), it also produces
Metadata (Data about Data).
 Metadata is nothing but a description of every namespace, class, method, Property etc.
 The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable
executable (PE) file.
 Microsoft Intermediate Language (MSIL) includes instructions for loading, storing,
initializing, and calling methods on objects.
Base Class Libraries (BCL)

 It is also known as framework class library(FCL)


 It is the object-oriented collection of reusable types. It is a Library of prepackaged
functionality and Applications.
 It provides classes which encapsulate a number of common functions, including file
reading & writing, Grahics rendering, database interaction and XML document
manipulation.
(2) ADO.Net and XML
 It is also known as data access layer. With the help of this layer we can access relational
databases. It work with XML and provides the disconnected Data Model.
 It is a part of BCL.it consists of two parts
o Data Provider
o Data Set
(3) Window Forms
 It is also known as Win Forms. It is used to create GUI for windows desktop application.
 it also provides integrated and unified way of developing GUI
 It has a rich variety of windows controls and user interface support like Textbox,
Button, Checkbox, Etc.
 Using visual Studio.NET, we can simply design the GUI by dragging the controls on a
form.

Page 4
Unit 1. Overview of Microsoft .NET Framework

(4) Web Forms & web Services


 It provides a tool for web application. It is a part of ASP. Net
 It is the forms engine that provides Browser –based user interface.
 Web Forms are similar to Windows Forms in that they provide properties, methods, and
events for the controls that are placed onto them.
 However, these UI elements render themselves in the appropriate markup language
required by the request, e.g. HTML.
 If you use Microsoft Visual Studio® .NET, you will also get the familiar drag-and-drop
interface used to create your UI for your Web application.
Web Services
 Web services are the applications that run on a web server and communicate with other
application. It uses a series of XML based communicating protocols that respond to
different requests.
 The protocols on which web services are built summarized below:
 UDDI (Universal Discovery and Description Integration)
 WSDL (Web services Description Language)
 SOAP (Simple Object Access Protocol)
 XML (Extensible Markup Language),HTTP(Hypertext Transfer Protocol),SMTP(Simple
Mail Transfer Protocol)

(5) The Common Language Specification (CLS)

 It is a set of rules and constraints that all language must follow which want to be
compatible with .NET framework.
 It is used to support the theme of .NET i.e. unification and interoperability (The ability
of computer systems or software to exchange and make use of information). That
means, if we want the code which we write in a language to be used by programs in
other language(cross-language integration) then it should hold on to the CLS.
 Thus the CLS describes a set of features that are common different languages.
CLS performs the following functions:

 Establishes a framework that helps enable cross-language integration, type safety,


and high performance code execution.
 Provides an object-oriented model that supports the complete implementation of
many programming languages.
 Defines rules that languages must follow, which helps ensure that objects written in
different languages can interact with each other.

Page 5
Unit 1. Overview of Microsoft .NET Framework

Some Concept which are important in .Net

Assembly All of the managed code that runs in .NET must be contained in an assembly.
Logically, the assembly is referenced as one EXE or DLL file. Physically, it may consist of a
collection of one or more files that contain code or resources such as images or XML data. An
assembly is created when a .NET compatible compiler converts a file containing source code
into a DLL or EXE file.

Manifest. Each assembly must have one file that contains a manifest. The manifest is a set of
tables containing metadata that lists the names of all files in the assembly, references to
external assemblies, and information such as name and version that identify the assembly.
Metadata When a compiler produces Microsoft Intermediate Language (MSIL), it also produces
Metadata (Data about Data). Metadata is nothing but a description of every namespace, class,
method, Property etc. The Microsoft Intermediate Language (MSIL) and Metadata are
contained in a portable executable (PE) file. It allows loading and locating code, enforcing code
security, generating native code, and providing reflection at runtime.

1.2 The Common Language Runtime

 .NET Framework provides runtime environment called Common Language Runtime


(CLR).It is the heart of .net framework. It is the engine that compiles and run the
application. It uses MSIL code which is language independent for execution. The MSIL
code is translated by JIT compiler.
 It provides an environment to run all the .NET Programs. The code which runs under the
CLR is called as Managed Code. Programmers need not to worry on managing the
memory if the programs are running under the CLR as it provides memory management
and thread management.

Page 6
Unit 1. Overview of Microsoft .NET Framework

Execution in CLR

When the .NET program is compiled, the output of the compiler is not an executable file but a
file that constraints a special type of code is called Microsoft intermediate language , which is a
low level set of instructions understand by CLR.

 The MSIL defines a set of portable instructions that are CPU indendendent.
 It’s the job of the CLR to translate this MSIL into native code when the program is
executed, making the program to run in any environment for which the CLR is
implemented. And that’s how the .NET framework achieves Portability (run in any
environment). This MSIL is converts into Native code using JIT(Just In Time)compiler
Purpose of CLR

Page 7
Unit 1. Overview of Microsoft .NET Framework

 Thread Support: Threads are managed under the Common Language Runtime.
Threading means parallel code execution. Threads are basically light weight processes
responsible for multi-tasking within a single application.
 COM Marshaler: It allows the communication between the application and COM
objects.
 Type Checker Type checker will verify types used in the application with CTS or CLS
standards supported by CLR, this provides type safety.
 Exception Manager: it handles all the runtime exceptions(Error) thrown by application
 Security Engine: It enforces security permissions at code level security, folder level
security, and machine level security using Dot Net Framework setting and tools
provided by Dot Net.
 Debug Engine: CLR allows us to perform debugging an application during runtime.
 MSIL: Microsoft Intermediate Language is considered to be the lowest form of human
readable language. It is CPU independent and includes instructions of how to load,
store, initialize objects. JIT converts this MSIL into native code which is independent on
the CPU
 Code Manager: CLR manages code. When we compile a .NET application you don't
generate code that can actually execute on your machine. You actually generate
Microsoft Intermediate Language (MSIL or IL). All .NET code is IL code. IL code is also
called Managed Code, because the .NET Common Language Runtime manages it.
 Garbage Collector Garbage Collector handles automatic memory management and it
will release memory of unused objects in an application, this provides automatic
memory management.
 Class Loader: as and when needed. It loads the class into the system memory.

1.3 The .Net Framework Class Library


 The Framework Class Library (FCL) is a collection of classes and other types
(enumerations, structures, and interfaces) that are available to managed code written
in any language that targets the CLR.
 The resources within the FCL are organized into logical groupings called namespaces.
For example, types used for graphical operations are grouped into the System.Drawing.
 Types required for file I/O are members of the System.IO namespace. Namespaces
represent a logical concept.
 The FCL comprises hundreds of assemblies (DLLs), and each assembly may contain multiple
namespaces.

Page 8
Unit 1. Overview of Microsoft .NET Framework

1.3.1 Namespace (IMP)

 Namespace is the Logical group of types (Class). We can say Namespace is a container (e.g.
Class, Structures, Interfaces, and Enumerations etc).

Lists some of the most important namespaces in .NET.


Namespace Use
System.Data Classes used for database operations (ADO.NET). The client namespaces
support Oracle and SQL Server, respectively; OledDb and Odbc define the
System.Data.OracleClient data connection used.

System.Data.SqlClient

System.Data.OleDb

System.Data.Odbc
System.IO Provides file and data stream I/O. These classes provide a way to access
the underlying file systems of the host operating system.
System.Windows.Forms Classes used to build Windows desktop GUI applications. Controls
including the ListBox, TextBox, DataGrid, and buttons are found here.
System.Xml Types for processing XML.
System.Web The Internet-related classes referred to as ASP.NET. They manage
browser-server communication requirements, manipulate cookies, and
contain the controls that adorn a Web page.
System.Web.Services Web.Services includes those classes required for SOAP-based XML
messaging.

Page 9
Unit 1. Overview of Microsoft .NET Framework

1.3.2 Common Type System (CTS)

It defines how types are declared, used, and managed in the common language runtime, and is
also an important part of the runtime's support for cross-language integration.
The common type system performs the following functions:
 Establishes a framework that helps enable cross-language integration, type safety, and
high-performance code execution.
 Provides an object-oriented model that supports the complete implementation of many
programming languages.
 Defines rules that languages must follow, which helps ensure that objects written in
different languages can interact with each other.
 Provides a library that contains the primitive data types (such
as Boolean, Byte, Char, Int32, and UInt64) used in application development.

For example, C# has an int data type and VB.NET has Integer data type. Hence a variable
declared as an int in C# and Integer in VB.NET, finally after compilation, uses the same
structure Int32 from CTS.

Page 10
Unit 1. Overview of Microsoft .NET Framework

1.3.2.1 Data Types

SrNo. Data Types Storage Size Description


1 Short 2 bytes -32,768 to 32,767
2 Integer 4 bytes -2,147,483,648 to 2,147,483,647
3 Long 8 bytes -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
4 Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values;
1.401298E-45 to 3.402823E+38 for positive values
5 Double 8 bytes -1.79769313486231E+308 to 4.94065645841247E-324
for negative
values; 4.94065645841247E-324 to
1.79769313486231E+308 for positive
values
6 Decimal 16 bytes Signed integer that can have 28 digits on either side of
decimal
7 Char 2 bytes 0 to 65535 (unsigned)
8 String Variable 0 to approximately 2 billion Unicode characters
length
9 Boolean 4 bytes True or False
10 Byte 1 bytes 0 to 255 (unsigned)
11 Date 8 bytes January 1, 0001 to December 31, 9999
12 Object 4 bytes Any type can be stored in a variable of type Object

Page 11
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Sascma BCA College
Unit 4.Object Oriented Programming

4.1. Creating Classes, Object Construction & Destruction


4.1.1 . Properties, Methods, Events

4.1.2 . Access Specifiers: Public, Private, Protected,


Protected Friend

4.1.3 . Me, MyBase and MyClass keywords

4.2. Abstraction, Encapsulation & Polymorphism

4.3. Interfaces & Inheritance

 Object Oriented Concepts


• Object-oriented programming (oop) is a programming approach that uses “objects”-data
structures consisting of data fields and methods and their interactions to design applications and
computer programs.
• Object oriented programming creates data as critical elements in the program development and
do not allow it to flow freely around the system.
• All OOP based languages supports the following concepts.
▪ Class and Object
▪ Abstraction and Encapsulation
▪ Constructor and Destructor
▪ Inheritance
▪ Polymorphism

4.1. Creating Classes, object Construction & Destruction

Class

• Class is a group of methods and variables where methods are known as Member function and variables
are known as Data Member.
• In vb.net class is created using Class Keyword and completed with End Class.
• Once class is created you can created any number of objects.
Syntax

[<attrlist>][Access Modifier]

[Shadows][MustInherit|NotInheritable]Class<classname>

[Implements interfacename][Inherits classname]

[statement(s)]

SASCMA BCA COLLEGE Page 1


Unit 4.Object Oriented Programming
End Class

o Access_Specifier: It defines the access levels of the class, like 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). Example

Objects

• It is basic runtime entities.It is variables if the class.


• It is member of class which is able to access methods and variables of class which has been declared in
Public Mode.
• In vb.net ,it can be created as follows:

Syntax
<object> As New <Class Name>

Example

Abstraction

• It refers to the act of representing essentials features without including the background details or
explanations.
• It defines way to abstract or hide your data and members from outside class.
• Classes use the concept of Abstraction.
• When we define a classes then different accessibility mode define the access level of variables and
methods. They are Public, Private, Protected.

Example

Public MustInherit Class Operators


MustOverride Sub add(ByVal a As Integer, ByVal b As Integer)
MustOverride Sub div(ByVal a As Integer, ByVal b As Integer)
End Class
Class Arithmetic
Inherits Operators

SASCMA BCA COLLEGE Page 2


Unit 4.Object Oriented Programming

Public Overrides Sub add(ByVal a As Integer, ByVal b As Integer)


MsgBox("Addition:" & (a + b))
End Sub

Public Overrides Sub div(ByVal a As Integer, ByVal b As Integer)


MsgBox("Division:" & (a / b))
End Sub
End Class
Add windows form and write down the following code in btnabstraction click event.
Public Class Form1

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


Handles Button1.Click
Dim d1 As New Arithmetic
d1.add(25, 75) d1.div(25,
5)
End Sub
End Class
Encapsulation

• It is a process to bind data and methods in a unit called class. When we define class that process itself
define the concept of Encapsulation.
• When we define class that process itself define the concept of Encapsulation.
• It can protect your data from accidental corruption.
• Rather than defining the data in the form of public, we can declare those fields as private.

Example:

Public Class Subject


Private scode As Integer
Private sname As String
Sub New(ByVal a As Integer, ByVal b As String)
scode = a sname = b
End Sub
Protected Overrides Sub finalize()
MsgBox(" i am Destructor")
Beep()

End Sub
Sub display()
MsgBox("Subject code:" & scode & " " & "Subject Name:" & sname)
End Sub
End Class
Constructor

• A constructor is a special procedures which are called automatically when object of the class is created
to initialize the object.New keyward is used to create constructor.Constructor can be overloaded.

SASCMA BCA COLLEGE Page 3


Unit 4.Object Oriented Programming
• Constructors are of the two types:Default Constructor and parameterized Constructor.Default
constructor is the constructor is the constructor which does not take any argument.Parameterised
constructor is a constructor which takes argument.
• In vb.net, The name of constructor is NEW().
• It can be overloaded.

Example:
Add class file and give name constructorexample

Public Class constructorexample


Dim x As Integer
Dim y As New Integer
Sub New() 'Default constructor
MsgBox("i am constuctor")
End Sub
Sub New(ByVal a As Integer) 'parameterized constructor
y = x
MsgBox("i am paramiterrized constructor")
MsgBox(y)
End Sub
Protected Overrides Sub finalize()
y = 0
MsgBox("i m desctuctor")
End Sub

End Class
• How to call Base Class Constructor o It can be called using
MyBase keyword. o It cannot be used to access private members
of class. o It refers to the immediate base class and its inherited
members .

Example:
Public Class ClsBase
Private x, y As Integer
Sub New() x = 0
y = 0
End Sub
Sub New(ByVal a As Integer, ByVal b As Integer)
x = y y = b
End Sub

End Class

Public Class clasderive


Inherits ClsBase

SASCMA BCA COLLEGE Page 4


Unit 4.Object Oriented Programming
Private z As Integer
Sub New() z = 0
End Sub
Sub New(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)
MyBase.New(a, b)
z = c
MsgBox(a & b & c)

End Sub
End Class

Add windows form and write down the following code in btnconstructor click event.
Public Class Form1

Private Sub btnConstructor_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnConstructor.Click
Dim obj As New clasderive
Dim obj1 As New clasderive(4, 5, 8)
End Sub
End Class

Destructor(Finalize)

• Destructor is a special function which is called automatically when a class is destroyed.It is a last method
run by a class.
• It is called when ever the .NET runtime is told directly or otherwise determines that an object is no
longer required.
• Within a destructor we can place code to clean up the object after it is used ,which might include
decrement counters releasing resources.
• It cannot be overloaded.

Syntax

Protected Overrides Sub Finalize()

Logic

End Sub

Example:

Protected Overrides Sub finalize()


y = 0
MsgBox("i m desctuctor")
End Sub

SASCMA BCA COLLEGE Page 5


Unit 4.Object Oriented Programming

Inheritance

o It is a process of creating a new class called derives class from the existing class called Base Class. o The
existing class is known as parent, base, super class.
• The new class is known as child, derive, sub class.
• It is also known as code reusability.
• It can be created by using inherits keyword.
• A derive class obtain all of the methods, properties, and events of the base class.

There are 3 modifier related with inheritance.

o Inherits
o NotInheritable o MustInherit(Abstract Class)

Syntax

Syntax
Class<class Name>

[inherits] Base className


Statements

End Class

Polymorphism

• It means “one name, multiple forms


• There are two types of it (1) Design time (2)Run time
• Design time polymorphism is achieved by function overloading
• Run time polymorphism is achieved by function overriding
• Function overloading means we can declare more than one functions with the same name but
arguments are different.

Example:

Public Class polymor


Function add(ByVal a As Integer)
Return MsgBox(a)

End Function

Function add(ByVal a As Integer, ByVal b As Integer)

SASCMA BCA COLLEGE Page 6


Unit 4.Object Oriented Programming
Return MsgBox(a + b)
End Function
Function add(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)
Return MsgBox(a + b + c)
End Function
End Class

Write this code on btnpoly_click event

Public Class Form1

Private Sub btnpoly_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btnpoly.Click
Dim obj As New polymor
obj.add(5) obj.add(5, 6)
obj.add(10, 20, 50)
End Sub
End Class
Run time polymorphism(function overriding)
• Function overriding means when we declare more than one function with same name but in
different class and the relationship between class is parent –child
• The overriding concept achieve only in inheritance.
• Derive class inherits methods from its base class
• If an inherited property or method needs to behave differently in the derived class.
• Overridable keyword is used to mark a function as override. We can redefine overridable
methods in derived class
• The overrides keyword is used to mark that a function is overriding some base class function.
• The overrides keyword overrides an overridable property or method defined in the base class

Example:

Public Class clsoverridable


Public Class base
Overridable Sub dis()
MsgBox("Base class")

End Sub
End Class
Public Class clsderived
Inherits base
Public Overrides Sub dis()
MyBase.dis()
MsgBox("Derived class")
End Sub
End Class
End Class

SASCMA BCA COLLEGE Page 7


Unit 4.Object Oriented Programming

Write this code in btnoverriding_click Event

Public Class Form1

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


System.EventArgs) Handles btnoverriding.Click
Dim obj As New clsoverridable.clsderived
obj.dis()
End Sub
End Class

• Interface

Why interface used?

We cannot inherit more than one class in vb.net. If we wants to inherit then? Use interface

Interface

• Interfaces like classes define a set of properties, methods and events. But unlike classes, an interface does
not contain any implementation code
• Interface represents “Has a” relationship
• Classes which implements interface they write the coding in the interface’s method
• We can implements multiple interface
• If we want to use interface then we need to write” Implements” keyword Syntax Public Interface iface1
….logic End Interface

Syntax
Public interface abc1
….logic
End interface

Add interface in your project

Public Interface Interface1


Sub abc()
End Interface

Add interface in your project

Public Interface Interface2


Sub hello()
End Interface

SASCMA BCA COLLEGE Page 8


Unit 4.Object Oriented Programming
Add Class File in your project

Public Class clssinterface


Implements Interface1, Interface2

Public Sub abc() Implements Interface1.abc


MsgBox("good morning")
End Sub

Public Sub hello() Implements Interface2.hello


MsgBox("hello hoe are you")
End Sub
End Class

Write down this code in btninterface_click Event


Public Class Form1

Private Sub btninterface_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles btninterface.Click
Dim obj As New clssinterface
obj.abc() obj.hello()

End Sub
End Class

SASCMA BCA COLLEGE Page 9


Unit 5 Database access using ADO.NET

5.1. Visual Database Tools

5.2. ADO .NET Object Model

5.3. ADO .NET Programming

5.1. Visual Database Tools


 The Visual Database Tools are a combination of design tools you can use to work with a
data source.
 You can use them to create queries, design or modify a database structure, or update
data.
 The tools are Database Diagram Designer, Table Designer, and Query and View Designer.
 The database is design, it allows you to create database object such as tables, columns,
keys, indexes, relationships, constraints and views.

Visual database tools provide 3 designers to create these objects:


I. Database diagram
II. Table designer
III. Query and View designer

i. Database Diagram
Database diagram tool allows user to design and visualize a database to
which we are connected. This diagram contains the tables along with the
relationship and primary key.
ii. Table designer
It provides an entire window to design the individual table. It also allow
user to change an existing database by changing, adding, duplicating and
deleting table. It is used to add or remove columns, specify its data type,
size, description, keys, constraints and relationships.

Page 1
Unit 5 Database access using ADO.NET

iii. Query and View designer


It helps user to create and maintain the data retrieval and data
vmanipulation.When user designs any query,view,functions,or stored
procedure,the designer is made up of panes.

 ADO.NET
o ADO.NET has the ability to separate data access mechanisms,data
manipulation mechanisms and data connectivity mechanisms.
o ADO.NET ia a set of classes that allow application to read and write
information in database.
o ADO.NET can be used by any .NET language.
o We need to add System.Data namespace for work with ADO.NET.
o Ado.Net is a technology which works between access database
Frontend Application. It is used to access database.

5.2. ADO.NET Object Model

 ADO.NET is an object-oriented set of libraries that allows you to interact


with data sources.
 The data source is a database,but it could also be a text file,an Excel spread-
sheet,or an XML file.
 There are many different types of databases available such
asMicrosoftSQLSever,MicrosoftAccess,Oracle,BorlandInterbase,IBMDB2
etc.
 Connected & Disconnected Data(Architecture)
The data access with ADO.NET consists of two parts:
(1) Data Provider
(2) DataSet

(1) Data Provider

 The Data Provider is responsible for providing and maintaining the connection
to the database.

Page 2
Unit 5 Database access using ADO.NET

 A DataProvider is a set of related components that work together to provide


data in an efficient and performance driven manner.
 The .NET Framework currently comes with two DataProviders: the SQL Data
Provider which is designed only to work with Microsoft's SQL Server 7.0 or
later and the OleDb DataProvider which allows us to connect to other types of
databases like Access and Oracle. Each DataProvider consists of the following
component classes:

The Connection object which provides a connection to the database


The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected
recordset
The DataAdapter object which populates a disconnected DataSet with data and
performs update

Data access with ADO.NET can be summarized as follows:

 A connection object establishes the connection for the application with the
database.
 The command object provides direct execution of the command to the database.
If the command returns more than a single value, the command object returns a
DataReader to provide the data.

Page 3
Unit 5 Database access using ADO.NET

 Alternatively, the DataAdapter can be used to fill the Datasetobject. The


database can be updated using the command object or the DataAdapter.

Data Providers:

 It is responsible for providing and maintaining the connection to the


database. We can use following data provider in Ado.Net

• Oledb (for Access Database)


• Sqlclient( for sqlserver Database)
• Oracle (for oracle Database)

Page 4
Unit 5 Database access using ADO.NET

• Odbc (for odbc Databse)

o Ado.NET Objects
ADO.NET consists of many objects that are used to work with data.
a) Connection Object
b) Command Object
c) DataAdapter Object
d) DataReader Object

a) Connection Object
 To establish connection with a database,you must have a connection
object.
 The connection object helps to identify the datadase sever,the
database name,user name,password,and other parameters that are
required for connecting to the database.
 A connection object is used by command objects so that it will know
on which database the command is executed.

Connection String – A string that specifies information about a data source


and the means of connection to it is called Connection String.
Dim con As New SqlConnection

con.ConnectionString = "Data
Source=.\SQLEXPRESS;AttachDbFilename=D:\jigisha\vb.netDemo_s
y6\sy6\sy6\Database1.mdf;Integrated Security=True;User
Instance=True"

Properties
Properties Description
conectionString It stores the connection string that is passed to the
connection object at the time of creating its object.
Database It stores the name of the database to which you need to
connect.
State It return the state of thae connectionEX.IsClose or IsOpen

Page 5
Unit 5 Database access using ADO.NET

Connection TimeOut Gets the time to wait while trying to establish a connection
before terminating the attempt and generating an error.

Methods
Methods Description
Open It opens the connection
Close It closes the connection
BeginTransaction It creates the Transaction Object.
ChangeDatabase It creates and returns a SqlCommand object associated with
the SqlConnection.
ChangeDatabase It changes the current database for an open SqlConnection.

(b) Command Object

 It is used to retrieve a subset of data.Also invoking SQL statements


insert,Update and Delete are directly require to set certain parameters on
the command before executing the statement.common use of the
command object
 Is to execute stored procedure and pass the appropriate parameters to the
stored procedure.

Properties
Properties Description
Connection To set a connection object.
CommandText It specifies the SQL string or stored procedure to be
executed.
CommandType It is used to determine how to interpret command text.
Ex. CommandText is storedprocedure or Text or DirectTable.
CommandTimeOut Gets the time to wait while trying to execute the command
before terminating the attempt and generating an error.

Methods
Methods Description
ExecuteNonQuery It will execute the SQL statement and returns the number
of rows affected by the query.
ExecuteScalar It will execute the SQL statement which return the

Page 6
Unit 5 Database access using ADO.NET

singleton value.
ExecuteReader It will execute the SQL statement and returns the records
in the form of DataReader.Ex.it is used to create the object
of DataReader.
CreateParameter It creates and returns a Sqlparameter object associated
with the SqlCommand.
Cancel It is used to cancel the command given for for execution.
ResetCommandTimeOut It is used to reset Command time out property to its
default value.

( C ) DataReader Object

 A SqlDatReader is used to read data in the most efficient manner.You


cannot use it for writing data.
 You can read forward-only and in sequential manner from
SqldataReader.

Properties
Properties Description
FieldCount It stroes number of fields in a row.
HasRows It specifies that the rows are selected or not for reading.
IsClosed It specifies that DataReader is closed or not.
RecordsAffected It returns -1 as DataReader is created on server.
Item It gets the value of the specified column name.

Methods
Methods Description
Read It reads the Next Record of DataReader.
Close It is used to Close the DataReader Connection with the
database.
IsDBNull It checks that the value of the column is Null or net.
GetSchemaTable It returns the object of the DataTable for which the
DataReader is created.
GetValues It returns the array of the values for the row.
NextResult It is used to nagate from one record set to another when

Page 7
Unit 5 Database access using ADO.NET

more than one record sets are used in the command.

(e) DataAdapter

 It acts as a bridge between data source and in-memory data objects such as
the Dataset.

Properties
Properties Description
selectCommand It is used to hold a Command that retrieves data from the
data source.
UpdateCommand It is used to hold a Command that updates data from the
data source.
DeleteCommand It is used to hold a Command that delete data from the data
source
InsertCommand It is used to hold a Command that insert data from the data
source
Command and Type It indicates CommandText property which contains SQL
statement or stored procedure.If commandText property
contains stroed procedure than user can set the value to
CommandType.stored procedure.Default value is
CommandType.Text for SQL statement.

Methods
Methods Description
Fill It is used to populate a dataset object with the data that the
DataAdapter object retrieve from the data store using its
SelectCommand.But before that we must initialize a Dataset
object.
Update It is used to update the database according to the changes
that are made in the DataSet.

(2) DataSet

Page 8
Unit 5 Database access using ADO.NET

 The dataset is a disconnected, in-memory representation of data. It can be


considered as a local copy of the relevant portions of the database.
 The DataSet is continue in memory and the data in it can be manipulated and
updated independent of the database.
 When the use of this DataSet is finished, changes can be made back to the
central database for updating.
 The data in DataSet can be loaded from any valid data source like Microsoft
SQL server database, an Oracle database or from a Microsoft Access database.

5.3. ADO.NET Programing


Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim Eid As Integer

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.Load
Try

con.ConnectionString = "Data
Source=.\SQLEXPRESS;AttachDbFilename=D:\jigisha\vb.net
Demo_Example\Demo_Example\Demo_Example\Database1.mdf;Integrated Security=True;User
Instance=True"
cmd.Connection = con

Catch ex As Exception
MsgBox(ex.Message)

End Try
display()
End Sub

Sub display()
Try
cmd.CommandText = "select * from Employee"
Dim dt As New DataTable
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Sub insert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles insert.Click
Try

Page 9
Unit 5 Database access using ADO.NET
cmd.CommandText = "insert into Employee values('" & txtid.Text & "','" &
txtname.Text & "'," & txtsalary.Text & " )"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Record is inserted")
Catch ex As Exception
MsgBox(ex.Message)

End Try
display()
clearconrtol()
End Sub

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Try
txtid = DataGridView1.Rows(e.RowIndex).Cells(0).Value
txtname = DataGridView1.Rows(e.RowIndex).Cells(1).Value
txtsalary = DataGridView1.Rows(e.RowIndex).Cells(2).Value

Catch ex As Exception
MsgBox(ex.Message)

End Try
End Sub

Private Sub update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles update.Click
Try
cmd.CommandText = "update Employee set Ename ='" & txtname.Text & "', salary
=" & txtsalary.Text & " where Eid = '" & txtid.Text & "' "
con.Open()
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Record is updated")
Catch ex As Exception
MsgBox(ex.Message)
End Try
display()
clearconrtol()

End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button3.Click
Try
cmd.CommandText = "delete from Employee where Eid=" & txtid.Text & " "
con.Open()
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Record is deleted")
Catch ex As Exception
MsgBox(ex.Message)
End Try
display()
clearconrtol()

Page 10
Unit 5 Database access using ADO.NET
End Sub
Sub clearconrtol()
txtname.Text = ""
txtid.Text = ""
txtsalary.Text = ""
End Sub
End Class

Output:

Output:

Page 11
Unit 5 Database access using ADO.NET

Page 12

You might also like