Anda di halaman 1dari 33

 Overview of the .

NET Framework

The .NET Framework is a platform for building, deploying, and running Web Services and
applications. It consist of components such as common language runtime (CLR) and the .NET
Framework class library, which includes classes, interfaces, and value types that support wide
range of technologies.

The .NET Framework is a class of reusable libraries (collection of classes) given by Microsoft to
be used in other , also .NET Framework provides an execution environment, simplified
development and deployment, and integration with a variety of programming languages,
including Visual Basic and Visual C#.

.Net Framework Architecture - The .NET Framework consists of three main parts:
1. Common Language Runtime - The common language runtime is the foundation of the .NET
Framework. Think of the runtime as an agent that manages code at execution time, providing
core services such as memory management, thread management, and remoting, while also
enforcing strict type safety and other forms of code accuracy that promote security and
robustness. In fact, the concept of code management is a fundamental principle of the runtime.
Code that targets the runtime is known as managed code, while code that doesn't target the
runtime is known as unmanaged code.

2. Unified class libraries - 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.

3. Active Server Pages called 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. Internet Information Services or IIS is a Microsoft component which is used to execute
anAsp.Net application.

 Common Language Runtime

The Common Language Runtime (CLR) is an Execution Environment . It works as a layer between
Operating Systems and the applications written in .Net languages that conforms to the Common
Language Specification (CLS).

The main function of Common Language Runtime (CLR) is to convert the Managed Code into
native code and then execute the Program. The Managed Code compiled only when it needed,
that is it converts the appropriate instructions when each function is called .

The Common Language Runtime (CLR) 's Just In Time (JIT) compilation converts Intermediate
Language (MSIL) to native code on demand at application run time.
During the execution of the program ,the Common Language Runtime (CLR) manages memory,
Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS),
code safety verifications, and other system services.

The CLR ( Common Language Runtime ) defines the


Common Type System (CTS), which is a standard
type system used by all .Net languages . That means
all .NET programming languages uses the same
representation for common Data Types , so
Common Language Runtime (CLR) is a language-
independent runtime environment .

The Common Language Runtime (CLR) environment


is also referred to as a managed environment, because during the execution of a program it also
controls the interaction with the Operating System. In the coming section you can see what are
the main functions of Common Language Runtime (CLR).

 Responsibilities of CLR:

1. Automatic memory management - CLR calls various predefined functions of .NET


framework to allocate and de-allocate memory of .NET objects. So that, developers need
not to write code to explicitly allocate and de-allocate memory.

2. Code access security - CLR allows access to code to perform only those tasks for that it has
permission. It also checks user’s permissions using authentication and configuration files
of .NET applications.

3. Garbage collection - GC is used to prevent memory leaks or holes. Garbage collector of


CLR automatically determines the best time to free the memory, which is allocated to an
object for execution.

4. JIT compilation - JIT stands for Just In Time. It is also an important part of Common
Language Runtime (CLR), JIT compiler converts MSIL code to targeted machine code for
execution.

 .NET Framework Assemblies

Microsoft .Net Assembly is a logical unit of code, that contains code which the Common
Language Runtime (CLR) executes. It is the smallest unit of deployment of a .net application and
it can be a .dll or an exe . Assembly is really a collection of types and resource information that
are built to work together and form a logical unit of functionality. It include both executable
application files that you can run directly from Windows without the need for any other
programs (.exe files), and libraries (.dll files) for use by other applications.
Assemblies are the building blocks of .NET Framework applications. During the compile
time Metadata is created with Microsoft Intermediate Language (MSIL) and stored in a file
called Assembly Manifest . Both Metadata and Microsoft Intermediate Language (MSIL)
together wrapped in a Portable Executable (PE) file. Assembly Manifest contains information
about itself. This information is called Assembly Manifest, it contains information about the
members, types, references and all the other data that the runtime needs for execution.

Every Assembly you create contains one or more program files and a Manifest. There are two
types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly can
have only one entry point (that is, DllMain, WinMain, or Main).

We can create two types of Assembly:

1. Private Assembly - A private Assembly is used only by a single application, and usually it is
stored in that application's install directory.

2. Shared Assembly - A shared Assembly is one that can be referenced by more than one
application.

If multiple applications need to access an Assembly, we should add the Assembly to the Global
Assembly Cache (GAC).

There is also a third and least known type of an assembly:

 Satellite Assembly - A Satellite Assembly contains only static objects like images and
other non-executable files required by the application.

 Uses of assemblies

i. It contains code that the common language runtime executes. Microsoft intermediate
language (MSIL) code in a portable executable (PE) file will not be executed if it does not
have an associated assembly manifest. Note that each assembly can have only one entry
point (that is, DllMain, WinMain, or Main).

ii. It forms a security boundary. An assembly is the unit at which permissions are requested
and granted.

iii. It forms a type boundary. Every type's identity includes the name of the assembly in which
it resides. A type called MyType that is loaded in the scope of one assembly is not the
same as a type called MyType that is loaded in the scope of another assembly.

iv. It forms a reference scope boundary. The assembly's manifest contains assembly
metadata that is used for resolving types and satisfying resource requests. It specifies the
types and resources that are exposed outside the assembly. The manifest also enumerates
other assemblies on which it depends.
v. It forms a version boundary. The assembly is the smallest versionable unit in the common
language runtime; all types and resources in the same assembly are versioned as a unit.
The assembly's manifest describes the version dependencies you specify for any
dependent assemblies.

vi. It forms a deployment unit. When an application starts, only the assemblies that the
application initially calls must be present. Other assemblies, such as localization resources
or assemblies containing utility classes, can be retrieved on demand. This allows
applications to be kept simple and thin when first downloaded.

 Global Assembly Cache (GAC)


global - applies to the entire machine
assembly - what .NET calls its code-libraries (DLLs)
cache - a place to store things for faster/common access
The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies
that are specifically designated to be shared by all applications executed on a system.

