0% found this document useful (1 vote)
342 views89 pages

ASP.net Material

The document provides a syllabus for the ASP.NET Programming course at AVS College of Arts & Science for the academic year 2025-26. It outlines the course structure, including five units covering topics such as .NET framework, C# fundamentals, ADO.NET, and XML classes. Additionally, it lists recommended textbooks and reference materials for students.

Uploaded by

t.ambika1991
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 (1 vote)
342 views89 pages

ASP.net Material

The document provides a syllabus for the ASP.NET Programming course at AVS College of Arts & Science for the academic year 2025-26. It outlines the course structure, including five units covering topics such as .NET framework, C# fundamentals, ADO.NET, and XML classes. Additionally, it lists recommended textbooks and reference materials for students.

Uploaded by

t.ambika1991
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/ 89

AVS COLLEGE OF ARTS & SCIENCE

(AUTONOMOUS)
Attur Main Road, Ramalingapuram, Salem - 106.
(Recognizedundersection2(f)&12(B)ofUGCAct1956and
Accredited by NAAC with 'A' Grade)
(Co-Educational Institution Affiliated to Periyar University, Salem ISO 9001: 2015
Certified Institution)

[email protected]| www.avscollege.ac.in
Ph: 98426 29322, 94427 00205.

Study Material

PAPER NAME ASP.NET PROGRAMMING

PAPER CODE 23UCACC06

BATCH 2025-26

SEMESTER ODD

STAFF INCHARGE NIVETHA V


23UCACC06-CORE COURSE X - ASP.NET PROGRAMMING
SYLLABUS
Unit – I
Introduction to .NET & Control Statement-Overview of .NET framework: Common
Language Runtime (CLR), Framework Class Library-C# Fundamentals: Primitive types and
Variables – Operators – Conditional statements - Looping statements – Creating and Using
Objects – Arrays – String operations.
Unit – II
IDE & HTML Controls-IntroductiontoASP.NET – IDE – Languages supported
Components – Working with Web Forms – Web form standard controls: Properties and its
events – HTML controls - List Controls: Properties and its events.
Unit – III
Rich Controls & Validation Controls-Rich Controls: Properties and its events – validation
controls: Properties and its events – File Stream classes - File Modes – File Share – Reading
and Writing to files – Creating, Moving, Copying and Deleting files – File uploading.
Unit – IV
ADO.NET & Database Connections-ADO.NET Overview – Database Connections –
Commands – Data Reader - Data Adapter - Data Sets - Data Controls and Its Properties –
Data Binding.
Unit – V
Grid View Control & XML Classes-Grid View control: Deleting, editing, Sorting and
Paging. XML classes Web form to manipulate XML files – Website Security –
Authentication – Authorization – Creating a Web application.
Text Book(s):
1. Svetlin Nakov, Veselin Kolev & Co, Fundamentals of Computer Programming with C#,
Faber publication, 2019.
2. Mathew, Mac Donald, TheCompleteReferenceASP.NET, Tata Mc Graw-Hill, 2015.
Reference Books:
1. Herbert Schildt, The Complete Reference C#.NET, Tata McGraw-Hill, 2017.
2. Kogent Learning Solutions, C# 2012 Programming Covers .NET4.5 Black Book, Dream
techpres, 2013.
3. Anne Boehm, Joel Murach, Murach„sC#2015, Mike Murach & AssociatesInc.2016.
4. Denielle Otey, Michael Otey, ADO. NET: The Complete reference, McGraw Hill, 2008.
5. Matthew Mac Donald, Beginning ASP.NET4inC#2010, APRESS, 2010.
UNIT-1
Introduction to .NET & Control Statement
Overview of .NET framework

What is .NET Framework?

 A software development platform developed by Microsoft.


 Used to build and run Windows applications.
 Includes a large class library (FCL) and a runtime (CLR).

Components:

 CLR (Common Language Runtime): Executes code and provides services like
memory management and security.
 FCL (Framework Class Library): Pre-built classes for common functionalities (I/O,
DB access, etc.).
 ASP.NET: For building web apps and services.
 ADO.NET: For database operations.
 Windows Forms / WPF: For desktop applications.

Features:

 Language Interoperability (supports C#, VB.NET, F#).


 Automatic memory management (Garbage Collection).
 Security with Code Access Security (CAS).
 Robust exception handling.
 Rich GUI and web application support.

Common Language Runtime (CLR)


 Common Language Runtime (CLR) is the core runtime environment of Microsoft’s .NET
Framework. It is responsible for managing the execution of .NET programs.
Functions of CLR:

1. Code Execution: Executes the compiled code (Intermediate Language - IL) in a


managed environment.
2. Memory Management: Handles memory allocation and garbage collection
automatically.
3. Security: Enforces code access security and validation.
4. Exception Handling: Provides a unified model for handling exceptions across
different languages.
5. Cross-language Integration: Supports code written in multiple languages like C#,
VB.NET, F#, etc.
6. Just-In-Time (JIT) Compilation: Converts IL code to native machine code at
runtime.

Framework Class Library

 The Framework Class Library (FCL) is a collection of reusable, object-oriented


classes and APIs provided by Microsoft as part of the .NET Framework.
 It works closely with the Common Language Runtime (CLR) to provide a rich set
of functionalities for .NET applications.
 Part of Microsoft‟s .NET Framework.
 Provides predefined classes, interfaces, and value types.
 Enables rapid development of apps (desktop, web, mobile).
 Supports object-oriented programming.
 Covers IO, threading, collections, data access, etc.
 Works with multiple .NET languages (C#, VB.NET, etc.).
 Ensures code reusability and consistency.
 Integrated with Common Language Runtime (CLR).
handling common programming tasks like:

 Input/Output (I/O) operations


 Data access (ADO.NET, Entity Framework)
 GUI creation (Windows Forms, WPF)
 Web applications (ASP.NET)
 XML manipulation
 Security and cryptography
 Threading and parallelism
 Collections and generics

FCL promotes code reuse, consistency, and productivity, enabling developers to focus on
solving business problems instead of writing low-level code.

C# Fundamentals
Primitive Types and Variables
Primitive Types
 Data types are sets (ranges) of values that have similar characteristics.
 For instance byte type specifies the set of integers in the range of [0 … 255].
 Data types are characterized by:
- Name – for example, int;
- Size (how much memory they use) – for example, 4 bytes;
- Default value – for example 0.
Types
 Basic data types in C# are distributed into the following types:
- Integer types – sbyte, byte, short, ushort, int, uint, long, ulong;
- Real floating-point types – float, double;
- Real type with decimal precision – decimal;
- Boolean type – bool;
- Character type – char;
- String – string;
- Object type – object.
 These data types are called primitive (built-in types)
 because they are embedded in C# language at the lowest level.
 The table below represents the above mentioned data types, their range and their default
values:
1. Integer Types
 Used for whole numbers (no decimal points).

2. Floating-Point Types

 Used for numbers with decimal points.

3. Character Type

4. Boolean Type

5. String Type
6. Object Type
 object is the base type for all data types in C#.
 Any type (value or reference) can be assigned to an object.
object obj = 123;
Variables
 A variable is a named storage that holds data which can be used and modified during
program execution.
 Syntax:
dataType variableName = value;
 A variable is a container of information, which can change its value.
 It provides means for:
- storing information
- retrieving the stored information
- modifying the stored information
Naming Variables – Rules
 The name of the variable can be any of our choice but must follow certain rules defined in
the C# language specification:
 - Variable names can contain the letters a-z, A-Z, the digits 0-9 as well as the character '_'.
 - Variable names cannot start with a digit.
 - Variable names cannot coincide with a keyword of the C# language.
 For example, base, char, default, int, object, this, null and many others cannot be used as
variable names.
Naming Variables – Examples
Proper names:
- name
- first_Name
- _name1
Improper names (will lead to compilation error):
- 1 (digit)
- if (keyword)
- 1name (starts with a digit)
Declaring Variables
 When you declare a variable, you perform the following steps:
- specify its type (such as int);
- specify its name (identifier, such as age);
- optionally specify initial value (such as 25) but this is not obligatory.
 The syntax for declaring variables in C# is as follows:
<data type> <identifier> [= <initialization>];
 Here is an example of declaring variables:
string name;
int age;
Assigning a Value
 Assigning a value to a variable is the act of providing a value that must be stored in the
variable.
 This operation is performed by the assignment operator "=".
 On the left side of the operator we put the variable name and on the right side – its new
value.
 Here is an example of assigning values to variables:
name = "John Smith";
age = 25;
Operators
 Operators are used to perform operations on variables and values.
 Operators in C# can be separated in several different categories:
- Arithmetic operators – they are used to perform simple mathematical
operations.
- Assignment operators – allow assigning values to variables.
- Comparison operators – allow comparison of two literals and/or
variables.
- Logical operators – operators that work with Boolean data types and
Boolean expressions.
- Binary operators – used to perform operations on the binary
representation of numerical data.
- Type conversion operators – allow conversion of data from one type to
another.
1.Arithmetic Operators
 Arithmetic operators are used to perform common mathematical operations such as
1. Addition ( + )
2. Subtraction ( - )
3. Multiplication ( * )
4. Division ( / )
5. Modulus ( % )
Example:
// Arithmetic operators
using System;

class Geeks
{
static void Main(string[] args)
{
int x = 8, y = 4;

// Using different arithmetic operators


Console.WriteLine("Addition: " + (x + y));
Console.WriteLine("Subtraction: " + (x - y));
Console.WriteLine("Multiplication: " + (x * y));
Console.WriteLine("Division: " + (x / y));
Console.WriteLine("Modulo: " + (x % y));
}
}
Output
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulo: 0
2. Assignment operators
 Used to assign values to variables.
 The syntax used for assigning value is as it follows:
operand1 = literal, expression or operand2;
 Example
int x = 6;
string helloString = "Hello string.";
int y = x;

3. Comparison operators
 Comparison operators in C# are used to compare two or more operands.
 C# supports the following comparison operators:
- greater than (>)
- less than (<)
- greater than or equal to (>=)
- less than or equal to (<=)
- equality (==)
- difference (!=)
 All comparison operators in C# are binary (take two operands) and the returned result is a
Boolean value (true or false).
 Comparison operators have lower priority than arithmetical operators but higher than the
assignment operators.
 The following example demonstrates the usage of comparison operators in C#:
int x = 10, y = 5;
Console.WriteLine("x > y : " + (x > y)); // True
Console.WriteLine("x < y : " + (x < y)); // False
Console.WriteLine("x >= y : " + (x >= y)); // True
Console.WriteLine("x <= y : " + (x <= y)); // False
Console.WriteLine("x == y : " + (x == y)); // False
Console.WriteLine("x != y : " + (x != y)); // True

4. Logical operators
 Logical (Boolean) operators take Boolean values and return a Boolean result (true or
false).
 The basic Boolean operators are "AND" (&&), "OR" (||), "exclusive OR" (^) and
logical negation (!).
 The following table contains the logical operators in C# and the operations that they
perform:

Example
bool a = true;
bool b = false;
Console.WriteLine(a && b); // False
Console.WriteLine(a || b); // True
Console.WriteLine(!b); // True
Console.WriteLine(b || true); // True
Console.WriteLine((5 > 7) ^ (a == b)); // False
5.Binary operators
 A bitwise operator is an operator that acts on the binary representation of numeric
types.
 In computers all the data and particularly numerical data is represented as a series of
ones and zeros.
 The binary numeral system is used for this purpose.
 For example, number 55 in the binary numeral system is represented as 00110111.
 Bitwise operators are very similar to the logical ones.
EXAMPLE
byte a = 3; // 0000 0011 = 3
byte b = 5; // 0000 0101 = 5
Console.WriteLine(a | b); // 0000 0111 = 7
Console.WriteLine(a & b); // 0000 0001 = 1
Console.WriteLine(a ^ b); // 0000 0110 = 6
Console.WriteLine(~a & b); // 0000 0100 = 4
Console.WriteLine(a << 1); // 0000 0110 = 6
Console.WriteLine(a << 2); // 0000 1100 = 12
Console.WriteLine(a >> 1); // 0000 0001 = 1
6. Type conversion operators
 Type conversion operators are used to convert a value from one data type to another.
This is also known as type casting.
 There are two main types of conversions:
1. Implicit Conversion
2. Explicit Conversion

1. Implicit Conversion
 No data loss
 Performed automatically by the compiler
 Safe conversions (e.g., smaller to larger data types)
 Example
int num = 100;
float value = num; // Implicit conversion from int to float

2. Explicit Conversion
 Requires manual cast using parentheses
 May lose data or cause exceptions
 Converts larger type to smaller or incompatible types
 Example
double value = 45.78;
int num = (int)value; // Explicit conversion from double to int

Conditional statements
 Conditional statements allow your program to make decisions and execute specific blocks of code
based on conditions.

1. if Statement
 Executes a block if the condition is true.
 Example
int num = 10;
if (num > 5)
{
Console.WriteLine("Number is greater than 5");
}
Output
Number is greater than 5

2. if-else Statement
 Executes one block if true, another if false.
 Example
int num = 3;
if (num > 5)
{
Console.WriteLine("Greater than 5");
}
else
{
Console.WriteLine("Less than or equal to 5");
}
Output
Less than or equal to 5

3. if-else if-else Statement


 Multiple conditions are checked in sequence.
 Example
int marks = 75;

if (marks >= 90)


{
Console.WriteLine("Grade A");
}
else if (marks >= 75)
{
Console.WriteLine("Grade B");
}
else
{
Console.WriteLine("Grade C");
}
Output
Grade B

4. switch Statement
 Used to select one of many blocks of code based on a variable’s value.
 Example
int day = 3;

switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Output
Wednesday

Looping statements
 A loop is a basic programming construct that allows repeated execution of a fragment of source
code.
 Depending on the type of the loop, the code in it is repeated a fixed number of times or repeats
until a given condition is true (exists).
 Loops that never end are called infinite loops.
 Using an infinite loop is rarely needed except in cases where somewhere in the body of the loop a
break operator is used to terminate its execution prematurely.
1. While Loops
 One of the simplest and most commonly used loops is while.
 Checks the condition before the loop starts. Runs as long as the condition is true.
SYNTAX
while (condition)
{
loop body;
}
 Example
int i = 1;
while (i <= 5)
{
Console.WriteLine("Count: " + i);
i++;
}
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

2. Do-While Loops
 The do-while loop is similar to the while loop, but it checks the condition after each
execution of its loop body.
 This type of loops is called loops with condition at the end (post-test loop).
 Initially the loop body is executed.
 Then its condition is checked. If it is true, the loop‟s body is repeated, otherwise the loop
ends.
 This logic is repeated until the condition of the loop is broken.
 The body of the loop is executed at least once.
 If the loop‟s condition is constantly true, the loop never ends.
SYNTAX
do
{
executable code;
} while (condition);
 Example
int i = 1;
do
{
Console.WriteLine("Count: " + i);
i++;
} while (i <= 5);
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

3.For Loops
 For-loops are a slightly more complicated than while and do-while loops but on the other
hand they can solve more complicated tasks with less code.
 Here is the scheme describing for-loops:
 for (int i=0; i<10; i++)
{
/* loop body */
}
 They contain an initialization block (A), condition (B), body (D) and updating commands for
the loop variables (C).
 We will explain them in details shortly.
 Before that, let’s look at how the program code of a for-loop looks like:
for (initialization; condition; update)
{
loop's body;
}
 Example
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Count: " + i);
}
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Creating and Using Objects
 objects are instances of classes, which are essentially blueprints or templates that define the
properties and behaviors of an object.
Creating Objects
To create an object in C#, you need to:
1. Define a class: A class is a template that defines the properties and methods of an object.
2. Instantiate the class: Use the new keyword to create an instance of the class.
// Define a class
public class Car
{
public string Color { get; set; }
public string Model { get; set; }

public void Honk()


{
Console.WriteLine("Beep beep!");
}
}

// Instantiate the class


Car myCar = new Car();
Using Objects
Once you've created an object, you can:
 Access properties: Use dot notation to access and modify properties.
 Call methods: Use dot notation to call methods on the object.
// Access properties
myCar.Color = "Red";
myCar.Model = "Mustang";

// Call methods
myCar.Honk();
Example
using System;

public class Car


{
public string Color { get; set; }
public string Model { get; set; }

public void Honk()


{
Console.WriteLine("Beep beep!");
}

public void Describe()


{
Console.WriteLine($"This car is a {Color} {Model}.");
}
}

class Program
{
static void Main(string[] args)
{
// Create objects
Car myCar = new Car();
Car yourCar = new Car();

// Set properties
myCar.Color = "Red";
myCar.Model = "Mustang";
yourCar.Color = "Blue";
yourCar.Model = "Camry";

// Call methods
myCar.Honk();
myCar.Describe();
yourCar.Honk();
yourCar.Describe();
}
}
 This example defines a Car class with properties and methods, creates two Car objects,
sets their properties, and calls their methods. The output will be:
Output
Beep beep!
This car is a Red Mustang.
Beep beep!
This car is a Blue Camry.

Arrays
 Arrays are vital for most programming languages.
 They are collections of variables, which we call elements.
 An array‟s elements in C# are numbered with 0, 1, 2, … N-1.

 Those numbers are called indices. The total number of elements in a given array we
call length of an array.
 All elements of a given array are of the same type, no matter whether they are
primitive or reference types.
 This allows us to represent a group of similar elements as an ordered sequence and
work on them as a whole.
 Arrays can be in different dimensions, but the most used are the one dimensional and
the two-dimensional arrays.
 One-dimensional arrays are also called vectors and two-dimensional are also known
as matrices.
Declaration and Allocation of Memory for Arrays
Declaring an Array
 We declare an array in C# in the following way:
int[] myArray;
 In this example the variable myArray is the name of the array, which is of integer type
(int[]).
Creation of an Array – the Operator "new"
 In C# we create an array with the help of the keyword new, which is used to allocate memory:
int[] myArray = new int[6];
 In this example we allocate an array with length of 6 elements of type int.
 This means that in the dynamic memory (heap) an area of 6 integer numbers is allocated and
they all are initialized with the value 0:
 Stack Heap myArray Stack H

Array Initialization and Default Values


 It has to be initialized or to have a default value. In some programming languages
there are no default values and then if we try to access an element, which is not
initialized, this may cause an error.
 In C# all variables, including the elements of arrays have a default initial value.
int[] myArray = { 1, 2, 3, 4, 5, 6 };
 In this case we create and initialize the elements of the array at the time of the
declaration.
 On the figure below we see how the array is allocated in the memory when its values
are initialized at the moment of its declaration:

 With this syntax we use curly brackets instead of the operator new.
 Between the brackets we list the initial values of the array, separated by commas.
 Their count defines the length of the array.
Declaration and Initialization of an Array – Example
 Here is one more example how to declare and initialize an array:
string[] daysOfWeek =
{ "Monday", "Tuesday", "Wednesday","Thursday", "Friday",
"Saturday", "Sunday" };

Boundaries of an Array
 Arrays are by default zero-based, which means the enumeration of the elements starts from 0.
 The first element has the index 0, the second – 1, etc. In an array of N elements, the last element
has the index N-1
Access to the Elements of an Array
 We access the array elements directly using their indices.
 Each element can be accessed through the name of the array and the element‟s index
(consecutive number) placed in the brackets.
 We can access given elements of the array both for reading and for writing, which
means we can treat elements as variables.
 Here is an example for accessing an element of an array:
myArray[index] = 100;
 In the example above we set a value of 100 to the element, which is at position index.
String operations
 String operations in C# are used to manipulate and analyze strings. Here are some
common string operations

1. Concatenation
 You can concatenate strings using the + operator or the string.Concat() method.
 Example
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);
Output: John Doe
2. String Interpolation
 String interpolation allows you to embed expressions within string literals. Use
