0% found this document useful (0 votes)
622 views

Net Framework and C# Programming

The document provides an overview of .NET Framework and C# programming. It covers topics like C# language features, OOP concepts, collections and generics, assemblies, threading and synchronization. The document is divided into 3 units - introduction to C#, C# OOPs, and assemblies, threading and AppDomains.

Uploaded by

Sumitesh Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
622 views

Net Framework and C# Programming

The document provides an overview of .NET Framework and C# programming. It covers topics like C# language features, OOP concepts, collections and generics, assemblies, threading and synchronization. The document is divided into 3 units - introduction to C#, C# OOPs, and assemblies, threading and AppDomains.

Uploaded by

Sumitesh Raj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

.

Net Framework and


C# Programming
Syllabus......................................................................................................................................................4
UNIT 1: Introduction to C#........................................................................................................................ 5
Overview................................................................................................................................................5
The .NET Architecture........................................................................................................................... 6
Common Language Runtime.................................................................................................................7
Common Language Specification..........................................................................................................8
Common Type System.......................................................................................................................... 9
MSIL...................................................................................................................................................... 9
.NET Framework Class Library........................................................................................................... 10
Garbage Collector............................................................................................................................... 10
.NET Assembly.................................................................................................................................... 10
Global Assembly Cache(GAC)............................................................................................................ 11
Visual Studio Console App.................................................................................................................. 12
Visual Studio Windows Form...............................................................................................................12
Features of C# Language....................................................................................................................12
Enumerations...................................................................................................................................... 14
Structures............................................................................................................................................ 16
Namespaces........................................................................................................................................19
UNIT 2: C# OOP’s.....................................................................................................................................20
OOPs................................................................................................................................................... 20
Encapsulation...................................................................................................................................... 20
Need for Encapsulation................................................................................................................. 20
Properties in C#............................................................................................................................. 21
Encapsulation using Accessor and Mutator...................................................................................22
Encapsulation using Properties..................................................................................................... 23
Inheritance........................................................................................................................................... 24
Polymorphism...................................................................................................................................... 26
Static / Compile Time Polymorphism............................................................................................. 26
Dynamic / Runtime Polymorphism.................................................................................................27
Abstraction...........................................................................................................................................29
Abstract Base Class...................................................................................................................... 29
Object Lifetime in .NET Framework.....................................................................................................30
The System.GC (Garbage Collection in C#)..................................................................................32
INTERFACE........................................................................................................................................ 32
Namespace Collection.........................................................................................................................35
Non Genric Collection in C#.......................................................................................................... 36
C# ArrayList................................................................................................................................... 36
C# SortedList................................................................................................................................. 38
STACK Class................................................................................................................................. 40
C# - Queue Class.......................................................................................................................... 42
C# - Hashtable Class.....................................................................................................................43
C# Dictionary................................................................................................................................. 45
C# - List......................................................................................................................................... 47
Generics in C#............................................................................................................................... 49
Advantages of Generics................................................................................................................ 51
Advanced Class Construction............................................................................................................. 52
Indexers in C#..................................................................................................................................... 52
Delegates:........................................................................................................................................... 54
Events in C#........................................................................................................................................ 56
Operator Overloading.......................................................................................................................... 57
Components in C# .NET......................................................................................................................60
Comparable and Cloneable Objects....................................................................................................61
Modules in C#.NET............................................................................................................................. 62
UNIT 3: Assemblies, Thread, and AppDomains................................................................................... 64
.Net Assembly..................................................................................................................................... 64
ILDASM & ILASM................................................................................................................................ 64
Private Assembly:................................................................................................................................ 65
Shared Assembly................................................................................................................................ 65
Global Assembly Cache(GAC)............................................................................................................ 66
Thread in C#........................................................................................................................................ 67
Thread Name, Thread Priority, and Thread State................................................................................69
Context object......................................................................................................................................70
AppDomain in C#.Net.......................................................................................................................... 71
C# Thread Synchronization................................................................................................................. 72
Lock in C#......................................................................................................................................72
Monitor in C#................................................................................................................................. 74
ReadWriterLock in C#....................................................................................................................76
Mutexes in C#................................................................................................................................79
Thread Pooling in C#........................................................................................................................... 81
UNIT 4: IO, Object serialization and remoting...................................................................................... 85
System.IO............................................................................................................................................ 85
Streams............................................................................................................................................... 86
C# FileStream......................................................................................................................................87
C# StreamWriter.................................................................................................................................. 88
C# StreamReader................................................................................................................................89
C# TextWriter....................................................................................................................................... 90
C# TextReader.....................................................................................................................................92
C# BinaryWriter................................................................................................................................... 93
C# BinaryReader................................................................................................................................. 94
C# Serialization................................................................................................................................... 96
BinaryFormatter:............................................................................................................................ 96
C# Deserialization............................................................................................................................... 98
Remoting........................................................................................................................................... 100
ADO.NET (ActiveX Data Object)....................................................................................................... 101
C# windows forms for data control.................................................................................................... 103
Connected and Disconnected Scenarios:......................................................................................... 105
ADO.NET System..............................................................................................................................108
Data............................................................................................................................................. 108
DataSet........................................................................................................................................108
Connections (`Connection` Classes)........................................................................................... 109
Adapters (`DataAdapter` Classes)...............................................................................................109
Commands (`Command` Classes).............................................................................................. 109
DataReaders................................................................................................................................109
UNIT 5: ASP.NET.................................................................................................................................... 110
ASP.NET............................................................................................................................................ 110
Features/Advantages of ASP.NET..................................................................................................... 111
ASP.Net Architecture......................................................................................................................... 112
ASP.NET Web Forms........................................................................................................................ 114
ASP.NET Web Forms Features................................................................................................... 115
Web Server........................................................................................................................................ 117
Server Controls in ASP.Net................................................................................................................118
Benefits of Server Controls:.........................................................................................................120
Data connectivity using ASP.net........................................................................................................ 120
XML and ASP.NET............................................................................................................................ 122
Syllabus
UNIT I
Introduction to C#, CLR, Visual Studio console app, Simple Windows
forms, C# language fundamentals, Enumerations, structures,
Namespaces

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

❖ Dot net is a technology created by Microsoft Company to develop


multiple applications i.e., Console Application, Windows
Application, Web Application, Web Services, and Web API.
❖ Dot Net supports 65+ languages.
❖ It is a Framework that supports Multiple Language and
Cross-language integration.
❖ It has IDE (Integrated Development Environment).
❖ .NET Framework provides interoperability between languages i.e.
Common Type System (CTS).
❖ .NET Framework also includes the .NET Common Language
Runtime (CLR), which is responsible for maintaining the execution
of all applications developed using the .NET library.
❖ The .NET Framework is made up of two major components: the
common language runtime (CLR) and the framework class
library (FCL).
❖ The CLR is the foundation of the .NET Framework and provides
various services that applications can use.
❖ The FCL is a collection of over 7000+ types that fulfill all the
services, and data structures that applications will ever need.
The .NET Architecture
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 conform 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 is compiled only when 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), 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.
Common Language Specification
❖ CLS stands for Common Language Specification and it is a subset
of CTS. It defines a set of rules and restrictions that every
language must follow which runs under .NET framework.
❖ The languages which follows these set of rules are said to be CLS
obedient. In simple words, CLS enables crosslanguage integration.
❖ Common Language Specification (CLS) is a set of basic language
features that .Net Languages needed to develop Applications and
Services, which are compatible with the .Net Framework.
❖ When there is a situation to communicate Objects written in
different .Net languages, those objects must expose the features
that are common to all the languages.
❖ Common Language Specification (CLS) ensures complete
interoperability among applications, regardless of the language
used to create the application.
❖ Common Language Specification (CLS) defines a subset of
Common Type System (CTS).
Common Type System
❖ Common Type System (CTS) describes a set of types that can be
used in different .Net languages in common.
❖ That is, the Common Type System (CTS) ensure that objects
written in different .Net languages can interact with each other.
❖ These types can be Value Types or Reference Types.
❖ The Value Types are passed by values and stored in the stack.
❖ The Reference Types are passed by references and stored in the
heap. Common Type System (CTS) provides base set of Data
Types which is responsible for cross-language integration.
❖ The Common Language Runtime (CLR) can load and execute the
source code written in any .Net language, only if the type is
described in the Common Type System (CTS).

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

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.