The GAC is a machine-wide code cache used for side-by-side execution of assemblies. The GAC
implements the feature of shared library where different applications reuse the code placed in
the files located in a common folder.

The two tools related to GAC are –

1. GAC Tool (gacutil.exe) - GAC Tool is used to check for assembly existence, register a shared
assembly, view and manipulate contents of GAC, etc. Being a system folder, it requires
administrator privileges to be used.
2. Assembly Cache Viewer (shfusion.dll) - Assembly Cache Viewer is used to display the details
(version, culture, etc.) associated with the assemblies contained in the cache.

GAC provides the benefits of code reuse, file security (due to its installation in ‘systemroot’
directory and hence deletion is only by users with Administrator privileges), side-by-side
execution (allowing multiple versions of an assembly maintained in the same folder), etc.

 Events in .NET Framework

An event is "something" that occurs in consequence of an action, in the given example, the action
is the button pressing. An event is a message sent by an object to signal the occurrence of an
action. The action could be caused by user interaction, such as a button click, or it could be raised
by some other program logic, such as changing a property’s value.
Events in the .NET Framework are based on the delegate model. The delegate model follows the
observer design pattern, which enables a subscriber to register with, and receive notifications
from a provider.

The objects that fire them (called event senders), however, don't know what must be done
when certain event occurs. For this is necessary to inform which method (called event handler)
will be executed at each occurrence of this event. This is not an difficult task and we do it every
day, even automatically.