the $ symbol before the string
 Example
string name = "John";
int age = 30;
string message = $"My name is {name} and I am {age} years old.";
Console.WriteLine(message);
Output: My name is John and I am 30 years old.
3. String Comparison
 You can compare strings using the == operator, string.Equals() method,
or string.Compare() method.
 Example
string str1 = “Hello”;
string str2 = “hello”;
bool isEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isEqual);
Output: True
4. Substring
 You can extract a substring from a string using the Substring() method.
 Example
string str = “Hello World”;
string substr = str.Substring(6);
Console.WriteLine(substr);
Output: World
5. Split
 You can split a string into an array of substrings using the Split() method.
 Example
string str = “apple,banana,orange”;
string[] fruits = str.Split(„,‟);
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Output:
apple
banana
orange
6. Trim
 You can remove whitespace characters from the beginning and end of a string using
the Trim() method.
 Example
string str = “ Hello World “;
string trimmedStr = str.Trim();
Console.WriteLine(trimmedStr);
Output: Hello World
7. Replace
 You can replace a substring with another string using the Replace() method.
 Example
string str = “Hello World”;
string newStr = str.Replace(“World”, “Universe”);
Console.WriteLine(newStr);
Output: Hello Universe
8. Contains
 You can check if a string contains a substring using the Contains() method.
 Example
string str = “Hello World”;
bool contains = str.Contains(“World”);
Console.WriteLine(contains);
Output: True
9. IndexOf
 You can find the index of a substring within a string using the IndexOf() method.
 Example
string str = “Hello World”;
int index = str.IndexOf(“World”);
Console.WriteLine(index);
Output: 6
10. ToUpper and ToLower
 You can convert a string to uppercase or lowercase using
the ToUpper() and ToLower() methods.
 Example
string str = “Hello World”;
string upperStr = str.ToUpper();
string lowerStr = str.ToLower();
Console.WriteLine(upperStr);
Console.WriteLine(lowerStr);
Output: HELLO WORLD
Output: hello world

ONE MARKS

1.What is the primary function of the Common Language Runtime (CLR) in the .NET
Framework?
a) To provide a set of pre-built classes for common tasks
b) To manage the execution of .NET applications
c) To compile C# code into machine code
d) To provide a user interface for .NET applications
Answer: b) To manage the execution of .NET applications
2.What is the Framework Class Library (FCL) in the .NET Framework?
a) A set of classes for building Windows Forms applications
b) A set of classes for building web applications
c) A comprehensive set of pre-built classes for common tasks
d) A set of classes for building console applications
Answer: c) A comprehensive set of pre-built classes for common tasks
3.Which of the following is a primitive type in C#?
a) string
b) int
c) Array
d) List<T>
Answer: b) int
4.What is the purpose of the var keyword in C#?
a) To declare a variable with a specific type
b) To declare a variable without specifying its type
c) To declare a constant variable
d) To declare a static variable
Answer: b) To declare a variable without specifying its type
5.What is the difference between the == operator and the Equals() method in C#?
a) == checks for reference equality, while Equals() checks for value equality
b) == checks for value equality, while Equals() checks for reference equality
c) == is used for strings, while Equals() is used for numbers
d) == is used for numbers, while Equals() is used for strings
Answer: a) == checks for reference equality, while Equals() checks for value equality
(although == can be overloaded to check for value equality)
6.What is the purpose of the switch statement in C#?
a) To execute a block of code repeatedly
b) To execute a block of code conditionally
c) To execute different blocks of code based on a specific value
d) To declare a variable
Answer: c) To execute different blocks of code based on a specific value
7.What is the difference between a while loop and a do-while loop in C#?
a) A while loop executes the code block at least once, while a do-while loop may not execute
the code block at all
b) A do-while loop executes the code block at least once, while a while loop may not execute
the code block at all
c) A while loop is used for arrays, while a do-while loop is used for lists
d) A while loop is used for numbers, while a do-while loop is used for strings
Answer: b) A do-while loop executes the code block at least once, while a while loop may
not execute the code block at all
8.What is the purpose of the new keyword in C#?
a) To declare a variable
b) To create an instance of a class
c) To call a method
d) To access a property
Answer: b) To create an instance of a class
9.How do you access a property of an object in C#?
a) Using the dot notation (e.g., obj.Property)
b) Using the bracket notation (e.g., obj["Property"])
c) Using the GetProperty() method
d) Using the SetProperty() method
Answer: a) Using the dot notation (e.g., obj.Property)
10.How do you declare an array in C#?
a) int[] arr = new int[5];
b) int arr = new int[5];
c) int[] arr = new int();
d) int arr = new int();
Answer: a) int[] arr = new int[5];
11.How do you access an element of an array in C#?
a) Using the dot notation (e.g., arr.0)
b) Using the bracket notation (e.g., arr[0])
c) Using the GetElement() method
d) Using the SetElement() method
Answer: b) Using the bracket notation (e.g., arr[0])
12.How do you concatenate two strings in C#?
a) Using the + operator
b) Using the Concat() method
c) Using the Join() method
d) Using the Split() method
Answer: a) Using the + operator (or b) Using the Concat() method)
13.How do you compare two strings in C#?
a) Using the == operator
b) Using the Equals() method
c) Using the Compare() method
d) Using the CompareTo() method
Answer: a) Using the == operator (or b) Using the Equals() method)
14. What is the purpose of the if-else statement in C#?
a) To execute a block of code repeatedly
b) To execute a block of code conditionally
c) To exit a loop or switch statement
d) To return a value from a method
Answer: b) To execute a block of code conditionally
15.What is the purpose of the switch statement in C#?
a) To execute a block of code repeatedly
b) To execute a block of code conditionally
c) To execute different blocks of code based on a specific value
d) To return a value from a method
Answer: c) To execute different blocks of code based on a specific value

5 MARKS
1.Explain about the Common Language Runtime.
2.what is variable? Explain about declaring and accessing variable in C#.
3.How to create a object in C#?
4.explain about string manipulation?

10MARKS
1.Discuss about the C# primitive data types in detail.
2.Explain about the operators in C#.
3.Discuss about the C# conditional statements.
4.What is loops in C#?Explain in detail.
5.Explain about arrays in C#.
6.Discuss about string manipulation in C#.
********UNIT-1********
UNIT-2

IDE & HTML Controls


Introduction to ASP.NET
 A web application framework developed by Microsoft.
 Used to build dynamic, scalable, and secure web applications.
Key Concepts
1. Controllers: Handle HTTP requests and return responses.
2. Actions: Methods within controllers that handle specific HTTP requests.
3. Views: Razor templates that render HTML responses.
4. Models: Classes that represent data and business logic.
Advantages
1. High-performance: ASP.NET is designed to deliver high-performance web applications.
2. Easy to learn: ASP.NET provides a familiar programming model for developers with
experience in Windows Forms or other Microsoft technologies.
3. Large community: ASP.NET has a large and active community of developers who
contribute to its ecosystem.
Use Cases
1. Web applications: ASP.NET is well-suited for building complex web applications, such as
e-commerce sites, social media platforms, and online forums.
2. Web services: ASP.NET can be used to build RESTful web services that provide data to
other applications.
3. Real-time applications: ASP.NET SignalR provides a library for building real-time web
applications.
IDE
 An IDE in ASP.NET is a software application that provides a centralized platform for
developing, testing, and deploying ASP.NET web applications.
 It offers a range of tools and features that help developers create high-quality web
applications more efficiently.
Key Features of an IDE in ASP.NET:
1. Code Editor: A code editor with features like syntax highlighting, auto-completion, and code
refactoring.
2. Project Management: A tool that helps manage project files, folders, and dependencies.
3. Debugging: A tool that allows developers to debug their web applications, set breakpoints,
and inspect variables.
4. Testing: Integration with testing frameworks to write and run unit tests.
5. Deployment: Tools for deploying web applications to various environments, such as IIS or
Azure.
6. IntelliSense: A feature that provides code completion, code snippets, and other productivity
features.
7. Design View: A visual interface for designing web pages and user controls.
Popular IDEs for ASP.NET:
1. Visual Studio: A comprehensive IDE developed by Microsoft, offering a wide range of tools
and features for ASP.NET development.
2. Visual Studio Code: A lightweight, open-source code editor developed by Microsoft, which
can be used for ASP.NET development with extensions.
3. Rider: A cross-platform IDE developed by JetBrains, offering advanced features for
ASP.NET development.
Benefits of using an IDE in ASP.NET:
1. Improved productivity: IDEs provide features that help developers write, test, and debug
code more efficiently.
2. Better code quality: IDEs often include features like code analysis, refactoring, and code
formatting.
3. Streamlined development: IDEs provide a centralized platform for managing projects,
debugging, and testing.
4. Faster development: IDEs offer features like code generation, templates, and snippets that
speed up development.
Using an IDE in ASP.NET:
1. Use project templates: Use pre-built project templates to get started with ASP.NET
development.
2. Take advantage of IntelliSense: Use IntelliSense features like code completion and code
snippets to improve productivity.
3. Use debugging tools: Use debugging tools to identify and fix errors in your code.
4. Write unit tests: Write unit tests to ensure your code is testable and meets requirements.
5. Use version control: Use version control systems like Git to manage your codebase.
Languages supported Components
 ASP.NET supports multiple programming languages, thanks to the Common
