0% found this document useful (0 votes)
79 views40 pages

ASPNETPROGRAMMINNGUNIT123

The document outlines the syllabus for the ASP.NET Programming course at Shri Sakthikailassh Women's College for the academic year 2025-2026. It covers the .NET framework, C# fundamentals, and various ASP.NET components, including web forms, file handling, and database operations using ADO.NET. The course aims to equip students with practical skills in web application development through a structured evaluation system.

Uploaded by

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

ASPNETPROGRAMMINNGUNIT123

The document outlines the syllabus for the ASP.NET Programming course at Shri Sakthikailassh Women's College for the academic year 2025-2026. It covers the .NET framework, C# fundamentals, and various ASP.NET components, including web forms, file handling, and database operations using ADO.NET. The course aims to equip students with practical skills in web application development through a structured evaluation system.

Uploaded by

pgcriteria2
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/ 40

SHRI SAKTHIKAILASSH WOMEN’S COLLEGE

(AUTONOMOUS)
SALEM

DEPARTMENT OF COMPUTER APPLICATIONS

SUBJECT NAME: ASP.NET PROGRAMMING

SUBJECT TITLE: 23UCA05

ACADEMIC YEAR
(2025-2026)
ODD SEMSTER
Paper Title ASP.NET PROGRAMMING

Semester Course Code Course Name Category L T P Credits

ASP.NET
V CAP05 PROGRAMMING CORE 5 - - 4

ASP.NET is a web application framework developed by Microsoft for building


dynamic websites and web applications. It supports languages like C# and VB.NET,
offers built-in controls, and provides features like security, state management, and
Preamble rapid development through Visual Studio.
Basic knowledge of HTML, CSS, JavaScript, and programming concepts in C# or
VB.NET. Familiarity with the .NET Framework and Visual Studio is also
Prerequisite recommended.
Course Outcomes(Cos)
Bloom's
Taxonomy
Knowledge
CO Number Course Outcomes(Cos) Statement Level
To identify and understand the goals and objectives of the
CO1 .NET frame work and ASP.NET with C# language. KI
To develop ASP.NET Web application using standard controls.
CO2 K2
To implement file handling operations.
CO3 K2
To handles SQL Server Data base using ADO.NET.
CO4 K3
Understand the Grid view control and XML classes.
CO5 K3

Mapping with Program Outcomes:


Cos/Pos PO1 PO2 PO3 PO4 PO5
CO1 3 1 2 2 1
CO2 3 2 2 2 2
CO3 3 3 2 2 3
CO4 3 1 2 2 1
CO5 3 1 2 2 1

Syllabus
E-Content/
Unit Content HOURS Resources

Overview of .NET Framework:


Common Language Runtime (CLR), Framework
Class Library (FCL)C# Fundamentals:
Primitive Types and Variables – Operators –
Conditional Statements – Looping Statements –
Creating and Using Objects – Arrays – String
I Operations. 15
Introduction to ASP.NET – IDE – Languages supported
– Components – Working with Web Forms – Web Form
standard controls: Properties and its events – HTML
II controls – List Controls: Properties and its events. 15
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
III files–File uploading 15
ADO.NET Overview – Data base Connections –
Commands – Data Reader – Data Adapter – Data Sets
IV – Data Controls and its Properties – Data Binding 15
Grid View control: Deleting, editing, Sorting and
Paging. XML classes Web form to manipulate XML
files – Website Security – Authentication
Authorization– Creating a Web application.
V 15
Total

Note:
1.Svetlin Nakov, Veselin Kolev & Co., Fundamentals of Computer
Programming with C#, Faber Publication, 2019.
2. Mathew MacDonald, The Complete Reference ASP.NET, Tata McGraw-
Text Books 1 Hill, 2015.

1 Herbert Schildt, The Complete Reference C#.NET, Tata McGraw-Hill, 2017.


Kogent Learning Solutions, C# 2012 Programming Covers .NET 4.5 Black
Reference 2 Book, Dreamtech Press, 2013.
Books Anne Boehm, Joel Murach, Murach’s C# 2015, Mike Murach & Associates
3 Inc., 2016.
Denielle Otey, Michael Otey, ADO.NET: The Complete Reference, McGraw-
4 Hill, 2008.

MSDN Magazine – Published by Microsoft, covering ASP.NET, .NET


Journals and Framework, C#, and related development tools.
Magazines
https://www.geeksforgeeks.org/introduction-to-net-framework/
E-Resources and https://www.javatpoint.com/net-framework
Website
Learning Methods

Focus of the Course


Methods of Evaluation

Continuous Internal Assessment


Test
Assignments
25 Marks
Seminar
Attendance and Class
Internal Evaluation participation
External Evaluation End Semester Examinations 75 Marks

Total 100 Marks


MODEL QUESTION PAPER

Time: 3 Hours Maximum :75 Marks

PART-A (15*1 =15 Marks)

(Answer All Questions)

1 TO 3- Unit I

4 TO 6- Unit II

7 TO 9- Unit III

10 TO 12- Unit IV

13 TO 15- Unit V

PART-B (5*2 =10 Marks)

(Answer ANY Two Questions)

16- Unit I

17- Unit II

18- Unit III

19- Unit IV

20- Unit V

PART-C (10*5 =50 Marks)

(Answer ALL Questions)

21. (a) (Or) (b) - Unit I

22. (a) (Or) (b) - Unit II

23. (a) (Or) (b) - Unit III

24. (a) (Or) (b) - Unit IV

22. (a) (Or) (b) - Unit V


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

You might also like