To define an event, you use the event (in C#) or Event (in Visual Basic) keyword in the signature
of your event class, and specify the type of delegate for the event.

Typically, to raise an event, you add a method that is marked as protected and virtual (in C#)
or Protected and Overridable (in Visual Basic). Name this method OnEventName; for
example, OnDataReceived. The method should take one parameter that specifies an event data
object. You provide this method to enable derived classes to override the logic for raising the
event. A derived class should always call the OnEventName method of the base class to ensure
that registered delegates receive the event.

 .Net Namespaces
The frameworks around them have greatly increased in size. The .NET framework provides a
huge number of base classes, data types, algorithms, etc. If every one of these items had to be
declared with a unique name, the naming task would be equally large and would leave very few
good names available for the .NET developer.
To ensure that naming conflicts do not occur, either within the .NET framework or in your own
programs, namespaces are used.

Namespaces are the way to organize .NET Framework Class Library into a logical grouping
according to their functionality, usability as well as category they should belong to, or we can
say Namespaces are logical grouping of types for the purpose of identification.
Syntax - namespace namespace-name {}

The .NET Framework Class Library (FCL ) is a large collection of thousands of Classes. These
Classes are organized in a hierarchical tree. The System Namespaces is the root for types in the
.NET Framework. We can uniquely identify any Class in the .NET Framework Class Library (FCL )
by using the full Namespaces of the class .In .Net languages every program is created with a
default Namespaces . Programmers can also create their own Namespaces in .Net languages.

Namespace Example
namespace FirstNamespace
{
class Test
{
public void ShowMessage()
{
Console.WriteLine("This is the first namespace!");
}}}
This code creates a new namespace named "FirstNamespace" and defines a "Test"
class containing a single method that outputs a string to the console.

 DLL in .NET Framework

A DLL is a library that contains code and data that can be used by more than one program at the

same time. By using a DLL, a program can be modularized into separate components. For example,

an accounting program may be sold by module. Each module can be loaded into the main program

at run time if that module is installed. Because the modules are separate, the load time of the

program is faster, and a module is only loaded when that functionality is requested.

Additionally, updates are easier to apply to each module without affecting other parts of the

program. For example, you may have a payroll program, and the tax rates change each year. When

these changes are isolated to a DLL, you can apply an update without needing to build or install

the whole program again.

 Types of DLLs

1. Load-time dynamic linking – In load-time dynamic linking, an application makes explicit calls to
exported DLL functions like local functions. To use load-time dynamic linking, provide a header
(.h) file and an import library (.lib) file when you compile and link the application. When you do
this, the linker will provide the system with the information that is required to load the DLL and
resolve the exported DLL function locations at load time.

2. Run-time dynamic linking - In run-time dynamic linking, an application calls either


the LoadLibrary function or the LoadLibraryExfunction to load the DLL at run time. After the DLL
is successfully loaded, you use the GetProcAddressfunction to obtain the address of the
exported DLL function that you want to call. When you use run-time dynamic linking, you do
not need an import library file.

 Console Application vs Windows Application

Console Application Windows Application


Console applications are light weight programs run Windows Applications are form based
inside the command prompt (DOS) window. standard Windows desktop applications for
common day to day tasks.
Console Applications don't have user interfaces and are Windows Forms applications do have user
run in the Command Prompt. interfaces.
A console program on the other hand is a text A Windows form application is an
application. application that has a graphical user
interface(GUI) like the Visual C# IDE.
Console-based applications include Alpine (an e-mail Microsoft word is an example of a Windows
client), Lynx (a web browser), Midnight application.
Commander (a file manager), Music on
Console (an audio player), nano (a text editor), etc..

 Visual Basic.Net (VB.Net)

VB.Net is a simple, modern, object-oriented computer programming language developed by


Microsoft to combine the power of .NET Framework and the common language runtime with the
productivity benefits that are the hallmark of Visual Basic.

Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String,
Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherits from the
base class Object.

 Procedures in VB.NET
A procedure is a group of logically related statements that is used to perform a specific task.
Using the concept of procedure a large application is divided into smaller units. These units are
known as procedures.
If an application contains a block of code that may executes once or more then once at that time
you can create a procedure. So instead of writing the same block of code again and again you
just have to call that procedure.

A procedure is a block of Visual Basic statements enclosed by a declaration statement


(Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in
Visual Basic must be within some procedure.

 Calling a Procedure

You invoke a procedure from some other place in the code. This is known as a procedure call.
When the procedure is finished running, it returns control to the code that invoked it, which is
known as the calling code. The calling code is a statement, or an expression within a statement,
that specifies the procedure by name and transfers control to it.
 Returning from a Procedure
A procedure returns control to the calling code when it has finished running. To do this, it can
use a Return Statement, the appropriate Exit Statement statement for the procedure, or the
procedure's End <keyword> Statement statement. Control then passes to the calling code
following the point of the procedure call.

 Types of Procedures

1. Sub Procedures - They perform actions but do not return a value to the calling code.

A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End
Substatements. The Sub procedure performs a task and then returns control to the calling code,
but it does not return a value to the calling code.

You can define a Sub procedure in modules, classes, and structures. By default, it is Public, which
means you can call it from anywhere in your application that has access to the module, class, or
structure in which you defined it. The term, method, describes a Sub or Function procedure that
is accessed from outside its defining module, class, or structure.
 Defining Sub Procedures
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
 Modifiers − specify the access level of the procedure; possible values are - Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing,
and shadowing.
 SubName − indicates the name of the Sub
 ParameterList − specifies the list of the parameters
Passing Parameters by Value
This is the default mechanism for passing parameters to a method. In this mechanism, when a
method is called, a new storage location is created for each value parameter. The values of the
actual parameters are copied into them. So, the changes made to the parameter inside the
method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword.
 Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created for
these parameters. The reference parameters represent the same memory location as the actual
parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword.

2. Function Procedures - - They return a value to the calling code. They can perform other
actions before returning.

A Function procedure is a series of Visual Basic statements enclosed by the Function and End
Function statements. The Function procedure performs a task and then returns control to the
calling code. When it returns control, it also returns a value to the calling code.

You can define a Function procedure in a module, class, or structure. It is Public by default,
which means you can call it from anywhere in your application that has access to the module,
class, or structure in which you defined it.
 Declaration Syntax
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function

 Event-handling procedures are Sub procedures that execute in response to an event raised by
user action or by an occurrence in a program.

 VB.Net - Classes & Objects

Class A container for data and code. The data within the class can be accessed with properties.
The code is referred to as methods.

Object An instance of a class in memory. An instance is created using a Dim statement and
the New keyword.

 Constructors and Destructors


 A class constructor is a special member Sub of a class that is executed whenever we create new
objects of that class. A constructor has the name New and it does not have any return type.
 A destructor is a special member Sub of a class that is executed whenever an object of its class
goes out of scope.A destructor has the name Finalize and it can neither return a value nor can it
take any parameters. Destructor can be very useful for releasing resources before coming out
of the program like closing files, releasing memories, etc.
 Property. A Property is similar to a Function. With a getter and a setter, it controls access
to a value. This value is called a backing store.
Methods for returning values are called getters and methods for setting values are
called setters.
With Get, a property returns a value. With Set it stores a value. We must have both Get and Set
unless we specify ReadOnly or WriteOnly on the property.
Get, Set. On the Number property, we provide Get and Set blocks. In Get we return a value—the
backing store _count. In Set we receive a parameter and then store it in the _count field.
 Types:A property can have any data type. It does not need to be an Integer. It can be a Class.
 And:Additional logic can be inserted in either Get or Set. This extra layer of indirection is often
used to validate arguments.
 Assign:When the value 1 is assigned to the Number property, Set is executed. The _count field
stores the value 1.
 Access:When the Number property is accessed but not assigned to, Get is executed. The value of
the _count field is returned.
 ReadOnly. Some properties are not meant to be assigned. For example, "Count" on collections is
not mutable. The ReadOnly modifier changes the Property type to only have a Get method.
 WriteOnly. Here we use the WriteOnly keyword on a property. WriteOnly means that a Property
has only a Set() method and no Get method. In Main we create and assign to the Id property.

 Creating Properties

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

 You can create a read-only or write-only property, as opposed to a Public variable, which will
always be read-write.
 You can add error handling within a Property statement to check for invalid values being set..
 You can expose calculated values as properties even if they are not stored as actual data within
the class. An example of this is a Length property. You probably don't want to store the length
of a line of text, as it could change.

 Inheritance
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance is the idea that one class, called a subclass, can be based on another class, called a
base class. Inheritance provides a mechanism for creating hierarchies of objects.
For example, a dog is a mammal and a collie is a dog. Thus the dog class inherits the properties
and methods of the mammalclass, and the collie class inherits from both dog and mammal.
The objects in a hierarchy have two different types of relationships to one another, referred to
in object-oriented parlance as HasA and IsA relationships. For example, a Collie IsA dog and
HasA tail.
When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing
class. This existing class is called the baseclass, and the new class is referred to as
the derived class.
 Base & Derived Classes
A class can be derived from more than one class or interface, which means that it can inherit
data and functions from multiple base classes or interfaces. Syntax -
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
 Inheritance Modifiers

1. Inherits statement — Specifies the base class.


2. NotInheritable modifier — Prevents programmers from using the class as a base class.
3. MustInherit modifier — Specifies that the class is intended for use as a base class only.
Instances of MustInherit classes cannot be created directly; they can only be created as base
class instances of a derived class

 Overriding Properties and Methods in Derived Classes

By default, a derived class inherits properties and methods from its base class. If an inherited
property or method has to behave differently in the derived class it can be overridden. That is,
you can define a new implementation of the method in the derived class. The following
modifiers are used to control how properties and methods are overridden:

 Overridable — Allows a property or method in a class to be overridden in a derived class.


 Overrides — Overrides an Overridable property or method defined in the base class.
 NotOverridable — Prevents a property or method from being overridden in an inheriting class.
By default, Public methods are NotOverridable.
 MustOverride — Requires that a derived class override the property or method. When
the MustOverride keyword is used, the method definition consists of just the Sub, Function,
or Property statement. No other statements are allowed, and specifically there is no End
Sub or End Function statement. MustOverride methods must be declared in MustInherit classes.
 The MyBase Keyword

The MyBase keyword behaves like an object variable that refers to the base class of the current
instance of a class. MyBase is frequently used to access base class members that are overridden
or shadowed in a derived class. In particular, MyBase.New is used to explicitly call a base class
constructor from a derived class constructor.
 The MyClass Keyword
The MyClass keyword behaves like an object variable that refers to the current instance of a
class as originally implemented. MyClass resembles Me, but every method and property call
on MyClassis treated as if the method or property were NotOverridable. Therefore, the method
or property is not affected by overriding in a derived class.

 Interfaces in VB.NET

Interfaces define the properties, methods, and events that classes can implement. Interfaces
allow you to define features as small groups of closely related properties, methods, and events;
this reduces compatibility problems because you can develop enhanced implementations for
your interfaces without jeopardizing existing code. You can add new features at any time by
developing additional interfaces and implementations.

 Declaring Interfaces
Interface definitions are enclosed within the Interface and End Interface statements. Following
the Interface statement, you can add an optional Inherits statement that lists one or more
inherited interfaces. The Inherits statements must precede all other statements in the
declaration except comments. The remaining statements in the interface definition should
be Event, Sub, Function, Property, Interface, Class, Structure, and Enum statements. Interfaces
cannot contain any implementation code or statements associated with implementation code,
such as End Sub or End Property.

In a namespace, interface statements are Friend by default, but they can also be explicitly
declared as Public or Friend. Interfaces defined within classes, modules, interfaces, and
structures are Public by default, but they can also be explicitly declared
as Public, Friend, Protected, or Private.

Implementing Interfaces - The Visual Basic reserved word Implements is used in two ways-

1. The Implements statement - signifies that a class or structure implements an interface.


The Implements statement requires a comma-separated list of interfaces to be
implemented by a class.
2. The Implements keyword - signifies that a class member or structure member implements
a specific interface member.
 Interface Examples-
Interface Interface1
Sub sub1(ByVal i As Integer)
End Interface

' Demonstrates interface inheritance.


Interface Interface2
Inherits Interface1
Sub M1(ByVal y As Integer)
ReadOnly Property Num() As Integer
End Interface

 Interface Inheritance
Interfaces support inheritance too. You can define an interface and define a second interface
that inherits from the original interface. By adding new interface members to the new interface,
you can extend the definition of an interface or inherit from multiple interfaces.

 Delegates in VB.NET

A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class
has a signature, and it can hold references only to methods that match its signature. Delegates
are similar to function pointers in C, C++. Delegates are objects that refer to methods. They are
sometimes described as type-safe function pointers because they are similar to function
pointers used in other programming languages. But unlike function pointers, Visual Basic
delegates are a reference type based on the class System.Delegate. Delegates can reference
both shared methods — methods that can be called without a specific instance of a class — and
instance methods.

Events in VB.NET are handled by delegates, which serve as a mechanism that defines one or
more callback functions to process events.

Although you can create your own delegates, in most cases Visual Basic creates the delegate and
takes care of the details for you. For example, an Event statement implicitly defines a delegate
class named <EventName>EventHandler as a nested class of the class containing
the Eventstatement, and with the same signature as the event. The AddressOf statement
implicitly creates an instance of a delegate that refers to a specific procedure.

 VB.NET – List

The List type belongs to a group that we call generic collections. List can store only one type of
objects, that type supplied as its generic parameter. List class is a collection and defined in the
System.Collections.Generic namespace and it provides the methods and properties like other
Collection classes such as add, insert, remove, search etc.
To use List(Of T), however, you have to understand how to implement the many methods that
the .NET Framework provides

List(Of T)

The parameter T is the type of elements in the list.

Add integer values in the List - Dim iList As New List(Of Integer)()

iList.Add(2)

Add string values in the List - Dim numbers As New List(Of String)()
numbers.Add("One")

 List methods

 Add(item) - This method takes an item as a parameter and adds to the end of the list.
 AddRange(collection) - Adds multiple items to the list, e.g. from an array.
 Clear() - Removes all items in the List.
 Contains(item) - Returns true/false depending on whether the List contains the given item.
 CopyTo(array) - Copies all items in the list to a given array. We can specify the starting index and
the number of items.
 IndexOf(item) - Returns the index of the first occurrence of a given item in the list (like with an
array). Returns -1 in case of failure.
 Insert(index, item) - Inserts an item at the given index, position, in the List.
 InsertRange(index, collection) - Inserts multiple items from the collection at the given index in
the List.
 LastIndexOf(item) - Returns the index of the last occurrence of a given item in the list. Returns -1
in case of failure.
 Remove(item) - Removes the first occurrence of an item.
 RemoveAt(index) - Removes the item at the specified index.
 RemoveRange(index, count) - Removes a specified number of items starting at a specific index.
 Reverse() - Works the same as it would in an array. It reverses the List so the first item is the last
and vice versa. The method doesn't return anything, the changes are made directly to the List.
 Sort() - This method sorts the items in the List. The method doesn't return anything either.
 ToArray() - Copies the items from the List to a given array and returns it.
 Average() - Returns the average of the items in the List as a double.
 Distinct() - Returns all of the items of which there is only one instance in the List.
 First() - Returns the first item.
 Last() - Returns the last item.
 Intersect(collection) - Returns the intersection of the List with the specified collection.
 Union() - Returns the union of the List with the specified collection.
 Min() - Returns the smallest element.
 Max() - Returns the largest element.
 Sum() - Returns the sum of the elements
 VB.Net - Collections

Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements
and accessing a list of items on the basis of an index, etc. These classes create collections of
objects of the Object class, which is the base class for all data types in VB.Net.

A collection is a class, so you must declare an instance of the class before you can add elements
to that collection.

If your collection contains elements of only one data type, you can use one of the classes in
the System.Collections.Generic namespace. A generic collection enforces type safety so that no
other data type can be added to it. When you retrieve an element from a generic collection, you
do not have to determine its data type or convert it.

 Various Collection Classes and Their Usage


Class Description and Useage
ArrayList It represents ordered collection of an object that can be indexed individually. It is
basically an alternative to an array. However, unlike array, you can add and
remove items from a list at a specified position using an index and the array
resizes itself automatically. It also allows dynamic memory allocation, add,
search and sort items in the list.
Hashtable It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can
identify a useful key value. Each item in the hash table has a key/value pair. The
key is used to access the items in the collection.
SortedList A sorted list is a combination of an array and a hash table. It contains a list of
items that can be accessed using a key or an index. If you access items using an
index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The
collection of items is always sorted by the key value.
Stack It represents a last-in, first out collection of object.
When you add an item in the list, it is called pushing the item, and when you
remove it, it is called popping the item.
Queue It represents a first-in, first out collection of object.
When you add an item in the list, it is called enqueue, and when you remove an
item, it is called deque.
BitArray It represents an array of the binary representationusing the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits in
advance. You can access items from the BitArray collection by using an integer
index, which starts from zero.
 VB.Net - Exception Handling
An exception is a problem that arises during the execution of a program. An exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords - Try, Catch, Finally and Throw.
 Try − A Try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more Catch blocks.
 Catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The Catch keyword indicates the catching of an
exception.
 Finally − The Finally block is used to execute a given set of statements, whether an exception is
thrown or not thrown. For example, if you open a file, it must be closed whether an exception is
raised or not.
 Throw − A program throws an exception when a problem shows up. This is done using a Throw
keyword.
Syntax
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
 Exception Classes in .Net Framework
Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to
an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is mismatched
with the array type.
System.NullReferenceException Handles errors generated from deferencing a null
object.
System.DivideByZeroException Handles errors generated from dividing a dividend
with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free
memory.
System.StackOverflowException Handles errors generated from stack overflow.

 Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try and
catch blocks. Using these blocks the core program statements are separated from the error-
handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
 Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from
the ApplicationException class.
 Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception
class.You can use a throw statement in the catch block to throw the present object as −

Throw [ expression ]

 Multithreading - VB.NET

Multithreading is a process of executing multiple threads simultaneously. So at this point we will


ask our selves what a thread is . A thread is a lightweight subprocess, a smallest unit of processing.
It is a separate path of execution. It shares the memory area of process. So in short,
Multithreading is a technique that allows a program or a process to execute many tasks
concurrently. at the same time and parallel. It allows a process to run its tasks in parallel mode on
a single processor system.

A multithreading is a specialized form of multitasking. Multitasking threads require less overhead


than multitasking processes.
With .NET, you can write applications that perform multiple operations at the same time.
Operations with the potential of holding up other operations can execute on separate threads, a
process known as multithreading or free threading. Multithreading is a technique by which you
can increase the efficiency of your program by 100%. Everybody wants to apply multi-threading in
their own applications.

Multithreading is a type of execution model that allows multiple threads to exist within the
context of a process such that they execute independently but share their process resources. A
thread maintains a list of information relevant to its execution including the priority schedule,
exception handlers, a set of CPU registers, and stack state in the address space of its hosting
process.
Multithreading is also known as threading

 methods of thread like

1. Stop() : which stops execution of the thread


2. Suspend() : which suspends execution of thread
3. Resume() : which resumes suspended thread
4. Sleep() : which halts the execution for certain milliseconds

 Vc #.net

C# is a modern, general-purpose, object-oriented programming language developed by


Microsoft and approved by European Computer Manufacturers Association (ECMA) and
International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of the executable code
and runtime environment that allows use of various high-level languages on different computer
platforms and architectures.
C# is an object-oriented programming language. In Object-Oriented Programming methodology,
a program consists of various objects that interact with each other by means of actions. The
actions that an object may take are called methods. Objects of the same kind are said to have
the same type or, are said to be in the same class.
For example, let us consider a Rectangle object. It has attributes such as length and width.
Depending upon the design, it may need ways for accepting the values of these attributes,
calculating the area, and displaying details.
 Features of C#

i. It is a modern, general-purpose programming language


ii. It is object oriented.
iii. It is component oriented.
iv. It is easy to learn.
v. It is a structured language.
vi. It produces efficient programs.
vii. It can be compiled on a variety of computer platforms.
viii. It is a part of .Net Framework.
C# programs run on the .NET Framework, that includes a virtual execution system called the
common language runtime (CLR) and a unified set of class libraries. The CLR is the commercial
implementation of the common language infrastructure (CLI), which is the basis for creating
execution and development environments in which languages and libraries work together
seamlessly.

Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI
specification. The IL code and resources, such as bitmaps and strings, are stored on disk in an
executable file called an assembly, typically with an extension of .exe or .dll. An assembly
contains a manifest that provides information about the assembly's types, version, culture, and
security requirements.

 C# - Data Types

Variables - A variable can be compared to a storage room, and is essential for the programmer.
In C#, a variable is declared like this: <visibility> <data type> <name> = <value>;

private string name = "John Doe";


The variables in C#, are categorized into the following types −
1. Value Type - Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which stores
numbers, alphabets, and floating point numbers, respectively.
Type Represents Range
bool Boolean value True or False
byte 8-bit unsigned integer 0 to 255
char 16-bit Unicode character U +0000 to U +ffff
decimal 128-bit precise decimal values with 28- (-7.9 x 1028 to 7.9 x 1028) / 100to 28
29 significant digits
double 64-bit double-precision floating point (+/-)5.0 x 10-324 to (+/-)1.7 x 10308
type
float 32-bit single-precision floating point -3.4 x 1038 to + 3.4 x 1038
type
int 32-bit signed integer type -2,147,483,648 to 2,147,483,647
long 64-bit signed integer type -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
sbyte 8-bit signed integer type -128 to 127
short 16-bit signed integer type -32,768 to 32,767
uint 32-bit unsigned integer type 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method.
2. Reference Type - The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables.
In other words, they refer to a memory location. If the data in the memory location is changed
by one of the variables, the other variable automatically reflects this change in value. Example
of built-in reference types are:
i. Object Type - The Object Type is the ultimate base class for all data types in C# Common Type
System (CTS). Object is an alias for System.Object class. The object types can be assigned values
of any other types, value types, reference types, predefined or user-defined types. However,
before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when
an object type is converted to a value type, it is called unboxing.
object obj;

obj = 100; // this is boxing

ii. Dynamic Type - You can store any type of value in the dynamic data type variable. Type
checking for these types of variables takes place at run-time. dynamic d = 20;
iii. String Type - The String Type allows you to assign any string values to a variable. The string type is
an alias for the System.String class. It is derived from object type. The value for a string type can
be assigned using string literals in two forms: quoted and @quoted.

3. Pointer Type - Pointer type variables store the memory address of another type. Pointers in C#
have the same capabilities as the pointers in C or C++.

 C# - Classes

When you define a class, you define a blueprint for a data type. This does not actually define any
data, but it does define what the class name means. That is, what an object of the class consists
of and what operations can be performed on that object. Objects are instances of a class. The
methods and variables that constitute a class are called members of the class.
 Defining a Class
using System; car = new Car("Red");
namespace ConsoleApplication1 Console.WriteLine(car.Describe());
{ car = new Car("Green");
class Program
{ Console.WriteLine(car.Describe());
static void Main(string[] args)
{ Console.ReadLine();
Car car; }
}
 Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class
definition similar to any other variable. It operates on any object of the class of which it is a
member, and has access to all the members of a class for that object.
Member variables are the attributes of an object (from design perspective) and they are kept
private to implement encapsulation. These variables can only be accessed using the public
member functions.

 C# Constructors
A class constructor is a special member function of a class that is executed whenever we create
new objects of that class.
A constructor has exactly the same name as that of class and it does not have any return type.
A default constructor does not have any parameter but if you need, a constructor can have
parameters. Such constructors are called parameterized constructors. This technique helps you
to assign initial value to an object at the time of its creation

 C# Destructors
A destructor is a special member function of a class that is executed whenever an object of its
class goes out of scope. A destructor has exactly the same name as that of the class with a
prefixed tilde (~) and it can neither return a value nor can it take any parameters.
Destructor can be very useful for releasing memory resources before exiting the program.
Destructors cannot be inherited or overloaded.

 Static Members of a C# Class


We can define class members as static using the static keyword. When we declare a member of
a class as static, it means no matter how many objects of the class are created, there is only one
copy of the static member.
The keyword static implies that only one instance of the member exists for a class. Static
variables are used for defining constants because their values can be retrieved by invoking the
class without creating an instance of it. Static variables can be initialized outside the member
function or class definition. You can also initialize static variables inside the class definition.

You can also declare a member function as static. Such functions can access only static variables.
The static functions exist even before the object is created.
using System;

namespace StaticVarApplication {

class StaticVar {

public static int num;

public void count() {

num++;

public int getNum() {

return num;

 C# - Method overloading

Method Overloading is the common way of implementing polymorphism. It is the ability to


redefine a function in more than one form. A user can implement function overloading by
defining two or more functions in a class sharing the same name.
C# can distinguish the methods with different method signatures. i.e. the methods can have the
same name but with different parameters list (i.e. the number of the parameters, order of the
parameters, and data types of the parameters) within the same class.

 Overloaded methods are differentiated based on the number and type of the parameters
passed as arguments to the methods.

 You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.

 The compiler does not consider the return type while differentiating the overloaded method.
But you cannot declare two methods with the same signature and different return type. It will
throw a compile-time error. If both methods have the same parameter types, but different
return type, then it is not possible.

 Why do we need Method Overloading ??


If we need to do the same kind of the operation in different ways i.e. for different inputs. In the
example described below, we are doing the addition operation for different inputs. It is hard to
find many different meaningful names for single action.
 C# - Strings
A string is a sequential collection of characters that is used to represent text. A String object is a
sequential collection of System.Char objects that represent a string.
In C#, you can use strings as array of characters, However, more common practice is to use
the string keyword to declare a string variable. The string keyword is an alias for
the System.String class.
 Creating a String Object
You can create string object using one of the following methods −
 By assigning a string literal to a String variable
 By using a String class constructor
 By using the string concatenation operator (+)
 By retrieving a property or calling a method that returns a string
 By calling a formatting method to convert a value or an object to its string representation
using System;
namespace StringApplication {
class Program {
static void Main(string[] args) {
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
char []letters= { 'H', 'e', 'l', 'l','o' };
string [] sarray={ "Hello", "From", "Tutorials", "Point" };
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//by using string constructor { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//methods returning string { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);
Console.WriteLine("Message: {0}", chat);
}
}
}
 Properties of the String Class
Property & Description
Chars
Gets the Char object at a specified position in the current Stringobject.
Length
Gets the number of characters in the current String object.

 Methods of the String Class


Methods & Description
public static int Compare(string strA, string strB)
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order.
public static string Concat(string str0, string str1)
Concatenates two string objects.
public bool Contains(string value)
Returns a value indicating whether the specified String object occurs within this string.
public static string Copy(string str)
Creates a new String object with the same value as the specified string.
public bool Equals(string value)
Determines whether the current String object and the specified String object have the same
value.
public int IndexOf(char value)
Returns the zero-based index of the first occurrence of the specified Unicode character in the
current string.
public string Insert(int startIndex, string value)
Returns a new string in which a specified string is inserted at a specified index position in the
current string object.
public string Remove(int startIndex)
Removes all the characters in the current instance, beginning at a specified position and
continuing through the last position, and returns the string.
public string Replace(char oldChar, char newChar)
Replaces all occurrences of a specified Unicode character in the current string object with the
specified Unicode character and returns the new string.
public char[] ToCharArray()
Returns a Unicode character array with all the characters in the current string object.
public string ToLower()
Returns a copy of this string converted to lowercase.
public string ToUpper()
Returns a copy of this string converted to uppercase.
public string Trim()
Removes all leading and trailing white-space characters from the current String object.
 C# .NET - Delegates and Events

1. Delegates - C# delegates are similar to pointers to functions, in C or C++. A delegate is a


reference type variable that holds the reference to a method. The reference can be
changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates
are implicitly derived from the System.Delegateclass.
A Delegate is an abstraction of one or more function pointers. The .NET has implemented the
concept of function pointers in the form of delegates. With delegates, you can treat a function
as data. Delegates allow functions to be passed as parameters, returned from a function as a
value and stored in an array.

Delegates provide a way to define and execute callbacks. Their flexibility allows you to define
the exact signature of the callback, and that information becomes part of the delegate type
itself. Delegates are type-safe, object-oriented and secure.

The delegate contains a couple of useful fields. The first one holds a reference to an object, and
the second holds a method pointer. When you invoke the delegate, the instance method is
called on the contained reference.

However, if the object reference is null then the runtime understands this to mean that the
method is a static method. Moreover, invoking a delegate syntactically is the exact same as
calling a regular function. Therefore, delegates are perfect for implementing callbacks.

 Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A
delegate can refer to a method, which has the same signature as that of the delegate.

delegate <return type> <delegate-name> <parameter list>

 Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the new keyword and
be associated with a particular method. When creating a delegate, the argument passed to
the new expression is written similar to a method call, but without the arguments to the
method. For example −
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
 Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls the two
delegates it was composed from. Only delegates of the same type can be composed. The "-"
operator can be used to remove a component delegate from a composed delegate.
Using this property of delegates you can create an invocation list of methods that will be called
when a delegate is invoked. This is called multicasting of a delegate.

2. Events - Events are user actions such as key press, clicks, mouse movements, etc., or some
occurrence such as system generated notifications. Applications need to respond to events
when they occur. For example, interrupts. Events are used for inter-process communication.

 Using Delegates with Events


The events are declared and raised in a class and associated with the event handlers using
delegates within the same class or some other class. The class containing the event is used to
publish the event. This is called the publisherclass. Some other class that accepts this event is
called the subscriber class. Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The event-
delegate association is also defined in this object. A publisher class object invokes the event and
it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The delegate in
the publisher class invokes the method (event handler) of the subscriber class.

 C# - Interfaces

An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow. The interface defines the 'what' part of the syntactical contract and the deriving
classes define the 'how' part of the syntactical contract.

Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
class to define the members. It often helps in providing a standard structure that the deriving
classes would follow.
Abstract classes to some extent serve the same purpose, however, they are mostly used when
only few methods are to be declared by the base class and the deriving class implements the
functionalities.
 Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface
statements are public by default. Following is an example of an interface declaration −

public interface ITransactions {

// interface members

void showTransaction();

double getAmount();

 System.Collections Namespace
The System.Collections namespace contains interfaces and classes that define various
collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries.

Classes
ArrayList Implements the IList interface using an array whose size is
dynamically increased as required.
BitArray Manages a compact array of bit values, which are represented as
Booleans, where true indicates that the bit is on (1)
and false indicates the bit is off (0).
CaseInsensitiveComparer Compares two objects for equivalence, ignoring the case of strings.
CaseInsensitiveHashCode Supplies a hash code for an object, using a hashing algorithm that
Provider ignores the case of strings.
CollectionBase Provides the abstract base class for a strongly typed collection.
Comparer Compares two objects for equivalence, where string comparisons
are case-sensitive.
DictionaryBase Provides the abstract base class for a strongly typed collection of
key/value pairs.
Hashtable Represents a collection of key/value pairs that are organized based
on the hash code of the key.
Queue Represents a first-in, first-out collection of objects.
ReadOnlyCollectionBase Provides the abstract base class for a strongly typed non-generic
read-only collection.
SortedList Represents a collection of key/value pairs that are sorted by the
keys and are accessible by key and by index.
Stack Represents a simple last-in-first-out (LIFO) non-generic collection of
objects.
StructuralComparisons Provides objects for performing a structural comparison of two
collection objects.
 C# - Queue And Stacks

1. Stack in C# - Stack is a linear data structure. It follows LIFO(Last In First Out) pattern for
Input/output. Following three basic operations are performed in the stack:
 Push: Adds an item in the stack. If the stack is full, then it is said to be a stack Overflow
condition.
 Pop: Removes an item from the stack. The items are popped in the reversed order in which they
are pushed. If the stack is empty, then it is said to be a stack Underflow condition.
 Peek : Return the topmost element of stack.
 Declaration of the stack

A stack is created with the help of the Stack Data type. The keyword "new" is used to create an
object of a Stack. The object is then assigned to the variable st.

Stack st = new Stack()


 Adding elements to the stack - Stack.push(element)

 Removing elements from the stack - Stack.pop()


 Count - This property is used to get the number of items in the Stack. Below is the general syntax
of this statement. Stack.Count
 Contains - This method is used to see if an element is present in the Stack. Below is the general
syntax of this statement. The statement will return true if the element exists, else it will return
the value false. Stack.Contains(element)

2. Queue in C# - The Queue is a special case collection which represents a first in first out concept. It
represents a first-in, first out collection of object. It is used when you need a first-in, first-out
access of items. When you add an item in the list, it is called enqueue, and when you remove an
item, it is called deque. (Methods same as stack )

 File System

A file is a collection of data stored in a disk with a specific name and a directory path. When a
file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There
are two main streams: the input stream and the output stream. The input stream is used for
reading data from file (read operation) and the output stream is used for writing into the file
(write operation).

File and stream I/O (input/output) refers to the transfer of data either to or from a storage
medium. In the .NET Framework, the System.IO namespaces contain types that enable reading
and writing, both synchronously and asynchronously, on data streams and files. These
namespaces also contain types that perform compression and decompression on files, and types
that enable communication through pipes and serial ports.

When you work with files, you work with directory paths, disk storage, and file and directory
names. In contrast, a stream is a sequence of bytes that you can use to read from and write to a
backing store, which can be one of several storage mediums (for example, disks or memory).
Just as there are several backing stores other than disks, there are several kinds of streams other
than file streams, such as network, memory, and pipe streams.

 Definition of a Stream
The .NET Framework uses streams to support reading from and writing to files.
You can think of a stream as a one-dimensional set of contiguous data, which
has a beginning and an end, and where the cursor indicates the current
position in the stream.

 Stream Operations
The data contained in the stream may come from memory, a file, or a TCP/IP socket. Streams have
fundamental operations that can be applied to them:

 Reading. You can read from a stream, transferring data from the stream into a data structure,
such as a string or an array of bytes.
 Writing. You can write to a stream, transferring data from a data source into the stream.
 Seeking. You can query and modify your position in the stream.

Some commonly used stream classes:

1. FileStream – for reading and writing to a file.


2. IsolatedStorageFileStream – for reading and writing to a file in isolated storage.
3. MemoryStream – for reading and writing to memory as the backing store.
4. BufferedStream – for improving performance of read and write operations.
5. NetworkStream – for reading and writing over network sockets.
6. PipeStream – for reading and writing over anonymous and named pipes.
7. CryptoStream – for linking data streams to cryptographic transformations.
8. The StreamReader and StreamWriter classes are used for reading from and writing data to text
files. These classes inherit from the abstract base class Stream, which supports reading and
writing bytes into a file stream.

1. The StreamReader Class - The StreamReader class also inherits from the abstract base class
TextReader that represents a reader for reading series of characters. methods of the
StreamReader class –
Method Name & Purpose
Public Overrides Sub Close
It closes the StreamReader object and the underlying stream and
releases any system resources associated with the reader.
Public Overrides Function Peek As Integer
Returns the next available character but does not consume it.
Public Overrides Function Read As Integer
Reads the next character from the input stream and advances the
character position by one character.

2. The StreamWriter Class - The StreamWriter class inherits from the abstract class TextWriter that
represents a writer, which can write a series of character. Methods of this class −
Method Name & Purpose
Public Overrides Sub Close
Closes the current StreamWriter object and the underlying stream.
Public Overrides Sub Write (value As Char)
Writes a character to the stream.
Public Overridable Sub Write (value As Decimal)
Writes the text representation of a decimal value to the text string or
stream.
Public Overrides Sub Write (value As String)
Writes a string to the stream.
Public Overridable Sub WriteLine
Writes a line terminator to the text string or stream.

 ADO.NET Architecture
 ADO is the acronym for ActiveX Data Object and is a Microsoft technology. ADO .NET is a
data access and manipulation protocol. Many applications need data access at one point
of time making it a crucial component when working with applications. Data access is
making the application interact with a database, where all the data is stored. Different
applications have different requirements for database access.

ADO.NET provides a bridge between the front end controls and the back end database. The
ADO.NET objects encapsulate all the data access operations and the controls interact with these
objects to display data, thus hiding the details of movement
of data.

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.

The two key components of ADO.NET are Data Providers and DataSet .

1. Data Providers - 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.

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.

A data provider contains Connection, Command, DataAdapter, and DataReader objects. These
four objects provides the functionality of Data Providers in the ADO.NET.

i. 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.

ii. 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.

iii. DataReader - The DataReader Object is a stream-based , forward-only, read-only retrieval


of query results from the Data Source, which do not update the data. DataReader requires
a live connection with the databse and provides a very intelligent way of consuming all or
part of the result set.

iv. 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.

The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is essentially
the middleman facilitating all communication between the database and a DataSet. The
DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's
Fill method. After the memory-resident data has been manipulated, the DataAdapter can
commit the changes to the database by calling the Update method. The DataAdapter provides
four properties that represent database commands:

SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the database and
the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.

2. DataSet - DataSet class provides mechanisms for managing data when it is disconnected from
the data source.

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.

 Accessing Data with ADO.NET

ADO.NET connects to the database to retrieve data, and connects again to update data when
you’ve made changes. Most applications spend most of their time simply reading through data
and displaying it; ADO.NET provides a disconnected subset of the data for your use while
reading and displaying.

 DataGrid - The Windows Forms DataGrid control provides a user interface to ADO.NET datasets,
displays ADO.NET tabular data in a scrollable grid, and allows for updates to the data source. In
cases where the DataGrid is bound to a data source with a single table containing no
relationships, the data appears in simple rows and columns, as in a spreadsheet.
The DataGrid control is one of the most useful and flexible controls in Windows Forms. As soon as
the DataGrid control is set to a valid data source, the control is automatically populated, by
creating columns and rows based on the structure of the data. The DataGrid control can be used
to display either a single table or the hierarchical relationships between a set of tables. Valid data
sources for the DataGridinclude:

 DataTable
 DataView
 DataSet
 DataViewManager
 A single dimension array
 Any component that implements the IListSource interface.

How It Works?After you get connected to the MS Access database, all records are displayed on
the DataGrid. When you run the application first time, the method "fnRefresh()" will be called. It
clears the contents of the DataSet, fills the DataAdapter, and displays the data from the data
source in the DataGrid. After that, all the buttons are ready to be used.
 Use of data adapter.

- The data adapter objects connect a command objects to a Dataset object.

- They provide the means for the exchange of data between the data store and the tables in the
DataSet.

- An OleDbDataAdapter object is used with an OLE-DB provider.

- A SqlDataAdapter object uses Tabular Data Services with MS SQL Server.

- Data adapters are an integral part of ADO.NET managed providers, which are the set of objects
used to communicate between a data source and a dataset.

- Adapters are used to exchange data between a data source and a dataset.

- In many applications, this means reading data from a database into a dataset, and then writing
changed data from the dataset back to the database.

- However, a data adapter can move data between any source and a dataset.

Anda mungkin juga menyukai