Language Runtime (CLR).
 Here are some of the key languages supported:
 Primary Languages:
o C#: A popular, modern language developed by Microsoft, widely used for web application
development.
o Visual Basic .NET (VB.NET): An evolution of the classic Visual Basic, providing an easy-
to-use syntax for building web applications.
o F#: A functional programming language that offers simplicity and robustness, ideal for
scientific programming and data analysis.
 Other Supported Languages:
o C++: A powerful, performance-oriented language that can be used for web development with
ASP.NET.
o IronPython: An implementation of Python for .NET, allowing Python developers to leverage
the ASP.NET framework.
o IronRuby: A Ruby implementation for .NET, enabling Ruby developers to build web
applications with ASP.NET.
o JScript .NET: A compiled version of JScript, suitable for rapid development and
prototyping.
o PHP (via Phalanger): Phalanger allows PHP developers to build web applications using the
.NET framework.
o Perl (via Active Perl): Active Perl enables Perl developers to transition their code to the
.NET framework.
o Visual COBOL .NET: A tool for modernizing legacy COBOL applications using the .NET
framework.
Working with Web Forms
 Web Forms is a part of the ASP.NET framework that allows developers to build web
applications using a programming model similar to Windows Forms.
 Web Forms provides a set of server-side controls, event handling, and state management
features that make it easy to build dynamic web applications.
 Server-side controls: Web Forms provides a set of server-side controls, such as TextBox,
Button, and GridView, that can be used to build web pages.
 Event-driven programming model: Web Forms uses an event-driven programming model,
where events are triggered by user interactions, such as button clicks.
 ViewState: Web Forms uses ViewState to maintain the state of controls between postbacks.
 PostBack: Web Forms uses postbacks to handle server-side events, such as button clicks.
Creating a Web Forms Application:
 Create a new project: Use Visual Studio to create a new ASP.NET Web Forms project.
 Design the UI: Use the Visual Studio designer to create the user interface of your web page,
adding server-side controls as needed.
 Write code-behind: Write code in the code-behind file to handle events and implement
logic.
Page Life Cycle:
 Page_Init: The page initialization event, where controls are initialized.
 Page_Load: The page load event, where the page is loaded and controls are populated
with data.
 Event handling: Events are handled, such as button clicks.
 Page_PreRender: The page pre-render event, where the page is prepared for
rendering.
 Page_Render: The page render event, where the page is rendered to the client.
 ViewState:ViewState is a hidden field on the page that stores the state of controls.
 When a postback occurs, the ViewState is sent back to the server, allowing the page
to restore the control state.
 Benefits and drawbacks: ViewState is useful for maintaining control state, but it can
impact page performance.
 Use ViewState judiciously: Use ViewState only when necessary, as it can impact
page performance.
 Use validation controls: Use validation controls to validate user input and prevent
security vulnerabilities.
 Use data binding: Use data binding to bind data to controls, rather than manually
populating controls.
 Optimize page performance: Optimize page performance by minimizing View State,
using caching, and reducing database queries.
Web form standard controls: Properties and its events
 some common Web Form standard controls, their properties, and events:
1. Text Box Control:
Properties:
Text: Gets or sets the text content of the control.
Max Length: Gets or sets the maximum number of characters allowed in the control.
Width and Height: Gets or sets the width and height of the control.
Events:
Text Changed: Occurs when the text content of the control changes.
2. Button Control:
Properties:
Text: Gets or sets the text displayed on the button.
Command Name and Command Argument: Gets or sets the command name and argument
associated with the button.
Events:
Click: Occurs when the button is clicked.
Command: Occurs when the button is clicked and a command name is associated with it.
3. Label Control:
Properties:
Text: Gets or sets the text content of the control.
Events:
None ( Label control does not raise events)
4. Drop Down List Control:
Properties:
Items: Gets or sets the collection of items in the control.
SelectedIndex: Gets or sets the index of the selected item.
SelectedValue: Gets or sets the value of the selected item.
Events:
SelectedIndexChanged: Occurs when the selected item changes.
5. ListBox Control:
Properties:
Items: Gets or sets the collection of items in the control.
SelectedIndex: Gets or sets the index of the selected item.
SelectionMode: Gets or sets the selection mode (Single or Multiple).
Events:
SelectedIndexChanged: Occurs when the selected item changes.
6. CheckBox Control:
Properties:
Checked: Gets or sets a value indicating whether the control is checked.
Text: Gets or sets the text associated with the control.
Events:
CheckedChanged: Occurs when the checked state changes.
7. RadioButton Control:
Properties:
Checked: Gets or sets a value indicating whether the control is checked.
GroupName: Gets or sets the group name for the control.
Text: Gets or sets the text associated with the control.
Events:
CheckedChanged: Occurs when the checked state changes.
8. ImageButton Control:
Properties:
Image Url: Gets or sets the URL of the image displayed on the control.
CommandName and CommandArgument: Gets or sets the command name and argument
associated with the control.
Events:
Click: Occurs when the control is clicked.
Command: Occurs when the control is clicked and a command name is associated with it.

HTML controls
 In ASP.NET, HTML controls refer to standard HTML elements that can be used on web
pages.
 These controls can be used to create user interfaces, collect user input, and interact with
users.
Types of HTML Controls in ASP.NET:
1. HTML Server Controls: These are HTML elements that are converted to server controls,
allowing them to be accessed and manipulated on the server-side.
2. HTML Client Controls: These are standard HTML elements that run on the client-side (in
the browser).
Common HTML Controls in ASP.NET:
1. Text Box: <input type="text">
2. Button: <input type="button"> or <button>
3. CheckBox: <input type="checkbox">
4. RadioButton: <input type="radio">
5. Drop Down List: <select>
6. Text Area: <textarea>
Using HTML Controls in ASP.NET:
1. Add HTML elements to a web page: Use standard HTML syntax to add elements to
a web page.
2. Add runat="server" attribute: To make an HTML element a server control, add the
runat="server" attribute.
3. Access controls on the server-side: Use the control's ID to access and manipulate it
on the server-side.

List Controls: Properties and its events


 The list controls include the
1. List Box,
2. Drop Down List,
3. Check Box List,
4. Radio Button List, and
5. Bulleted List.
 They all work in essentially the same way but are rendered differently
in the browser.
 The List Box is a rectangular list that displays several entries, while
the Drop Down List shows only the selected item.
 The Check Box List and Radio Button List are similar to the List Box,
but every item is rendered as a check box or option button,
respectively.
 Bulleted List is the only list control that isn‟t selectable. Instead, it
renders itself as a sequence of numbered or bulleted items.
 All the selectable list controls provide a Selected Index property that
indicates the selected row as a zero-based index.
 For example, if the first item in the list is selected, the Selected Index
will be 0.
 Selectable list controls also provide an additional Selected Item
property, which allows your code to retrieve the List Item object that
represents the selected item.
 The List Item object provides three important properties:
1. Text (the displayed content),
2. Value (the hidden value from the HTML markup), and
3. Selected (true or false depending on whether the item is
selected).

ONE MARKS
1.What is ASP.NET?
a) A client-side scripting language
b) A server-side web development framework
c) A database management system
d) A web server
Answer: b) A server-side web development framework
2.What is the primary purpose of ASP.NET?
a) To create desktop applications
b) To create web applications
c) To create mobile applications
d) To create games
Answer: b) To create web applications
3.What is the most commonly used IDE for ASP.NET development?
a) Visual Studio
b) Eclipse
c) NetBeans
d) IntelliJ IDEA
Answer: a) Visual Studio
4.What is the purpose of an IDE in ASP.NET development?
a) To write code
b) To design web pages
c) To debug applications
d) All of the above
Answer: d) All of the above
5.Which of the following languages are supported by ASP.NET?
a) C#
b) VB.NET
c) F#
d) All of the above
Answer: d) All of the above
6.What is a component in ASP.NET?
a) A reusable piece of code
b) A web page
c) A database table
d) A web server
Answer: a) A reusable piece of code
7.What is an example of a component in ASP.NET?
a) A web control
b) A class library
c) A web service
d) All of the above
Answer: d) All of the above
8.What is a Web Form in ASP.NET?
a) A web page that uses server-side controls
b) A web page that uses client-side scripting
c) A web page that uses a database
d) A web page that uses a web service
Answer: a) A web page that uses server-side controls
9.How do you create a new Web Form in ASP.NET?
a) By adding a new item to a project
b) By creating a new project
c) By copying an existing Web Form
d) By using a template
Answer: a) By adding a new item to a project
10.What is a standard control in ASP.NET?
a) A control that is included in the .NET Framework
b) A control that is created by a developer
c) A control that is used for data binding
d) A control that is used for validation
Answer: a) A control that is included in the .NET Framework
11.What are some examples of standard controls in ASP.NET?
a) Button, TextBox, Label
b) GridView, DetailsView, FormView
c) Menu, TreeView, SiteMapPath
d) All of the above
Answer: d) All of the above
12.What is a property of a control in ASP.NET?
a) A characteristic of the control
b) An action that the control can perform
c) A method that the control can call
d) An event that the control can raise
Answer: a) A characteristic of the control
13.What is an event of a control in ASP.NET?
a) A characteristic of the control
b) An action that the control can perform
c) A notification that something has happened
d) A method that the control can call
Answer: c) A notification that something has happened
14.What is an HTML control in ASP.NET?
a) A server-side control
b) A client-side control
c) A control that is used for data binding
d) A control that is used for validation
Answer: b) A client-side control
15.How do you add an HTML control to a Web Form?
a) By dragging and dropping the control from the toolbox
b) By writing HTML code
c) By using a server-side control
d) By using a third-party control
Answer: b) By writing HTML code
5 MARKS
1. What are the benefits of using ASP.NET for web development?
2. How do you create a new ASP.NET project in Visual Studio?
3. What is a Web Form in ASP.NET?
4. How do you create a new Web Form in ASP.NET?
5. What are some examples of standard controls in ASP.NET?
6. What are the benefits of using HTML controls?

10 MARKS
1.Explain about the IDE in ASP.NET.
2.Discuss about working with web forms in asp.net.
3.What are the basic standard controls in web forms?
4.explain about the list controls and its properties.
********UNIT-2********
UNIT-3
Rich Controls & Validation Controls
Rich Controls: Properties and its events
 Rich Controls, also known as Rich Text Boxes or Rich Edit controls, are graphical user
interface components that allow users to edit and format text with various styles, colors, and
fonts.
Properties:
1. Text: The text content of the control.
2. Font: The font family, size, and style (e.g., bold, italic) applied to the text.
3. ForeColor and BackColor: The text color and background color of the control.
4. Selection: The currently selected text or the position of the caret.
5. Multiline: A property that determines whether the control can display multiple lines of
text.
Events:
1. TextChanged: Fired when the text content of the control changes.
2. SelectionChanged: Fired when the selection or caret position changes.
3. LinkClicked: Fired when a link in the control is clicked (if the control supports links).
4. ContentsResized: Fired when the content size changes, such as when text is added or
removed.
 These properties and events enable developers to customize the behavior and appearance of
Rich Controls, making them suitable for various applications, such as text editors, chat
interfaces, or report generators.

validation controls: Properties and its events


 Validation controls are used to validate user input in web forms, ensuring that the data
entered meets specific criteria. Here are some common properties and events:
Properties:
1. ControlToValidate: Specifies the input control to be validated.
2. ErrorMessage: The error message displayed when validation fails.
3. ValidationGroup: Allows grouping of controls for validation.
4. Enabled: Enables or disables the validation control.
5. ValidateEmptyText: Determines whether to validate empty text.
Common Validation Controls:
1. RequiredFieldValidator: Ensures a field is not left blank.
2. RangeValidator: Checks if a value falls within a specified range.
3. RegularExpressionValidator: Validates input against a regular expression pattern.
4. CompareValidator: Compares the value of one control to another or a constant value.
Events:
1. ServerValidate (for CustomValidator): Fired on the server-side for custom validation
logic.
2. OnServerValidate: The event handler for ServerValidate.
 These properties and events help developers implement robust validation logic, enhancing
the user experience and preventing invalid data from being processed.

File Stream classes


 File Stream classes are used to read and write files
File Stream Classes:
1. FileStream: A stream for reading and writing files.
2. StreamReader: A stream reader for reading text files.
3. StreamWriter: A stream writer for writing text files.
4. BinaryReader and BinaryWriter: Used for reading and writing binary data.
FileStream Methods:
1. Read(): Reads data from a file.
2. Write(): Writes data to a file.
3. Seek(): Moves the file pointer to a specific position.
4. Close(): Closes the file stream.
Example:
using System.IO;

class FileStreamExample
{
public static void Main()
{
// Create a FileStream
using (FileStream fs = new FileStream("example.txt", FileMode.Create))
{
// Write to the file
using (StreamWriter writer = new StreamWriter(fs))
{
writer.WriteLine("Hello, World!");
}
}

// Read from the file


using (FileStream fs = new FileStream("example.txt", FileMode.Open))
{
using (StreamReader reader = new StreamReader(fs))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}
}
FileMode:
1. Create: Creates a new file.
2. Open: Opens an existing file.
3. Append: Appends to an existing file.
FileAccess:
1. Read: Allows reading from the file.
2. Write: Allows writing to the file.
3. ReadWrite: Allows both reading and writing.

File Share
 File sharing is the process of sharing files between different users or systems over a
network. In ASP.NET, file sharing can be implemented by uploading files to a server and
allowing other users to download them.
Example:
 Suppose we have an ASP.NET web application where users can upload and share files.
Here's a basic example:
1. Upload File:
 User selects a file using a file upload control.
 The file is uploaded to the server and stored in a designated folder.
2. Share File:
 The uploaded file is listed on a webpage with a download link.
 Other users can click on the download link to download the file.
Reading and Writing to files
 C# provides several classes for reading and writing to files, including:
1. File: Provides static methods for reading and writing to files.
2. FileStream: Provides a stream for reading and writing to files.
3. StreamReader: Provides a reader for reading text from a file.
4. StreamWriter: Provides a writer for writing text to a file.
Reading from a File
Using File.ReadAllText():
string filePath = "example.txt";
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);

