Net Framework and C# Programming
Net Framework and C# Programming
UNIT II
C# Object oriented programming: OOPs, Encapsulation, Inheritance,
Polymorphism, Object Lifetime, Components, Modules, Windows
Forms, Interface, Cloneable objects, Comparable objects, Collections
Namepaces
Advanced Class Construction: Custom Indexer, Overloading
operators, Delegates, Events
UNIT III
Assemblies, Thread, and AppDomains: C# assemblies, GAC,
threads, contexts, Appdomains, Processes concepts, Concurrency and
synchronization- Locks, Monitors, ReaderWriterLock, Mutexes, Thread
pooling
UNIT IV
IO, Object serialization and remoting: System.IO, Streams,
TextWriter, TextReader, BinaryWirter, BinaryReader, Serialized Object
Persistence and formatters, Remoting ADO.Net, C# windows forms for
data control: Grid, Datasource and databinding controls, Connected and
disconnected scenarios, ADO.Net system, Data, Dataset, connections,
Adapters, commands, datareaders,
UNIT V
ASP.net: Introduction, Architecture, Web forms,Web servers, Server
controls, Data connectivity using ASP.net, Introduction of XML, Using
XML with ASP.nat
UNIT 1: Introduction to C#
Overview
MSIL
❖ A.NET programming language (C#, VB, J# etc.) does not compile
into executable code; instead, it compiles into an intermediate
code called Microsoft Intermediate Language (MSIL).
❖ The MSIL code is then sent to the CLR (Common Language
Runtime) that converts the code to machine language, which is,
then run on the host machine.
❖ MSIL is similar to Java Byte code.
❖ MSIL is the CPU-independent instruction set into which .NET
Framework programs are compiled. It contains instructions for
loading, storing, initializing, and calling methods on objects.
❖ Combined with metadata and the common type system, MSIL
allows for true crosslanguage integration. Before execution, MSIL
is converted to machine code.
.NET Framework Class Library
❖ The .NET Framework class library is a library of classes,
interfaces, and value types that provide access to system
functionality.
❖ It is the foundation on which .NET Framework applications,
components, and controls are built.
❖ Path of .Net Framework in Windows
❖ C:\Windows\assembly-For .NET 2.0 -3.5 assembly
❖ C:\Windows\Microsoft.NET\assembly-For .NET 4.0 assemblies
❖ Eg. Namespace System
❖ The System namespace contains fundamental classes and base
classes that define commonly-used value and reference data
types, events and event handlers, interfaces, attributes, and
processing exceptions.
Garbage Collector
❖ CLR also contains a Garbage Collector (GC) which runs in a
low-priority thread and checks for unreferenced dynamically
allocated memory space.
❖ If it finds some data that is no longer referenced by any
variable/reference, it re-claims it and returns the occupied memory
to the Operating System; so that it can be used by other programs
as necessary.
❖ The presence of a standard Garbage Collector frees the
programmer from keeping track of dangling data.
.NET Assembly
❖ 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) is
together wrapped in a Portable Executable (PE) file (an .exe or
.dll).
❖ 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.
❖ We can create two types of Assembly: 1. Private Assembly 2.
Shared Assembly
❖ Private Assembly: A private Assembly is used only by a single
application, and usually it is stored in that application's install
directory.
❖ 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).
Features of C# Language
Simple: C# is a user-friendly language that offers a structured approach
to problem-solving. It provides a wide range of library functions and
data types to work.
OOPs
OOP stands for Object-Oriented Programming, which is a programming
paradigm that organizes data and behavior into classes and objects.
OOP has many benefits, such as code reusability, modularity,
encapsulation, abstraction, inheritance, and polymorphism. OOP is
widely used in C#, which is a modern and powerful programming
language that runs on the .NET platform.
Encapsulation
❖ Encapsulation is the procedure of covering up of data and
functions into a single unit (called class).
❖ Using accessor(get method)and mutator methods(set method) we
can make encapsulation.
Properties in C#
❖ A property is a member that provides a flexible mechanism to
read, write, or compute the value of a private field.
❖ Properties can be used as if they are public data members, but
they are actually special methods called accessors. This enables
data to be accessed easily and still helps promote the safety and
flexibility of methods.
❖ Properties enable a class to expose a public way of getting and
setting values.
❖ A get property accessor is used to return the property value, and a
set property accessor is used to assign a new value. These
accessors can have different access levels.
❖ The value keyword is used to define the value being assigned by
the set accessor.
Encapsulation using Accessor and Mutator
Encapsulation using Properties
Inheritance
❖ Inheritance is a process of deriving a new class from an already
existing class.
❖ Inheritance is one of the fundamental attributes of object-oriented
programming.
❖ It allows you to define a child class that reuses (inherits), extends,
or modifies the behavior of a parent class.
❖ The class whose members are inherited is called the base class.
The class that inherits the members of the base class is called the
derived class.
❖ C# and .NET support single inheritance only. That is, a class can
only inherit from a single class.
❖ However, inheritance is transitive, which allows you to define an
inheritance hierarchy for a set of types. In other words, type D can
inherit from type C, which inherits from type B, which inherits from
the base class type A.
❖ Because inheritance is transitive, the members of type A are
available to type D.
Polymorphism
❖ Polymorphism is a Greek word meaning "one name many forms".
In other words, one object has many forms or has one name with
multiple functionalities.
❖ "Poly" means many and "morph" means forms.
❖ Polymorphism provides the ability to class multiple
implementations with the same name. At run time, objects of a
derived class may be treated as objects of a base class.
Types of Polymorphism:
❖ Static / Compile Time Polymorphism.
❖ Dynamic / Runtime Polymorphism.
Abstraction
❖ Abstraction is "To represent the essential feature without
representing the background details.“
❖ Abstraction lets you focus on what the object does instead of how
it does it.
❖ The word abstract means a concept or an idea not associated with
any specific instance.
❖ In programming, we apply the same meaning of abstraction by
making classes not associated with any specific instance.
❖ Abstraction is done when we need to only inherit from a certain
class, but do not need to instantiate objects of that class.
❖ In such a case the base class can be regarded as "Incomplete".
Such classes are known as an "Abstract Base Class".
INTERFACE
❖ Interface in C# is like abstract class because all the methods which
are declared inside the interface are abstract methods.
❖ An interface in C# contains only the declaration of the methods.
But not the implementation.
❖ It is used to achieve multiple inheritance which can't be achieved
by class. It is used to achieve fully abstraction because it cannot
have method body.
❖ Its implementation must be provided by class or struct. The class
or struct which implements the interface, must provide the
implementation of all the methods declared inside the interface.
❖ In C#, an interface can be defined using the interface keyword.
The call of the method is also not different. Just create an object of the
class and invoke it.
Namespace Collection
❖ C# includes specialized classes that hold many values or objects
in a specific series, that are called 'collection'.
❖ There are two types of collections available in C#: non-generic
collections and generic collections.
C# ArrayList
ArrayList is a non-generic type of collection in C#. It can contain
elements of any data types. It is similar to an array, except that it grows
automatically as you add items in it. Unlike an array, you don't need to
specify the size of ArrayList.
STACK Class
❖ It represents a last-in, first out collection of object.
❖ It is used when you need a last-in, first-out access of items.
❖ 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.
❖ C# includes a special type of collection which stores elements in
LIFO style(Last In First Out). C# includes a generic and
non-generic Stack
❖ Stack allows null value and also duplicate values. It provides a
Push() method to add a value and Pop() or Peek() methods to
retrieve values.
C# - Queue Class
❖ C# includes a Queue collection class in the System.Collection
namespace.
❖ Queue stores the elements in FIFO style (First In First Out),
exactly opposite of the Stack collection. It contains the elements in
the order they were added.
❖ Queue collection allows multiple null and duplicate values. Use the
Enqueue() method to add values and the Dequeue() method to
retrieve the values from the Queue.
C# - Hashtable Class
Advantages of Generics
Reusability: You can use a single generic type definition for multiple
purposes in the same code without any alterations. For example, you
can create a generic method to add two numbers. This method can be
used to add two integers as well as two floats without any modification
in the code.
Type Safety: Generic data types provide better type safety, especially
in the case of collections. When using generics you need to define the
type of objects to be passed to a collection. This helps the compiler to
ensure that only those object types that are defined in the definition can
be passed to the collection.
Performance: Generic types provide better performance as compared
to normal system types because they reduce the need for boxing,
unboxing, and typecasting of variables or objects.
Advanced Class Construction
Indexers in C#
An indexer allows an instance of a class or struct to be indexed as an
array. If the user will define an indexer for a class, then the class will
behave like a virtual array. Array access operator i.e ([ ]) is used to
access the instance of the class which uses an indexer. A user can
retrieve or set the indexed value without pointing an instance or a type
member. Indexers are almost similar to the Properties. The main
difference between Indexers and Properties is that the accessors of the
Indexers will take parameters.
Example:
Delegates:
❖ A delegate is an object which refers to a method or you can say it
is a reference type variable that can hold a reference to the
methods.
❖ Delegates in C# are similar to the function pointer in C/C++. It
provides a way which tells which method is to be called when an
event is triggered.
❖ For example, if you click on a Button on a form (Windows Form
application), the program would call a specific method. In simple
words, it is a type that represents references to methods with a
particular parameter list and return type and then calls the method
in a program for execution when it is needed.
Example:
Events in C#
❖ An event is a message sent by an object to signal the occurrence
of an action. This action can be caused by user interaction such as
button click, mouse click, etc.
❖ The Object that sent the event is called the event sender. The
object that receives the event and responds according to that is
called the event receiver. Actually, in communication between the
sender and the receiver, the sender does not know which method
or object will receive the event it raises.
❖ The mediator between these two is called a "Delegate".
❖ A delegate is an object that can hold a reference to a method. The
Delegate has a signature and it can hold the reference only to the
methods that match to its signature
Here onClick is a event listener, which will call the btn_Click function
whenever the button will be clicked.
Operator Overloading
❖ The concept of overloading a function can also be applied to
operators.
❖ Operator overloading gives the ability to use the same operator to
do various operations.
❖ It provides additional capabilities to C# operators when they are
applied to userdefined data types. It enables to make user-defined
implementations of various operations where one or both of the
operands are of a user-defined class.
❖ Only the predefined set of C# operators can be overloaded.
❖ To make operations on a userdefined data type is not as simple as
the operations on a built-in data type.
❖ To use operators with user-defined data types, they need to be
overloaded according to a programmer’s requirement.
❖ An operator can be overloaded by defining a function to it. The
function of the operator is declared by using the operator
keyword.
Example:
Components in C# .NET
In C# .NET, components play a crucial role in developing applications.
They are reusable, self-contained modules that provide specific
functionality. There are several types of components in C# .NET:
1. ICloneable Interface:
- `ICloneable` allows an object to create a copy of itself. It contains a
single method, `Clone()`, which returns a new object that is a copy of
the current instance.
- Implementing `ICloneable` enables objects to support cloning
operations, but it's important to note that the interface itself lacks
specifics about the depth of cloning (shallow or deep) and might require
additional logic depending on the complexity of the object.
Example:
```csharp
public class MyClass : ICloneable
{
public int MyProperty { get; set; }
2. IComparable Interface:
- `IComparable` is used to define a natural ordering for objects of a
class. It consists of a single method, `CompareTo()`, which compares
the current instance with another object of the same type.
- Implementing `IComparable` allows objects to define their own
sorting behavior based on their properties or fields.
Example:
```csharp
public class MyComparableClass :
IComparable<MyComparableClass>
{
public int SomeValue { get; set; }
Modules in C#.NET
In C# Object-Oriented Programming (OOP), modules refer to the logical
units of code organization used to encapsulate related functionalities
and data. The primary modules in C# OOP are:
1. Classes:
- Classes are fundamental building blocks in C# OOP. They
encapsulate data and behavior into a single unit.
- They define the blueprint for objects, containing fields (data),
methods (functions), properties, events, constructors, and more.
- Objects are instances of classes. They represent real-world entities
and are created using the `new` keyword.
2. Interfaces:
- Interfaces define a contract that classes can implement. They
declare a set of members (methods, properties, events) without
providing implementation details.
- Classes that implement an interface must provide concrete
implementations for all its members.
3. Abstract Classes:
- Abstract classes are similar to interfaces but can contain both
abstract (without implementation) and concrete members.
- They cannot be instantiated directly and serve as a blueprint for
other classes to inherit from.
UNIT 3: Assemblies, Thread, and AppDomains
.Net Assembly
Private Assembly:
A private Assembly is used only by a single application, and usually it is
stored in that application's install directory.
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).
Global Assembly Cache(GAC)
❖ Each computer on which the Common Language Runtime is
installed has a machine-wide code cache called the 'Global
Assembly Cache'.
❖ GAC is a folder in the Windows directory to store the .NET
assemblies that are specifically designated to be shared by all
applications executed on a system.
❖ Assemblies can be shared among multiple applications on the
machine by registering them in global Assembly cache(GAC).
❖ The GAC is automatically installed with the .NET runtime. The
global assembly cache is located in the 'Windows' directory and
inherits the directory's access control list that administrators have
used to protect the folder.
❖ With the introduction of .Net 4.0, we have two GAC’s
C:\Windows\assembly-For .NET 2.0 -3.5 assembly
C:\Windows\Microsoft.NET\assembly-For .NET 4.0 assemblies
1. If the assembly is not signed with public key pair, the assembly is
week named and not guaranteed to be unique, and may cause
DLL hell.
2. Strong named assembly are guaranteed to be unique and solves
DLL hell problem. You can not install an assembly into GAC
unless, the assembly is strongly named.
Thread in C#
❖ C# threading allows developers to create multiple threads in
C#.NET.
❖ When a new application starts on Windows, it creates a process
for the application with a process id and some resources are
allocated to this new process. Every process contains at least one
primary thread which takes care of the entry point of the
application execution. A single thread can have only one path of
execution but as mentioned earlier, sometimes you may need
multiple paths of execution and that is where threads play a role.
❖ In .NET, the common language runtime (CLR) plays a major role in
creating and managing threads lifecycle. In .NET application, the
CLR creates a single foreground thread to execute application
code via the Main method. This thread is called primary or main
thread. Along with this main thread, a process can create one or
more threads to execute a portion of the code. Additionally, a
program can use the ThreadPool class to execute code on worker
threads that are managed by the CLR.
Example:-
Output:-
workerThread.Priority = ThreadPriority.Highest;
Thread State
Context object
❖ In C# .NET, the term "Context Object" generally refers to an object
that encapsulates information about the environment or state in
which a particular operation is being performed. The "Context
Object" pattern is used to pass around this information in a
structured and centralized manner within an application.
❖ The context object serves as a container for various contextual
data or settings that multiple parts of an application might need
access to, eliminating the need to pass numerous individual
parameters or variables through method calls.
❖ The ASP.Net Context object is the same as the Session Object.
The Context Object is used to store the Value and Send it to the
other page in ASP.Net.
❖ The main Difference between Context and Session is the Context
Object will be null when we send page to server.
❖ That means we use Context Object we must use Server.Transfer
Method to redirect user to other page. If we use
Response.Redirect the Context object value will be null on other
page.
❖ We can use Response.Redirect and Server.Transfer with Session
Object in ASP.Net, but Response.Redirect can’t use with Context
Object in ASP.Net.
AppDomain in C#.Net
❖ Asp.Net introduces the concept of an Application Domain which is
shortly known as AppDomain.
❖ It can be considered as a Lightweight process which is both a
container and boundary.
❖ The .NET runtime uses an AppDomain as a container for code and
data, just like the operating system uses a process as a container
for code and data.
❖ As the operating system uses a process to isolate misbehaving
code, the .NET runtime uses an AppDomain to isolate code inside
of a secure boundary.
❖ The CLR isolates each application domain from all other
application domains and prevents the configuration, security, or
stability of a running .NET applications from affecting other
applications.
❖ Mulitple Appdomains can exist in Win32 process. As we discussed
the main aim of AppDomain is to isolate applications from each
other and the process is same as the working of operating system
process.
❖ Win32 processes provide isolation by having distinct memory
addresses. The .Net runtime enforces AppDomain isolation by
keeping control over the use of memory. All memory in the App
domain is managed by the run time so the runtime can ensure that
AppDomains do not access each others memory.
❖ AppDomains are created using the CreateDomain method.
AppDomain instances are used to load and execute assemblies
(Assembly). When an AppDomain is no longer in use, it can be
unloaded.
C# Thread Synchronization
❖ Synchronization is a technique that allows only one thread to
access the resource for the particular time. No other thread can
interrupt until the assigned thread finishes its task.
❖ In multithreading program, threads are allowed to access any
resource for the required execution time. Threads share resources
and executes asynchronously. Accessing shared resources (data)
is critical task that sometimes may halt the system. We deal with it
by making threads synchronized.
❖ It is mainly used in case of transactions like deposit, withdraw etc.
❖ Advantage of Thread Synchronization
1. Consistency Maintain 2. No Thread Interference
Lock in C#
The lock keyword is a simple way to synchronize access to a resource
by preventing multiple threads from accessing it simultaneously. It uses
a monitor to ensure that only one thread can execute a block of code at
a time.
In this example, we are using lock. This example executes
synchronously. In other words, there is no contextswitching between the
threads. In the output section, we can see that second thread starts
working after first threads finishes its tasks
Output:
Monitor in C#
class Program
{
private static readonly object lockObject = new object();
private static int sharedResource = 0;
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
In this example:
ReadWriterLock in C#
❖ In C# .NET, ReaderWriterLock (or ReaderWriterLockSlim in newer
versions of the framework) is a synchronization primitive used to
control access to a shared resource in multithreaded
environments.
❖ It allows multiple threads to read simultaneously while ensuring
exclusive write access.
❖ ReaderWriterLock and ReaderWriterLockSlim provide a way to
optimize synchronization by allowing multiple threads to read data
concurrently when there are no write operations ongoing. This is
beneficial when the data is predominantly read and less frequently
modified.
❖
Example:
using System;
using System.Threading;
class Program
{
private static ReaderWriterLockSlim rwLock = new
ReaderWriterLockSlim();
private static int sharedData = 0;
In this example:
❖ ReaderWriterLockSlim is used to control access to the
sharedData.
❖ Multiple reader threads (readerThreads) can concurrently read
from sharedData using EnterReadLock() and ExitReadLock().
❖ Writer threads (writerThreads) exclusively write to sharedData
using EnterWriteLock() and ExitWriteLock().
❖ Using ReaderWriterLockSlim allows for multiple threads to read
concurrently without blocking each other, enhancing performance
in scenarios where read operations are frequent compared to write
operations. However, it's essential to balance usage based on the
application's requirements to ensure proper synchronization and
avoid potential deadlock situations.
Mutexes in C#
In C# and .NET, a Mutex (Mutual Exclusion) is a synchronization
primitive used to control access to a shared resource among multiple
threads or processes. It ensures that only one thread or process can
acquire the mutex at a time, providing mutual exclusion to the critical
section of code.
class Program
{
private static Mutex mutex = new Mutex();
private static int sharedData = 0;
try
{
// Perform operations on the shared resource
sharedData++;
Console.WriteLine("Updated shared data: " + sharedData);
}
finally
{
mutex.ReleaseMutex(); // Release the mutex after usage
}
}
}
In this example:
Thread Pooling in C#
❖ Thread pooling in C# involves the efficient management and reuse
of threads to improve the performance of applications that involve
frequent and short-lived operations. It aims to minimize the
overhead of creating and destroying threads by reusing existing
ones from a pool of threads.
❖ In .NET, the ThreadPool class provides a built-in thread pool that
manages a collection of worker threads, allowing developers to
execute tasks asynchronously without explicitly creating and
managing threads.
Example:
using System;
using System.Threading;
class Program
{
static void Main()
{
// Queue some work items to the thread pool
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork),
i);
}
In this example:
System.IO
C# FileStream
C# FileStream class provides a stream for file operation. It can be used
to perform synchronous and asynchronous read and write operations.
By the help of FileStream class, we can easily read and write data into
file.
C# StreamWriter
C# StreamWriter class is used to write characters to a stream in specific
encoding. It inherits TextWriter class. It provides overloaded write() and
writeln() methods to write data into file.
Example:
C# StreamReader
C# StreamReader class is used to read string from the stream. It
inherits TextReader class. It provides Read() and ReadLine() methods
to read data from the stream.
Example:
C# TextWriter
C# TextWriter class is an abstract class. It is used to write text or
sequential series of characters into file. It is found in System.IO
namespace.
Example:
C# TextReader
C# TextReader class is found in System.IO namespace. It represents a
reader that can be used to read text or sequential series of characters.
Example:
Read All Data -
Read one line:
C# BinaryWriter
C# BinaryWriter class is used to write binary information into stream. It
is found in System.IO namespace. It also supports writing string in
specific encoding.
Example:
C# BinaryReader
C# BinaryReader class is used to read binary information from stream.
It is found in System.IO namespace. It also supports reading string in
specific encoding.
Example:
C# Serialization
In C#, serialization is the process of converting object into byte stream
so that it can be saved to memory, file or database. The reverse
process of serialization is called deserialization.
BinaryFormatter:
Syntax:
formatter.Serialize(fileStream, yourObject);
Example:
C# Deserialization
In C# programming, deserialization is the reverse process of
serialization. It means you can read the object from byte stream. Here,
we are going to use BinaryFormatter.Deserialize(stream) method to
deserialize the stream.
Example:
Remoting
Remoting in C# refers to a technology that allows objects residing in
different application domains or on different machines to communicate
with each other transparently as if they were local objects. It enables
distributed applications to interact by passing messages or invoking
methods across boundaries, such as between different processes or
even between different machines in a network.
1. Marshal-by-Reference (MBR):
2. Marshal-by-Value (MBV):
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteObject), "RemoteObjectURI",
WellKnownObjectMode.Singleton);
❖ ADO.NET has two main components that are used for accessing
and manipulating data are the .NET Framework data provider
and the DataSet.
Data Providers
These are the components that are designed for data manipulation and
fast access to data. It provides various objects such as Connection,
Command, DataReader and DataAdapter that are used to perform
database operations.
The .NET Framework provides the following data providers that we can
use in our application.
Data Set
It is used to access data independently from any data resource.
DataSet contains a collection of one or more DataTable objects of data.
1. DataGridView:
- `DataGridView` is a powerful grid-based control used to display and
edit tabular data in a grid format.
- It allows users to view, sort, edit, and manipulate data easily.
- Developers can customize its appearance, behavior, and columns
programmatically or through design-time settings.
- Example of setting `DataGridView`'s data source and displaying
data:
2. BindingSource:
- `BindingSource` acts as a layer between a data source and
data-bound controls, providing a way to manage and interact with the
data.
- It simplifies data binding by allowing easier navigation, filtering,
sorting, and change tracking.
- Example of using `BindingSource`:
3. Data-binding:
- Data-binding is the process of connecting data from a data source
(like a database, collection, etc.) to controls in a Windows Form.
- It establishes a link between the data and the UI controls, enabling
automatic synchronization of data changes between them.
- Example of data-binding a `DataGridView` to a `BindingSource`:
4. Control Properties:
- Controls like `TextBox`, `ComboBox`, and `Label` have properties
like `DataBindings` that allow binding them to specific fields in a data
source.
- Example of binding a `TextBox` to a field in the data source through
a `BindingSource`:
By using these controls and concepts together, you can create powerful
data-driven Windows Forms applications that display, manipulate, and
update data efficiently. They offer flexibility and ease in managing data
interactions between the UI and underlying data sources.
Connected Scenario:
In a connected scenario:
Disconnected Scenario:
In a disconnected scenario:
ADO.NET System
Data
- Data in ADO.NET refers to information retrieved from a data source,
such as a database. It represents the actual records, rows, or
information that an application retrieves, manipulates, and manages.
Data in ADO.NET is typically organized in a tabular format, comprising
rows and columns.
DataSet
- DataSet in ADO.NET is an in-memory representation of data retrieved
from a data source. It acts as a local cache that stores multiple
`DataTable` objects, including data rows, columns, relationships, and
constraints. A `DataSet` can hold multiple tables with their respective
schema and data.
Connections (`Connection` Classes)
- Connections in ADO.NET are objects responsible for establishing a
connection between an application and a data source, such as a
database. Different connection classes like `SqlConnection`,
`OleDbConnection`, `OracleConnection`, and `OdbcConnection` are
used to connect to specific types of databases or data sources.
DataReaders
- DataReaders in ADO.NET (e.g., `SqlDataReader`,
`OleDbDataReader`, `OracleDataReader`, `OdbcDataReader`) provide
a forward-only, read-only stream of data retrieved from the data source.
DataReaders are efficient for retrieving large result sets or streaming
data from the database without needing to load the entire dataset into
memory.
UNIT 5: ASP.NET
ASP.NET
❖ ASP stands for Active Server Pages
❖ It is a web framework designed and developed by Microsoft.
❖ It is used to develop websites, web applications and web services.
❖ It provides fantastic integration of HTML, CSS and JavaScript.
❖ It was first released in January 2002.
❖ It is built on the Common Language Runtime (CLR) and allows
programmers to write code using any supported .NET language.
1. Web Forms
2. ASP.NET MVC
3. ASP.NET Web Pages
Web Forms
It is an event driven development framework. It is used to develop
application with powerful data access. It provides server side controls
and events to create web application.
ASP.NET MVC
It gives us a MVC (Model View Controller), patterns-based way to build
dynamic websites. It enables a clean separation of concerns and that
gives you full control over markup for enjoyable, agile development. It
also provides many features that enable fast development for creating
outstanding applications.
ASP.NET Web Pages
It is used to create dynamic web pages. It provides fast and lightweight
way to combine server code with HTML. It helps to add video, link to the
social sites. It also provides other features like you can create beautiful
sites that conform to the latest web standards.
All these are stable and well equipped frameworks. We can create web
applications with any of them. These are also based on the .NET
Framework and share core functionalities of .NET and ASP.NET.
Features/Advantages of ASP.NET
1. Extending .NET Framework: ASP.NET is a subset of .NET
Framework as it extends the .NET Framework with some libraries
and tools to develop web apps. The thing that it adds to the .NET
Framework is Libraries for common web patterns like MVC, Editor
Extensions, the base framework to process the web requests, and
web-page templating syntax like Razor, etc.
3. Backend Code: With the help of ASP.NET you can write the
backend code for data access and any logic in C#.
4. Dynamic Pages: In ASP.NET, Razor provides the syntax for
developing the dynamic web pages with the help of C# and HTML.
ASP.NET can be integrated with JS(JavaScript) and it also
includes the frameworks like React and Angular for the SPA(Single
Page Application.)
ASP.Net Architecture
ASP.NET architecture comprises various components and layers that
work together to handle web requests, process them, and generate
responses. The architecture includes:
2. Web Server: The web server hosts the ASP.NET application and
manages the processing of incoming HTTP requests.
XML
● XML stands for eXtensible Markup Language
● XML is a markup language much like HTML
● XML was designed to store and transport data
● XML was designed to be self-descriptive
● XML is a W3C Recommendation
The XML above does not DO anything. XML is just information wrapped
in tags.
2. Master Pages
It allows us to create a consistent layout for the pages in our application.
This page defines the look and feel and standard behavior that we want for
all of the pages in our application. When users request the content pages,
they merge with the master page to produce output that combines the layout
of the master page with the content from the content page.
4. Membership
Project's Account folder contains the files that implement the various parts of
membership: registering, logging in, changing a password, and authorizing
access. Additionally, ASP.NET Web Forms supports OAuth and OpenID.
These authentication enhancements allow users to log into your site using
existing credentials, from such accounts as Facebook, Twitter and Google.
6. Routing
We can configure URL routing of our application. A request URL is simply
the URL a user enters into their browser to find a page on our web site. We
use routing to define URLs that are semantically meaningful to users and
that can help with search-engine optimization (SEO).
7. State Management
ASP.NET Web Forms includes several options that help you preserve data
on both a per-page basis and an application-wide basis.
8. Security
Developing a secure application is most important aspect of software
development process. ASP.NET Web Forms allow us to add extensibility
points and configuration options that enable us to customize various security
behaviors in the application.
9. Performance
Web Forms provides good performance and allows us to modify
performance related to page and server control processing, state
management, data access, application configuration and loading, and
efficient coding practices.
Web Server
ASP.NET applications are typically hosted on web servers capable of
running the .NET Framework or .NET Core runtime. Here are some
common web server options for hosting ASP.NET applications:
Self-Hosting:
1. HTML Controls:
● Basic HTML controls like `<input>`, `<button>`, `<label>`, etc., are
enhanced with server-side functionality by adding `runat="server"`
attribute. For example, `<asp:TextBox>` renders as an HTML
`<input>` control.
2. Web Controls:
● Web controls (also known as ASP.NET controls) offer a wide range
of functionalities and enhanced capabilities compared to standard
HTML controls. Examples include:
- `asp:TextBox`, `asp:Button`, `asp:Label`: Enhanced versions of
HTML elements with server-side events and properties.
- `asp:GridView`, `asp:Repeater`, `asp:DataList`: Controls for
displaying and manipulating data from databases or other sources.
- `asp:DropDownList`, `asp:ListBox`, `asp:RadioButtonList`: Controls
for creating dropdown lists, list boxes, and radio button lists.
- `asp:Calendar`, `asp:FileUpload`, `asp:Menu`: Controls for
calendar, file upload, and navigation menu functionalities.
3. Validation Controls:
- `asp:RequiredFieldValidator`, `asp:RegularExpressionValidator`,
`asp:CompareValidator`: Controls used for client-side and server-side
validation of user input.
4. User Controls:
- User controls (ascx) allow developers to create custom reusable
components by encapsulating markup and code in a separate file.
- These controls can be embedded within ASP.NET pages similar to
built-in controls.
5. Composite Controls:
- Composite controls allow the creation of custom controls by
combining existing server controls or HTML elements.
1. ADO.NET:
● ADO.NET is a fundamental part of data connectivity in ASP.NET. It
provides classes and APIs for accessing and manipulating data
from various data sources, primarily databases.
2. Connection Object:
3. Command Object:
4. DataReader:
5. DataAdapters:
6. DataSet/DataTable:
● Use DataSet and DataTable to represent in-memory caches of
data retrieved from the database. These objects allow offline
manipulation and storage of data.