[go: up one dir, main page]

0% found this document useful (0 votes)
10 views92 pages

Net All

The document provides an overview of Object-Oriented Programming concepts in C#, focusing on classes and objects, including their declaration, member access modifiers, constructors, and the differences between value types and reference types. It explains the creation of classes and objects, the use of constructors (default and parameterized), and the concept of sealed classes and static members. Additionally, it covers string operations and the distinction between value types and reference types in C#.

Uploaded by

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

Net All

The document provides an overview of Object-Oriented Programming concepts in C#, focusing on classes and objects, including their declaration, member access modifiers, constructors, and the differences between value types and reference types. It explains the creation of classes and objects, the use of constructors (default and parameterized), and the concept of sealed classes and static members. Additionally, it covers string operations and the distinction between value types and reference types in C#.

Uploaded by

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

Object and Classes:

Class and Object are the basic concepts of Object-Oriented Programming which revolve around
the real-life entities. A class is a user-defined blueprint or prototype from which objects are
created. Basically, a class combines the fields and methods(member function which defines
actions) into a single unit. In C#, classes support polymorphism, inheritance and also provide
the concept of derived classes and base classes.
Generally, a class declaration contains only a keyword class, followed by
an identifier(name) of the class. But there are some optional attributes that can be used with
class declaration according to the application requirement. In general, class declarations can
include these components, in order:
• Modifiers: A class can be public or internal etc. By default modifier of the class is internal.
• Keyword class: A class keyword is used to declare the type class.
• Class Identifier: The variable of type class is provided. The identifier(or name of the
class) should begin with an initial letter which should be capitalized by convention.
• Base class or Super class: The name of the class’s parent (superclass), if any, preceded by
the : (colon). This is optional.
• Interfaces: A comma-separated list of interfaces implemented by the class, if any,
preceded by the : (colon). A class can implement more than one interface. This is optional.
• Body: The class body is surrounded by { } (curly braces).

Declaration of Classes
Class is an user-defined data type. To create a class, you start with the class keyword followed by a name
and its body delimited by curly brackets. The following is an example of a very simple class declaration

Class classname
{
//class-body
}

Members of Class
Class is a mechanism to implement the encapsulation, it bind the data and a function in a single
unit. Therefore, data and functions are the members of class, which is known as member data and
member function.
Member Access Modifiers
Access modifiers provide the accessibility control for the members of classes to outside the class.
They also provide the concept of data hiding. There are five member access modifiers provided by
the C# Language.

Objects

It is a basic unit of Object-Oriented Programming and represents real-life entities. A typical C#


program creates many objects, which as you know, interact by invoking methods. An object
consists of :
• State: It is represented by attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an
object with other objects.
• Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Object Creation In C#
objects are created using the new keyword. Actually it new is an operator, creates an object of the
specified class and returns a reference to that object. Here is an example :

public class Exercise


{
public void Welcome()
{
Console.WriteLine("This is Exercise class");

}
}
public class Class1
{
static void Main()
{
Exercise exo = new Exercise();
}
}

C# Constructors
A constructor is a special method of the class which gets automatically invoked whenever an
instance of the class is created. Like methods, a constructor also contains the collection of
instructions that are executed at the time of Object creation. It is used to assign initial values to
the data members of the same class.

• Constructor of a class must have the same name as the class name in which it resides.
• A constructor cannot be abstract, final, and Synchronized.
• Within a class, you can create only one static constructor.
• A constructor doesn’t have any return type, not even void.
• A static constructor cannot be a parameterized constructor.
• A class can have any number of constructors.
• Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.

Types of Constructor

1. Default Constructor
2. Parameterized Constructor
C# Default Constructor:

A constructor which has no argument is known as default constructor. It is invoked at the time of
creating object.

C# Default Constructor Example: Having Main() within class:

using System;
public class Employee
{
public Employee()
{
Console.WriteLine("Default Constructor Invoked");
}
public static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee();
}
}

Output:
Default Constructor Invoked
Default Constructor Invoked

C# Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects.

using System;
public class Employee
{
public int id;
public String name;
public float salary;
public Employee(int i, String n,float s)
{
id = i;
name = n;
salary = s;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+salary);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Employee e1 = new Employee(101, "Sonoo", 890000f);
Employee e2 = new Employee(102, "Mahesh", 490000f);
e1.display();
e2.display();

}
}

Output:

101 Sonoo 890000


102 Mahesh 490000

C# Constructor Overloading:

In C#, similar to method overloading, we can also overload constructors. For constructor
overloading, there must be two or more constructors with the same name but different
• number of parameters
• types of parameters
• order of parameters
Different number of parameters

We can overload the constructor if the number of parameters in a constructor are different.

using System;

namespace ConstructorOverload {

class Car {

// constructor with no parameter


Car() {
Console.WriteLine("Car constructor");
}

// constructor with one parameter


Car(string brand) {
Console.WriteLine("Car constructor with one parameter");
Console.WriteLine("Brand: " + brand);
}

static void Main(string[] args) {

// call with no parameter


Car car = new Car();

Console.WriteLine();

// call with one parameter


Car car2 = new Car("Bugatti");

Console.ReadLine();
}
}
}

Output-
car constructor
Car constructor with one parameter
Brand: Bugatti
Different types of parameters:
using System;

namespace ConstructorOverload {

class Car {

// constructor with string parameter


Car(string brand) {
Console.WriteLine("Brand: " + brand);
}

// constructor with int parameter


Car(int price) {
Console.WriteLine("Price: " + price);
}

static void Main(string[] args) {

// call constructor with string parameter


Car car = new Car("Lamborghini");

Console.WriteLine();

// call constructor with int parameter


Car car2 =new Car(50000);

Console.ReadLine();
}
}
}

Output-
Brand: Lamborghini

Price: 50000

Different order of parameters:


using System;

namespace ConstructorOverload {
class Car {

// constructor with string and int parameter


Car(string brand, int price) {

Console.WriteLine("Brand: " + brand);


Console.WriteLine("Price: " + price);
}

// constructor with int and string parameter


Car(int speed, string color) {

Console.WriteLine("Speed: " + speed + " km/hr");


Console.WriteLine("Color: " + color);
}
static void Main(string[] args) {

// call constructor with string and int parameter


Car car = new Car("Bugatti", 50000);

Console.WriteLine();

// call constructor with int and string parameter


Car car2 =new Car(60, "Red");

Console.ReadLine();
}
}
}

Output-
Brand: Bugatti
Price: 50000

Speed: 60 km/hr
Color: Red
C# Sealed Class:
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed
by using the sealed keyword. The keyword tells the compiler that the class is sealed, and
therefore, cannot be extended. No class can be derived from a sealed class.

The following is the syntax of a sealed class :


sealed class class_name
{
// data members
// methods
.
.
.

A method can also be sealed, and in that case, the method cannot be overridden. However, a
method can be sealed in the classes in which they have been inherited. If you want to declare a
method as sealed, then it has to be declared as virtual in its base class.
The following class definition defines a sealed class in C#:
// C# code to define
// a Sealed Class
using System;

// Sealed class
sealed class SealedClass {

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

class Program {

// Main Method
static void Main(string[] args)
{

// Creating an object of Sealed Class


SealedClass slc = new SealedClass();
// Performing Addition operation
int total = slc.Add(6, 4);
Console.WriteLine("Total = " + total.ToString());
}
}
Output :
Total = 10
Now, if it tries to inherit a class from a sealed class then an error will be produced stating that ”
It cannot be derived from a Sealed class “.
// C# code to show restrictions
// of a Sealed Class
using System;

class Bird {

// Creating a sealed class


sealed class Test : Bird {
}

// Inheriting the Sealed Class


class Example : Test {
}

// Driver Class
class Program {

// Main Method
static void Main()
{
}
}

Error CS0509 ‘Example’ : cannot derive from sealed type ‘Test’.

Why Sealed Classes?


• Sealed class is used to stop a class to be inherited. You cannot derive or extend any class
from it.
• Sealed method is implemented so that no other class can overthrow it and implement its own
method.
• The main purpose of the sealed class is to withdraw the inheritance attribute from the user
so that they can’t attain a class from a sealed class. Sealed classes are used best when you
have a class with static members.
e.g the “Pens” and “Brushes” classes of the System. Drawing namespace. The Pens class
represents the pens for standard colors. This class has only static members. For example,
“Pens. Red” represents a pen with red color. Similarly, the “Brushes” class represents
standard brushes. “Brushes. Red” represents a brush with red color.

Static Keyword in C#:

The static keyword in C# language is used to declare static classes and static class members. The
static classes and static class members such as constructors, fields, properties, methods, and events
are useful when only one copy of the object (class or class members) are needed and shared among
all instances (objects) of a type (and members).

In C#, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C#, static can be field, method, constructor, class,
properties, operator and event.

Advantage of C# static keyword

Memory efficient: Now we don't need to create instance for accessing the static members, so it
saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance
is created.

C# static field example 3: Counting Objects


using System;
public class Account
{
public int accno;
public String name;
public static int count=0;
public Account(int accno, String name)
{
this.accno = accno;
this.name = name;
count++;
}

public void display()


{
Console.WriteLine(accno + " " + name);
}
}
class TestAccount{
public static void Main(string[] args)
{
Account a1 = new Account(101, "Sonoo");
Account a2 = new Account(102, "Mahesh");
Account a3 = new Account(103, "Ajeet");
a1.display();
a2.display();
a3.display();
Console.WriteLine("Total Objects are: "+Account.count);
}
}

Output:

101 Sonoo
102 Mahesh
103 Ajeet
Total Objects are: 3

C# String
In C#, a string is a sequence of characters.
We use the string keyword to create a string. For example,
// create a string
string str = "C# Programming";
Example: Create string in C#
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

// create string
string str1 = "C# Programming";
string str2 = "Programiz";

// print string
Console.WriteLine(str1);
Console.WriteLine(str2);

Console.ReadLine();
}
}
}
Output:
C# Programming
Programiz