Using StreamReader:
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string fileContent = reader.ReadToEnd();
Console.WriteLine(fileContent);
}
Writing to a File
Using File.WriteAllText():
string filePath = "example.txt";
string fileContent = "Hello, World!";
File.WriteAllText(filePath, fileContent);
Using StreamWriter:
string filePath = "example.txt";
string fileContent = "Hello, World!";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(fileContent);
}
Reading and Writing to a File Line by Line
Using File.ReadAllLines():
string filePath = "example.txt";
string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
Console.WriteLine(line);
}
Using StreamReader:
string filePath = "example.txt";
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Common File Modes
1. FileMode.Create: Creates a new file or overwrites an existing one.
2. FileMode.Append: Appends to an existing file or creates a new one if it doesn't exist.
3. FileMode.Open: Opens an existing file.
4. FileMode.OpenOrCreate: Opens an existing file or creates a new one if it doesn't
exist.
File Access
1. FileAccess.Read: Allows reading from a file.
2. FileAccess.Write: Allows writing to a file.
3. FileAccess.ReadWrite: Allows both reading and writing to a file.

Creating, Moving,Copying and Deleting files


 C# provides several classes for performing file operations, including:
1. File: Provides static methods for creating, moving, copying, and deleting files.
2. FileInfo: Provides instance methods for creating, moving, copying, and deleting files.
Creating a File
1. Using File.Create():
Example
string filePath = "example.txt";
using (FileStream stream = File.Create(filePath))
{
// File is created
}
2. Using File.WriteAllText():
Example
string filePath = "example.txt";
string fileContent = "Hello, World!";
File.WriteAllText(filePath, fileContent);
Moving a File
1. Using File.Move():
Example
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
File.Move(sourcePath, destinationPath);
Copying a File
1. Using File.Copy():
Example
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
File.Copy(sourcePath, destinationPath);
2. Using File.Copy() with Overwrite:
Example
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
File.Copy(sourcePath, destinationPath, true); // Overwrites destination file if it exists
Deleting a File
1. Using File.Delete():
Example
string filePath = "example.txt";
File.Delete(filePath);

1. Check for file existence: Verify that a file exists before attempting to move, copy, or
delete it.
2. Handle exceptions: Catch and handle exceptions that may occur during file
operations.
3. Use try-catch blocks: Ensure that file operations are wrapped in try-catch blocks to
handle potential errors.
FileInfo Class
The FileInfo class provides instance methods for performing file operations. Here's an example:
Example
FileInfo fileInfo = new FileInfo("example.txt");
if (fileInfo.Exists)
{
fileInfo.CopyTo("destination.txt");
fileInfo.MoveTo("newLocation.txt");
fileInfo.Delete();
}
Common File Operations Exceptions
1. FileNotFoundException: Thrown when a file is not found.
2. IOException: Thrown when an I/O error occurs.
3. UnauthorizedAccessException: Thrown when access to a file is denied.
File uploading
 File uploading is a common feature in web applications that allows users to upload files to
the server.
 Here's an example of how to implement file uploading in ASP.NET:
ASPX Page
Aspx
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click"
/>
<asp:Label ID="lblStatus" runat="server" Text="" />

Code-Behind C#

protected void btnUpload_Click(object sender, EventArgs e)


{
if (FileUpload1.HasFile)
{
try
{
string fileName = Path.GetFileName(FileUpload1.FileName);
string filePath = Server.MapPath("~/Uploads/") + fileName;
FileUpload1.SaveAs(filePath);
lblStatus.Text = "File uploaded successfully!";
}
catch (Exception ex)
{
lblStatus.Text = "Error: " + ex.Message;
}
}
else
{
lblStatus.Text = "Please select a file.";
}
}
Security Considerations
1. Validate file types: Ensure that only allowed file types are uploaded.
2. Check file size: Limit the size of files that can be uploaded.
3. Use secure upload folder: Store uploaded files in a secure folder that is not accessible
directly from the web.
Must know
1. Use try-catch blocks: Catch and handle exceptions that may occur during file uploads.
2. Validate user input: Ensure that user input is validated and sanitized to prevent
security vulnerabilities.
3. Use secure protocols: Use secure protocols like HTTPS to encrypt file uploads.
File Upload Controls
1. FileUpload: A built-in ASP.NET control for uploading files.
2. AsyncFileUpload: An AJAX control for asynchronous file uploads.
File Upload Events
1. HasFile: A property that indicates whether a file has been selected.
2. FileName: A property that gets the file name of the uploaded file.
3. SaveAs: A method that saves the uploaded file to a specified location.
Example with Validation
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.FileName);
string fileExtension = Path.GetExtension(fileName).ToLower();

if (fileExtension == ".pdf" || fileExtension == ".docx")


{
if (FileUpload1.PostedFile.ContentLength < 1024 * 1024 * 5) // 5MB
{
try
{
string filePath = Server.MapPath("~/Uploads/") + fileName;
FileUpload1.SaveAs(filePath);
lblStatus.Text = "File uploaded successfully!";
}
catch (Exception ex)
{
lblStatus.Text = "Error: " + ex.Message;
}
}
else
{
lblStatus.Text = "File size exceeds the limit.";
}
}
else
{
lblStatus.Text = "Invalid file type.";
}
}
else
{
lblStatus.Text = "Please select a file.";
}
}
 This example demonstrates how to validate file types and sizes during file uploads.
ONE MARKS
1.Which of the following is a rich control in ASP.NET?
a) TextBox
b) Button
c) GridView
d) Label
Answer: c) GridView
2.What is the purpose of the DataBind() method in a GridView control?
a) To bind data to the control
b) To validate user input
c) To handle events
d) To style the control
Answer: a) To bind data to the control
3.Which of the following validation controls is used to check if a field is not empty?
a) RequiredFieldValidator
b) RangeValidator
c) RegularExpressionValidator
d) CompareValidator
Answer: a) RequiredFieldValidator
4.What is the purpose of the ErrorMessage property in a validation control?
a) To specify the error message to display when validation fails
b) To specify the validation rule
c) To specify the control to validate
d) To specify the validation group
Answer: a) To specify the error message to display when validation fails
5.Which of the following classes is used to read and write to a file?
a) FileStream
b) StreamReader
c) StreamWriter
d) All of the above
Answer: d) All of the above
6.What is the purpose of the using statement when working with file streams?
a) To ensure that the file is properly closed and disposed of
b) To specify the file mode
c) To specify the file access
d) To specify the file share
Answer: a) To ensure that the file is properly closed and disposed of
7.Which of the following file modes creates a new file or overwrites an existing one?
a) FileMode.Create
b) FileMode.Append
c) FileMode.Open
d) FileMode.OpenOrCreate
Answer: a) FileMode.Create
8.Which of the following file modes opens an existing file or creates a new one if it doesn't exist?
a) FileMode.Create
b) FileMode.Append
c) FileMode.Open
d) FileMode.OpenOrCreate
Answer: d) FileMode.OpenOrCreate
9.What is the purpose of the FileShare enum?
a) To specify the file mode
b) To specify the file access
c) To specify how a file can be shared by multiple processes
d) To specify the file type
Answer: c) To specify how a file can be shared by multiple processes
Reading and Writing to Files
10.Which of the following methods is used to read the contents of a file?
a) File.ReadAllText()
b) File.WriteAllText()
c) File.AppendAllText()
d) File.CreateText()
Answer: a) File.ReadAllText()
11.Which of the following methods is used to write to a file?
a) File.ReadAllText()
b) File.WriteAllText()
c) File.AppendAllText()
d) File.OpenText()
Answer: b) File.WriteAllText()
12.Creating, Moving, Copying, and Deleting Files
Which of the following methods is used to create a new file?
a) File.Create()
b) File.Open()
c) File.Move()
d) File.Copy()
Answer: a) File.Create()
13.Which of the following methods is used to delete a file?
a) File.Delete()
b) File.Move()
c) File.Copy()
d) File.Create()
Answer: a) File.Delete()
14.Which of the following controls is used to upload files in ASP.NET?
a) FileUpload
b) TextBox
c) Button
d) Label
Answer: a) FileUpload
15.What is the purpose of the HasFile property in the FileUpload control?
a) To check if a file has been selected
b) To specify the file type
c) To specify the file size
d) To upload the file
Answer: a) To check if a file has been selected

5 MARKS
1. Explain the different file modes available in .NET, such as Create, Append, Open, and
OpenOrCreate. Provide examples.
2. Explain how to use the FileUpload control in ASP.NET to upload files. Provide an example.
3.How do you validate the file type and size of an uploaded file?
4.How do you create a new file using the File.Create method? Provide an example.
10 MARKS
1.Explain about rich controls and its properties in detail.
2. Explain about validation controls and its properties in detail.
3.How to share files explain in detail?
4. Explain the different file modes available in .NET, such as Create, Append, Open, and Open Or
Create. Provide examples
5.how to read and write to a file?
********UNIT-3********
Unit - IV

ADO.NET & Database Connections

ADO.NET Overview

What is ADO.NET?​

●​ Microsoft's primary data access technology for the .NET Framework.


●​ Provides a set of classes and components for interacting with various data
sources (databases, XML files, etc.).
●​ Enables applications to connect to databases, execute queries, retrieve data,
and update information.

Key Components/Architectures:​

●​ Connected Layer (DataProviders):


○​ Used for direct, connected access to a data source.
○​ Components: Connection, Command, DataReader, Transaction.
○​ Connection: Establishes and manages the connection to the database.
○​ Command: Executes SQL commands (SELECT, INSERT, UPDATE,
DELETE, stored procedures).
○​ DataReader: Provides fast, forward-only, read-only access to data.
Efficient for retrieving large datasets.
○​ Transaction: Ensures atomicity of database operations.

●​ Disconnected Layer (DataSet):


○​ Used for disconnected, cached access to data.
○​ Components: DataSet, DataTable, DataRow, DataColumn,
DataRelation, DataAdapter.
○​ DataSet: An in-memory cache of data, representing one or more
DataTable objects.
○​ DataTable: Represents a single table of data within a DataSet.
○​ DataRow, DataColumn: Represent individual rows and columns within a
DataTable.
○​ DataRelation: Defines relationships between DataTable objects
within a DataSet.
○​ DataAdapter: Acts as a bridge between the DataSet and the data
source, handling data retrieval and updates.

Database Connections

What is a Database Connection in ASP.NET?​

●​ The fundamental mechanism for an ASP.NET web application to communicate


with a database server (e.g., SQL Server, MySQL, Oracle).
●​ Allows web pages and backend code to retrieve, store, update, and delete data
essential for dynamic web content and user interactions.

Core ADO.NET Components for Connections:​

●​ SqlConnection Class: The primary class in ADO.NET (specifically


System.Data.SqlClient namespace for SQL Server) used to establish and
manage a connection to a SQL Server database.

●​ Connection String: A vital string that provides all necessary details for the
SqlConnection to locate and authenticate with the database.
○​ Key elements: Data Source (server name/IP), Initial Catalog
(database name), Integrated Security=True (Windows
authentication) or User ID and Password (SQL Server authentication).
○​ Typically stored securely in the web.config file within the
<connectionStrings> section for easy management and security.
Establishing and Managing Connections (Basic Flow):​

Declare and Instantiate SqlConnection:​


C#​
using System.Data.SqlClient; // Required namespace

// ...

SqlConnection connection = new SqlConnection(connectionString);

1.​ Open the Connection: connection.Open();


○​ Establishes the actual link to the database. This is a critical step before
executing any commands.
2.​ Execute Database Operations: Use SqlCommand and SqlDataReader or
SqlDataAdapter (from ADO.NET) to interact with data.
3.​ Close the Connection (Crucial!): connection.Close();
○​ Why it's vital: Releases the database resources back to the server.
Failing to close connections leads to resource exhaustion and
performance degradation, especially under high traffic.

Best Practice: using statement: Ensures the connection is automatically closed and
disposed of, even if errors occur.​
C#​
using (SqlConnection connection = new SqlConnection(connectionString))

connection.Open();

// Perform database operations here

} // Connection is automatically closed and disposed when exiting the 'using' block

Connection Pooling in ASP.NET:​

●​ Automatic Feature: ASP.NET's ADO.NET data providers automatically


implement connection pooling.
●​ Benefit: Greatly enhances performance and scalability of web applications.
●​ How it works: When a connection is "closed," it's often returned to a pool of
available connections instead of being truly disconnected. The next request for a
connection uses one from the pool, saving the overhead of establishing a new
physical connection.
●​ Important Note: Even with pooling, always explicitly call Close() or use a
using statement to return the connection to the pool.

Security Best Practices for ASP.NET Database Connections:​

●​ Store Connection Strings Securely:


○​ In web.config within <connectionStrings> (recommended).
○​ Encrypt the <connectionStrings> section of web.config for
production environments.
○​ Never hardcode connection strings directly in C# code.
●​ Use Parameterized Queries:
○​ Crucial for preventing SQL Injection attacks.
○​ Pass user input as parameters to SqlCommand objects, rather than
concatenating them directly into SQL strings.
●​ Least Privilege Principle:
○​ The database user account specified in the connection string should have
only the minimum necessary permissions on the database.
●​ Integrated Security (Windows Authentication): Prefer Integrated
Security=True when your web server and database server are in the same
Windows domain, as it avoids storing explicit usernames/passwords in the
connection string.

Higher-Level Data Access (Beyond Raw ADO.NET - Often covered in ASP.NET


courses):​

●​ While understanding raw ADO.NET (SqlConnection, SqlCommand,


SqlDataReader) is fundamental, modern ASP.NET development often
leverages Object-Relational Mappers (ORMs).
●​ Entity Framework (EF Core): The most popular ORM for .NET. It abstracts
away much of the direct ADO.NET connection and command management,
allowing developers to work with C# objects instead of direct SQL. However, EF
Core still relies on underlying ADO.NET connections.
●​ Why ORMs? Faster development, improved maintainability, reduced boilerplate
code.