Visual Studio Console App


Tutorial: Create a simple C# console app - Visual Studio (Windows) |
Microsoft Learn

Visual Studio Windows Form


Introduction to C# Windows Forms Applications - GeeksforGeeks

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.

Modern Programming Language: C# programming is a popular and


powerful language that is for creating scalable, interoperable, and
robust applications.

Object Oriented: C# is an object-oriented programming language,


which makes development and maintenance easier. In contrast, with
procedure-oriented programming languages, managing code becomes
difficult as project size grows.
Type Safe: The code is type safe can only access memory locations
that it has permission to execute. This feature significantly enhances
program security.

Interoperability: The interoperability process allows C# programs to


perform all the tasks that a native C++ application.

Scalable and Updateable: C# is a programming language that is


scalable and can be updated automatically. To update our application,
we remove the old files and replace them with new ones.

Component Oriented: It is widely used as a software development


methodology to create applications that are more strong and can easily
scale.

Structured Programming Language: C# is a structured programming


language that allows us to divide programs into parts using functions,
making it easy to understand and modify.

Fast Speed: The compilation and execution time of C# language is


fast.
Enumerations
❖ An enumeration is a set of named integer constants. An
enumerated type is declared using the enum keyword.
❖ C# enumerations are value data type.
❖ Syntax: enum <enum_name> { enumeration list }
❖ Eg: enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
❖ By default, the first member of an enum has the value 0, and the
value of each successive enum member is increased by 1.
❖ A change in the value of the first enum member will automatically
assign incremental values to the other members sequentially.
Structures
❖ A structure in C# is simply a composite data type consisting of a
number of elements of other types.
❖ A C# structure is a value type and the instances of a structure are
created in the stack.
❖ The structure in C# can contain fields, methods, constants,
constructors, properties, operators, etc.
❖ The keyword struct can be used to declare a structure. The
general form of a structure declaration in C# is as follows:

<modifiers> struct <struct_name> { //Structure members }


**Note: A struct cannot contain a parameterless constructor. It can
only contain parameterized constructors or a static constructor.
Namespaces
❖ A namespace is designed for providing a way to keep one set of
names separate from another. The class names declared in one
namespace does not conflict with the same class names declared
in another.
❖ Defining a Namespace: A namespace definition begins with the
keyword namespace followed by the namespace name as follows:

namespace namespace_name { // code declarations }


UNIT 2: C# OOP’s

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

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.

Need for Encapsulation


❖ Encapsulation provides a way to protect data from accidental
corruption. Rather than defining the data in the form of public, we
can declare those fields as private.
❖ The Private data are manipulated indirectly by two ways.
❖ Let us see some example programs in C# to demonstrate
Encapsulation by those two methods.
❖ The first method is using a pair of conventional accessor and
mutator methods. Another method is using a named property.

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.

Static / Compile Time Polymorphism


❖ It is also known as Early Binding.
❖ Method overloading is an example of Static Polymorphism. In
Overloading, the method / function has the same name but
different signatures.
❖ It is also known as Compile Time Polymorphism because the
decision of which method is to be called is made at compile time.
❖ Overloading is the concept in which method names are the same
with a different set of parameters.
❖ Here the compiler checks the number of parameters passed and
the type of parameter and make the decision of which method to
call and it throw an error if no matching method is found.
Dynamic / Runtime Polymorphism
❖ Dynamic / runtime polymorphism is also known as late binding.
Here, the method name and the method signature (number of
parameters and parameter type must be the same and may have a
different implementation).
❖ Method overriding is an example of dynamic polymorphism.
❖ Method overriding can be done using inheritance. With method
overriding it is possible for the base class and derived class to
have the same method.
❖ The compiler requires an Area() method and it compiles
successfully but the right version of the Area() method is not being
determined at compile time but determined at runtime. Finally the
overriding methods must have the same name and signature
(number of parameters and type), as the virtual or abstract method
defined in the base class method and that it is overriding in the
derived class.
❖ At run time, objects of a derived class may be treated as objects of
a base class.
❖ To call a method of derived class from base class reference
variable is called method overriding.

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

Abstract Base Class


❖ An Abstract Base class cannot be instantiated; it means the object
of that class cannot be created.
❖ Class having the abstract keyword with some of its methods (not
all) is known as an Abstract Base Class.
❖ Class having the Abstract keyword with all of its methods is known
as pure Abstract Base Class.
❖ An abstract class holds the methods but the actual implementation
of those methods is made in derived class.
❖ An abstract class cannot be inherited from by structures.
❖ An abstract class cannot support multiple inheritance.

Object Lifetime in .NET Framework


❖ Object lifetime is the time when a block of memory is allocated to
the object during some process of execution and that block of
memory is released when the process ends.
❖ Once the object is allocated with memory, it is necessary to
release that memory so that it is used for further processing,
otherwise it would result in memory leaks.
❖ We have a class in .Net that releases memory automatically for us
when the object is no longer used.
❖ When the new operator is used to create an object, memory is
taken from the managed heap for this object and the managed
heap is more than just a random chunk of memory accessed by
the CLR. When the object is no longer used then it is de-allocated
from the memory so that this memory can be reused.
❖ The key pillar of the .NET Framework is the automatic garbage
collection that manages memory for all .NET applications. When
an object is instantiated, the garbage collector will destroy the
object when it is no longer needed.
❖ The garbage collector cleans up managed resources automatically
since managed code is directly targeted by the CLR.
❖ But when the object uses unmanaged resources like database
connections or file manipulation, that needs to be released
manually and this can be done by a finalize method.
The System.GC (Garbage Collection in C#)
❖ In C#, the deallocation or freeing of resources consumed by
created instances occurs automatically on a system-determined
schedule by an intelligent mechanism known as garbage
collection.
❖ Garbage collector is responsible for releasing the memory that is
not being used by the application. But GC has limitation that, it can
reclaim or release only memory which is used by managed
resources.
❖ There are a couple of resources which GC is not able to release as
it doesn't have information that, how to claim memory from those
resources like File handlers, window handlers, network sockets,
database connections etc. If your application using these
resources than it's programs responsibility to release unmanaged
resources.
❖ For example, if we open a file in our program and not closed it
after processing than that file will not be available for other
operation or it is being used by other application than they can not
open or modify that file. For this purpose FileStream class provides
Dispose method. We must call this method after file processing
finished. Otherwise it will through exception Access Denied or file
is being used by other program.

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.

Interface are of two types:


1. Implicit Interface
2. Explicit Interface
Implicit interface implementation
This is the most regular or obvious way to implement members of an
interface. Here we don't specify the interface name of the members and
implement implicitly. The method can be declared at any interface (s)
the class implements.

The call of the method is also not different. Just create an object of the
class and invoke it.

Explicit interface implementation


This is another way to implement members of an interface. Here we
need to specify the; interface name of the members.
The constraint with explicit implementation is that an explicitly
implemented member cannot be accessed using a class instance, but
only through an instance of the interface.

DIFFERENCE BETWEEN AN ABSTRACT CLASS AND AN


INTERFACE

❖ An Abstract class doesn't provide full abstraction but an interface


does provide full abstraction; i.e. both a declaration and a definition
is given in an abstract class but not so in an interface.
❖ Using Abstract we can not achieve multiple inheritance but using
an Interface we can achieve multiple inheritance.
❖ We can not use any access modifier i.e. public , private , protected
and, internal etc. because within an interface by default everything
is public.
❖ An Interface member cannot be defined using the keyword static,
virtual, abstract or sealed.
❖ A class can implement any number of interfaces but a subclass
can at most use only one abstract class.
❖ An abstract class can have non-abstract Methods while in case of
Interface all the methods has to be abstract.
❖ An abstract class can declare or use any variables while an
interface is not allowed to do so.

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.

Non Genric Collection in C#

❖ Non-generic collections hold elements of different datatypes.


❖ The System.Collections namespace includes following non-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.

Add elements into ArrayList:


Use the Add() method to add a single element or the AddRange()
method to add multiple elements from the other collections into an
ArrayList. Here, the element means the literal value of a primitive or
non-primitive type.

Access ArrayList Elements:


ArrayList elements can be accessed using indexer, in the same way as
an array. However, you need to cast it to the appropriate type or use the
implicit type var keyword while accessing it.
C# SortedList
❖ The SortedList collection stores key-value pairs in the ascending
order of key by default.
❖ SortedList class implements IDictionary & ICollection interfaces, so
elements can be accessed both by key and index.
❖ C# includes two types of SortedList, generic SortedList and
nongeneric SortedList. Here, we will learn about non-generic
SortedList.

Add elements in SortedList:


❖ Use the Add() method to add key-value pairs into a SortedList.
❖ Add() method signature: void Add(object key, object value)
❖ Key cannot be null but value can be null.
❖ Also, datatype of all keys must be same, so that it can compare
otherwise it will throw runtime exception.
Access SortedList
SortedList can be accessed by index or key. Unlike other collection,
SortedList requires key instead of index to access a value for that key.
Remove elements from SortedList
Use the Remove() or RemoveAt() method to remove elements from a
SortedList.
Remove() signature: void Remove(object key) RemoveAt() signature:
void RemoveAt(int index)

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

❖ C# includes Hashtable collection in System.Collections


namespace, which is similar to generic Dictionary collection.
❖ The Hashtable collection stores key-value pairs. It optimizes
lookups by computing the hash code of each key and stores it in a
different bucket internally and then matches the hash code of the
specified key at the time of accessing values.
You can access a hashtable value using indexer.
Eg. ht[1], ht[“Fv”]
C# Dictionary
❖ The Dictionary in C# is a collection of Keys and Values, where key
is like word and value is like definition.
❖ Dictionary is a generic collection included in the
System.Collection.Generic namespace.
❖ TKey denotes the type of key and TValue is the type of Value.

Access Dictionary Elements:


❖ Dictionary elements can be accessed by many ways e.g. foreach,
for loop or indexer.
❖ Use foreach or for loop to iterate access all the elements of
dictionary.
❖ The dictionary stores key-value pairs. So you can use a
KeyValuePair type or an implicitly typed variable var in foreach
loop as shown below.
C# - List
❖ List class is a generic class.
❖ List class represents the list of objects which can be accessed by
index.
❖ It comes under the System.Collection.Generic namespace. List
class can be used to create a collection of different types like
integers, strings etc.
❖ Example: List List list = new List();
Generics in C#
❖ Generics makes code type independent.
❖ Generics allow you to write a class or method that can work with
any data type.
❖ Generics allow you to define a class with placeholders for the type
of its fields, methods, parameters, etc. Generics replace these
placeholders with some specific type at compile time.
❖ A generic class can be defined using angle brackets <>.
❖ For example, the following is a simple generic class with a generic
member variable, generic method and property.
❖ Use generic types to maximize code reuse, type safety, and
performance.
❖ The most common use of generics is to create collection classes.
❖ The .NET Framework class library contains several new generic
collection classes in the System.Collections.Generic namespace.

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.

❖ Operator overloading is basically the mechanism of providing a


special meaning to an ideal C# operator w.r.t. a user-defined data
type such as structures or classes.

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. Class Components: These are the fundamental building blocks in


C#. Classes encapsulate data and behavior within one unit. They can
have properties, methods, events, constructors, and more.

2. Assemblies: Assemblies are the deployment units in .NET. They can


contain multiple components, including compiled code (DLLs or EXEs),
metadata, and resources. Assemblies can be shared among
applications, aiding code reusability.

3. User Controls: These are composite controls made by grouping


existing controls together to create a custom reusable control. They
simplify UI development by encapsulating a set of controls and their
logic into a single unit.

4. Custom Controls: These are controls created by inheriting from


base classes like `Control` or `UserControl` and adding custom
functionality. They provide specialized behavior not available in
standard controls.

5. Web Services: Components that expose functionality over the web


using standard protocols like HTTP, SOAP, or REST. They enable
interoperability between different platforms and languages.

6. COM (Component Object Model) Components: Though less


common now, .NET supports COM interoperability. COM components
allow integration with older systems or those written in other languages.

7. Components in Windows Forms: In desktop applications,


components refer to elements like buttons, textboxes, menus, etc., that
are used to build the user interface.
Understanding these different types of components helps in building
robust, modular, and maintainable applications in C# .NET.

Comparable and Cloneable Objects


In C# .NET, `ICloneable` and `IComparable` are interfaces that provide
specific functionalities to objects.

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; }

public object Clone()


{
return new MyClass { MyProperty = this.MyProperty };
}
}
```

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; }

public int CompareTo(MyComparableClass other)


{
// Implement comparison logic based on SomeValue
return this.SomeValue.CompareTo(other.SomeValue);
}
}
```

By implementing these interfaces, objects gain the ability to provide


standardized behavior for cloning (in the case of `ICloneable`) or for
comparison (in the case of `IComparable`), aiding in custom
functionality and interoperability across various components of a C#
.NET application.

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

C# assemblies, GAC, threads, contexts, Appdomains, Processes


concepts, Concurrency and synchronization- Locks, Monitors,
ReaderWriterLock, Mutexes, Thread pooling

.Net Assembly

❖ Microsoft .Net Assembly is a logical unit of code, that contains


code which is executed by Common Language Runtime (CLR).
❖ 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 .

ILDASM & ILASM

ILDASM- Intermediate Language Disassembler


ILASM - Intermediate Language Assembler

❖ When Any .NET application compile it creates Assembly(.EXE or


.DLL)
❖ Assembly contains – manifest and IL.
❖ Some Information in the assembly manifest can be modified using
Attributes.
❖ We use ILDASM (Intermediate language Disassembler) tool to
export manifiest and IL to a text file.
❖ We use ILASM.exe (Intermediate language Assembler) to
reconstruct an assembly from a text file that contains manifest and
IL.
Types of Assembly
There are 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).
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