String Operations
C# string provides various methods to perform different operations on strings. We will look into
some of the commonly used string operations.

1. Get the Length of a string


To find the length of a string, we use the Length property. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

// create string
string str = "C# Programming";
Console.WriteLine("string: " + str);

// get length of str


int length = str.Length;

Console.WriteLine("Length: "+ length);

Console.ReadLine();
}
}
}
Output
string: C# Programming
Length: 14

2. Join two strings in C#


We can join two strings in C# using the Concat() method. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

// create string
string str1 = "C# ";
Console.WriteLine("string str1: " + str1);

// create string
string str2 = "Programming";
Console.WriteLine("string str2: " + str2);

// join two strings


string joinedString = string.Concat(str1, str2);

Console.WriteLine("Joined string: " + joinedString);

Console.ReadLine();
}
}
}
Output
string str1: C#
string str2: Programming
Joined string: C# Programming

3. C# compare two strings


In C#, we can make comparisons between two strings using the Equals() method.
The Equals() method checks if two strings are equal or not. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";

// compare str1 and str2


Boolean result1 = str1.Equals(str2);

Console.WriteLine("string str1 and str2 are equal: " + result1);

//compare str1 and str3


Boolean result2 = str1.Equals(str3);

Console.WriteLine("string str1 and str3 are equal: " + result2);

Console.ReadLine();
}
}
}
Output
string str1 and str2 are equal: True
string str1 and str3 are equal: False

Value Types:
A data type is a value type if it holds a data value within its own memory space. It means the
variables of these data types directly contain values.

The following data types are all of value type:

• bool
• byte
• char
• decimal
• double
• enum
• float
• int
• long
• sbyte
• short
• struct

int x = 10;
int y = x;
y = 20;
// after this statement x holds value 10 and y holds value 20

Reference Type:

Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address
where the value is being stored. In other words, a reference type contains a pointer to another
memory location that holds the data.
For example, consider the following string variable:
string s = "Hello World!!";

The followings are reference type data types:

• String
• Arrays (even if their elements are value types)
• Class
• Delegate

Example: Passing Reference Type Variable


static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Rudransh";
}

static void Main(string[] args)


{
Student std1 = new Student();
std1.StudentName = "Bill";

ChangeReferenceType(std1);

Console.WriteLine(std1.StudentName);
}

Output:
Rudransh

Boxing and unboxing:


Boxing and unboxing is an important concept in C# type system. With Boxing and unboxing
one can link between value-types and reference-types by allowing any value of a value-type to
be converted to and from type object.

Boxing
• Boxing is a mechanism in which value type is converted into reference type.
• It is implicit conversion process in which object type (super type) is used.
• In this process type and value both are stored in object type
Unboxing

• Unboxing is a mechanism in which reference type is converted into value.


• It is explicit conversion process.

Example
int i, j;
object obj;
string s;
i = 32;
obj = i; // boxed copy
i = 19;
j = (int) obj; // unboxed
C# Exception Handling:

Exception Handling in C# is a process to handle runtime errors. We perform exception


handling so that normal flow of the application can be maintained even after runtime errors.

In C#, exception is an event or object which is thrown at runtime. All exceptions the derived
from System.Exception class. It is a runtime error which can be handled. If we don't handle
the exception, it prints exception message and terminates the program.

C# Exception Classes
All the exception classes in C# are derived from System.Exception

Exception Description

System.DivideByZeroException handles the error generated by dividing a number


with zero.

System.NullReferenceException handles the error generated by referencing the


null object.

System.InvalidCastException handles the error generated by invalid


typecasting.

System.IO.IOException handles the Input Output errors.

System.FieldAccessException handles the error generated by invalid private or


protected field access.

C# Exception Handling Keywords


In C#, we use 4 keywords to perform exception handling:
o try
o catch
o finally, and
o throw

C# try/catch

In C# programming, exception handling is performed by try/catch statement. The try block in


C# is used to place the code that may throw exception. The catch block is used to handled the
exception. The catch block must be preceded by try block.
C# example without try/catch
using System;
public class ExExample
{
public static void Main(string[] args)
{
int a = 10;
int b = 0;
int x = a/b;
Console.WriteLine("Rest of the code");
}
}

Output:

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero

C# try/catch example
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }

Console.WriteLine("You can not divide a number by zero");


}
}
Output:
System.DivideByZeroException: Attempted to divide by zero.
You can not divide a number by zero.
Unit 03: Object Oriented Programming with C#

C# Encapsulation:
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the
mechanism that binds together the data and the functions that manipulate them. In a different
way, encapsulation is a protective shield that prevents the data from being accessed by the code
outside this shield.

 Technically in encapsulation, the variables or data of a class are hidden from any other class
and can be accessed only through any member function of its own class in which they are
declared.
 As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.
 Encapsulation can be achieved by: Declaring all the variables in the class as private and
using C# Properties in the class to set and get the values of variables.

Encapsulation in object-oriented programming (OOP) is a mechanism of hiding the internal details


(implementation) of an object from other objects and the outside world. It is one of the four
fundamental principles of OOP, along with inheritance, polymorphism, and abstraction.
Encapsulation allows an object to control access to its data and methods, which can improve the
security and stability of the system. In OOP, encapsulation is typically achieved through the use
of access modifiers, such as "private" and "protected," which restrict access to certain members of
a class.

Why do we need encapsulation?

Encapsulation is an important concept in object-oriented programming (OOP) because it allows


you to hide the internal details (implementation) of an object from other objects and the outside
world. This provides a number of benefits, such as:

Abstraction: Encapsulation allows you to create a level of abstraction between the internal
workings of an object and its external behavior. This makes it easier to understand the code and
reduces the risk of errors caused by changing the internal data directly.
Modularity: Encapsulation allows you to create self-contained objects that can be reused and
combined in different ways. This makes your code more modular and easier to maintain.

Security: Encapsulation allows you to control access to the internal data of an object, which can
improve the security of the system by preventing unauthorized access or modification of sensitive
data.

Flexibility: Encapsulation allows you to change the internal implementation of an object without
affecting the rest of the system. This makes your code more flexible and adaptable to changing
requirements.

Extensibility: Encapsulation allows you to create a stable and robust system, as it allows you to
add new features and functionality to the objects without affecting the existing code.

Encapsulation in C#:
In C#, encapsulation is achieved through the use of access modifiers, such as "private,"
"protected," and "internal."
 "private" members of a class can only be accessed within the class itself.
 "protected" members can be accessed within the class and any derived classes.
 "internal" members can be accessed within the same assembly.

By default, members of a class are private.

A fully encapsulated class has getter and setter functions that are used to read and write data. This
class does not allow data access directly.

Example to Understand Encapsulation in C#:


public class Employee
{
private string _employeeName;
public string EmployeeName
{
get
{
return _employeeName;
}
set
{
_employeeName = value;
}

}
}
public class Departmentmain {
public static void Main(string[] args)
{
Employeeemp = newEmployee();
emp.EmployeeName = "Mukesh Kumar";
Console.WriteLine("Employee Name is " + emp.EmployeeName);
}
}

Output: Employee name is Mukesh Kumar.