Commands

What are Commands in ASP.NET (ADO.NET)?​

●​ Represent a specific SQL statement or the name of a stored procedure to be


executed against a database.
●​ Act as the "instruction" sent from your ASP.NET application to the database to
perform actions like retrieving, inserting, updating, or deleting data.
●​ They work in conjunction with a Connection object (e.g., SqlConnection)
which defines where the command will be executed.

Key ADO.NET Command Class:​

●​ SqlCommand Class: The primary class in System.Data.SqlClient (for SQL


Server) used to define and execute SQL commands. Other database providers
(e.g., OdbcCommand, OleDbCommand, MySqlCommand) offer similar
functionalities.

Essential Properties of SqlCommand:​

●​ Connection: A reference to the SqlConnection object, specifying which


database to execute the command against.
●​ CommandText: The actual SQL query string (e.g., SELECT * FROM Products,
INSERT INTO Customers ...) or the name of a stored procedure.
●​ CommandType:
○​ CommandType.Text (default): Indicates CommandText is a SQL
statement.
○​ CommandType.StoredProcedure: Indicates CommandText is the
name of a stored procedure.
○​ CommandType.TableDirect: (Less common in ASP.NET for relational
databases) Indicates CommandText is a table name to return all rows.
●​ Parameters: A collection of SqlParameter objects, used for passing values
into the SQL command in a safe and efficient manner (crucial for security and
performance).

Methods for Executing Commands:​

●​ ExecuteReader():
○​ Purpose: Used for SELECT queries that return a set of rows.
○​ Returns: A SqlDataReader object, which provides fast, forward-only,
read-only access to the query results. Ideal for displaying data in grids or
lists.
●​ ExecuteNonQuery():
○​ Purpose: Used for SQL statements that do not return rows (e.g., INSERT,
UPDATE, DELETE, CREATE TABLE).
○​ Returns: An integer representing the number of rows affected by the
operation.
●​ ExecuteScalar():
○​ Purpose: Used for SELECT queries that return a single, scalar value (e.g.,
SELECT COUNT(*) FROM Products, SELECT MAX(Price) FROM
Items).
○​ Returns: The first column of the first row in the result set, cast as an
object.

Why Use Parameters (Crucial for ASP.NET):​

●​ SQL Injection Prevention: The most critical reason. Parameters prevent


malicious code from being injected into your SQL queries via user input.
●​ Type Safety: Ensures data types are correctly handled, avoiding conversion
errors.
●​ Performance: Can improve query performance by allowing the database to
cache execution plans.
●​ Readability: Makes your SQL code cleaner and easier to understand.

Example Usage Pattern (Conceptual):​



C#​
using (SqlConnection connection = new SqlConnection(connectionString))

connection.Open();

using (SqlCommand command = new SqlCommand("SELECT ProductName FROM


Products WHERE CategoryID = @categoryId", connection))

command.Parameters.AddWithValue("@categoryId", 1); // Parameterized query

using (SqlDataReader reader = command.ExecuteReader())

while (reader.Read())

// Process data: reader["ProductName"].ToString()

}
Commands with Stored Procedures:​

●​ Process: Set CommandType to CommandType.StoredProcedure and


CommandText to the stored procedure name.
●​ Parameters: Use SqlCommand.Parameters.Add() or AddWithValue() to
pass input and retrieve output/return value parameters of the stored procedure.
●​ Benefits: Encapsulation of logic, improved performance, enhanced security.

Relationship to Higher-Level Data Access:​

●​ While ORMs like Entity Framework abstract away direct SqlCommand usage,
they internally generate and execute ADO.NET commands. Understanding
SqlCommand provides a foundational understanding of how these ORMs interact
with databases.

Data Reader

●​ What is a DataReader (specifically SqlDataReader in ASP.NET)?​

○​ An object in ADO.NET (System.Data.SqlClient.SqlDataReader


for SQL Server) used to retrieve data from a database.
○​ Provides a fast, forward-only, read-only stream of data from a database
query result.
○​ It's part of the "connected" ADO.NET architecture, meaning it requires
an active, open database connection while data is being read.

●​ Key Characteristics and Benefits:​

○​ High Performance: Very efficient for retrieving large amounts of data


because it processes one row at a time and doesn't load the entire result
set into memory.
○​ Lightweight: Consumes minimal memory on both the client (ASP.NET
application) and server.
○​ Forward-Only: You can only move forward through the records; you
cannot go back to a previously read row without re-executing the query.
○​ Read-Only: Data retrieved cannot be modified directly through the
DataReader. You would use SqlCommand for updates, inserts, or
deletes.
○​ Connected Mode: Requires the database connection to remain open
throughout the data reading process.

●​ How to Use SqlDataReader (Typical Steps):​

○​ Establish a SqlConnection: Open a connection to the database.


○​ Create a SqlCommand: Define your SELECT query.
○​ Execute the Command: Call command.ExecuteReader() to get a
SqlDataReader object.
○​ Read Data (Loop): Use a while (reader.Read()) loop to iterate
through each row returned by the query.
■​ Inside the loop, access individual column values by:
■​ Column Name (recommended for readability):
reader["ColumnName"].ToString() or
(int)reader["Id"].
■​ Column Ordinal (index - faster but less readable):
reader.GetString(0), reader.GetInt32(1).
■​ Type-specific methods: reader.GetString(),
reader.GetInt32(), reader.GetDecimal(), etc., for
type-safe retrieval.
○​ Close the DataReader: Call reader.Close() when you are finished
reading data.
○​ Close the Connection: Close the SqlConnection after the
DataReader is closed.

●​ Crucial Resource Management (Using using Statements):​


○​ Always use using statements for both the SqlConnection and
SqlDataReader objects. This ensures they are automatically closed and
disposed of, even if errors occur, preventing resource leaks.

Example Structure:​
C#​
using (SqlConnection connection = new SqlConnection(connectionString))

connection.Open();

using (SqlCommand command = new SqlCommand("SELECT Id, Name FROM


Products", connection))

using (SqlDataReader reader = command.ExecuteReader())

while (reader.Read())

int id = reader.GetInt32(0);

string name = reader.GetString(1);

// Do something with id and name (e.g., populate a list, display on a web


page)

} // reader is closed and disposed here

} // connection is closed and disposed here

●​ When to Use SqlDataReader in ASP.NET:​


○​ When you need to display data on a web page efficiently, especially large
result sets.
○​ When you only need to read data once in a forward sequence.
○​ For populating controls that bind directly to a data source that can handle
IDataReader (e.g., some list controls).
○​ When performance and minimal memory usage are critical.

●​ Contrast with DataSet/DataTable (Disconnected Architecture):​

○​ DataReader is connected; DataSet is disconnected (data is loaded into


memory).
○​ DataReader is read-only, forward-only; DataSet allows navigation,
sorting, filtering, and updates offline.
○​ DataReader is typically faster for pure reading; DataSet is more flexible
for complex data manipulation and caching.
○​ ASP.NET applications often use DataReader for initial display and
DataSet for more interactive, editable data scenarios.

Data Adapter

What is a DataAdapter (specifically SqlDataAdapter in ASP.NET)?​

●​ A key component in ADO.NET (System.Data.SqlClient.SqlDataAdapter


for SQL Server) that acts as a bridge between a disconnected
DataSet/DataTable and a database.
●​ It's central to the "disconnected" ADO.NET architecture, allowing you to work
with data in memory (within a DataSet) without maintaining a continuous open
connection to the database.

Core Purpose and Functionality:​


●​ Populating a DataSet: The DataAdapter uses its internal SelectCommand
to retrieve data from the database and fill one or more DataTable objects within
a DataSet.
●​ Updating the Database: It uses its internal InsertCommand, UpdateCommand,
and DeleteCommand to push changes made in the DataSet back to the
database.

Key Properties of SqlDataAdapter:​

●​ SelectCommand: A SqlCommand object representing the SELECT query used


to retrieve data from the database.
●​ InsertCommand: A SqlCommand object representing the INSERT statement
used to add new rows to the database.
●​ UpdateCommand: A SqlCommand object representing the UPDATE statement
used to modify existing rows in the database.
●​ DeleteCommand: A SqlCommand object representing the DELETE statement
used to remove rows from the database.
●​ TableMappings: (Less commonly explicitly used for simple scenarios) Maps
table and column names between the database and the DataSet if they differ.

Essential Methods of SqlDataAdapter:​

●​ Fill(DataSet ds, string tableName):


○​ Purpose: Retrieves data from the database using the SelectCommand
and populates the specified DataTable within the DataSet.
○​ Process: Opens the connection, executes the SelectCommand, fills the
DataSet, and then closes the connection.
●​ Update(DataSet ds, string tableName):
○​ Purpose: Examines the changes (added, modified, deleted rows) in the
specified DataTable within the DataSet and applies those changes
back to the database.
○​ Process: Iterates through the changed rows, executing the appropriate
InsertCommand, UpdateCommand, or DeleteCommand for each
change. Opens and closes the connection for each batch of updates.

Typical Usage Pattern in ASP.NET (Disconnected Model):​

1.​ Create SqlConnection: (Though DataAdapter handles opening/closing it,


you still need to define it or pass it.)

Create SqlDataAdapter:​
C#​
using (SqlConnection connection = new SqlConnection(connectionString))

// The DataAdapter needs the connection and the select command

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Products",


connection);

DataSet ds = new DataSet();

adapter.Fill(ds, "Products"); // Fills the DataSet with data from "Products" table

// Now, ds (and ds.Tables["Products"]) holds the data offline

} // Connection is closed by adapter.Fill()

2.​ Work with Data Offline: Manipulate data in the DataSet (e.g., add new rows,
modify existing rows, delete rows).​

C#​
// Example: Adding a new row

DataTable productsTable = ds.Tables["Products"];


DataRow newRow = productsTable.NewRow();

newRow["ProductName"] = "New Gadget";

newRow["Price"] = 99.99;

productsTable.Rows.Add(newRow);

// Example: Modifying an existing row

// DataRow existingRow = productsTable.Rows[0];

// existingRow["Price"] = 105.00;

3.​ Update the Database:​

C#​
// IMPORTANT: Before calling Update, you need to configure the
InsertCommand, UpdateCommand, DeleteCommand

// This is often done using SqlCommandBuilder or by manually creating commands.

SqlCommandBuilder builder = new SqlCommandBuilder(adapter); // Auto-generates


INSERT/UPDATE/DELETE commands

adapter.Update(ds, "Products"); // Pushes changes from DataSet back to DB

4.​ Generating Commands (SqlCommandBuilder):​

●​ Simplifies DataAdapter usage by automatically generating the


InsertCommand, UpdateCommand, and DeleteCommand based on the
SelectCommand.
●​ Caveats: Only works for simple SELECT statements (e.g., SELECT * FROM
TableName). Not suitable for complex queries or stored procedures.
When to Use SqlDataAdapter in ASP.NET:​

●​ When you need to work with a disconnected copy of data (e.g., for caching,
filtering, sorting, or complex manipulation on the client-side).
●​ When displaying editable data in controls like GridView or DetailsView that
support data binding to DataSet/DataTable and require updates back to the
database.
●​ When you need to perform multiple operations (read, modify, delete) on the same
set of data before committing changes.

Relationship to Other ADO.NET Components:​

●​ Relies on SqlConnection to connect.


●​ Relies on SqlCommand to execute actual SQL statements for selection and
updates.
●​ Fills and updates DataSet objects.

Data Sets

●​ What is a DataSet?​

1.​ A core component in ADO.NET (System.Data.DataSet) representing


an in-memory, disconnected cache of data.
2.​ It's a collection of one or more DataTable objects, along with
relationships between them, constraints, and data stored in XML format.
3.​ Think of it as a miniature, in-memory relational database.

●​ Key Characteristics and Benefits:​


1.​ Disconnected Architecture: The most significant feature. Once filled, the
DataSet can be used and manipulated without an active connection to
the database. This frees up database resources and improves scalability
for web applications.
2.​ In-Memory Cache: All data is loaded into the application's memory.
3.​ Independent: Can retrieve data from multiple data sources and even
combine data from different database types.
4.​ XML-Based: Internally represents data using XML, allowing for easy
serialization, deserialization, and transfer (e.g., across web services).
5.​ Navigability: Allows you to move forwards and backwards through
records, sort, filter, and search data.
6.​ Updatable: You can add, modify, or delete rows in a DataTable within a
DataSet and then push those changes back to the database using a
DataAdapter.
7.​ Schema and Data: Stores both the schema (structure like column names,
data types) and the actual data.

●​ Core Components of a DataSet:​

1.​ DataTable:
■​ Represents a single table of data within the DataSet.
■​ Contains DataRow objects (representing records) and
DataColumn objects (representing fields).
■​ You interact with data primarily through DataTable objects.
2.​ DataRow: Represents a single row (record) in a DataTable. Provides
methods to access and modify column values.
3.​ DataColumn: Represents a single column (field) in a DataTable,
defining its name, data type, and other properties.
4.​ DataRelation: Defines relationships (like foreign keys) between two
DataTable objects within the DataSet, allowing for parent-child
navigation.
5.​ Constraints: (e.g., UniqueConstraint, ForeignKeyConstraint)
Enforce data integrity rules within the DataSet.
When to Use DataSet in ASP.NET:​

○​ When you need to cache data in memory for repeated access without
hitting the database.
○​ For complex data manipulations on the client-side (sorting, filtering,
searching, relations) before updating the database.
○​ When you need to pass data between layers of your application (e.g.,
from a data access layer to a business logic layer).
○​ For data binding to ASP.NET Web Forms controls like GridView,
DetailsView, FormView that support two-way data binding and editing.
○​ When integrating with XML technologies.

●​ Contrast with DataReader:​

○​ DataSet: Disconnected, in-memory, full functionality (read/write,


navigate), higher memory footprint.
○​ DataReader: Connected, stream-based, read-only, forward-only, lower
memory footprint, best for fast, one-time reads.

●​ Typed DataSets (Optional, but often covered):​

○​ A derived class of DataSet that provides strongly-typed access to tables


and columns (e.g., myDataSet.Products[0].ProductName instead of
myDataSet.Tables["Products"].Rows[0]["ProductName"]).
○​ Generated automatically by Visual Studio when you drag tables from
Server Explorer onto a designer surface.
○​ Offers compile-time checking and IntelliSense, reducing errors.