An assembly consist of 4 parts:


1. The textual assembly name
2. The assembly version number
3. Assembly Culture Information
4. The assembly should have been signed with public key pair.(Public
Key Token)
In .NET assemblies can be broadly classified into 2 types:
1. Week Named Assembly 2. Strong Named Assembly

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.

❖ GAC contains strong named assemblies. Assemblies in the GAC


can be shared by all the applications running on that machine,
without having to copy the assembly locally.
❖ It is recommended to install an assembly into GAC, only when
required and shared by applications, otherwise they should be kept
private.
❖ Tool to install an assembly into GAC We use Gacutil.exe(GAC
utility tool).

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:-

Thread Name, Thread Priority, and Thread State


We can set a thread's name and priority using Name and Priority
properties.

workerThread.Name = "Hard Worker";

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#

❖ In C#, the Monitor class is a part of the .NET Framework and is


used for managing synchronization among threads to ensure that
only one thread can enter a critical section of code at a time. This
helps in preventing race conditions and ensures thread-safe
access to shared resources.

❖ The Monitor class provides mechanisms for exclusive locking and


releasing of locks using the Enter and Exit methods.
using System;
using System.Threading;

class Program
{
private static readonly object lockObject = new object();
private static int sharedResource = 0;

static void Main()


{
// Creating multiple threads to access a shared resource
Thread thread1 = new Thread(IncrementSharedResource);
Thread thread2 = new Thread(IncrementSharedResource);

thread1.Start();
thread2.Start();

thread1.Join();
thread2.Join();

Console.WriteLine("Final shared resource value: " +


sharedResource);
}

static void IncrementSharedResource()


{
// Enter a critical section using Monitor
Monitor.Enter(lockObject);
try
{
// Access the shared resource safely
for (int i = 0; i < 10000; i++)
{
sharedResource++;
}
}
finally
{
// Exit the critical section
Monitor.Exit(lockObject);
}
}
}