In C#, we use Access Modifier to hide the data from the outer world. The following are the access
modifiers.
 Private
It is used to restrict the member function or variable to be called outside from the class. If we
create any function or variable inside the class as private then it will not be accessible to
outside the class.
 Public
A member function or variable declared as public can be accessed from outside the class. It
means you can access public member from anywhere.
 Internal
The member functions and variables which are declared as Internal only can be accessible
inside the same namespace. You cannot access these members outside the namespace where
these are declared.
 Protected
The Protected members can only be accessible from its child class or in same class. It is best
when you are using inheritance in your project.
 ProtectedInternal
It can be accessible within the assembly where it is declared or in derived class of other
assembly.

Inheritance:

In C#, inheritance is a process in which one object acquires all the properties and behaviors of its
parent object automatically. In such way, you can reuse, extend or modify the attributes and
behaviors which is defined in other class.
In C#, the class which inherits the members of another class is called derived class and the class
whose members are inherited is called base class. The derived class is the specialized class for the
base class.

Acquiring (taking) the properties of one class into another is called inheritance. Code reusability
is one of the key features of OOPs, and it is achieved via inheritance. Using inheritance, one or
more classes can derive from an existing class. The existing class is called a base class, and the
inherited class is called a derived or inherited class.
The following are the types of inheritance in C#.

The inheritance concept is based on a base class and its derived classes. Let us see the definition
of base and derived classes.

 Base class - the class from which features are to be inherited into another class.
 Derived class - the class that is inherited from the base class.

Single inheritance in C#

It is the type of inheritance in which there is one base class and one derived class.

public class Accountcreditinfo //base class


{
public string Credit()
{
return "balance is credited";
}
}
public class debitinfo : Accountcreditinfo //derived class
{
public string debit()
{
Credit(); ////derived class method
return "balance is debited";
}
}

Hierarchical inheritance in C#

This is the type of inheritance in which there are multiple classes derived from one base class.
This type of inheritance is used when there is a requirement of one class feature that is needed in
multiple classes.

class A //base class


{
public string msg()
{
return "this is A class Method";
}
}
class B : A
{
public string info()
{
msg();
return "this is B class Method";
}
class C : A
{
public string getinfo()
{
msg();
return "this is B class Method";
}
}
}

Multilevel inheritance in C#

When one class is derived from another, this type of inheritance is called multilevel inheritance.

public class Person


{
public string persondet()
{
return "this is the person class";
}
}
public class Bird : Person
{
public string birddet()
{
persondet();
return "this is the birddet Class";
}
}
public class Animal : Bird
{
public string animaldet()
{
persondet();
birddet();
return "this is the Animal Class";
}
}

Polymorphism in C#:
Polymorphism is a Greek word meaning "one name many forms." "Poly" means many, and
"morph" means forms. In other words, one object has many forms or has one name with multiple
functionalities. Polymorphism allows a class to have multiple implementations with the same
name. It is one of the core principles of Object Oriented Programming after encapsulation and
inheritance. In this article, you'll learn what polymorphism is, how it works, and how to implement
it in C#.

Types of Polymorphism

There are two types of polymorphism in C#:

 Static / Compile Time Polymorphism


 Dynamic / Runtime Polymorphism

Static or compile-time polymorphism


Method overloading is an example of Static polymorphism. To Overloading is the concept in
which method names are the same with different parameters. The method/function has the same
name but different signatures in overloading. It is also known as Early binding. It is also known
as compile-time polymorphism because the decision of which method is to be called is made at
compile time.

Polymorphism using overloading and overriding-


Method Overloading:

using System;
namespace DemoCsharp
{
class Program
{
public int Add(int num1, int num2)
{
return (num1 + num2);
}
public int Add(int num1, int num2, int num3)
{
return (num1 + num2 + num3);
}

public string Add(string value1, string value2)


{
return (value1 + " " + value2);
}
static void Main(string[] args)
{
Program objProgram = new Program();
Console.WriteLine("Add with two int parameter :" + objProgram.Add(3, 2));
Console.WriteLine("Add with three int parameter :" + objProgram.Add(3, 2, 8));
Console.WriteLine("Add with two string parameter :" + objProgram.Add("hello",
"world"));
Console.ReadLine();
}
}
}
Output:

Method overriding:
using System;
namespace DemoCsharp
{
class BaseClass
{
public virtual int Add(int num1, int num2)
{
return (num1 + num2);
}
}
class ChildClass : BaseClass
{
public override int Add(int num1, int num2)
{
if (num1 <= 0 || num2 <= 0)
{
Console.WriteLine("Values could not be less than zero or equals to zero");
Console.WriteLine("Enter First value : ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter First value : ");
num2 = Convert.ToInt32(Console.ReadLine());
}
return (num1 + num2);
}
}
class Program
{
static void Main(string[] args)
{
BaseClass baseClassObj;
baseClassObj = new BaseClass();
Console.WriteLine("Base class method Add :" + baseClassObj.Add(-4, 8));
baseClassObj = new ChildClass();
Console.WriteLine("Child class method Add :" + baseClassObj.Add(-3, 2));
Console.ReadLine();
}
}
}

Output:

Virtual and Override keywords (Method Overriding)


Virtual keyword:
It is used to specify the virtual method in the base class and the method with the same signature
that needs to be overridden in the derived class.

Override keyword:
We generally use override with virtual. When we need to override the base class method into a
derived class then we use the override keyword.

Virtual and Override Keyword Example:

using System;

namespace Polymorphism

class A

public virtual void Test() { Console.WriteLine("A::Test()"); }


}

class B : A

public override void Test() { Console.WriteLine("B::Test()"); }

class C : B

public override void Test() { Console.WriteLine("C::Test()"); }

class Program

static void Main(string[] args)

A a = new A();

B b = new B();

C c = new C();

a.Test();

b.Test();

c.Test();

a = new B();

a.Test();

b = new C();

b.Test();
Console.ReadKey();

Output:
A::Test()
B::Test()
C::Test()
B::Test()
C::Test()

C# Abstract:
Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide
the internal details and showing functionality only. Abstraction can be achieved by two ways:

1. Abstract class
2. Interface

Abstract class and interface both can have abstract methods which are necessary for abstraction.

Abstract Method

A method which is declared abstract and has no body is called abstract method. It can be
declared inside the abstract class only. Its implementation must be provided by derived classes.
For example:

public abstract void draw();

C# Abstract class

In C#, abstract class is a class which is declared abstract. It can have abstract and non-abstract
methods. It cannot be instantiated. Its implementation must be provided by derived classes. Here,
derived class is forced to provide the implementation of all the abstract methods.
using System;
public abstract class Shape
{
public abstract void draw();
}
public class Rectangle : Shape
{
public override void draw()
{
Console.WriteLine("drawing rectangle...");
}
}
public class Circle : Shape
{
public override void draw()
{
Console.WriteLine("drawing circle...");
}
}
public class TestAbstract
{
public static void Main()
{
Shape s;
s = new Rectangle();
s.draw();
s = new Circle();
s.draw();
}
}

Output:

drawing ractangle...

drawing circle...
Garbage Collection in C# | .NET Framework:
Garbage collection is a memory management technique used in the .NET Framework and many
other programming languages. In C#, the garbage collector is responsible for managing memory
and automatically freeing up memory that is no longer being used by the application.
The garbage collector works by periodically scanning the application’s memory to determine
which objects are still being used and which are no longer needed. Objects that are no longer being
used are marked for garbage collection, and their memory is freed up automatically by the garbage
collector.
Some of the key features of the garbage collector in C# include:
1. Automatic memory management: With the garbage collector, developers don’t need to
worry about manually allocating or freeing up memory. The garbage collector takes care
of memory management automatically, which can help reduce the risk of memory leaks
and other issues.
2. Low impact on application performance: The garbage collector runs in the background and
typically has a low impact on application performance. However, in some cases, garbage
collection can cause brief pauses or slowdowns in the application, particularly when large
amounts of memory need to be freed up at once.
3. Generation-based collection: The garbage collector in C# uses a generation-based approach
to memory management. Objects are initially allocated in a “young” generation and are
moved to an “old” generation if they survive multiple garbage collection cycles. This
approach helps reduce the amount of time required for garbage collection, as most objects
are collected in the young generation.
4. Finalization: The garbage collector also provides support for finalization, which is a
process that allows objects to perform cleanup tasks before they are destroyed. Objects
with finalizers are moved to a separate finalization queue, which is processed by the
garbage collector after all other objects have been collected.
Automatic memory management is made possible by Garbage Collection in .NET Framework.
When a class object is created at runtime, a certain memory space is allocated to it in the heap
memory. However, after all the actions related to the object are completed in the program, the
memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is
very useful as it automatically releases the memory space after it is no longer required.
Garbage collection will always work on Managed Heap and internally it has an Engine which
is known as the Optimization Engine. Garbage Collection occurs if at least one of multiple
conditions is satisfied. These conditions are given as follows:
 If the system has low physical memory, then garbage collection is necessary.
 If the memory allocated to various objects in the heap memory exceeds a pre-set threshold,