●​ Relationship to Entity Framework:​

○​ While DataSet is part of ADO.NET, modern ASP.NET development often


favors ORMs like Entity Framework (EF Core) for data access.
○​ EF Core provides a more object-oriented approach to data, often replacing
the need for explicit DataSet management in many scenarios. However,
understanding DataSet is foundational to grasp the underlying data
access mechanisms.

Data Controls and Its Properties

What are ASP.NET Data Controls?​

●​ Specialized ASP.NET Web Server controls designed to display, edit, and manage
data from various data sources (databases, XML files, objects).
●​ They provide a declarative, often code-free, way to bind UI elements directly to
data.
●​ They encapsulate complex data access logic, simplifying web development.

Key Categories of Data Controls:​

●​ Display Controls (Read-Only): Primarily for showing data.


○​ GridView
○​ Repeater
○​ DataList
○​ ListView
●​ Editable Controls (Read/Write): Allow users to view, insert, update, and delete
data.
○​ GridView (when editing is enabled)
○​ DetailsView
○​ FormView

Common Essential Properties Across Data Controls:​

●​ DataSourceID:​
○​ Purpose: The most crucial property. Specifies the ID of the data source
control (e.g., SqlDataSource, ObjectDataSource) from which the
data control will retrieve its data.
○​ Example: <asp:GridView ID="myGrid" runat="server"
DataSourceID="SqlDataSource1">

●​ DataSource:​

○​ Purpose: Used for programmatic data binding (when you don't use a
DataSourceID). You set this property to an enumerable object (e.g.,
DataSet, DataTable, List<T>).
○​ Requires: DataBind() method to be called manually.
○​ Example (in code-behind): myGrid.DataSource = myDataTable;
myGrid.DataBind();

●​ DataKeyNames:​

○​ Purpose: Specifies the primary key column(s) of the data source.


○​ Importance: Essential for enabling editing, updating, and deleting
functionalities in controls like GridView, DetailsView, and FormView
as it tells the control which row to uniquely identify.
○​ Example: <asp:GridView DataKeyNames="ProductID" ...>

●​ AutoGenerateColumns (for GridView, DetailsView):​

○​ Purpose: A boolean property that determines whether the control


automatically creates columns for each field in the data source.
○​ True (Default): Quick setup, but less control over appearance.
○​ False: Allows manual definition of columns using <Columns> template,
providing full customization.
●​ AllowPaging (for GridView, ListView):​

○​ Purpose: Enables built-in pagination, allowing data to be displayed in


manageable chunks.
○​ Requires: PageSize property to be set.
○​ Example: <asp:GridView AllowPaging="True" PageSize="10"
...>

●​ AllowSorting (for GridView):​

○​ Purpose: Enables built-in sorting capabilities based on column headers.


○​ Requires: A data source control that supports sorting.
○​ Example: <asp:GridView AllowSorting="True" ...>

●​ AutoGenerateEditButton, AutoGenerateDeleteButton,
AutoGenerateInsertButton (for GridView, DetailsView, FormView):​

○​ Purpose: Boolean properties that automatically render "Edit," "Delete," or


"New" command buttons for each row/item.
○​ Requires: DataKeyNames and appropriate UpdateCommand,
DeleteCommand, InsertCommand in the linked data source control.

Control-Specific Key Properties & Concepts:​

●​ GridView:​

○​ Columns Template: Allows defining BoundField (for displaying data),


TemplateField (for custom layouts/controls), CommandField (for
Edit/Delete/Select buttons), CheckBoxField, HyperLinkField, etc.
○​ HeaderStyle, RowStyle, AlternatingRowStyle: For styling the
grid.
○​ Events: RowEditing, RowUpdating, RowDeleting,
PageIndexChanging, Sorting, etc., for handling user interactions.

●​ DetailsView:​

○​ DefaultMode: ReadOnly, Edit, Insert. Sets the initial mode of the


control.
○​ Fields Template: Similar to GridView columns, defines BoundField
or TemplateField.
○​ EmptyDataTemplate: Content displayed when no data is returned.

●​ FormView:​

○​ ItemTemplate: Defines the layout for displaying a single record in


read-only mode.
○​ EditItemTemplate: Defines the layout for editing a single record.
○​ InsertItemTemplate: Defines the layout for inserting a new record.
○​ EmptyDataTemplate: Content displayed when no data.
○​ More flexible than DetailsView for custom layouts.

●​ Repeater, DataList, ListView:​

○​ Template-Based: Primarily rely on <ItemTemplate>,


<HeaderTemplate>, <FooterTemplate>,
<AlternatingItemTemplate>, etc., for complete control over
rendering.
○​ No built-in UI for editing/paging/sorting (must be coded manually or
with custom controls).

Interaction with Data Source Controls:​


●​ Data controls use the methods exposed by data source controls (e.g.,
Select(), Update(), Delete(), Insert()) to perform database operations
automatically when their properties like DataSourceID are set.
●​ This provides the "declarative programming" benefit of ASP.NET.

Data Binding

What is Data Binding?​

●​ The process of establishing a link between a user interface (UI) element (like an
ASP.NET Web control) and a data source.
●​ Allows data from a database, collection, XML file, or other sources to be
displayed in and/or updated from web page controls.
●​ Simplifies the process of displaying and manipulating dynamic content on web
pages.

Key Goals of Data Binding:​

●​ Reduce the amount of code needed to display data.


●​ Provide a declarative way to connect UI to data.
●​ Automate the flow of data between the presentation layer and the data layer.

Types of Data Binding in ASP.NET:​

●​ Single-Value Data Binding (One-Way):​

○​ Binds a single property of a control to a single data value.


○​ Often used for displaying a single field, like a label or text box.
○​ Uses <%# Eval("FieldName") %> or <%# Bind("FieldName") %>
(though Bind is primarily for two-way).
○​ Requires Page.DataBind() or Control.DataBind() to be called
explicitly, typically in Page_Load (making sure it only runs once, e.g., if
(!IsPostBack)).

●​ Templated Data Binding (Declarative):​

○​ Used with complex data controls like GridView, Repeater, DataList,


FormView, ListView.
○​ Involves defining templates (<ItemTemplate>, <HeaderTemplate>,
etc.) within the data control.
○​ Uses Eval() for one-way binding (read-only display) and Bind() for
two-way binding (read-write).
○​ The data control automatically handles the DataBind() call when its
DataSourceID property is set.

●​ Two-Way Data Binding:​

○​ Allows data to flow in both directions: from the data source to the UI
control and from the UI control back to the data source.
○​ Primarily achieved using the <%# Bind("FieldName") %> syntax
within editable data controls (GridView in edit mode, DetailsView,
FormView).
○​ Requires the data source control (e.g., SqlDataSource) to have
UpdateCommand, InsertCommand, or DeleteCommand defined, and
the data control to have DataKeyNames set.

Core Elements and Syntax:​

●​ <# ... #> (Data-binding expression delimiter):​

○​ <%# ... %>: Standard data-binding expression. Requires DataBind().


○​ <%= ... %>: Renders the value of an expression to the output stream
immediately (not true data binding in the sense of a connected source, but
often used for simple values).

●​ Eval() Method:​

○​ <%# Eval("FieldName") %>


○​ Used for one-way data binding (read-only).
○​ Retrieves the value of the specified field from the current data item.
○​ Can take an optional format string: Eval("DateColumn", "{0:d}").

●​ Bind() Method:​

○​ <%# Bind("FieldName") %>


○​ Used for two-way data binding (read-write).
○​ Retrieves the value for display and also provides the mechanism for the
control to update the data source when changes occur (e.g., in a text box
within an EditItemTemplate).

How Data Binding Works (Simplified):​

1.​ An ASP.NET data control's DataSourceID property is set to a data source


control (or its DataSource property is set programmatically).
2.​ When DataBind() is called (either automatically by the data control or explicitly
in code), the data control iterates through the data provided by the data source.
3.​ For each data item (e.g., a row in a DataTable), the data control evaluates the
Eval() or Bind() expressions within its templates.
4.​ The retrieved values are then rendered into the HTML output.
5.​ For two-way binding, when a postback occurs (e.g., user clicks Update), the data
control retrieves values from the input controls (e.g., TextBox), updates its
internal data item, and then calls the appropriate Update() or Insert()
method on the data source control.
Benefits in ASP.NET:​

●​ Productivity: Quickly display complex data structures with minimal code.


●​ Separation of Concerns: Helps separate presentation logic (UI) from data
access logic.
●​ Maintainability: Easier to update UI or data source independently.
●​ Reusability: Data controls are reusable components.

Common Data Sources for Binding:​

●​ Databases: DataSet, DataTable, SqlDataReader (programmatic), LINQ


queries.
●​ Collections: List<T>, ArrayList, IEnumerable.
●​ XML Data: XmlDocument, XmlReader.
●​ Objects: Custom classes (often used with ObjectDataSource).

Debugging Data Binding:​

●​ Ensure DataBind() is called at the correct time (e.g., !IsPostBack).


●​ Check DataSourceID or DataSource property values.
●​ Verify correct field names in Eval() and Bind().
●​ Use the debugger to inspect the data source before binding.

—------------------------------------------------------------------------------------------------------------------
Unit - IV: ADO.NET & Database Connections

MCQ (1 Mark Each)

1.​ Which of the following ADO.NET objects is primarily used for fast, forward-only,
read-only data retrieval?

a) DataSet b) DataRow c) DataReader d) DataAdapter​

2.​ Which property of an SqlCommand object is used to specify the SQL query or
stored procedure name?

a) Connection b) Parameters c) CommandType d) CommandText​

3.​ The Fill() method is typically associated with which ADO.NET object to
populate a DataSet?

a) SqlConnection b) SqlCommand c) SqlDataAdapter d) SqlDataReader​

4.​ Which of the following data binding expressions is used for two-way data
binding in ASP.NET?

a) <%# Eval("FieldName") %> b) <%= FieldName %> c) <%#


Bind("FieldName") %> d) <% FieldName %>​

5.​ What is the primary benefit of using connection pooling in ASP.NET


applications?

a) Enhances security by encrypting connections. b) Reduces the overhead of


frequently opening and closing physical database connections. c) Allows
disconnected data access. d) Enables automatic generation of SQL commands.​

6.​ Which property of an ASP.NET Data Control (like GridView) links it to a data
source control?
a) DataSource b) DataMember c) DataSourceID d) DataKeyNames​

7.​ A DataSet is considered a part of which ADO.NET architecture?

a) Connected b) Stream-based c) Disconnected d) Forward-only​

8.​ What is the main purpose of SqlParameter objects in ADO.NET commands?

a) To specify the database server name. b) To define the type of command (e.g.,
Text, StoredProcedure). c) To prevent SQL Injection attacks and provide type
safety. d) To execute queries that return a single scalar value.​

9.​ Which ASP.NET Data Control provides the most granular control over the
rendering of each item using templates, but requires manual coding for sorting,
paging, etc.?

a) GridView b) DetailsView c) Repeater d) FormView​

10.​When using a DataReader, why is it essential to close the DataReader object


and the Connection object?

a) To commit transactions to the database. b) To free up database and


application resources. c) To automatically update changes back to the database.
d) To prevent compilation errors.

MCQ Answers:

1.​ c) DataReader
2.​ d) CommandText
3.​ c) SqlDataAdapter
4.​ c) <%# Bind("FieldName") %>
5.​ b) Reduces the overhead of frequently opening and closing physical database
connections.
6.​ c) DataSourceID
7.​ c) Disconnected
8.​ c) To prevent SQL Injection attacks and provide type safety.
9.​ c) Repeater
10.​b) To free up database and application resources.

5-Mark Questions

1.​ Resource Management: Why must you always close SqlConnection and
SqlDataReader objects?​

2.​ DataSet vs. DataReader: State two key differences between DataSet
(disconnected) and SqlDataReader (connected).​

3.​ SQL Injection Prevention: What is SQL Injection, and what is the primary
ADO.NET technique to prevent it?​

4.​ SqlDataAdapter Function: Briefly explain the role of SqlDataAdapter in


moving data between a database and a DataSet.​

10-Mark Questions

1.​ Connected Data Access Steps: Outline the essential steps (objects and
methods) for an ASP.NET application to fetch and display data using ADO.NET's
connected architecture.​

2.​ Disconnected Data Access Flow: Describe the process of retrieving, modifying,
and updating data using the ADO.NET disconnected architecture (DataSet
and SqlDataAdapter).​

3.​ ASP.NET Data Controls Comparison: Compare any two ASP.NET Data
Controls (e.g., GridView, DetailsView, Repeater) based on their primary
use and how they handle column/field display.​

4.​ Data Binding Types: Explain the difference between one-way and two-way
data binding in ASP.NET. Provide the syntax for each.

—------------------------------------------------------------------------------------------------------------------
Unit - V

Grid View Control & XML Classes

Grid View control

What is the GridView Control?​

●​ An ASP.NET Web Server Control (<asp:GridView>).


●​ Designed for displaying data in a tabular (grid) format on a web page.
●​ Provides built-in functionalities for sorting, paging, selecting, editing, and
deleting data without extensive code.
●​ Successor to the older DataGrid control.

Key Characteristics & Benefits:​

●​ Declarative Setup: Can be largely configured directly in the ASP.NET markup,


often requiring minimal code-behind.
●​ Automatic Features: Simplifies common data operations like pagination and
sorting through simple property settings.
●​ Styling: Extensive options for styling headers, rows, columns, and alternating
rows.
●​ Flexible Column Types: Supports various column types for displaying data,
buttons, or custom content.

Essential Properties:​

●​ DataSourceID: (Most common) Specifies the ID of a data source control (e.g.,


SqlDataSource, ObjectDataSource, XmlDataSource) that provides the
data.
●​ DataSource: Used for programmatic data binding (e.g., binding to a DataSet,
DataTable, List<T>) from code-behind. Requires
myGridView.DataBind().
●​ AutoGenerateColumns: True (default) automatically creates a column for
each field in the data source. False requires explicit column definition within the
<Columns> template.
●​ DataKeyNames: Crucial for enabling editing, updating, and deleting. Specifies
the primary key column(s) of the underlying data. Example:
DataKeyNames="ProductID".
●​ AllowPaging: True enables pagination. Requires PageSize to be set.
●​ PageSize: Number of records to display per page when paging is enabled.
●​ AllowSorting: True enables column header sorting. Requires a data source
control that supports sorting.
●​ AutoGenerateEditButton: True adds an "Edit" link/button to each row.
●​ AutoGenerateDeleteButton: True adds a "Delete" link/button to each row.