In this example:

lockObject is used as a synchronization object to control access to the


shared resource.

Monitor.Enter(lockObject) is used to acquire the lock, allowing only


one thread at a time to access the critical section enclosed by the try
block.
The shared resource (sharedResource in this case) is incremented
within the critical section.

Monitor.Exit(lockObject) releases the lock, allowing other threads


waiting to access the critical section to proceed.

Using Monitor class methods Enter and Exit helps in preventing


concurrent access to critical sections of code, ensuring data integrity
and avoiding race conditions in multithreaded applications.

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;

static void Main()


{
// Creating multiple threads for reading and writing
Thread[] readerThreads = new Thread[5];
Thread[] writerThreads = new Thread[2];

for (int i = 0; i < readerThreads.Length; i++)


{
readerThreads[i] = new Thread(ReadSharedData);
readerThreads[i].Start();
}

for (int i = 0; i < writerThreads.Length; i++)


{
writerThreads[i] = new Thread(WriteSharedData);
writerThreads[i].Start();
}
foreach (Thread thread in readerThreads)
{
thread.Join();
}

foreach (Thread thread in writerThreads)


{
thread.Join();
}

Console.WriteLine("Final value of shared data: " + sharedData);


}

static void ReadSharedData()


{
rwLock.EnterReadLock();
try
{
// Reading from the shared resource
Console.WriteLine("Read value: " + sharedData);
}
finally
{
rwLock.ExitReadLock();
}
}

static void WriteSharedData()


{
rwLock.EnterWriteLock();
try
{
// Writing to the shared resource
sharedData += 10;
Console.WriteLine("Wrote value: " + sharedData);
}
finally
{
rwLock.ExitWriteLock();
}
}
}

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.

Here's an example demonstrating the usage of Mutex in a


multithreaded scenario:
using System;
using System.Threading;

class Program
{
private static Mutex mutex = new Mutex();
private static int sharedData = 0;

static void Main()


{
// Creating multiple threads that access the shared resource
Thread[] threads = new Thread[5];

for (int i = 0; i < threads.Length; i++)


{
threads[i] = new Thread(UpdateSharedData);
threads[i].Start();
}

foreach (Thread thread in threads)


{
thread.Join();
}

Console.WriteLine("Final value of shared data: " + sharedData);


}

static void UpdateSharedData()


{
mutex.WaitOne(); // Wait to acquire the mutex

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:

❖ The Mutex is created using new Mutex().


❖ Multiple threads (threads) are created to update the sharedData.
❖ Each thread calls WaitOne() to acquire the mutex before updating
the shared data. Only one thread can acquire the mutex at a time.
❖ The critical section of code (incrementing sharedData) is executed
within the try block, and the mutex is released using
ReleaseMutex() in the finally block.
❖ Mutexes are versatile synchronization primitives used to protect
critical sections in multi-threaded applications, ensuring that only
one thread can access the protected resource at any given time.
Additionally, mutexes can be used across multiple processes for
synchronization by providing a named mutex, allowing
inter-process synchronization.

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);
}

Console.WriteLine("Work items queued to the thread pool.");

// The main thread continues its work


// ...

// Wait for a key press to prevent the program from exiting


immediately
Console.ReadKey();
}

static void DoWork(object state)


{
int taskId = (int)state;
Console.WriteLine("Task {0} is executing on thread {1}", taskId,
Thread.CurrentThread.ManagedThreadId);
// Simulate some work being done
Thread.Sleep(1000);

Console.WriteLine("Task {0} completed", taskId);


}
}

In this example:

❖ The ThreadPool.QueueUserWorkItem method queues work items


to the thread pool for asynchronous execution.
❖ The DoWork method simulates some work that each queued task
performs.
❖ The main thread continues its execution without waiting for the
thread pool tasks to complete.

Key points about ThreadPool:

Automatic Management: The ThreadPool manages the number of


threads automatically based on system resources and workload.

Task Queuing: Tasks are queued using


ThreadPool.QueueUserWorkItem or other asynchronous methods. The
thread pool assigns available threads to execute these tasks.

Task Execution: The tasks are executed asynchronously, and the


thread pool reuses threads once the task completes, reducing the
overhead of thread creation.

Reuse and Scalability: Thread pooling helps in reusing threads


efficiently, making it suitable for scenarios with many short-duration
tasks and enhancing the scalability of applications.

Thread pooling in C# provides a convenient way to perform


asynchronous operations without the overhead of managing individual
threads manually. However, it's essential to use thread pooling
judiciously and consider potential thread contention and synchronization
issues in multi-threaded applications.
UNIT 4: IO, Object serialization and remoting
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,

System.IO

The System.IO namespace consists of IO related classes, structures,


delegates and enumerations. These classes can be used to reads and
write data to files or data streams. It also contains classes for file and
directory support.
Some Classes in System.IO namespace:
Streams
In C#, a Stream is an abstract base class representing a sequence of
bytes. It provides a uniform way to access input and output operations
from different sources and destinations, such as files, memory, network
sockets, and more, by providing a common set of methods and
properties.

The Stream class is found in the System.IO namespace and serves as


the foundation for performing input/output operations in .NET.

Here are some important aspects of the Stream class:

Abstract Base Class: Stream is an abstract class, meaning it cannot


be instantiated directly. Instead, it serves as a base class for various
derived stream classes that represent specific sources or destinations.

Reading and Writing: Stream provides methods for reading (Read)


and writing (Write) bytes from/to the underlying data source or
destination.

Seeking: Streams support seeking operations (Seek) to navigate to a


specific position within the stream, allowing random access to the data.

Position and Length: Position property represents the current position


within the stream, and Length property indicates the length of the
stream in bytes.

Closing and Disposing: Streams should be properly closed (Close) or