then garbage collection occurs.
 If the GC.Collect method is called, then garbage collection occurs. However, this method
is only called under unusual situations as normally garbage collector runs automatically.

Phases in Garbage Collection:


There are mainly 3 phases in garbage collection. Details about these are given as follows:

1. Marking Phase: A list of all the live objects is created during the marking phase. This is
done by following the references from all the root objects. All of the objects that are not
on the list of live objects are potentially deleted from the heap memory.
2. Relocating Phase: The references of all the objects that were on the list of all the live
objects are updated in the relocating phase so that they point to the new location where
the objects will be relocated to in the compacting phase.
3. Compacting Phase: The heap gets compacted in the compacting phase as the space
occupied by the dead objects is released and the live objects remaining are moved. All the
live objects that remain after the garbage collection are moved towards the older end of
the heap memory in their original order.

Heap Generations in Garbage Collection:


The heap memory is organized into 3 generations so that various objects with different
lifetimes can be handled appropriately during garbage collection. The memory to each
Generation will be given by the Common Language Runtime(CLR) depending on the
project size. Internally, Optimization Engine will call the Collection Means Method to select
which objects will go into Generation 1 or Generation 2.

 Generation 0 : All the short-lived objects such as temporary variables are contained in
the generation 0 of the heap memory. All the newly allocated objects are also generation
0 objects implicitly unless they are large objects. In general, the frequency of garbage
collection is the highest in generation 0.
 Generation 1 : If space occupied by some generation 0 objects that are not released in a
garbage collection run, then these objects get moved to generation 1. The objects in this
generation are a sort of buffer between the short-lived objects in generation 0 and the
long-lived objects in generation 2.
 Generation 2 : If space occupied by some generation 1 objects that are not released in
the next garbage collection run, then these objects get moved to generation 2. The objects
in generation 2 are long lived such as static objects as they remain in the heap memory
for the whole process duration.

Methods in GC Class
The GC class controls the garbage collector of the system. Some of the methods in the GC
class are given as follows:
GC.GetGeneration() Method: This method returns the generation number of the target
object. It requires a single parameter i.e. the target object for which the generation number is
required.
using System;

public class Demo {

public static void Main(string[] args)


{
Demo obj = new Demo();
Console.WriteLine(
"The generation number of object obj is: "
+ GC.GetGeneration(obj));
}
}

Output:
The generation number of object obj is: 0

GC.GetTotalMemory() Method: This method returns the number of bytes that are allocated
in the system. It requires a single boolean parameter where true means that the method waits
for the occurrence of garbage collection before returning and false means the opposite.

using System;

public class Demo {

public static void Main(string[] args)


{
Console.WriteLine("Total Memory:"
+ GC.GetTotalMemory(false));

Demo obj = new Demo();

Console.WriteLine(
"The generation number of object obj is: "
+ GC.GetGeneration(obj));

Console.WriteLine("Total Memory:"
+ GC.GetTotalMemory(false));
}
}
Output:
Total Memory:4197120
The generation number of object obj is: 0
Total Memory:4204024
GC.Collect() Method : Garbage collection can be forced in the system using the GC.Collect()
method. This method requires a single parameter i.e. number of the oldest generation for which
garbage collection occurs.

using System;

public class Demo {

public static void Main(string[] args)


{
GC.Collect(0);
Console.WriteLine(
"Garbage Collection in Generation 0 is: "
+ GC.CollectionCount(0));
}
}
Output:
Garbage Collection in Generation 0 is: 1

Benefits of Garbage Collection


 Garbage Collection succeeds in allocating objects efficiently on the heap memory using
the generations of garbage collection.
 Manual freeing of memory is not needed as garbage collection automatically releases the
memory space after it is no longer required.
 Garbage collection handles memory allocation safely so that no object uses the contents of
another object mistakenly.
 The constructors of newly created objects do not have to initialize all the data fields as
garbage collection clears the memory of objects that were previously released.

Interfaces:

An interface in C# is a contract that defines a set of methods, properties, events, and indexers
that a class or struct must implement. Interfaces cannot be instantiated directly, but they can
be implemented by classes and structs. They are one of several tools for implementing object-
oriented design in C#.
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which
are declared inside the interface are abstract methods. It cannot have method body and cannot
be instantiated.
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.

Syntax
An interface in C# is created using the interface keyword. The syntax for defining an interface
in C# is:
interface MyInterface
{
void MyMethod();
string MyProperty { get; set; }
event EventHandler MyEvent;
}
To implement an interface in C#, you use the : symbol, followed by the name of the interface.
The syntax for implementing an interface is as follows:
class MyClass : MyInterface
{
public void MyMethod()
{
// implementation of MyMethod()
}

public string MyProperty


{
get { return "MyValue"; }
set { }
}

public event EventHandler MyEvent;


}

Example:

using System;

// Create an interface called IAnimal


interface IAnimal
{
// Define a method called Speak()
void Speak();
}

// Create a class called Dog that implements the IAnimal interface


class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Woof!");
}
}

// Create a class called Cat that implements the IAnimal interface


class Cat : IAnimal
{
public void Speak()
{
Console.WriteLine("Meow!");
}
}

// Create a main method to test the program


public class Program
{
public static void Main(string[] args)
{
// Create a Dog object
Dog dog = new Dog();

// Call the Speak() method on the Dog object


dog.Speak();

// Create a Cat object


Cat cat = new Cat();

// Call the Speak() method on the Cat object


cat.Speak();
}
}

Output:
Woof!
Meow!

Use of Interfaces:

Interfaces can be used in C# to achieve a number of different goals, including:


 Abstraction: Interfaces can be used to abstract away the implementation details of a class
or struct. This can make code more modular and easier to understand.
 Multiple inheritance: C# does not support multiple inheritance of classes, but it does
support multiple inheritance of interfaces. This allows a class to inherit the functionality of
multiple different interfaces.

IComparable Interface:
Defines a generalized type-specific comparison method that a value type or class implements to
order or sort its instances. Comparing objects involves determining whether two objects are equal
or determining their relative ordering. Equality comparison checks whether two objects have the
same state, while ordering comparison determines which object comes before or after the other.

C#-
public interface IComparable

Example-

using System;
using System.Collections;

public class Temperature : IComparable


{
// The temperature value
protected double temperatureF;

public int CompareTo(object obj) {


if (obj == null) return 1;

Temperature otherTemperature = obj as Temperature;


if (otherTemperature != null)
return this.temperatureF.CompareTo(otherTemperature.temperatureF);
else
throw new ArgumentException("Object is not a Temperature");
}

public double Fahrenheit


{
get
{
return this.temperatureF;
}
set
{
this.temperatureF = value;
}
}

public double Celsius


{
get
{
return (this.temperatureF - 32) * (5.0/9);
}
set
{
this.temperatureF = (value * 9.0/5) + 32;
}
}
}

public class CompareTemperatures


{
public static void Main()
{
ArrayList temperatures = new ArrayList();
// Initialize random number generator.
Random rnd = new Random();

// Generate 10 temperatures between 0 and 100 randomly.


for (int ctr = 1; ctr <= 10; ctr++)
{
int degrees = rnd.Next(0, 100);
Temperature temp = new Temperature();
temp.Fahrenheit = degrees;
temperatures.Add(temp);
}

// Sort ArrayList.
temperatures.Sort();

foreach (Temperature temp in temperatures)


Console.WriteLine(temp.Fahrenheit);
}
}

Output:

2
7
16
17
31
37
58
66
72
95

ICloneable Interface:
Supports cloning, which creates a new instance of a class with the same value as an existing
instance.Cloning refers to the process of creating an exact copy of an existing object. In many
programming languages, objects are reference types, meaning that variables hold references to
objects rather than the objects themselves. When you assign one object variable to another, you're
creating another reference to the same object. Cloning allows you to create a new object that has
the same state as the original object but is distinct from it.

C#-
public interface ICloneable

Build Clone able objects-