Column Types within <Columns> Template:​

●​ BoundField: Displays data from a single field. (e.g., <asp:BoundField


DataField="ProductName" HeaderText="Product Name" />)
●​ TemplateField: Provides maximum flexibility. Allows placing any HTML or
Web controls (e.g., TextBox, Button, Image) within the header, item, edit item,
or footer templates. Essential for custom display or input.
●​ CommandField: Automatically generates common command buttons like Select,
Edit, Delete, New. (e.g., <asp:CommandField ShowEditButton="True"
ShowDeleteButton="True" />)
●​ CheckBoxField: Displays boolean data as checkboxes.
●​ HyperLinkField: Displays data as a hyperlink.
●​ ButtonField: Displays a button for custom command handling.

Common Events (for GridView interactions):​

●​ PageIndexChanging: Fired when a user clicks a pager button (to change


page).
●​ Sorting: Fired when a user clicks a column header to sort.
●​ RowEditing: Fired when an "Edit" button is clicked.
●​ RowUpdating: Fired when an "Update" button is clicked after editing.
●​ RowDeleting: Fired when a "Delete" button is clicked.
●​ RowCancelingEdit: Fired when a "Cancel" button is clicked during edit mode.
●​ RowDataBound: Fired for each row as it's being bound to data, useful for
formatting or conditional logic.

GridView and XML Data (XML Classes Unit Connection):​

●​ The GridView control can directly bind to XML data.


●​ This is achieved by using the XmlDataSource control.
●​ XmlDataSource can load XML from a file, a URL, or an inline XML string.
●​ It internally uses XML classes (like XmlDocument or XPathNavigator) to
process the XML data, which the GridView then renders.

Example:​
HTML​
<asp:XmlDataSource ID="XmlDataSource1" runat="server"
DataFile="~/App_Data/Products.xml"
XPath="Products/Product"></asp:XmlDataSource>
<asp:GridView ID="GridView1" runat="server"
DataSourceID="XmlDataSource1"></asp:GridView>

●​ XPath property in XmlDataSource is critical for selecting specific nodes to


display.

Disadvantages/When not to use:​

●​ Less control over the exact HTML output compared to Repeater or ListView.
●​ Can generate large amounts of HTML for very complex layouts.
Grid View control: Deleting, Editing, Sorting and Paging

Deleting:​

●​ Enable Deletion: Set AutoGenerateDeleteButton="True" on the


GridView.
●​ DataKeyNames: The GridView's DataKeyNames property must be set to the
primary key column(s) of your data source. This allows the GridView to identify
which record to delete.
●​ Data Source Requirement: The data source control (e.g., SqlDataSource,
ObjectDataSource) must have a properly configured DeleteCommand that
uses parameters to delete the correct record based on the primary key.
●​ Event: The RowDeleting event fires before the delete operation. You can use
this to add confirmation prompts or custom logic.

Editing:​

●​ Enable Editing: Set AutoGenerateEditButton="True" on the GridView.


●​ DataKeyNames: Required, as with deleting.
●​ Data Source Requirement: The data source control must have
UpdateCommand and SelectCommand defined. The UpdateCommand must
use parameters to update the correct record.
●​ Edit Mode: When the user clicks "Edit," the GridView switches to edit mode for
that row, typically displaying text boxes for editing.
●​ Events:
○​ RowEditing: Fires when the "Edit" button is clicked.
○​ RowUpdating: Fires when the "Update" button is clicked.
○​ RowCancelingEdit: Fires when the "Cancel" button is clicked.

Sorting:​

●​ Enable Sorting: Set AllowSorting="True" on the GridView.


●​ Data Source Requirement: The data source control must support sorting.
SqlDataSource usually does this automatically. ObjectDataSource might
require you to handle sorting in your code.
●​ Automatic Sorting: The GridView automatically adds sort links to the header
of each sortable column.
●​ Event: The Sorting event fires when a user clicks a sortable column header.
You can use this to customize the sorting behavior.

Paging:​

●​ Enable Paging: Set AllowPaging="True" on the GridView.


●​ PageSize: Set the number of records to display per page (e.g.,
PageSize="10").
●​ Automatic Paging UI: The GridView automatically displays paging controls
(page numbers, next/previous buttons).
●​ Event: The PageIndexChanging event fires when the user clicks a paging
control. You can use this to handle custom paging logic, though usually, the
built-in paging is sufficient.

XML Data and GridView (Related to XML Classes Unit):​

●​ When the GridView is bound to an XmlDataSource, the same principles for


deleting, editing, sorting, and paging apply, but with some differences:
○​ XPath: The XmlDataSource's XPath property becomes crucial for
selecting the nodes that will be displayed in the GridView.
○​ Editing/Deleting XML: Modifying XML data often requires more custom
code in the RowUpdating and RowDeleting events to update the
underlying XML document.
○​ Sorting/Paging XML: Sorting and paging XML data can be more complex
and might require custom implementations or XSLT transformations.
●​ The XmlDataSource typically handles these operations by using XML classes
to manipulate the XML document.
●​ For simple XML structures, the built-in features might work; for complex
structures, you might need to write code to update the XML.
XML classes Web form to manipulate XML files

What are XML Classes in .NET?​

●​ A set of classes within the System.Xml and System.Xml.Linq namespaces


in the .NET Framework.
●​ Provide programmatic ways to create, read, write, navigate, and modify XML
documents and data.
●​ Fundamental for working with XML data in ASP.NET applications.

Key XML Classes for Manipulation:​

●​ XmlDocument (DOM - Document Object Model):​

○​ Purpose: Loads an entire XML document into memory as a tree structure


(nodes, elements, attributes).
○​ Manipulation: Ideal for navigating, querying, and modifying XML data
using methods like CreateElement(), CreateAttribute(),
AppendChild(), RemoveChild(), SelectNodes(),
SelectSingleNode().
○​ Saving: Changes are saved back to the file using Save(filePath).
○​ Pros: Easy to navigate and modify any part of the document.
○​ Cons: Can be memory-intensive for very large XML files, as the entire
document is loaded.

●​ XPathNavigator:​

○​ Purpose: Provides a cursor-like model for navigating XML data using


XPath expressions.
○​ Manipulation: Primarily used for efficient querying and reading of XML
data. Can be used for updates in conjunction with XmlDocument.
○​ Pros: Efficient for large XML documents, good for querying.
○​ Cons: Not as intuitive for direct modification compared to XmlDocument.
●​ XDocument (LINQ to XML):​

○​ Purpose: A modern, more intuitive, and LINQ-enabled approach to


working with XML.
○​ Manipulation: Uses methods like Add(), Remove(),
SetElementValue(), SetAttributeValue() on XElement and
XAttribute objects.
○​ Saving: Changes are saved using Save(filePath).
○​ Pros: Extremely powerful and concise for querying and manipulating
XML, integrates well with LINQ.
○​ Cons: Requires familiarity with LINQ concepts.

How ASP.NET Web Forms Manipulate XML Files:​

1.​ Loading the XML:​

○​ Read the XML file content using XmlDocument.Load(filePath) or


XDocument.Load(filePath).
○​ Alternatively, the XmlDataSource control internally handles loading the
XML data for data-bound controls.

2.​ Modifying Data (e.g., for GridView Editing/Deleting):​

○​ When a user edits a row in a GridView bound to XML, you'd typically


handle the GridView's RowUpdating or RowDeleting event.
○​ Inside the Event Handler:
■​ Get the unique identifier (primary key) of the row being
edited/deleted from GridView.DataKeys.
■​ Load the XML file into an XmlDocument or XDocument object.
■​ Use XPath or LINQ to XML queries to locate the specific XML
element corresponding to the row.
■​ Modify the element's attributes or child elements (for updates) or
remove the element (for deletes).
■​ Save the modified XmlDocument or XDocument back to the XML
file.
3.​ Adding New Data (e.g., for GridView Insertion - though GridView doesn't
have built-in insert):​

○​ When adding new data (often via a separate form or a FormView), load
the XML file.
○​ Create new XElement or XmlElement objects representing the new
record/node.
○​ Append the new element to the appropriate parent node in the XML
document.
○​ Save the XML document.

4.​ Error Handling:​

○​ Crucial to include try-catch blocks for file operations and XML parsing
to handle potential errors (e.g., file not found, invalid XML format,
concurrent access).

XmlDataSource Integration (Connecting to GridView):​

●​ The XmlDataSource control simplifies reading and displaying XML data in


GridView.
●​ It handles the parsing and loading of the XML file.
●​ However, XmlDataSource typically does NOT provide built-in
update/insert/delete capabilities for the XML file itself.
●​ For actual XML file manipulation (saving changes back to the file), you almost
always need to write code-behind using the System.Xml or System.Xml.Linq
classes in response to GridView events (RowUpdating, RowDeleting).
Website Security

What is Website Security?​

●​ Protecting web applications and data from unauthorized access, use, disclosure,
disruption, modification, or destruction.
●​ Essential for maintaining data integrity, user privacy, and application availability.

Core Security Principles (General):​

●​ Confidentiality: Protecting sensitive information from unauthorized disclosure.


●​ Integrity: Ensuring data is accurate and not tampered with.
●​ Availability: Ensuring the application and its resources are accessible when
needed.
●​ Authentication: Verifying the identity of users.
●​ Authorization: Determining what an authenticated user is permitted to do.

Common Web Application Vulnerabilities (Relevant to ASP.NET):​

●​ SQL Injection:​

○​ Description: Attacker inserts malicious SQL code into input fields, tricking
the database into executing unintended commands.
○​ Relevance to ADO.NET/GridView: Directly impacts applications using
SqlCommand to interact with databases.
○​ Mitigation: Always use Parameterized Queries (e.g.,
command.Parameters.AddWithValue()). Never concatenate user
input directly into SQL strings.

●​ Cross-Site Scripting (XSS):​

○​ Description: Attacker injects malicious client-side scripts (e.g.,


JavaScript) into web pages, which are then executed by other users'
browsers.
○​ Relevance to GridView/Display: If user-supplied data displayed in a
GridView (or any control) is not properly encoded, it can lead to XSS.

○​ Mitigation:
■​ Output Encoding: Always encode user-supplied data before
displaying it (e.g., using HttpUtility.HtmlEncode()).
ASP.NET controls often do this automatically for BoundFields, but
be careful with TemplateFields.
■​ Input Validation: Validate input to ensure it adheres to expected
formats and doesn't contain malicious scripts.

●​ Cross-Site Request Forgery (CSRF):​

○​ Description: Attacker tricks a logged-in user into performing an


unintended action on a web application where they are authenticated
(e.g., changing password, making a purchase).
○​ Relevance to ASP.NET Forms: Affects forms that submit data (like those
connected to GridView updates/deletes).
○​ Mitigation: Use Anti-Forgery Tokens (<asp:ValidationSummary>
can help, but specifically __RequestVerificationToken generated by
ASP.NET).

●​ Insecure Direct Object References:​

○​ Description: Application exposes direct references to internal


implementation objects (e.g., file paths, database keys) allowing attackers
to bypass authorization checks.
○​ Relevance to GridView/URLs: If GridView uses IDs in query strings
(e.g., ?id=123), ensure robust server-side authorization checks for every
request, not just at login.

●​ XML External Entities (XXE) Injection:​


○​ Description: Attackers exploit XML parsers that can process external
entity references, potentially reading local files, performing
denial-of-service, or making network requests.
○​ Relevance to XML Classes Unit: Directly impacts applications
manipulating XML files using XmlDocument or XDocument if not
configured securely.
○​ Mitigation:
■​ Disable DTD Processing: For XmlDocument or XDocument,
disable DTD (Document Type Definition) processing when dealing
with untrusted XML sources.
■​ Use XmlReaderSettings with DtdProcessing =
DtdProcessing.Prohibit or DtdProcessing.Ignore for
safe parsing.
■​ Avoid processing external entities from untrusted sources.

Key Security Measures in ASP.NET:​

●​ Input Validation: Validate all user input on both the client-side (for UX) and,
more importantly, server-side (for security).
●​ Output Encoding: Encode all data rendered from user input to prevent XSS.
●​ Secure Connection Strings:
○​ Store them in web.config within the <connectionStrings> section.
○​ Encrypt the web.config section for production environments
(aspnet_regiis -pef).
○​ Never hardcode connection strings in code.
●​ Authentication & Authorization:
○​ Use ASP.NET's built-in authentication (Forms, Windows) and authorization
mechanisms (roles, URL authorization).
○​ Implement Principle of Least Privilege: Grant users/application pool
identities only the necessary permissions on the database and file system.
●​ Error Handling: Implement robust custom error pages and avoid displaying
detailed error messages (e.g., stack traces) to users, which can reveal sensitive
information.
●​ HTTPS/SSL/TLS: Always use HTTPS to encrypt communication between the
client and server, protecting data in transit.
●​ Regular Security Audits & Updates: Keep ASP.NET framework, libraries, and
server software updated with the latest security patches.
Authentication

What is Authentication?​

●​ The process of verifying the identity of a user (or an application) trying to


access a system or resource.
●​ It answers the question: "Who are you?"
●​ It's the first step in securing a web application, followed by authorization.

Key Concepts in ASP.NET Authentication:​

●​ Identity: A set of claims that describes a user (e.g., username, email, roles).
●​ Credentials: Information provided by the user to prove their identity (e.g.,
username/password, token, certificate).
●​ Authentication Provider: The mechanism that verifies credentials against a
stored identity (e.g., a database, Active Directory).

Common Authentication Types in ASP.NET Web Forms:​

1.​ Forms Authentication:​

○​ How it Works:
■​ User provides credentials (typically username/password) via a login
form.
■​ ASP.NET verifies these credentials against a data store (e.g.,
database, XML file, web.config).
■​ If valid, an encrypted "authentication ticket" (cookie) is issued to the
user's browser.
■​ Subsequent requests include this ticket, allowing ASP.NET to
identify the user without re-authenticating.
○​ Configuration: Primarily configured in web.config within the
<authentication mode="Forms"> section.
○​ Advantages: Flexible, customizable, good for public-facing websites.
○​ Relevance to Units: You'd likely store user credentials in a database
(accessed via ADO.NET, possibly GridView to manage users) or even
an XML file (managed with XML Classes).