disposed (Dispose) after use to release resources and ensure proper
cleanup.

Some of the Streams classes are:


❖ FileStream
❖ StreamReader
❖ StreamWriter
❖ BinaryReader
❖ BinaryWriter

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.

Example: Writing in a file


Reading a 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.

Serialization is internally used in remote applications.

❖ In C#, object persistence refers to the process of saving objects'


state to a persistent storage medium (like a file or a database) so
that it can be retrieved later. Serialization is the process of
converting an object into a format that can be easily persisted or
transmitted, and deserialization is the reverse process—converting
the serialized data back into an object.
❖ C# provides various ways to perform object serialization and
persistence using formatters. Formatters handle the serialization
and deserialization process by converting objects to and from a
specific format

BinaryFormatter:

❖ The BinaryFormatter class in the


System.Runtime.Serialization.Formatters.Binary namespace
serializes objects to binary format.
❖ It is suitable for scenarios where binary data serialization is
required.

Syntax:

BinaryFormatter formatter = new BinaryFormatter();

FileStream fileStream = new FileStream("data.bin", FileMode.Create)

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.

There are two types of remoting in C#:

1. Marshal-by-Reference (MBR):

❖ MBR remoting allows objects to be passed by reference between


application domains or across machines.
❖ Objects in MBR remoting inherit from MarshalByRefObject and are
accessed through proxy instances.
❖ Remote objects maintain their identity across application domain
or machine boundaries.

2. Marshal-by-Value (MBV):

❖ MBV remoting involves passing serialized copies of objects


between application domains or across machines.
❖ Objects in MBV remoting are serializable and are transmitted as
copies rather than references.
❖ Remote objects lose their identity and exist as independent copies
at the receiving end.

In .NET, remoting was a mechanism used in earlier versions to enable


communication between distributed components. It provided support for
TCP/IP and HTTP protocols for communication between remote
objects. However, with the advancements in technologies like Windows
Communication Foundation (WCF) and later .NET Core/.NET 5+ (now
.NET 6+), remoting has been largely replaced by more modern
communication frameworks due to their enhanced capabilities and
better support for various communication scenarios.

Here's a basic example demonstrating a simple MBR remoting scenario


using .NET Remoting:

1. Define a remote object that inherits from MarshalByRefObject:

public class RemoteObject : MarshalByRefObject


{
public int Add(int a, int b)
{
return a + b;
}
}

2. Host the remote object:

RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteObject), "RemoteObjectURI",
WellKnownObjectMode.Singleton);

3. Access the remote object from a client:

RemoteObject remoteObj = (RemoteObject)Activator.GetObject(


typeof(RemoteObject),
"tcp://hostname:port/RemoteObjectURI");

int result = remoteObj.Add(5, 3);


Console.WriteLine("Result from remote object: " + result);

ADO.NET (ActiveX Data Object)


❖ It is a module of .Net Framework which is used to establish
connection between application and data sources. Data sources
can be such as SQL Server and XML. ADO.NET consists of
classes that can be used to connect, retrieve, insert and delete
data.

❖ All the ADO.NET classes are located into System.Data.dll and


integrated with XML classes located into System.Xml.dll.

❖ ADO.NET has two main components that are used for accessing
and manipulating data are the .NET Framework data provider
and the DataSet.

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.

Data provider is used to connect to the database, execute commands


and retrieve the record. It is lightweight component with better
performance. It also allows us to place the data into DataSet to use it
further in our application.

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.

We should consider the following points to use DataSet.

❖ It caches data locally at our application, so we can manipulate it.


❖ It interacts with data dynamically such as binding to windows forms
control.
❖ It allows performing processing on data without an open
connection. It means it can work while connection is disconnected.

C# windows forms for data control

In C# Windows Forms applications, data controls such as


`DataGridView`, `BindingSource`, and data-binding functionality provide
a convenient way to display and manipulate data from various data
sources, including databases, collections, or other sources.

Here's an overview of these controls and concepts:

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:

dataGridView1.DataSource = yourDataSource; // Assign your data


source (e.g., DataTable)

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`:

BindingSource bindingSource = new BindingSource();


bindingSource.DataSource = yourDataSource; // Set your data
source

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`:

dataGridView1.DataSource = bindingSource; // Set BindingSource