using System;
class Program
{
static void Main()
{
string[] arr = { "Amit", "Nitin", "Ankit", "Sunny", "Rahul" };
string[] arrCloned = arr.Clone() as string[];

Console.WriteLine(string.Join(",", arr));
Console.WriteLine(string.Join(",", arrCloned));
Console.ReadLine();
}
}

Output:
Amit, Nitin, Ankit, Sunny,Rahul
Unit no- 04
Introduction to ADO.NET And Windows Forms

ADO.NET 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.
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.

Architecture of ADO.NET:
.NET Framework Data Providers
These are the components that are designed for data manipulation and fast access to data. It
provides various objects such as Connection, Command, DataReader and DataAdapter that are
used to perform database operations.
The DataSet
It is used to access data independently from any data resource. DataSet contains a collection of
one or more DataTable objects of data. The following diagram shows the relationship between
.NET Framework data provider and DataSet.
ADO.NET Framework Data Providers
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.

.NET Framework Data Providers Objects


Following are the core object of Data Providers.
.NET Framework Data Provider for SQL Server
Data provider for SQL Server is a lightweight component. It provides better performance because
it directly access SQL Server without any middle connectivity layer.
The .NET Framework Data Provider for SQL Server classes is located in
the System.Data.SqlClient namespace. We can include this namespace in our C# application by
using the following syntax.
using System.Data.SqlClient;
.NET Framework Data Provider for Oracle
It is used to connect with Oracle database through Oracle client. The data provider supports Oracle
client software version 8.1.7 or a later version. This data provider supports both local and
distributed transactions.
Oracle Data Provider classes are located into System.Data.OracleClient namespace. We must
use both System.Data.OracleClient and System.data to connect our application with the Oracle
database.
using System.Data;
using System.Data.OracleClient;

ADO.NET SQL Server Connection


To connect with SQL Server, we must have it installed in our system. We are using Microsoft SQL
Server Management Tool to connect with the SQL Server. We can use this tool to handle database.
1. Open Microsoft SQL Server Management Tool
It will prompt for database connection. Provide the server name and authentication.
After successful connection, it displays the following window.

2. Creating Database
Now, create database by selecting database option then right click on it. It pops up an option menu
and provides couple of options.

Click on the New Database then it will ask for the database name. Here, we have created
a Student database.
Click on the Ok button then it will create a database.
3. Establish connection and create a table
After creating database, now, let's create a table by using the following C# code. In this source
code, we are using created student database to connect.
Program-
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=S
SPI");
// writing sql query
SqlCommand cm = new SqlCommand("create table student(id int not null,
name varchar(100), email varchar(50), join_date date)", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
// Displaying a message
Console.WriteLine("Table created Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong."+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}

Output-

1. Insert Data into the Table


// Program.cs
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated secu
rity=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("insert into student
(id, name, email, join_date)values('101','Ronald Trump','ronald@example.c
om','1/12/2017')", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
// Displaying a message
Console.WriteLine("Record Inserted Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong."+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}

Retrieve Record

// Program.cs

using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("Select * from student", con);
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
// Iterating Data
while (sdr.Read())
{
Console.WriteLine(sdr["id"] + " " + sdr["name"]+" "+sdr["email"]); // Displaying
Record
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n"+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}

Deleting Record
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("delete from student where id = '101'", con);
// Opening Connection
con.Open();
// Executing the SQL query
cm.ExecuteNonQuery();
Console.WriteLine("Record Deleted Successfully");
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n"+e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}

ADO.NET SqlConnection Class:


It is used to establish an open connection to the SQL Server database. It is a sealed class so that
cannot be inherited. SqlConnection class uses SqlDataAdapter and SqlCommand classes together
to increase performance when connecting to a Microsoft SQL Server database.
Connection does not close explicitly even it goes out of scope. Therefore, you must explicitly close
the connection by calling Close() method.

using (SqlConnection connection = new SqlConnection(connectionString))


{
connection.Open();
}

Program:

using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().Connecting();
}
public void Connecting()
{
using (
// Creating Connection
SqlConnection con = new SqlConnection("data source=.; database=student; inte
grated security=SSPI")
)
{
con.Open();
Console.WriteLine("Connection Established Successfully");
}
}
}
}

Output:

ADO.NET Connection-Oriented Data Access Architecture:


In the case of Connection-Oriented Data Access Architecture, an open and active connection
is always required between the .NET Application and the database. An example is Data Reader,
and when we access data from the database, the Data Reader object requires an active and open
connection to access the data. If the connection is closed, we cannot access the data from the
database; in that case, we will get the runtime error.
The Connection Oriented Data Access Architecture is forward only. That means we can
only access the data in the forward direction using this architecture mode. Once we read a row,
it will move to the next data row, and there is no chance to move back to the previous row.
The Connection Oriented Data Access Architecture is read-only. This means that by using
this architecture, we can only read the data. We cannot modify the data, i.e., we cannot update
and delete the data row.
For Connection Oriented Architecture, we generally use the object of the ADO.NET
DataReader class. The DataReader object is used to retrieve the data from the database, and it
also ensures that an open and active connection is maintained while accessing the data from
the database. In Connection Oriented Architecture, the .NET Application is directly linked
with the corresponding Database.
ADO.NET Disconnection-Oriented Data Access Architecture:
In the case of Disconnection Oriented Data Access Architecture, an open and active connection
is not required between the .NET Application and the database. In this architecture,
connectivity is required only to read the data from the database and update the data within the
database.
An example is DataAdapter and DataSet or DataTable classes. Here, using the DataAdapter
object and an active and open connection, we can retrieve the data from the database and store
the data in a DataSet or DataTable. The DataSets or DataTables are in-memory objects, or you
can say they store the data temporarily within the .NET Application. Then, whenever required
in our .NET Application, we can fetch the data from the dataset or data table and process the
data. Here, we can modify the data, insert new data, and delete the data from within the dataset
or data tables. So, we do not require an active and open connection while processing the data
within the .NET Application using DataSet or Datatable.
Finally, when we process the data in our .NET Application, we need to establish the connection
again if we want to update the modified data stored inside the dataset or Datatable in the
database.
using System;
using System.Data;
using System.Data.SqlClient;
namespace BatchOperationUsingSqlDataAdapter
{
class Program
{
static void Main(string[] args)
{
try
{
// Connection string.
string connectionString = @"data source=LAPTOP-ICA2LCQL\SQLEXPRESS;
database=EmployeeDB; integrated security=SSPI";

// Connect to the EmployeeDB database.


using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create a SqlDataAdapter
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
EMPLOYEE", connection);
//Fetch the Employee Data and Store it in the DataTable
DataTable dataTable = new DataTable();

//The Fill method will open the connection, fetch the data, fill the data in
//the data table and close the connection automatically
adapter.Fill(dataTable);

// Set the UPDATE command and parameters.


string UpdateQuery = "UPDATE Employee SET Name=@Name,
Email=@Email, Mobile=@Mobile WHERE ID=@EmployeeID;";
adapter.UpdateCommand = new SqlCommand(UpdateQuery, connection);
adapter.UpdateCommand.Parameters.Add("@Name", SqlDbType.NVarChar,
50, "Name");
adapter.UpdateCommand.Parameters.Add("@Email", SqlDbType.NVarChar,
50, "Email");
adapter.UpdateCommand.Parameters.Add("@Mobile", SqlDbType.NVarChar,
50, "Mobile");
adapter.UpdateCommand.Parameters.Add("@EmployeeID", SqlDbType.Int, 4,
"ID");
//Set UpdatedRowSource value as None
//Any Returned parameters or rows are Ignored.
adapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
//Change the Column Values of Few Rows
DataRow Row1 = dataTable.Rows[0];
Row1["Name"] = "Name Changed";
DataRow Row2 = dataTable.Rows[1];
Row2["Email"] = "Email Changed";
DataRow Row3 = dataTable.Rows[2];
Row2["Mobile"] = "Mobile Changed";

// Execute the update.


//The Update method will open the connection, execute the Update command by
takking
//the data table data and then close the connection automatically
adapter.Update(dataTable);

Console.WriteLine($"Updated Data Saved into the DataBase");


}
}
catch (Exception ex)
{
Console.WriteLine($"Exception Occurred: {ex.Message}");
}

Console.ReadKey();
}
}
}

Data Binding in ADO.NET:

The user can bind values to the respective controls in ADO.NET. Depending on the type of
binding offered, they are distinguished as follows:

1. Simple Data Binding


2. Complex Data Binding

1. Simple Data Binding