2.​ Windows Authentication:​

○​ How it Works:
■​ Leverages the operating system's (Windows) built-in authentication
mechanisms.
■​ The web server (IIS) authenticates the user against Windows user
accounts or Active Directory.
■​ The user's Windows credentials are used, often transparently.
○​ Configuration: Configured in web.config within <authentication
mode="Windows">. Requires specific IIS settings.
○​ Advantages: Seamless for intranet applications, highly secure within a
Windows domain.
○​ Disadvantages: Not suitable for internet applications or non-Windows
clients.

3.​ No Authentication (Anonymous Access):​

○​ How it Works: All users are considered anonymous. No identity


verification is performed.
○​ Configuration: Default in web.config unless other authentication is set.
○​ Use Case: Public content, landing pages, or APIs where user identity isn't
required.

Authentication-Related Classes and Controls:​

●​ System.Web.Security Namespace: Contains classes for Forms


Authentication, role management, etc.
●​ Login Controls (<asp:Login>, <asp:LoginView>, <asp:LoginStatus>,
<asp:CreateUserWizard>, <asp:PasswordRecovery>):
○​ Built-in ASP.NET Web Forms controls that provide ready-to-use UI for
login, user creation, password recovery, etc.
○​ They integrate directly with ASP.NET's membership providers (which can
use SQL Server databases or custom providers).

Integration with Data Access (ADO.NET / XML Classes):​

●​ Storing User Data: User accounts and roles are typically stored in a database
(SQL Server, etc.) accessed via ADO.NET.
○​ You might use a GridView to display and manage user accounts if you
build an admin interface.
●​ Custom Authentication: If you implement a custom membership provider, you'll
directly use ADO.NET commands or XML classes to validate user credentials
against your custom data store.
●​ XML Files for Users: While less common for production, educational examples
might store simple user lists in XML files. XML Classes (XmlDocument,
XDocument) would be used to read and verify these credentials.

Security Considerations in Authentication:​

●​ Password Hashing: Never store passwords in plain text. Always store


cryptographic hashes of passwords (e.g., using PBKDF2, bcrypt, scrypt) and use
a salt.
●​ Secure Credential Transmission: Use HTTPS/SSL/TLS to encrypt all login
communications to prevent credentials from being intercepted.
●​ Account Lockout: Implement policies to lock out accounts after multiple failed
login attempts to prevent brute-force attacks.
●​ Session Management: Secure session IDs (e.g., regenerate on login) and set
appropriate session timeouts.
Authorization

What is Authorization?​

●​ The process of determining what an authenticated user is allowed to do or


access.
●​ It answers the question: "What can you do?"
●​ Occurs after a user has been successfully authenticated.

Key Concepts in ASP.NET Authorization:​

●​ Identity: The verified user (from authentication).


●​ Permissions/Rights: Specific actions a user is allowed to perform (e.g., view
products, edit prices, delete users).
●​ Roles: Groups of users who share a common set of permissions (e.g.,
"Administrators," "Managers," "Customers"). This simplifies management
compared to assigning permissions to individual users.

Common Authorization Types in ASP.NET Web Forms:​

1.​ File/URL Authorization:​

○​ How it Works: Controls access to specific web pages (.aspx files) or


folders based on user roles or names.
○​ Configuration: Done in the web.config file using the
<authorization> section within <system.web>.
○​ Examples:
■​ Allow only authenticated users: <deny users="?" />
■​ Allow specific roles: <allow roles="Administrators,
Managers" />
■​ Deny specific users: <deny users="baduser" />
○​ Advantages: Simple to set up, effective for broad access control.
○​ Disadvantages: Only works at the file/folder level, not granular control
within a page.
2.​ Role-Based Authorization:​

○​ How it Works: Grants or denies access based on the roles assigned to


an authenticated user.
○​ Configuration:
■​ web.config: As above, allow roles="RoleName".
■​ Code-Behind: Use User.IsInRole("RoleName") method to
conditionally display UI elements or execute code blocks.
○​ Advantages: Scalable, easy to manage permissions for groups of users.
○​ Relevance to Units: You'd likely store user roles in a database (managed
via ADO.NET, potentially a GridView for admin), or an XML file
(managed with XML Classes).

3.​ Programmatic Authorization (Code-Based):​

○​ How it Works: You write C# code in your ASP.NET page's code-behind to


determine if a user has permission to perform an action.
○​ Methods Used:
■​ User.Identity.IsAuthenticated: Checks if the user is
logged in.
■​ User.Identity.Name: Gets the authenticated user's name.
■​ User.IsInRole("RoleName"): Checks if the authenticated user
belongs to a specific role.
○​ Use Cases:
■​ Showing/hiding buttons (myButton.Visible =
User.IsInRole("Admin");).
■​ Enabling/disabling controls.
■​ Controlling access to specific data rows (e.g., in a GridView, only
show records owned by the current user).
■​ Performing database operations only if authorized.
○​ Advantages: Most granular control, can apply to specific data or UI
elements.

Integration with Data Access (GridView / XML Classes):​


●​ GridView and Authorization:​

○​ Row-Level Authorization: In the GridView's RowDataBound event, you


can use User.IsInRole() to:
■​ Hide/show CommandField buttons (Edit/Delete).
■​ Disable specific cells or controls within a TemplateField.
■​ Change background color based on user permissions.
○​ Data Filtering: Modify the SELECT command or XPath query to only
retrieve data that the current user is authorized to see (e.g., SELECT *
FROM Orders WHERE CustomerID = @currentUserId).

●​ XML Classes and Authorization:​

○​ When reading/writing XML data using XmlDocument or XDocument, you


can implement authorization checks:
■​ Before saving changes to an XML file, verify
User.IsInRole("Editor").
■​ When parsing XML to display, filter elements based on user roles or
specific user IDs embedded in the XML itself.
■​ For sensitive XML configuration files, ensure only authorized
application pool identities have file system read/write permissions.\

Security Best Practices in Authorization:​

●​ Principle of Least Privilege: Grant users/roles only the minimum necessary


permissions.
●​ "Fail Securely": Default to denying access and explicitly grant permissions.
●​ Layered Security: Implement authorization checks at multiple layers (URL,
code-behind, database).
●​ Server-Side Validation: Always enforce authorization on the server-side.
Client-side checks are for user experience, not security.
●​ Protect Admin Interfaces: Ensure robust authorization for any pages or
features that manage users, roles, or critical application settings.
Creating a Web Application

What is a Web Application?​

●​ A software application accessed via a web browser over a network (internet or


intranet).
●​ Typically follows a client-server model: users interact with the client (browser),
which communicates with the server-side application.
●​ ASP.NET is a framework for building these server-side web applications.

Core Components of an ASP.NET Web Application:​

●​ Web Forms (.aspx files): The individual pages that users see and interact with.
They combine HTML, ASP.NET server controls, and code-behind logic.
●​ Code-Behind Files (.aspx.cs or .aspx.vb): Contains the C# (or VB.NET)
code that handles page events, interacts with data, and implements business
logic.
●​ web.config: The main configuration file for the application, defining settings for
authentication, authorization, connection strings, error handling, etc.
●​ Global.asax: (Optional) Handles application-level events (e.g.,
Application_Start).
●​ App_Data Folder: Used to store application data files, including databases (like
.mdf files for SQL Server Express) or XML files.
●​ Bin Folder: Contains compiled assemblies (DLLs) of your application code and
any referenced libraries.

Steps to Create a Basic ASP.NET Web Application (Conceptual):​

1.​ Project Setup (Visual Studio):​

○​ Open Visual Studio.


○​ Select "Create a new project."
○​ Choose "ASP.NET Web Application (.NET Framework)" or "ASP.NET Core
Web App" (depending on the course's framework version).
○​ Select the "Empty" template or "Web Forms" template.

2.​ Designing the User Interface (UI):​

○​ Add a new Web Form (.aspx file) to your project.


○​ Drag and drop ASP.NET Web Server Controls (e.g., Label, TextBox,
Button, GridView) from the Toolbox onto the design surface or write
them directly in HTML.
○​ Use HTML, CSS, and JavaScript for presentation and client-side
interactivity.

3.​ Connecting to Data (ADO.NET Integration):​

○​ Database Setup: Ensure a database (e.g., SQL Server) is available.


○​ Connection String: Define the database connection string in
web.config within the <connectionStrings> section.
○​ Data Source Controls:
■​ Drag and drop a SqlDataSource (for databases) or
XmlDataSource (for XML files) onto the .aspx page.
■​ Configure its ConnectionString and SelectCommand
properties (and InsertCommand, UpdateCommand,
DeleteCommand for editable data).
○​ Manual ADO.NET (Code-Behind): Alternatively, write C# code using
SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter,
DataSet to interact with the database directly.

4.​ Displaying Data (GridView Control):​

○​ Drag a GridView control onto the .aspx page.


○​ Set its DataSourceID property to the ID of your configured
SqlDataSource or XmlDataSource.
○​ Configure GridView properties: AutoGenerateColumns="True" (for
quick display) or AutoGenerateColumns="False" with custom
<Columns> for specific fields (BoundField, TemplateField).
○​ Enable features like AllowPaging, AllowSorting,
AutoGenerateEditButton, AutoGenerateDeleteButton as
needed.

5.​ Manipulating XML Files (XML Classes Integration):​

○​ To read/write/modify XML files, use classes from System.Xml


(XmlDocument) or System.Xml.Linq (XDocument).
○​ This is typically done in the code-behind (.aspx.cs) in response to user
actions (e.g., a button click, GridView's RowUpdating event).
○​ Example: Loading an XML file to populate a dropdown, or saving user
settings to an XML file.

6.​ Implementing Business Logic (Code-Behind):​

○​ Handle control events (e.g., Button_Click, GridView_RowEditing,


GridView_PageIndexChanging).
○​ Write C# code to process user input, validate data, perform calculations,
and interact with the data layer.

7.​ Adding Security (Authentication & Authorization):​

○​ Authentication: Configure Forms Authentication in web.config and use


ASP.NET Login controls (e.g., Login.aspx). Manage user accounts
(often in a database).
○​ Authorization:
■​ Use web.config <authorization> rules to protect entire
pages/folders.
■​ Use User.IsInRole() in code-behind to hide/show UI elements
or control access to specific actions/data (e.g., hide a GridView
column for non-admins).
8.​ Testing and Debugging:​

○​ Run the application in the browser (F5 in Visual Studio).


○​ Use the debugger to step through code and inspect variables.
○​ Test all functionalities: data display, paging, sorting, editing, deleting, login,
etc.

9.​ Deployment:​

○​ Publish the web application to an IIS web server or cloud platform (e.g.,
Azure App Service).

Iterative Development: Web application creation is an iterative process, involving


repeated cycles of design, coding, testing, and refinement.

—------------------------------------------------------------------------------------------------------------------
Unit - V: Grid View Control & XML Classes

MCQ (1 Mark Each)

1.​ Which GridView property must be set to enable deletion and editing features?
a) AllowPaging b) AllowSorting c) DataKeyNames d)
AutoGenerateColumns​

2.​ To automatically display an "Edit" button in each GridView row, which property
should be set to True? a) AutoGenerateDeleteButton b)
AutoGenerateEditButton c) ShowEditButton d) EditMode​

3.​ Which GridView event fires when a user clicks a column header to sort data? a)
PageIndexChanging b) RowEditing c) Sorting d) RowDataBound​

4.​ Which XML class is best suited for loading an entire XML document into memory
and navigating/modifying it like a tree structure? a) XmlReader b) XmlWriter c)
XPathNavigator d) XmlDocument​

5.​ What is the primary method used by XmlDocument to save changes back to an
XML file? a) Update() b) Save() c) Write() d) Commit()​

6.​ Which security vulnerability involves attackers inserting malicious SQL code into
input fields? a) XSS b) CSRF c) SQL Injection d) XXE Injection​

7.​ Which technique is the primary defense against SQL Injection attacks in
ASP.NET? a) Output Encoding b) Input Validation c) Parameterized Queries d)
HTTPS​

8.​ The process of verifying a user's identity is known as: a) Authorization b)


Authentication c) Encryption d) Hashing​

9.​ Which web.config section is typically used to configure access rules based on
user roles or names? a) <connectionStrings> b) <appSettings> c)
<authentication> d) <authorization>​
10.​In ASP.NET Web Forms, where are connection strings for databases most
securely stored? a) Hardcoded in .aspx.cs files b) In web.config c) In
browser cookies d) In JavaScript files​

MCQ Answers:

1.​ c) DataKeyNames
2.​ b) AutoGenerateEditButton
3.​ c) Sorting
4.​ d) XmlDocument
5.​ b) Save()
6.​ c) SQL Injection
7.​ c) Parameterized Queries
8.​ b) Authentication
9.​ d) <authorization>
10.​b) In web.config

5-Mark Questions

1.​ GridView Editing/Deleting Prerequisite: What single GridView property is


essential to enable both its editing and deleting features, and why?​

2.​ XML File Modification: Name two System.Xml or System.Xml.Linq classes


commonly used to modify (add/change/delete nodes) an XML file from an
ASP.NET Web Form.​

3.​ Authentication vs. Authorization: Briefly differentiate between "Authentication"


and "Authorization" in website security.​

4.​ SQL Injection: Define SQL Injection. What is the primary method to prevent it in
ASP.NET?​

10-Mark Questions

1.​ GridView Data Operations: Describe how to enable and manage paging and
sorting for a GridView control in ASP.NET. Mention the key GridView
properties involved.​
2.​ Manipulating XML with Code: Explain the general process for an ASP.NET
Web Form to modify an existing XML file (e.g., changing a value or deleting a
node) using XML classes.​

3.​ Forms Authentication Flow: Outline the typical step-by-step process of how
Forms Authentication works in an ASP.NET web application from user login to
accessing a protected page.​

4.​ Website Security Measures: Discuss three critical security measures for
ASP.NET web applications, focusing on vulnerabilities like SQL Injection, XSS, or
storing sensitive data.

—------------------------------------------------------------------------------------------------------------------

You might also like