as DataGridView's data source

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`:

textBox1.DataBindings.Add("Text", bindingSource, "FieldName");

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 and Disconnected Scenarios:


In ADO.NET, data access can be performed in both connected and
disconnected scenarios, each offering different approaches to interact
with the data source and manipulate data. These scenarios cater to
different requirements and provide flexibility in handling data in .NET
applications.

Connected Scenario:

In a connected scenario:

1. Connection Remains Open:


❖ The connection to the data source remains open during the entire
data access operation.
❖ A connection is explicitly opened using a connection object
(`SqlConnection`, `OleDbConnection`, etc.) and closed after the
operation is completed.
Example:

using (SqlConnection connection = new


SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("SELECT * FROM
Table", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Read data while connection remains open
// Process data
reader.Close();
connection.Close(); // Close connection explicitly
}

2. Live Data Access:


❖ Data is accessed directly from the data source while the
connection is open.
❖ The data is read using a `DataReader` or manipulated directly
using command objects (`SqlCommand`, `OleDbCommand`).

3. Suitable for Real-time Updates:


❖ Useful for scenarios where live data access is required and
frequent interactions with the data source occur.
❖ It's efficient for single, short-lived operations but can be
resource-intensive for longer sessions.

Disconnected Scenario:
In a disconnected scenario:

1. Connection is Briefly Opened:


❖ The connection to the data source is opened, data is fetched, and
then the connection is closed promptly.
❖ Data is fetched into in-memory objects such as `DataSet` or
`DataTable` and disconnected from the data source.
Example:

using (SqlConnection connection = new


SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT *
FROM Table", connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "Table"); // Fill DataSet with data
// Close connection after data is fetched
}

2. Data Stored in Memory:


❖ Data retrieved from the data source is stored in local memory
objects (`DataSet`, `DataTable`) and disconnected from the data
source.
❖ The application works with the data in memory, manipulating,
updating, and querying the in-memory data.

3. Offline Manipulation and Updates:


❖ Suitable for scenarios where the application needs to work with the
data offline, manipulate it, and later synchronize changes with the
data source.
❖ The disconnected data model allows for efficient data manipulation
and reduces load on the data source.
Both connected and disconnected scenarios in ADO.NET offer
advantages based on specific requirements. Connected scenarios are
suitable for real-time data access, whereas disconnected scenarios are
more efficient for offline data manipulation and synchronization.
Choosing between these scenarios depends on factors such as
application needs, performance, and data access patterns.

ADO.NET System

ADO.NET (ActiveX Data Objects for .NET) is a set of libraries and


components in the .NET Framework used for accessing and
manipulating data from different data sources, primarily databases. It
provides a rich set of classes and features for performing data access
operations in C# and other .NET languages.

Key components and concepts within ADO.NET include:

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.

Adapters (`DataAdapter` Classes)


- Adapters in ADO.NET, represented by classes like `DataAdapter`, are
used to bridge the gap between a `DataSet` and a data source.
Adapters, such as `SqlDataAdapter`, `OleDbDataAdapter`,
`OracleDataAdapter`, and `OdbcDataAdapter`, fetch data from the data
source and populate the `DataSet` with data. They also reconcile
changes made in the `DataSet` back to the data source.

Commands (`Command` Classes)


- Commands in ADO.NET, represented by classes like `SqlCommand`,
`OleDbCommand`, `OracleCommand`, and `OdbcCommand`, are used
to execute commands against a data source. They can execute SQL
queries, stored procedures, and other commands to retrieve, update,
delete, or manipulate data in the data source.

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: Introduction, Architecture, Web forms,Web servers, Server


controls, Data connectivity using ASP.net, Introduction of XML, Using
XML with ASP.nat

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.

ASP.NET provides three development styles for creating web


applications:

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.

We can use any development style to create application. The selection


of style is depends on the skills and experience of the programmer.

Although each framework is independent to other, we can combine and


use any of that at any level of our application. For example, to develop
client interaction module, we can use MVC and for data control, we can
use Web Forms.

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.

2. Performance: It is faster than the other web frameworks available


in the market.

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

5. Supporting different OS: You can develop and execute ASP.NET


apps on Windows, Linux, Docker, and MacOS. The Visual Studio
provides the tools to build .NET apps different OS.

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:

1. Client-Side: The client side consists of web browsers or client


applications that send HTTP requests to the web server hosting
the ASP.NET application.

2. Web Server: The web server hosts the ASP.NET application and
manages the processing of incoming HTTP requests.

3. HTTP Request Pipeline: When an HTTP request is received by


the web server, it goes through the ASP.NET HTTP request
pipeline.
4. HTTP Modules: Modules in ASP.NET, known as HTTP Modules,
intercept and handle requests during different stages of the
request processing pipeline.
They can perform tasks like authentication, logging, URL rewriting,
etc.

5. Routing: ASP.NET Routing helps map incoming requests to


specific handlers or controllers based on URL patterns, enabling
cleaner and more flexible URL structures.
6. Handlers and Controllers: Handlers and Controllers process
incoming requests. In ASP.NET MVC or Razor Pages, Controllers
handle requests and perform actions based on the requested
URLs.
ASP.NET Web Forms uses HTTP Handlers to process requests
and generate responses.

7. Model-View-Controller (MVC) Architecture: In ASP.NET MVC,


the architecture follows the MVC pattern, separating the
application into Models (data), Views (UI), and Controllers (logic).

8. Model: The Model represents the application's data and business


logic. It encapsulates data manipulation and interacts with the
database or other data sources.

9. View: The View represents the user interface and is responsible


for presenting data to the user. It generates HTML output that is
rendered in the browser.

10. Controller: The Controller acts as an intermediary between the


Model and View. It handles user input, processes requests,
invokes the appropriate Model actions, and selects the appropriate
View to display results.

11. ASP.NET Core Middleware: In ASP.NET Core, Middleware


components are used to handle requests and responses.
Middleware components are arranged in a pipeline, similar to
HTTP Modules.

12. Services and Dependency Injection: ASP.NET Core


emphasizes dependency injection and provides a built-in container
for managing and injecting services, enabling better testability and
modularity.
13. ASP.NET Core Hosting: ASP.NET Core applications can be
hosted on various servers, including IIS (Internet Information
Services), Kestrel, or self-hosted within a .NET Core application.

This architecture provides flexibility, scalability, and separation of


concerns, allowing developers to build robust, maintainable, and
high-performance web applications using ASP.NET. The specific
architecture may vary based on the chosen ASP.NET framework (MVC,
Web Forms, Razor Pages) and application requirements.

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.

ASP.NET Web Forms


❖ Web Forms are web pages built on the ASP.NET Technology. It
executes on the server and generates output to the browser. It is
compatible to any browser to any language supported by .NET
common language runtime. It is flexible and allows us to create
and add custom controls.
❖ We can use Visual Studio to create ASP.NET Web Forms. It is an
IDE (Integrated Development Environment) that allows us to drag
and drop server controls to the web forms. It also allows us to set
properties, events and methods for the controls. To write business
logic, we can choose any .NET language like: Visual Basic or
Visual C#.

❖ Web Forms are made up of two components: the visual portion


(the ASPX file), and the code behind the form, which resides in a
separate class file.
❖ The main purpose of Web Forms is to overcome the limitations of
ASP and separate view from the application logic.
❖ ASP.NET provides various controls like: server controls and
HTML controls for the Web Forms.

ASP.NET Web Forms Features


1. Server Controls
Web Forms provides rich set of server controls. These controls are objects
that run when the page is requested and render markup to the browser.
Some Web server controls are similar to familiar HTML elements, such as
buttons and text boxes. It also provides controls that we can use to connect
to data sources and display data.

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.

3. Working with Data


In an ASP.NET Web Forms application, we use data-bound controls to
automate the presentation or input of data in web page UI elements such as
tables and text boxes and drop-down lists.

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.

5. Client Script and Client Frameworks


We can enhance the server-based features of ASP.NET by including
client-script functionality in ASP.NET Web Form pages. We can use client
script to provide a richer, more responsive user interface to the users. We
can also use client script to make asynchronous calls to the Web server
while a page is running in the browser.

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.

10. Debugging and Error Handling


We can diagnose problems that occur in our Web Forms application.
Debugging and error handling are well supported within ASP.NET Web
Forms so that our applications compile and run effectively.

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:

Internet Information Services (IIS):

● IIS is a popular web server developed by Microsoft and is


commonly used to host ASP.NET applications.
● It provides a robust and feature-rich platform for hosting web
applications, including ASP.NET.
● IIS supports various versions of ASP.NET and allows configuration
of application pools, security settings, and more.

ASP.NET Core Hosting:


● ASP.NET Core applications can be hosted on multiple servers,
including IIS, but the recommended server for ASP.NET Core is
Kestrel.
● Kestrel is a cross-platform web server developed by Microsoft
specifically for hosting ASP.NET Core applications. It's lightweight
and fast.
● ASP.NET Core applications can be self-hosted using Kestrel or
can use IIS as a reverse proxy in combination with Kestrel.

Apache HTTP Server with mod_mono:

● Apache HTTP Server, a widely used open-source web server, can


also be used to host ASP.NET applications using the mod_mono
module.
● mod_mono enables Apache to serve ASP.NET applications by
interfacing with the Mono framework (an open-source
implementation of .NET).

Nginx with ASP.NET Core:

● Nginx, a popular open-source web server, can be used as a


reverse proxy in front of Kestrel to host ASP.NET Core applications
on Linux-based systems.
● It serves static content and passes requests to Kestrel for
processing ASP.NET Core requests.

Self-Hosting:

● For development or in specific scenarios, ASP.NET applications


can be self-hosted without using a dedicated web server.
● In self-hosting, the application hosts its own web server using
built-in mechanisms or third-party libraries.
These web servers provide the necessary infrastructure to handle
incoming HTTP requests, manage application pools, serve web content,
and execute ASP.NET code, enabling the hosting and execution of
ASP.NET web applications. The choice of web server often depends on
factors such as performance requirements, scalability, compatibility, and
specific deployment scenarios.

Server Controls in ASP.Net


In ASP.NET, server controls are an integral part of web development,
offering a rich set of pre-built UI components that execute on the server
and generate HTML to be rendered in the browser. These controls
simplify web development by providing a consistent and reusable way
to create interactive and dynamic web pages. Here are some common
types of server controls in ASP.NET:

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.

Benefits of Server Controls:


● Event-Driven Model: Server controls provide event-driven
programming models where actions (events) on controls trigger
server-side code execution.
● State Management: They support server-side state management,
maintaining control state across postbacks.
● Rich Functionality: Provide built-in functionalities, reducing the
need for manual coding.
● Code Reusability: Encapsulate complex functionalities into
reusable components for easy reuse across multiple pages.

These server controls simplify development, promote code reusability,


and offer a consistent way to build interactive and feature-rich web
applications in ASP.NET.

Data connectivity using ASP.net


In ASP.NET, data connectivity involves establishing connections to
databases or other data sources, retrieving data, performing operations
(such as CRUD - Create, Read, Update, Delete), and displaying or
manipulating that data within web applications. Here are the key
components and steps involved in data connectivity using ASP.NET:

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:

● Use connection objects (SqlConnection for SQL Server,


OleDbConnection for other databases via OLE DB, etc.) to
establish connections to the database.

3. Command Object:

● Use command objects (SqlCommand, OleDbCommand, etc.) to


execute SQL queries, stored procedures, or other commands
against the database.

4. DataReader:

● Use a DataReader (e.g., SqlDataReader, OleDbDataReader) to


retrieve data from the database in a forward-only, read-only
stream.

5. DataAdapters:

● DataAdapters (SqlDataAdapter, OleDbDataAdapter) are used to fill


a DataSet with data retrieved from the database and reconcile
changes made in the DataSet back to the database.

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.

Basic steps for data connectivity in ASP.NET:

Step 1: Establish a Connection to the Database.

// Example for SQL Server


using (SqlConnection connection = new
SqlConnection(connectionString))
{
connection.Open();
// Perform operations using commands
// Close connection when done
}

Step 2: Execute Commands and Retrieve Data

// Example for executing a SELECT query


using (SqlCommand command = new SqlCommand("SELECT * FROM
Table", connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// Process retrieved data
}
}
}

Step 3: Using DataAdapters and DataSets (For Disconnected Scenario)

// Example for filling a DataSet with data using a DataAdapter


using (SqlConnection connection = new
SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Table", connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "Table"); // Fill DataSet with data
}

XML and ASP.NET

XML (eXtensible Markup Language) is a widely used standard for


storing and transporting data. In ASP.NET, XML can be utilized in
various scenarios, such as configuration files, data exchange, and
manipulation. Here are some ways XML is integrated into ASP.NET
applications:

1. XML as Data Source:


● Reading XML Data: ASP.NET allows you to read XML data from
files, databases, or web services using classes like XmlReader,
XmlDocument, or LINQ to XML (XDocument, XElement).
● Processing XML Data: You can parse XML documents, navigate
through nodes, extract data, and perform manipulations using
various XML APIs available in .NET.
2. Configuration Files (web.config):
● Configuration Settings: ASP.NET applications commonly use
XML-based configuration files (web.config) to store settings related
to the application, including database connections, application
settings, security configurations, etc.
● Custom Configuration Sections: Developers can create custom
configuration sections using XML within the web.config file to store
application-specific settings.
3. Data Exchange and Serialization:
● XML Serialization: ASP.NET allows serialization of objects into
XML format using the XmlSerializer class, enabling easy data
exchange between different systems or platforms.

You might also like