The Simple Data Binding is the process of binding the control with the single value in the
dataset. The controls like text box, label can be bound to the control through the control
properties.
Consider an example to display the result of the students in an examination. The details are
added in the following format.

1. Create a Windows Form Application in Visual Studio .NET. The following customized
format is created for user.

2. Once the design of the form is created, select the View option from the menu bar. Click on
the Properties window.
3. Select the first text box and the properties for it appear in the window.
4. Expand the DataBindings property
5. Select the Text property for enabling the drop down list.
6. Click the Add Project Data Source from the drop down list
7. Make a connection with the CurrentInfo database and select the Student table
8. Select the Other Data Sources, Project Data Sources, CurrentInfoDataSet, Student table.
9. Select the Name column and bind it with the textbox.
10. Bind all the other text boxes with the database values.
11. Press F5 and execute the Windows Form.
12. The following output is displayed to the user.

2. Complex Data Binding

The Complex Data Binding is the process of binding the component with the Database. The
controls can be GridView, Dropdown list, or combo box. Multiple values can be displayed from
the dataset through the binding.

The controls that can be used for binding the multiple values from the database to the Windows
Form are listed below.

1. DataGridView: It is used to display the multiple records and columns. The DataSource
property of the DataGridView control is used for binding the specific data element.
2. ComboBox: The control contains a text box for entering the data and drop down list for
displaying the values. The DataSource property is useful for binding the control. The
element specific information can be bind through the DisplayMember property
3. ListBox: It is used for displaying the data for the column from several records of datasets.
The DataSource property is used for binding the control to the data source.
4. The DisplayMember property is used for binding the control to the specific data element.
Navigating Records in ADO.NET
A BindingNavigator control is used for handling the binding to the data source through the
pointer to the current item in the list of records.

The navigator control is used with the BindingSource control for enabling the users to navigate
the data records on a form. It provides a layer between the controls and windows form of the data
source. Users can navigate and modify the records in the Windows form.

The following figure displays the BindingNavigator control and the BindingSource control in the
Windows Form.
The Binding Navigator control has many controls for modifying the data source. The list of
controls and their functions are mentioned below:

1. Binding Navigator Add New Item Button: The + sign indicates that the new row can be
added to the data source.
2. Binding Navigator Delete Item Button: The X sign indicates that the current row can be
deleted from the data source.
3. Binding Navigator Move First Item Button: The button indicates that the user can move
to the first item in the data source.
4. Binding Navigator Move Last Item Button: The button indicates that the user can move
to the last item in the data source
5. Binding Navigator Move Next Item Button: The button indicates that the user can move
to the next item in the data source
6. Binding Navigator Move Previous Item Button: The button indicates that the user can
move to the previous item in the data source
7. Binding Navigator Position Item textbox: The returns current position in the data source
8. Binding Navigator Count Item Text box: The is used to return the total number of items
in the data source.
Consider the Order details table containing the data about the orders to be added. The data is
organized into a format as shown below:

1. Open Visual studio application and add Windows Forms Application from the template
pane.
2. Add the labels and a binding Navigator control, and textbox controls to the form
3. Click OK button
4. Click View, Properties Window, and open the Properties Window.
5. Add the appropriate names to the controls present in the web form.

6. Open the Data Source Configuration Wizard. The Database icon must be selected. Click
Next Button
7. Click New Connection Button. Add Connection dialog box is shown.
8. Add the Server Name, select Use SQL Server Authentication option from the Log on the
server section
9. Add the User name as sa and password as abcd1234
10. Select the Order Details database and click Test Connection button
11. Click OK and close the Add Connection dialog box
12. Click Next button. In the Choose Your Database Objects dialog box, expand Tables node.
13. Select the Orderdata table and click Finish button.
For binding the data to the control in the Windows Form, the following steps are executed.

1. Select the textbox1, and expand the DataBindings property.


2. Select the Text property and click on the drop down list.
3. Expand the Other Data Sources, Project Data, Sources, Orderdataset, Orderdata nodes.
4. Select the OrderID column and bind it with textbox1.
5. Perform the similar operations for all the textboxes.
Press F5 or click Debug -> Start Debugging option from the menu. The Order Details form is
displayed as shown below:
Unit 05
Introduction to ASP.NET
ASP.NET is a web development platform, which provides a programming model, a
comprehensive software infrastructure and various services required to build up robust web
applications for PC as well as mobile devices.
ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and
policies to set a browser-to-server bilateral communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written
using the extensible and reusable components or objects present in
.Net framework. These codes can use the entire hierarchy of classes in .Net
framework.
ASP.NET application codes can be written in any of the following languages:
 C#
 Visual Basic.Net
 Jscript
 J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It consists
of a large number of controls such as text boxes, buttons, and labels for assembling, configuring,
and manipulating code to create HTML pages.
Components and their Description
(1) Common Language Runtime or CLR
It performs memory management, exception handling, debugging, security checking, thread
execution, code execution, code safety, verification, and compilation. The code that is directly
managed by the CLR is called the managed code. When the managed code is compiled, the
compiler converts the source code into a CPU independent intermediate language (IL) code. A
Just-In-Time (JIT) compiler compiles the IL code into native code, which is CPU specific.

(2) .Net Framework Class Library


It contains a huge library of reusable types, classes, interfaces, structures, and enumerated values,
which are collectively called types.
(3) Common Language Specification
It contains the specifications for the .Net supported languages and implementation of language
integration.
(4) Common Type System
It provides guidelines for declaring, using, and managing types at runtime, and cross-language
communication.
(5) Metadata and Assemblies
Metadata is the binary information describing the program, which is either stored in a portable
executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly
manifest, type metadata, IL code, and a set of resources like image files.
(6) Windows Forms
Windows forms contain the graphical representation of any window displayed in the application.
(7) ADO.NET
It is the technology used for working with data and databases. It provides access to data sources
like SQL server, OLE DB, XML etc. The ADO.NET allows connection to data sources for
retrieving, manipulating, and updating data.

(8) Windows Workflow Foundation (WF)


It helps in building workflow-based applications in Windows. It contains activities, workflow
runtime, workflow designer, and a rules engine.
(9) Windows Presentation Foundation
It provides a separation between the user interface and the business logic. It helps in developing
visually stunning interfaces using documents, media, two and three dimensional graphics,
animations, and more.

(10) Windows Communication Foundation (WCF)


It is the technology used for building and executing connected systems.
(11) Windows CardSpace
It provides safety for accessing resources and sharing personal information on the internet.
(12) LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the
tradition query language SQL.

Introduction to C# Windows Forms Applications:


Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net
Framework. Its main purpose is to provide an easier interface to develop the applications for
desktop, tablet, PCs. It is also termed as the WinForms. The applications which are developed by
using Windows Forms or WinForms are known as the Windows Forms Applications that runs on
the desktop computer. WinForms can be used only to develop the Windows Forms Applications
not web applications. WinForms applications can contain the different type of controls like labels,
list boxes, tooltip etc.

1. Editor Window or Main Window: Here, you will work with forms and code editing. You
can notice the layout of form which is now blank. You will double click the form then it
will open the code for that.
2. Solution Explorer Window: It is used to navigate between all items in solution. For
example, if you will select a file form this window then particular information will be
display in the property window.
3. Properties Window: This window is used to change the different properties of the selected
item in the Solution Explorer. Also, you can change the properties of components or
controls that you will add to the forms.
Now to add the controls to your WinForms application go to Toolbox tab present in the
extreme left side of Visual Studio. Here, you can see a list of controls. To access the most
commonly used controls go to Common Controls present in Toolbox tab.

Now drag and drop the controls that you needed on created Form. For example, if you can
add TextBox, ListBox, Button etc. as shown below. By clicking on the particular dropped
control you can see and change its properties present in the right most corner of Visual
Studio.
C# Windows Forms is a graphical user interface (GUI) framework that enables developers to
create desktop applications for the Windows operating system. Windows Forms applications
are created using the C# programming language and the .NET framework. They are built by
dragging and dropping controls such as buttons, text boxes, labels, and other user interface
elements onto a form.
1. The Windows Forms framework provides a rich set of controls that developers can use to
build applications with. These controls are designed to provide a consistent and familiar
user interface for Windows users. Developers can customize the appearance and behavior
of these controls by setting various properties and handling events.
2. To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which
is an integrated development environment (IDE) that provides a visual designer to create
and layout the user interface elements. The visual designer is a drag-and-drop interface for
building your UI, and you can easily configure each control’s properties through a user-
friendly interface.
3. In addition to the visual designer, Visual Studio also provides a code editor that enables
developers to write the C# code for the application’s logic. Developers can handle events
and perform tasks such as data validation, data manipulation, and business logic
implementation.
4. Windows Forms applications are versatile and can be used to create various types of
applications such as data entry, management, and reporting applications, as well as games
and multimedia applications.
Resizing Menus:
In Windows Forms applications, resizing menus typically involves adjusting the layout of your
controls dynamically as the form size changes.
Anchor and Dock Properties: Ensure that your menu controls (like MenuStrip) and other controls
on the form are anchored or docked properly. This allows them to resize and reposition themselves
automatically when the form is resized.
Handling Form Resize Event: You can handle the Resize event of the form to adjust the size and
position of your menu controls accordingly. Here's a simple example in C#:
private void Form1_Resize(object sender, EventArgs e)
{
// Adjust the menu control position
menuStrip1.Width = this.Width;

// Optionally, adjust other controls based on the form size


// control1.Width = this.Width - someOffset;
// control1.Height = this.Height - someOffset;
}

Relative Sizing: Instead of setting absolute sizes for controls, you can use relative sizing
techniques. For example, you can set the menu width as a percentage of the form width, ensuring
that it scales appropriately.
Handling Menu Items: If you have dynamic menu items or menus, you may need to adjust their
size and position programmatically in response to the form's resize event.
Testing: After implementing the resizing logic, thoroughly test your application by resizing the
form to different sizes to ensure that the menu and other controls adjust correctly.
private void Form1_Resize(object sender, EventArgs e)
{
menuStrip1.Width = this.Width;
}

This code assumes that the Menu Strip control (named menuStrip1) is docked at the top of the
form and that you want it to resize horizontally with the form.
Differences between Windows Forms and Web Forms:
Technology:
Windows Forms: Windows Forms applications are designed to run on a local machine's operating
system (Windows). They provide a rich user interface that interacts directly with the user's
machine.
Web Forms: Web Forms applications are designed to run on a web server and are accessed through
a web browser. They use HTML, CSS, and JavaScript to render the user interface on the client-
side.

Deployment:
Windows Forms: Windows Forms applications are deployed as standalone executables that need
to be installed on each user's machine.
Web Forms: Web Forms applications are deployed on a web server and accessed through a browser
without the need for installation on user machines.

User Interface:
Windows Forms: Windows Forms provide a rich, desktop-like user interface with controls tailored
for desktop applications.
Web Forms: Web Forms provide a web-based user interface that works within the limitations of
web browsers and web technologies.

State Management:
Windows Forms: Windows Forms applications can store state on the local machine, such as in
registry settings or local files.
Web Forms: Web Forms applications need to manage state on the server-side or through client-
side mechanisms like cookies, session variables, or hidden fields.

Security:
Windows Forms: Windows Forms applications have access to the local file system and resources,
which can raise security concerns if not properly managed.
Web Forms: Web Forms applications run in a sandboxed environment within the browser, limiting
access to the user's system for security reasons.

Connectivity:
Windows Forms: Windows Forms applications can connect directly to local resources and
databases without the need for internet connectivity.
Web Forms: Web Forms applications need an internet connection to communicate with a web
server and access remote resources.

Cross-Platform Compatibility:
Windows Forms: Windows Forms applications are limited to Windows-based operating systems
and do not have native support for cross-platform deployment.
Web Forms: Web Forms applications can be accessed on any device with a web browser, making
them more cross-platform compatible.

Common controls:
1. Label: Displays text that the user cannot edit.
2. TextBox: Allows users to input text.
3. Button: Triggers an action when clicked.
4. DropDownList: Presents a list of options for users to select from.
5. CheckBox: Represents a single checkbox for users to toggle.
6. RadioButton: Allows users to select a single option from a group.
7. GridView: Displays tabular data with options for sorting, paging, and editing.
8. ListView: Similar to the GridView but offers more flexibility in design.
9. Repeater: A basic control for repeating a template at runtime.
10. FileUpload: Enables users to upload files to the server.
11. Image: Displays an image on the web page.
12. HyperLink: Renders a hyperlink that users can click to navigate to another page.
13. Calendar: Provides a calendar for date selection.
14. Validator Controls (e.g., RequiredFieldValidator, RegularExpressionValidator):
Validates user input based on specified criteria.
15. DropDownMenu: Displays a hierarchical menu of items for navigation.

These controls help you build interactive and user-friendly web applications in ASP.NET Web
Forms. They provide a wide range of functionality, from basic text input to complex data
presentation and validation mechanisms.

ASP.NET:
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. It is part of
the ASP.NET framework. We will discuss it further in next chapters.

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. We will discuss it further in next chapters.

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.
ASP.NET Page Lifecycle:

In ASP.NET, a web page has execution lifecycle that includes various phases. These phases
include initialization, instantiation, restoring and maintaining state etc. it is required to
understand the page lifecycle so that we can put custom code at any stage to perform our
business logic.

 Page Request: When the user requests a page, the server checks the request and then
compiles the page.
 Page Start: In this phase, the two steps are carried out first is "request" and second
is"response". The request holds all information from the page.
 Page Initialization: In this phase, all the controls on the page are set, and each has a
particular ID, and themes are applied to the pages.
 Page Load: In Page Load, all the control properties are loaded, and information is set using
view state and control state.
 Validation: The validation happens when the page execution goes successful it returns
true else the execution fails it returns false.
 Event Handling: This happens in response to validation. In this case, the page is loaded
again. So, the postback event handler is called.
 Rendering: It occurs before all the response information is sent to the user. It also stores
all the information sent to the user.
 Unload: This phase helps to clean all the unwanted information. And it also cleans the
memory once the page output is sent to the user.

Page Life Cycle Stages:

 PreInit: It is the first event in the page life cycle. And it checks the IsPostBack property
and determines whether the page is a postback. It sets the themes and master pages, creates
dynamic controls, and gets and sets profile property values. The PreInit event can be
handled by overloading the OnPreInit method.
 Init: This event is used to initialize the control property and the control tree is built. The
Init event can be handled by overloading the OnInit method or creating a Page_Init handler.
 InitComplete: This event allows tracking of the view state. And it controls turn-on view-
state tracking. The InitComplete event can be used to make changes in ViewState.
 PreLoad: This event is raised when the page loads the ViewState. And it Loads the
PostBack data.
 Load: The page's load event is raised first, followed by recursively raising all child
controls' load events. The control tree's controls are made. The OnLoad method can be
overloaded to handle this event, or a Page Load handler can be made.
 Control Events: It is used to handle specific control events such as Button control' Click
event.
 LoadComplete: LoadComplete event occurs at the end of the event-handling stage. We
can use this event for tasks that require all other controls on the page to be loaded.
 PreRender: This event takes place just before the output is rendered. By handling this
event, pages, and controls can perform any updates before the output is rendered. This
event occurs after the page object has created all controls that are required in order to render
the page.
 PreRenderComplete: This event is triggered recursively for all child controls, make sure
that the pre-rendering phase is completely done. This event happens once each data-bound
control with its DataSourceID property set calls the DataBind method.
 SaveStateComplete: The SaveStateComplete is raised after the view state and the control
state have been saved for the page and for all controls.
 Render: This is not an event; rather, the Page object calls this method on each control at
this step of processing.
 Unload: This is the last event and it is raised for each control and then for the page. It can
be handled by modifying the On UnLoad method.
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.

ASP.NET provides various controls like: server controls and HTML controls for the Web
Forms.
HTML Controls:
These controls render by the browser.

ASP.NET Web Forms Features:


o Server Controls
o Master Pages
o Working with data
o Membership
o Client Script and Client Frameworks
o Routing
o State Management
o Security
o Performance
o Error Handling
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.

Master Pages
It allowsus 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.

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.

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.

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.

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

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.

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.

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.
Difference between asp.net controls and html controls:

The main difference between ASP.NET controls and HTML controls lies in how they are created
and rendered in a web application:

ASP.NET Controls:
Server-side Controls:
ASP.NET controls are server-side controls that are created and manipulated on the server.
They provide a higher level of abstraction and are easier to work with in the code-behind file.

Event-Driven Model:
ASP.NET controls have built-in event-handling mechanisms that make it easy to respond to user
interactions, such as button clicks.
Events are handled on the server-side, simplifying interaction with the control.

ViewState Support:
ASP.NET controls automatically maintain their state across postbacks using ViewState.
This allows for easier management of control states and data preservation.

Rich Functionality:
ASP.NET controls come with rich functionality out of the box, such as validation controls, data
binding controls, and user interface controls like GridView and Repeater.

HTML Controls:
Client-side Controls:
HTML controls are client-side controls that are rendered directly in HTML markup.
They are lightweight and do not provide the same level of functionality and ease of interaction as
ASP.NET controls.

Limited Functionality:
HTML controls are basic input elements like <input> , <button> , <select> , and <textarea> .
They typically do not have built-in event-handling mechanisms or advanced features like data
binding.

Direct Markup:
HTML controls are directly represented in HTML markup and are manipulated using client-side
JavaScript or other client-side technologies.
They require more manual coding compared to ASP.NET controls.

No View State:
HTML controls do not have built-in mechanisms for maintaining state across postbacks like
ASP.NET controls.
State management needs to be handled manually using techniques like hidden fields or client-side
storage.
ASP.NET State Management:
State Management is a process by which state and page information is maintained over multiple
requests for same or different pages. As HTTP is a stateless protocol, server does not store any
information once the
response is sent back to client based on his request. When user submits request again, the server
treats it as a new user. This is called stateless model. This model was workable when static web
sites were developed and hosted in the past. Now, with interactive web sites or dynamic web site,
there is a need to preserve some information to identify user, interact with user again and again
within same session and same application. This concept is known as Stateful protocol. The
information can be related to user, data objects, web pages or server objects.

Server Side State Management Options

ASP.NET provides facility to save information on server side as well as in client side. The
following options are available in Server Side State Management.
o Application State: Application state allows saving of data at application level which is
accessible throughout the life of an application. The life of application starts when IIS is
started and ends when IIS is stopped.
o Session State: The session state persists till the user is active or session time expires. When
a user submits request, a session is started. The session gets over either when time expires
or user explicitly abandons the sessions. The required information can be saved in session
for later user by same user within the same application.
o Profile Properties: This option also allows saving of user specific data. It is similar to
Session state except the data stored in Profile state never expires on use this property, the
SQLProfileProvider class needs to be configured. It allows storing of data in SQL database.
Since data is stored in database and not in application memory, therefore there is no risk of
losing data even if IIS is restarted again and again.
o Cache: Caching is a technique by which frequently used data and web pages are stored in
cache so that repeated cost of retrieval can be avoided. Storing frequently used data in
cache ensures high availability, improved performance and scalability. Cache is object of
System.Web Caching Cache class. The main disadvantage of using Cache is that it is
unreliable. The previously stored data stored in cache is deleted automatically to meet
memory requirement of current process.
Client Side State Management Options
The options available in client side state management help in storing information either in the page
or at the client computer. No information is stored at server side. The followings options are used
for client side state management.
o View State: View state provides facility to preserve page and values of controls at the
client side. The information is stored after post back. Post back is a request from user for
the page which is not for the first time. If value of IsPostBack property is true, it means
page is not requested for the first time. The view state can be at page level, application
level, machine level and control level. In page level state management, as long as the user
is on current page, the information is retained. Whenever user submits form, the current
state of page and controls are hashed into a string and saved in hidden field of the page.
More than one hidden field can be used if data exceed limit set
by MaxPageStateFieldLength property. When page is sent to server, the page parses the
view state string and restores the information. This is default mechanism. The view state
can be disabled at any stage. The property EnableViewState="false" is used in code when
it is required to disable view state
The demonstrate the concept of view state option, consider an ASP.NET project haring one ben
Each time a button is clicked, it displays the number of times the button is clicked.
o Control State: This is another client side state management option. This is used when
there is a need to store control data related to Custom control. View state can be disabled
but control state cannot be disabled.
o Hidden Field State: ASP.NET allows storing information in a hidden field which is a
server control and can be used to store information at page level. The value of the hidden
field is sent to HTTP form collection along with value of other controls. The hidden file
can be created in source file as given below.<input type="hidden" id="username"
name="username" value=""
This hidden field can be accessed in code behind file as given below. Dim st as String = Request
QueryString("username")
o Cookies: Cookie is a small amount of information that is stored in client machine.
o QueryString: A QueryString contains the information that is sent to server with URL.

Master Page In ASP.NET:


Master page allows you to create a consistent look and behavior for all the pages in your web
applications. Master Page Design is common for all the pages. Master page actually consists of
two pieces, the master page itself and one or more content pages. A master page is an ASP.NET
file with the extension .master. Content Placeholder control, which defines a region on the master
page, is where the content pages can plug in page specific content.
Advantages of using Master Page in ASP.NET:
Master pages enable consistent and standardized layout of the website.

- You can make layout changes of the site in the master page instead of making changes in the
pages.

- It is very easy to implement.

- It provides an object model which allows you to customize the master page from individual
content pages.
- It allows you to centralize the common functionality of your pages so that you can make
updates in just one place.

A Master page offers a template for one or more web forms.

- It defines placeholders for the content, which can be overridden by the content pages.

- The content pages contain only content.

- When users request the content page, ASP.NET merges the layout of the master page with the
content of the content page and produce output.

Advantage and disadvantage of asp.net:


Advantages:
1. Rapid Development: ASP.NET facilitates rapid development of web applications due to
its built-in features, controls, and libraries. Developers can utilize tools like Visual Studio
to streamline the development process.

2. Scalability: ASP.NET applications can easily scale to accommodate increased user loads
and data volume. It provides features like caching, session state management, and
application pooling to optimize performance.

3. Security: ASP.NET offers robust security features such as authentication, authorization,


and encryption. Developers can implement security measures to protect against common
web vulnerabilities like SQL injection and cross-site scripting (XSS).

4. Language Support: ASP.NET supports multiple programming languages, including C#,


VB.NET, and F#, allowing developers to choose the language that best suits their project
requirements and expertise.

5. Integration with Microsoft Technologies: ASP.NET seamlessly integrates with other


Microsoft technologies such as Azure cloud services, SQL Server databases, and Active
Directory, enabling developers to build comprehensive solutions within the Microsoft
ecosystem.

Disadvantages:

Platform Dependency: ASP.NET applications are primarily designed to run on Windows servers,
which may limit deployment options for developers who prefer other platforms like Linux or
macOS.

Cost: While ASP.NET itself is free and open-source, developers may incur costs associated with
licensing fees for development tools like Visual Studio and server hosting fees for Windows
servers.
Steep Learning Curve: ASP.NET has a steep learning curve, especially for beginners with limited
experience in web development or Microsoft technologies. Developers may require time and
resources to acquire proficiency in ASP.NET development.

Vendor Lock-In: Since ASP.NET is a Microsoft product, developers may face vendor lock-in,
making it challenging to migrate to alternative platforms or technologies in the future.

Performance Overhead: While ASP.NET offers excellent performance and scalability, it may
introduce some performance overhead compared to lightweight frameworks or languages like
Node.js or PHP, especially for simple or static content.

Web server scripting and Client server scripting-


The scripts may be created in two ways: on the client side or the server side, where the server-side
scripts are processed on a server. In contrast, client-side scripting needs browsers to execute scripts
on the client system but doesn't connect with the server executing the client-side scripts.

Server-side scripting is a programming technique for creating code that may run software on the
server side. In other words, server-side scripting is any scripting method that may operate on a web
server. At the server end, actions such as website customization, dynamic changes in website
content, response creation to user requests, database access, and many more are carried out.

Server-side scripting creates a communication channel between a server and a client.


Previously, CGI (Common Gateway Interface) scripts were used to implement server-side
scripting, and CGI was created to execute scripts written in computer languages such as C++ or
Perl on websites.

The server-side is made up of three parts: the database, the server, the APIs, and the backend web
software written in the server-side scripting language. When a browser requests a page with server-
side scripting, the web server evaluates the script before delivering the page to the browser. In this
case, script processing may entail collecting information from a database, performing simple
computations, or selecting the relevant material to be shown on the client end. The output is
provided to the web browser when the script is processed. The web server hides the scripts from
the end user until the content is delivered, making the data and source code safer.

Server-side scripting languages-


Python
PHP

Client-side scripting generates code that may be executed on the client end without needing
server-side processing. These scripts are typically embedded into HTML text. Client-side scripting
may be utilized to check the user's form for problems before submitting it and to change the content
based on the user input. The web needs three components to function: client, database, and server.

The client-side scripting may significantly reduce server demand. It is intended to be utilized as a
scripting language with a web browser as the host program. The HTML and CSS are delivered as
plain text when a user uses a browser to request a webpage from the server, and the browser
understands and renders the web content at the client end.

Client-side Scripting Languages-


HTML
CSS
JAVASCRIPT
VBSCRIPT

Head-to-head comparison between Server-side Scripting and Client-side Scripting:

You might also like