DEPARTMENT OF COMPUTER SCIENCE
[Link] WEB PROGRAMMING
10 Model Question Papers with Answers
Subject Code: CS/IT - [Link]
Total Questions: 5 Questions per Paper (1 per Unit)
Marks per Question: 14 Marks (7+7) each
Total Marks: 70 Marks
No. of Models: 10
Units Covered: Unit I to Unit V
MODEL QUESTION PAPER – 1
Subject: [Link] Web Programming Model: 1 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Explain the architecture of .NET Framework with CLR and FCL.
[7 Marks]
Answer:
The .NET Framework has two main components:
CLR (Common Language Runtime):
• Managed execution environment
• Handles garbage collection, memory management, JIT compilation
• Converts MSIL to native code using JIT compiler
• Provides exception handling, thread management, and security
• Languages like C#, [Link] compile to MSIL which CLR executes
FCL (Framework Class Library):
• Large library of pre-built classes
• Organized into namespaces: System, [Link], [Link], [Link], [Link]
• Supports file I/O, networking, database access, UI development
• Reduces development time by providing reusable components
Execution Flow: Source Code → Compiler → MSIL → CLR (JIT) → Native Code → Execution
1(b). Describe all primitive data types in C# with size and examples.
[7 Marks]
Answer:
C# Primitive Data Types:
bool – 1 bit – true/false – bool flag = true;
byte – 1 byte – 0 to 255 – byte b = 200;
sbyte – 1 byte – -128 to 127
short – 2 bytes – -32768 to 32767
int – 4 bytes – -2.1B to 2.1B – int age = 25;
long – 8 bytes – large integers – long l = 100000L;
float – 4 bytes – 7 digits precision – float f = 3.14f;
double – 8 bytes – 15 digits precision – double d = 3.14159;
decimal – 16 bytes – financial – decimal price = 99.99m;
char – 2 bytes – single Unicode char – char c = 'A';
string – variable – text – string s = "Hello";
object – base type of all types
Variable naming rules:
• Must start with letter or underscore
• Cannot use C# reserved keywords
• Case-sensitive (age ≠ Age)
PART 2 – Unit II – [Link] and Web Forms
2(a). Explain the architecture and features of [Link].
[7 Marks]
Answer:
[Link] Architecture:
[Link] is a server-side web framework built on .NET Framework for building web applications and
services.
Request-Response Cycle:
1. Browser sends HTTP request to IIS server
2. IIS passes request to [Link] runtime
3. [Link] processes the request (runs code-behind)
4. HTML response is generated and sent back to browser
Key Features:
• Web Forms – Drag-and-drop controls, event-driven model
• Code-Behind – Separation of HTML and C# logic
• Master Pages – Consistent page layout
• State Management – ViewState, Session, Cookies
• Cache Support – Improves performance
• Built-in Security – Forms authentication, Windows authentication
• Rich Server Controls – GridView, DetailsView, etc.
[Link] Page Lifecycle:
1. Page_Init – Page and controls initialized
2. Page_Load – Data loaded, IsPostBack checked
3. Event Handling – Button click, etc.
4. Page_PreRender – Before rendering
5. Page_Unload – Cleanup
File Extensions:
• .aspx – Web Form page
• .cs – C# code-behind file
• .config – Configuration file ([Link])
2(b). Describe Visual Studio IDE features for [Link] development.
[7 Marks]
Answer:
Visual Studio IDE for [Link]:
Key Windows/Panels:
• Solution Explorer – Manages project files
• Toolbox – Drag-and-drop server controls
• Properties Window – Configure control properties
• Error List – Compilation errors
• Output Window – Build results
Design Views:
• Design View – Visual drag-and-drop interface
• Source View – HTML/ASPX markup
• Split View – Both simultaneously
Code Editor Features:
• IntelliSense – Auto-completion and suggestions
• Syntax Highlighting – Different colors for keywords
• Code Snippets – Templates for common code
• Refactoring – Rename, extract method
• Debugger – Breakpoints, step over/into, watch window
Built-in Tools:
• IIS Express – Local web server for testing
• NuGet Package Manager – Third-party library management
• Database Explorer – Connect to SQL Server
• Browser Link – Live browser reload
Languages Supported by [Link]:
• C# – Primary language, strongly typed
• [Link] – Visual Basic, readable syntax
• F# – Functional programming
• J# – Deprecated, Java-like syntax
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain Rich Controls in [Link]: Calendar, FileUpload, AdRotator.
[7 Marks]
Answer:
[Link] Rich Controls:
1. Calendar Control:
Displays a monthly calendar.
Properties:
• SelectedDate – Currently selected date
• TodaysDate – Today's date
• SelectionMode (Day/DayWeek/DayWeekMonth/None)
• FirstDayOfWeek
Events: SelectionChanged, VisibleMonthChanged
Example:
protected void cal_SelectionChanged(object sender, EventArgs e) {
[Link] = [Link]();
2. FileUpload Control:
Allows users to upload files to server.
Properties:
• HasFile – true if file selected
• FileName – Name of uploaded file
• PostedFile – The uploaded file object
Usage:
if ([Link])
[Link]([Link]("~/uploads/") + [Link]);
3. AdRotator:
Displays rotating advertisements.
Properties:
• AdvertisementFile – XML file with ad info
• Target – Window to open ad
Events: AdCreated
XML Format:
<Advertisements>
<Ad><ImageUrl>[Link]</ImageUrl><NavigateUrl>[Link]
</Advertisements>
4. MultiView / View:
Creates multiple views in one page.
ActiveViewIndex property switches between views.
5. Wizard Control:
Multi-step form with Next/Back navigation.
3(b). Explain all validation controls in [Link] with examples.
[7 Marks]
Answer:
[Link] Validation Controls:
1. RequiredFieldValidator:
Ensures a field is not empty.
<asp:RequiredFieldValidator ControlToValidate="txtName"
ErrorMessage="Name required!" runat="server" />
2. RangeValidator:
Validates value within min-max range.
Properties: MinimumValue, MaximumValue, Type
Example: Age between 18 and 60.
3. RegularExpressionValidator:
Pattern matching using regex.
Email: ValidationExpression="\\w+@\\w+\\.\\w+"
Mobile: ValidationExpression="^[0-9]{10}$"
4. CompareValidator:
Compares two field values.
Used for password confirmation.
Properties: ControlToCompare, Operator (Equal/GreaterThan/etc.)
5. CustomValidator:
Server-side or client-side custom logic.
Events: ServerValidate
protected void cv_ServerValidate(object src, ServerValidateEventArgs e) {
[Link] = ([Link] > 5);
6. ValidationSummary:
Shows all errors in one place.
Properties: DisplayMode, ShowSummary, ShowMessageBox
Key Properties (all validators):
• ControlToValidate – Target control ID
• ErrorMessage – Message to display
• Display (Static/Dynamic/None)
• IsValid – validation result
[Link] – true only if all validators pass.
PART 4 – Unit IV – [Link] and Database
4(a). Explain [Link] architecture and its components.
[7 Marks]
Answer:
[Link] Architecture:
[Link] (ActiveX Data Objects .NET) is the data access layer in .NET Framework for interacting with
databases.
Two Main Architectures:
1. Connected Architecture:
Requires continuous connection to database.
Components: Connection → Command → DataReader
Best for: Small data reads, quick operations
2. Disconnected Architecture:
Data loaded into memory, connection closed.
Components: Connection → DataAdapter → DataSet
Best for: Large data sets, offline processing
Core [Link] Components:
• Connection (SqlConnection):
Manages database connection
Connection string: "Server=.;Database=myDB;Integrated Security=True;"
• Command (SqlCommand):
Executes SQL: SELECT, INSERT, UPDATE, DELETE
Types: Text, StoredProcedure, TableDirect
• DataReader (SqlDataReader):
Forward-only, read-only data stream
Fast and lightweight
• DataAdapter (SqlDataAdapter):
Bridge between DataSet and database
SelectCommand, InsertCommand, UpdateCommand, DeleteCommand
• DataSet:
In-memory database representation
Contains DataTables, DataRelations, Constraints
• DataTable:
Represents one table of in-memory data
Namespaces:
• [Link] – Core [Link] types
• [Link] – SQL Server provider
• [Link] – Access, Excel provider
4(b). Explain database connections in [Link] with connection string examples.
[7 Marks]
Answer:
Database Connections in [Link]:
SqlConnection Class:
Used to connect to Microsoft SQL Server.
Connection String Formats:
1. Windows Authentication (Integrated Security):
string cs = "Server=localhost;Database=SchoolDB;Integrated Security=True;";
2. SQL Server Authentication:
string cs = "Server=localhost;Database=SchoolDB;User Id=sa;Password=pass123;";
3. Named Instance:
string cs = "Server=PC\\SQLEXPRESS;Database=myDB;Integrated Security=True;";
Opening and Closing Connection:
SqlConnection con = new SqlConnection(connectionString);
try {
[Link]();
// Perform database operations
[Link]("State: " + [Link]); // Open
} catch (SqlException ex) {
[Link]("Error: " + [Link]);
} finally {
[Link](); // Always close in finally
Using Statement (recommended):
using (SqlConnection con = new SqlConnection(cs)) {
[Link]();
// Operations here
} // Auto-closed
ConnectionState Enum:
• Open, Closed, Connecting, Executing, Fetching
Best Practices:
• Store connection string in [Link] <connectionStrings> section
• Always use try-catch-finally
• Use 'using' statement for automatic disposal
• Connection pooling is automatic in [Link]
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Write a complete program for GridView with Edit, Delete, Sort and Page.
[7 Marks]
Answer:
GridView Complete Program:
ASPX:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" PageSize="5"
DataKeyNames="StudentID"
OnSorting="gv_Sorting"
OnPageIndexChanging="gv_PageIndexChanging"
OnRowEditing="gv_RowEditing"
OnRowUpdating="gv_RowUpdating"
OnRowCancelingEdit="gv_RowCancelingEdit"
OnRowDeleting="gv_RowDeleting">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Marks" HeaderText="Marks" SortExpression="Marks" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
C# Code-Behind:
protected void BindGrid() {
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", cs);
DataTable dt = new DataTable();
[Link](dt);
[Link] = dt;
[Link]();
}
protected void gv_PageIndexChanging(object s, GridViewPageEventArgs e) {
[Link] = [Link]; BindGrid();
protected void gv_RowEditing(object s, GridViewEditEventArgs e) {
[Link] = [Link]; BindGrid();
protected void gv_RowCancelingEdit(object s, GridViewCancelEditEventArgs e) {
[Link] = -1; BindGrid();
protected void gv_RowUpdating(object s, GridViewUpdateEventArgs e) {
string name = ((TextBox)[Link][[Link]].Cells[0].Controls[0]).Text;
// Execute UPDATE SQL
[Link] = -1; BindGrid();
protected void gv_RowDeleting(object s, GridViewDeleteEventArgs e) {
int id = (int)[Link][[Link]].Value;
// Execute DELETE SQL WHERE StudentID = id
BindGrid();
5(b). Explain XML classes in .NET for reading and writing XML.
[7 Marks]
Answer:
XML in .NET Framework:
Key XML Classes ([Link] namespace):
1. XmlDocument:
DOM-based approach (loads entire XML into memory).
Reading XML:
XmlDocument doc = new XmlDocument();
[Link]([Link]("[Link]"));
XmlNodeList nodes = [Link]("Student");
foreach (XmlNode node in nodes) {
string name = node["Name"].InnerText;
string marks = node["Marks"].InnerText;
[Link](name + " - " + marks + "<br/>");
Creating XML:
XmlDocument doc = new XmlDocument();
XmlElement root = [Link]("Students");
XmlElement student = [Link]("Student");
[Link]("ID", "1");
XmlElement name = [Link]("Name");
[Link] = "Alice";
[Link](name);
[Link](student);
[Link](root);
[Link]([Link]("[Link]"));
2. XmlReader (forward-only reading, fast):
using (XmlReader reader = [Link]("[Link]")) {
while ([Link]()) {
if ([Link] == [Link])
[Link]([Link]);
3. XmlWriter (forward-only writing):
using (XmlWriter writer = [Link]("[Link]")) {
[Link]();
[Link]("Root");
[Link]("Name", "Alice");
[Link]();
[Link]();
— End of Model 1 —
MODEL QUESTION PAPER – 2
Subject: [Link] Web Programming Model: 2 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Describe all primitive data types in C# with size and examples.
[7 Marks]
Answer:
C# Primitive Data Types:
bool – 1 bit – true/false – bool flag = true;
byte – 1 byte – 0 to 255 – byte b = 200;
sbyte – 1 byte – -128 to 127
short – 2 bytes – -32768 to 32767
int – 4 bytes – -2.1B to 2.1B – int age = 25;
long – 8 bytes – large integers – long l = 100000L;
float – 4 bytes – 7 digits precision – float f = 3.14f;
double – 8 bytes – 15 digits precision – double d = 3.14159;
decimal – 16 bytes – financial – decimal price = 99.99m;
char – 2 bytes – single Unicode char – char c = 'A';
string – variable – text – string s = "Hello";
object – base type of all types
Variable naming rules:
• Must start with letter or underscore
• Cannot use C# reserved keywords
• Case-sensitive (age ≠ Age)
1(b). Explain different types of operators in C# with examples.
[7 Marks]
Answer:
C# Operators:
1. Arithmetic Operators: +, -, *, /, %
int a=10, b=3; a/b=3, a%b=1
2. Relational Operators: ==, !=, >, <, >=, <=
Return bool: (5 > 3) → true
3. Logical Operators: && (AND), || (OR), ! (NOT)
Used to combine boolean expressions
4. Assignment Operators: =, +=, -=, *=, /=, %=
a += 5 means a = a + 5
5. Increment/Decrement: ++, --
Pre: ++a (increment then use)
Post: a++ (use then increment)
6. Bitwise Operators: &, |, ^, ~, <<, >>
Operate on binary representation
7. Ternary Operator: condition ? true_val : false_val
int max = (a > b) ? a : b;
8. typeof and sizeof operators
sizeof(int) returns 4
PART 2 – Unit II – [Link] and Web Forms
2(a). Describe Visual Studio IDE features for [Link] development.
[7 Marks]
Answer:
Visual Studio IDE for [Link]:
Key Windows/Panels:
• Solution Explorer – Manages project files
• Toolbox – Drag-and-drop server controls
• Properties Window – Configure control properties
• Error List – Compilation errors
• Output Window – Build results
Design Views:
• Design View – Visual drag-and-drop interface
• Source View – HTML/ASPX markup
• Split View – Both simultaneously
Code Editor Features:
• IntelliSense – Auto-completion and suggestions
• Syntax Highlighting – Different colors for keywords
• Code Snippets – Templates for common code
• Refactoring – Rename, extract method
• Debugger – Breakpoints, step over/into, watch window
Built-in Tools:
• IIS Express – Local web server for testing
• NuGet Package Manager – Third-party library management
• Database Explorer – Connect to SQL Server
• Browser Link – Live browser reload
Languages Supported by [Link]:
• C# – Primary language, strongly typed
• [Link] – Visual Basic, readable syntax
• F# – Functional programming
• J# – Deprecated, Java-like syntax
2(b). Explain the Web Forms model in [Link] including page lifecycle.
[7 Marks]
Answer:
[Link] Web Forms:
Web Forms is an event-driven model for building web applications, similar to Windows Forms.
Page Structure (.aspx file):
<%@ Page Language="C#" CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form runat="server">
<!-- Server controls go here -->
</form>
</body>
</html>
Code-Behind (.[Link] file):
public partial class Default : [Link] {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
[Link] = "Welcome!";
PostBack:
• When user submits form, page posts back to server
• IsPostBack property is true on subsequent requests
• ViewState preserves control values across postbacks
Page Lifecycle Events:
1. PreInit – Set master page, themes
2. Init – Initialize controls
3. InitComplete – Initialization complete
4. PreLoad – Before Load
5. Load – Page_Load fires here
6. Control Events – Button_Click etc.
7. PreRender – Last chance to modify output
8. Render – HTML is generated
9. Unload – Cleanup resources
AutoPostBack – Controls like DropDownList post back automatically when changed.
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain all validation controls in [Link] with examples.
[7 Marks]
Answer:
[Link] Validation Controls:
1. RequiredFieldValidator:
Ensures a field is not empty.
<asp:RequiredFieldValidator ControlToValidate="txtName"
ErrorMessage="Name required!" runat="server" />
2. RangeValidator:
Validates value within min-max range.
Properties: MinimumValue, MaximumValue, Type
Example: Age between 18 and 60.
3. RegularExpressionValidator:
Pattern matching using regex.
Email: ValidationExpression="\\w+@\\w+\\.\\w+"
Mobile: ValidationExpression="^[0-9]{10}$"
4. CompareValidator:
Compares two field values.
Used for password confirmation.
Properties: ControlToCompare, Operator (Equal/GreaterThan/etc.)
5. CustomValidator:
Server-side or client-side custom logic.
Events: ServerValidate
protected void cv_ServerValidate(object src, ServerValidateEventArgs e) {
[Link] = ([Link] > 5);
6. ValidationSummary:
Shows all errors in one place.
Properties: DisplayMode, ShowSummary, ShowMessageBox
Key Properties (all validators):
• ControlToValidate – Target control ID
• ErrorMessage – Message to display
• Display (Static/Dynamic/None)
• IsValid – validation result
[Link] – true only if all validators pass.
3(b). Explain FileStream, StreamReader and StreamWriter with examples.
[7 Marks]
Answer:
File Handling in C# ([Link] Namespace):
1. FileStream Class:
Provides byte-level file access.
Constructor: FileStream(path, FileMode, FileAccess)
FileAccess: Read, Write, ReadWrite
Example – Write bytes:
FileStream fs = new FileStream("[Link]", [Link], [Link]);
byte[] data = {65, 66, 67}; // ABC
[Link](data, 0, [Link]);
[Link]();
2. StreamWriter Class:
Writes text to files.
Example:
StreamWriter sw = new StreamWriter("[Link]");
[Link]("Hello World");
[Link]("[Link] Programming");
[Link]();
Using statement (auto-closes):
using (StreamWriter sw = new StreamWriter("[Link]")) {
[Link]("Content here");
}
3. StreamReader Class:
Reads text from files.
Example:
StreamReader sr = new StreamReader("[Link]");
string line;
while ((line = [Link]()) != null)
[Link](line);
[Link]();
ReadToEnd() – reads entire file as string:
string content = [Link]();
Note: Always close streams in finally block or use 'using' statement to free resources.
PART 4 – Unit IV – [Link] and Database
4(a). Explain database connections in [Link] with connection string examples.
[7 Marks]
Answer:
Database Connections in [Link]:
SqlConnection Class:
Used to connect to Microsoft SQL Server.
Connection String Formats:
1. Windows Authentication (Integrated Security):
string cs = "Server=localhost;Database=SchoolDB;Integrated Security=True;";
2. SQL Server Authentication:
string cs = "Server=localhost;Database=SchoolDB;User Id=sa;Password=pass123;";
3. Named Instance:
string cs = "Server=PC\\SQLEXPRESS;Database=myDB;Integrated Security=True;";
Opening and Closing Connection:
SqlConnection con = new SqlConnection(connectionString);
try {
[Link]();
// Perform database operations
[Link]("State: " + [Link]); // Open
} catch (SqlException ex) {
[Link]("Error: " + [Link]);
} finally {
[Link](); // Always close in finally
Using Statement (recommended):
using (SqlConnection con = new SqlConnection(cs)) {
[Link]();
// Operations here
} // Auto-closed
ConnectionState Enum:
• Open, Closed, Connecting, Executing, Fetching
Best Practices:
• Store connection string in [Link] <connectionStrings> section
• Always use try-catch-finally
• Use 'using' statement for automatic disposal
• Connection pooling is automatic in [Link]
4(b). Explain SqlCommand class with ExecuteReader, ExecuteNonQuery and
ExecuteScalar.
[7 Marks]
Answer:
SqlCommand in [Link]:
SqlCommand executes SQL statements against SQL Server.
Creating Command:
SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con);
// or
[Link] = "INSERT INTO Students VALUES(@name, @age)";
[Link] = [Link];
CommandType Enum:
• Text – SQL string (default)
• StoredProcedure – Calls a stored procedure
• TableDirect – Returns entire table
1. ExecuteReader():
Returns SqlDataReader for SELECT queries.
SqlDataReader dr = [Link]();
while ([Link]()) {
[Link](dr["Name"] + " " + dr["Age"]);
[Link]();
2. ExecuteNonQuery():
For INSERT, UPDATE, DELETE. Returns rows affected.
[Link] = "DELETE FROM Students WHERE ID=@id";
[Link]("@id", 5);
int rows = [Link]();
[Link](rows + " row(s) deleted.");
3. ExecuteScalar():
Returns single value (first row, first column).
[Link] = "SELECT COUNT(*) FROM Students";
int count = (int)[Link]();
Parameters (prevent SQL Injection):
[Link]("@name", [Link]);
[Link]("@age", [Link]).Value = 20;
Always use parameters instead of string concatenation!
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Explain XML classes in .NET for reading and writing XML.
[7 Marks]
Answer:
XML in .NET Framework:
Key XML Classes ([Link] namespace):
1. XmlDocument:
DOM-based approach (loads entire XML into memory).
Reading XML:
XmlDocument doc = new XmlDocument();
[Link]([Link]("[Link]"));
XmlNodeList nodes = [Link]("Student");
foreach (XmlNode node in nodes) {
string name = node["Name"].InnerText;
string marks = node["Marks"].InnerText;
[Link](name + " - " + marks + "<br/>");
Creating XML:
XmlDocument doc = new XmlDocument();
XmlElement root = [Link]("Students");
XmlElement student = [Link]("Student");
[Link]("ID", "1");
XmlElement name = [Link]("Name");
[Link] = "Alice";
[Link](name);
[Link](student);
[Link](root);
[Link]([Link]("[Link]"));
2. XmlReader (forward-only reading, fast):
using (XmlReader reader = [Link]("[Link]")) {
while ([Link]()) {
if ([Link] == [Link])
[Link]([Link]);
3. XmlWriter (forward-only writing):
using (XmlWriter writer = [Link]("[Link]")) {
[Link]();
[Link]("Root");
[Link]("Name", "Alice");
[Link]();
[Link]();
5(b). Write an [Link] program to add, display and delete XML records.
[7 Marks]
Answer:
XML Manipulation using Web Forms:
[Link] structure:
<Students>
<Student>
<ID>1</ID>
<Name>Alice</Name>
<Marks>90</Marks>
</Student>
</Students>
[Link]:
<asp:TextBox ID="txtName" runat="server" />
<asp:TextBox ID="txtMarks" runat="server" />
<asp:Button ID="btnAdd" Text="Add" OnClick="btnAdd_Click" runat="server" />
<asp:Button ID="btnLoad" Text="Load" OnClick="btnLoad_Click" runat="server" />
<asp:GridView ID="gvStudents" runat="server" />
Code-Behind:
string xmlPath;
protected void Page_Load(object sender, EventArgs e) {
xmlPath = [Link]("~/App_Data/[Link]");
protected void btnAdd_Click(object sender, EventArgs e) {
XmlDocument doc = new XmlDocument();
if ([Link](xmlPath)) [Link](xmlPath);
else [Link]([Link]("Students"));
XmlElement s = [Link]("Student");
XmlElement nm = [Link]("Name");
[Link] = [Link];
XmlElement mk = [Link]("Marks");
[Link] = [Link];
[Link](nm); [Link](mk);
[Link](s);
[Link](xmlPath);
[Link] = "Record added!";
protected void btnLoad_Click(object sender, EventArgs e) {
DataSet ds = new DataSet();
[Link](xmlPath);
[Link] = ds;
[Link]();
— End of Model 2 —
MODEL QUESTION PAPER – 3
Subject: [Link] Web Programming Model: 3 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Explain different types of operators in C# with examples.
[7 Marks]
Answer:
C# Operators:
1. Arithmetic Operators: +, -, *, /, %
int a=10, b=3; a/b=3, a%b=1
2. Relational Operators: ==, !=, >, <, >=, <=
Return bool: (5 > 3) → true
3. Logical Operators: && (AND), || (OR), ! (NOT)
Used to combine boolean expressions
4. Assignment Operators: =, +=, -=, *=, /=, %=
a += 5 means a = a + 5
5. Increment/Decrement: ++, --
Pre: ++a (increment then use)
Post: a++ (use then increment)
6. Bitwise Operators: &, |, ^, ~, <<, >>
Operate on binary representation
7. Ternary Operator: condition ? true_val : false_val
int max = (a > b) ? a : b;
8. typeof and sizeof operators
sizeof(int) returns 4
1(b). Write a C# program using all types of conditional statements.
[7 Marks]
Answer:
Conditional Statements in C#:
1. Simple if:
if (age >= 18)
[Link]("Adult");
2. if-else:
if (marks >= 50)
[Link]("Pass");
else
[Link]("Fail");
3. if-else if-else ladder:
if (marks >= 90) grade = 'A';
else if (marks >= 80) grade = 'B';
else if (marks >= 70) grade = 'C';
else grade = 'D';
4. Nested if:
if (gender == 'M')
if (age > 60) [Link]("Senior Male");
5. switch-case:
switch (day) {
case 1: [Link]("Mon"); break;
case 2: [Link]("Tue"); break;
default: [Link]("Unknown"); break;
Note: switch works with int, char, string, enum types.
PART 2 – Unit II – [Link] and Web Forms
2(a). Explain the Web Forms model in [Link] including page lifecycle.
[7 Marks]
Answer:
[Link] Web Forms:
Web Forms is an event-driven model for building web applications, similar to Windows Forms.
Page Structure (.aspx file):
<%@ Page Language="C#" CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form runat="server">
<!-- Server controls go here -->
</form>
</body>
</html>
Code-Behind (.[Link] file):
public partial class Default : [Link] {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
[Link] = "Welcome!";
PostBack:
• When user submits form, page posts back to server
• IsPostBack property is true on subsequent requests
• ViewState preserves control values across postbacks
Page Lifecycle Events:
1. PreInit – Set master page, themes
2. Init – Initialize controls
3. InitComplete – Initialization complete
4. PreLoad – Before Load
5. Load – Page_Load fires here
6. Control Events – Button_Click etc.
7. PreRender – Last chance to modify output
8. Render – HTML is generated
9. Unload – Cleanup resources
AutoPostBack – Controls like DropDownList post back automatically when changed.
2(b). List and explain all standard [Link] server controls with properties and events.
[7 Marks]
Answer:
[Link] Standard Server Controls:
1. TextBox:
Properties: Text, TextMode, MaxLength, Columns, Rows, ReadOnly
Events: TextChanged (fires on postback)
2. Button / LinkButton / ImageButton:
Properties: Text, CommandName, CommandArgument
Events: Click, Command
3. Label:
Properties: Text, ForeColor, BackColor, Font, Visible
4. HyperLink:
Properties: Text, NavigateUrl, Target, ImageUrl
5. Image:
Properties: ImageUrl, AlternateText, Width, Height
6. CheckBox:
Properties: Text, Checked, TextAlign, AutoPostBack
Events: CheckedChanged
7. RadioButton:
Properties: Text, GroupName, Checked, AutoPostBack
Events: CheckedChanged
8. DropDownList:
Properties: Items, SelectedIndex, SelectedValue, SelectedItem
Events: SelectedIndexChanged
9. ListBox:
Properties: Items, SelectionMode (Single/Multiple), Rows
Events: SelectedIndexChanged
10. Panel:
Properties: GroupingText, ScrollBars, Visible
Used as container for other controls
11. PlaceHolder:
Holds dynamically added controls
All server controls have runat="server" attribute.
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain FileStream, StreamReader and StreamWriter with examples.
[7 Marks]
Answer:
File Handling in C# ([Link] Namespace):
1. FileStream Class:
Provides byte-level file access.
Constructor: FileStream(path, FileMode, FileAccess)
FileAccess: Read, Write, ReadWrite
Example – Write bytes:
FileStream fs = new FileStream("[Link]", [Link], [Link]);
byte[] data = {65, 66, 67}; // ABC
[Link](data, 0, [Link]);
[Link]();
2. StreamWriter Class:
Writes text to files.
Example:
StreamWriter sw = new StreamWriter("[Link]");
[Link]("Hello World");
[Link]("[Link] Programming");
[Link]();
Using statement (auto-closes):
using (StreamWriter sw = new StreamWriter("[Link]")) {
[Link]("Content here");
3. StreamReader Class:
Reads text from files.
Example:
StreamReader sr = new StreamReader("[Link]");
string line;
while ((line = [Link]()) != null)
[Link](line);
[Link]();
ReadToEnd() – reads entire file as string:
string content = [Link]();
Note: Always close streams in finally block or use 'using' statement to free resources.
3(b). Explain FileMode, FileAccess and FileShare enumerations.
[7 Marks]
Answer:
File Enumeration Types in C#:
FileMode Enumeration:
Used in FileStream constructor to specify how to open a file.
• [Link]:
Creates new file. Overwrites if already exists. (Equivalent to CreateNew + Truncate)
• [Link]:
Creates new file only. Throws IOException if file exists.
• [Link]:
Opens existing file. Throws FileNotFoundException if not found.
• [Link]:
Opens if exists, creates if not. Good for append scenarios.
• [Link]:
Opens file for appending. Creates if not found. Seek only at end.
• [Link]:
Opens existing file and truncates to zero length. Write-only.
FileAccess Enumeration:
• Read – Can only read file
• Write – Can only write to file
• ReadWrite – Can read and write
FileShare Enumeration:
Controls concurrent access by other processes:
• None – No sharing, exclusive access
• Read – Other processes can read
• Write – Other processes can write
• ReadWrite – Others can read and write
• Delete – Others can delete
• Inheritable – File handle can be inherited by child processes
Example:
FileStream fs = new FileStream("[Link]", [Link], [Link], [Link]);
// Appends to file while allowing others to read simultaneously
PART 4 – Unit IV – [Link] and Database
4(a). Explain SqlCommand class with ExecuteReader, ExecuteNonQuery and
ExecuteScalar.
[7 Marks]
Answer:
SqlCommand in [Link]:
SqlCommand executes SQL statements against SQL Server.
Creating Command:
SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con);
// or
[Link] = "INSERT INTO Students VALUES(@name, @age)";
[Link] = [Link];
CommandType Enum:
• Text – SQL string (default)
• StoredProcedure – Calls a stored procedure
• TableDirect – Returns entire table
1. ExecuteReader():
Returns SqlDataReader for SELECT queries.
SqlDataReader dr = [Link]();
while ([Link]()) {
[Link](dr["Name"] + " " + dr["Age"]);
[Link]();
2. ExecuteNonQuery():
For INSERT, UPDATE, DELETE. Returns rows affected.
[Link] = "DELETE FROM Students WHERE ID=@id";
[Link]("@id", 5);
int rows = [Link]();
[Link](rows + " row(s) deleted.");
3. ExecuteScalar():
Returns single value (first row, first column).
[Link] = "SELECT COUNT(*) FROM Students";
int count = (int)[Link]();
Parameters (prevent SQL Injection):
[Link]("@name", [Link]);
[Link]("@age", [Link]).Value = 20;
Always use parameters instead of string concatenation!
4(b). Explain SqlDataReader with a complete program to display data.
[7 Marks]
Answer:
SqlDataReader in [Link]:
SqlDataReader provides fast, forward-only, read-only access to query results (connected mode).
Characteristics:
• Reads one row at a time
• Very fast and memory efficient
• Connection must remain open while reading
• Cannot go backwards or jump to random row
Complete Program:
protected void Page_Load(object sender, EventArgs e) {
string cs = [Link]["myCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs)) {
[Link]();
SqlCommand cmd = new SqlCommand(
"SELECT StudentID, Name, Marks FROM Students", con);
SqlDataReader dr = [Link]();
// Bind to GridView
[Link] = dr;
[Link]();
[Link]();
Accessing Columns:
• By index: dr[0]
• By name: dr["Name"]
• By typed method: [Link](1), dr.GetInt32(2)
Multiple Result Sets:
[Link] = "SELECT * FROM T1; SELECT * FROM T2";
SqlDataReader dr = [Link]();
do {
while ([Link]()) { /* process rows */ }
} while ([Link]());
Useful Properties:
• [Link] – true if result has rows
• [Link] – number of columns
• [Link] – connection state
• [Link](i) – column name
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Write an [Link] program to add, display and delete XML records.
[7 Marks]
Answer:
XML Manipulation using Web Forms:
[Link] structure:
<Students>
<Student>
<ID>1</ID>
<Name>Alice</Name>
<Marks>90</Marks>
</Student>
</Students>
[Link]:
<asp:TextBox ID="txtName" runat="server" />
<asp:TextBox ID="txtMarks" runat="server" />
<asp:Button ID="btnAdd" Text="Add" OnClick="btnAdd_Click" runat="server" />
<asp:Button ID="btnLoad" Text="Load" OnClick="btnLoad_Click" runat="server" />
<asp:GridView ID="gvStudents" runat="server" />
Code-Behind:
string xmlPath;
protected void Page_Load(object sender, EventArgs e) {
xmlPath = [Link]("~/App_Data/[Link]");
protected void btnAdd_Click(object sender, EventArgs e) {
XmlDocument doc = new XmlDocument();
if ([Link](xmlPath)) [Link](xmlPath);
else [Link]([Link]("Students"));
XmlElement s = [Link]("Student");
XmlElement nm = [Link]("Name");
[Link] = [Link];
XmlElement mk = [Link]("Marks");
[Link] = [Link];
[Link](nm); [Link](mk);
[Link](s);
[Link](xmlPath);
[Link] = "Record added!";
protected void btnLoad_Click(object sender, EventArgs e) {
DataSet ds = new DataSet();
[Link](xmlPath);
[Link] = ds;
[Link]();
}
5(b). Explain Website Security, Authentication and Authorization in [Link].
[7 Marks]
Answer:
[Link] Website Security:
Authentication – Verifying WHO the user is.
Authorization – Verifying WHAT the user can access.
1. Forms Authentication:
Most common for web apps. Login form stores credentials.
[Link] setup:
<authentication mode="Forms">
<forms loginUrl="~/[Link]" timeout="30" />
</authentication>
<authorization>
<deny users="?" /> <!-- deny anonymous -->
</authorization>
Login Code:
if ([Link](username, password))
[Link](username, false);
Logout:
[Link]();
[Link]("[Link]");
2. Windows Authentication:
Uses Windows OS credentials.
<authentication mode="Windows" />
Good for intranet applications.
3. Role-Based Authorization:
Restrict pages by role:
<location path="Admin">
<[Link]>
<authorization>
<allow roles="Admin" />
<deny users="*" />
</authorization>
</[Link]>
</location>
Check role in code:
if ([Link]("Admin"))
[Link] = true;
4. Membership and Login Controls:
• Login – Username/password form
• LoginView – Content based on login state
• PasswordRecovery – Reset password
• CreateUserWizard – Registration
5. SSL/HTTPS: Encrypts data in transit.
— End of Model 3 —
MODEL QUESTION PAPER – 4
Subject: [Link] Web Programming Model: 4 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Write a C# program using all types of conditional statements.
[7 Marks]
Answer:
Conditional Statements in C#:
1. Simple if:
if (age >= 18)
[Link]("Adult");
2. if-else:
if (marks >= 50)
[Link]("Pass");
else
[Link]("Fail");
3. if-else if-else ladder:
if (marks >= 90) grade = 'A';
else if (marks >= 80) grade = 'B';
else if (marks >= 70) grade = 'C';
else grade = 'D';
4. Nested if:
if (gender == 'M')
if (age > 60) [Link]("Senior Male");
5. switch-case:
switch (day) {
case 1: [Link]("Mon"); break;
case 2: [Link]("Tue"); break;
default: [Link]("Unknown"); break;
Note: switch works with int, char, string, enum types.
1(b). Compare for, while, do-while and foreach loops in C#.
[7 Marks]
Answer:
Loops in C#:
1. for loop – known iterations:
for (int i=0; i<5; i++)
[Link](i);
Structure: initialization; condition; increment
2. while loop – condition checked before:
int i = 0;
while (i < 5) { [Link](i); i++; }
May not execute if condition is false initially
3. do-while loop – executes at least once:
int i = 0;
do { [Link](i); i++; } while (i < 5);
4. foreach loop – iterates over collections:
int[] arr = {1,2,3,4,5};
foreach (int x in arr)
[Link](x);
Comparison:
• for: best when count is known
• while: best when condition-based
• do-while: best when at least one execution needed
• foreach: best for arrays/collections, no index manipulation
Break and Continue:
• break – exits the loop
• continue – skips current iteration
PART 2 – Unit II – [Link] and Web Forms
2(a). List and explain all standard [Link] server controls with properties and events.
[7 Marks]
Answer:
[Link] Standard Server Controls:
1. TextBox:
Properties: Text, TextMode, MaxLength, Columns, Rows, ReadOnly
Events: TextChanged (fires on postback)
2. Button / LinkButton / ImageButton:
Properties: Text, CommandName, CommandArgument
Events: Click, Command
3. Label:
Properties: Text, ForeColor, BackColor, Font, Visible
4. HyperLink:
Properties: Text, NavigateUrl, Target, ImageUrl
5. Image:
Properties: ImageUrl, AlternateText, Width, Height
6. CheckBox:
Properties: Text, Checked, TextAlign, AutoPostBack
Events: CheckedChanged
7. RadioButton:
Properties: Text, GroupName, Checked, AutoPostBack
Events: CheckedChanged
8. DropDownList:
Properties: Items, SelectedIndex, SelectedValue, SelectedItem
Events: SelectedIndexChanged
9. ListBox:
Properties: Items, SelectionMode (Single/Multiple), Rows
Events: SelectedIndexChanged
10. Panel:
Properties: GroupingText, ScrollBars, Visible
Used as container for other controls
11. PlaceHolder:
Holds dynamically added controls
All server controls have runat="server" attribute.
2(b). Explain HTML server controls in [Link].
[7 Marks]
Answer:
HTML Server Controls:
HTML controls are standard HTML elements with runat="server" attribute added, making them accessible
from server-side code.
Converting HTML to Server Control:
<input type="text" id="txtName" runat="server" />
Now accessible as: [Link]
Common HTML Server Controls:
1. HtmlInputText:
<input type="text" id="txt1" runat="server" />
Properties: Value, MaxLength, Size, ReadOnly
2. HtmlInputButton:
<input type="button" id="btn1" runat="server" />
Events: ServerClick
3. HtmlInputCheckBox:
<input type="checkbox" id="chk1" runat="server" />
Properties: Checked, Value
4. HtmlInputRadioButton:
<input type="radio" id="rb1" runat="server" />
Properties: Checked, Value, Name (for grouping)
5. HtmlSelect:
<select id="sel1" runat="server"></select>
Properties: Items, SelectedIndex, Multiple
6. HtmlTextArea:
<textarea id="ta1" runat="server"></textarea>
Properties: Value, Rows, Cols
7. HtmlAnchor:
<a id="lnk1" runat="server">Click</a>
Properties: HRef, Target
Difference from [Link] Server Controls:
• HTML controls map directly to HTML elements
• Less overhead, simpler model
• [Link] controls provide richer functionality
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain FileMode, FileAccess and FileShare enumerations.
[7 Marks]
Answer:
File Enumeration Types in C#:
FileMode Enumeration:
Used in FileStream constructor to specify how to open a file.
• [Link]:
Creates new file. Overwrites if already exists. (Equivalent to CreateNew + Truncate)
• [Link]:
Creates new file only. Throws IOException if file exists.
• [Link]:
Opens existing file. Throws FileNotFoundException if not found.
• [Link]:
Opens if exists, creates if not. Good for append scenarios.
• [Link]:
Opens file for appending. Creates if not found. Seek only at end.
• [Link]:
Opens existing file and truncates to zero length. Write-only.
FileAccess Enumeration:
• Read – Can only read file
• Write – Can only write to file
• ReadWrite – Can read and write
FileShare Enumeration:
Controls concurrent access by other processes:
• None – No sharing, exclusive access
• Read – Other processes can read
• Write – Other processes can write
• ReadWrite – Others can read and write
• Delete – Others can delete
• Inheritable – File handle can be inherited by child processes
Example:
FileStream fs = new FileStream("[Link]", [Link], [Link], [Link]);
// Appends to file while allowing others to read simultaneously
3(b). Write programs to read from and write to files in C#.
[7 Marks]
Answer:
File Operations in C#:
Writing to a File:
Method 1 – StreamWriter:
using (StreamWriter writer = new StreamWriter("[Link]")) {
[Link]("Roll No, Name, Marks");
[Link]("1, Alice, 90");
[Link]("2, Bob, 85");
}
Method 2 – File class shortcut:
[Link]("[Link]", "Hello World");
[Link]("[Link]", [Link] + "\n");
Reading from a File:
Method 1 – StreamReader:
using (StreamReader reader = new StreamReader("[Link]")) {
string line;
while ((line = [Link]()) != null)
[Link](line);
Method 2 – ReadToEnd:
string content = [Link]("[Link]");
[Link](content);
Method 3 – Read all lines:
string[] lines = [Link]("[Link]");
foreach (string line in lines)
[Link](line);
Check if file exists:
if ([Link]("[Link]"))
[Link]("File found!");
[Link]() – appends multiple lines.
[Link]() – reads binary files.
[Link]() – writes binary files.
PART 4 – Unit IV – [Link] and Database
4(a). Explain SqlDataReader with a complete program to display data.
[7 Marks]
Answer:
SqlDataReader in [Link]:
SqlDataReader provides fast, forward-only, read-only access to query results (connected mode).
Characteristics:
• Reads one row at a time
• Very fast and memory efficient
• Connection must remain open while reading
• Cannot go backwards or jump to random row
Complete Program:
protected void Page_Load(object sender, EventArgs e) {
string cs = [Link]["myCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs)) {
[Link]();
SqlCommand cmd = new SqlCommand(
"SELECT StudentID, Name, Marks FROM Students", con);
SqlDataReader dr = [Link]();
// Bind to GridView
[Link] = dr;
[Link]();
[Link]();
Accessing Columns:
• By index: dr[0]
• By name: dr["Name"]
• By typed method: [Link](1), dr.GetInt32(2)
Multiple Result Sets:
[Link] = "SELECT * FROM T1; SELECT * FROM T2";
SqlDataReader dr = [Link]();
do {
while ([Link]()) { /* process rows */ }
} while ([Link]());
Useful Properties:
• [Link] – true if result has rows
• [Link] – number of columns
• [Link] – connection state
• [Link](i) – column name
4(b). Explain DataAdapter and DataSet with CRUD operations.
[7 Marks]
Answer:
DataAdapter and DataSet:
Disconnected Architecture Pattern:
Connection → DataAdapter → DataSet → (work offline) → DataAdapter → Database
Loading Data into DataSet:
string cs = "Server=.;Database=SchoolDB;Integrated Security=True;";
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", con);
DataSet ds = new DataSet();
[Link](ds, "Students"); // fills DataTable named "Students"
// Bind to GridView
[Link] = [Link]["Students"];
[Link]();
DataTable Access:
DataTable dt = [Link]["Students"];
foreach (DataRow row in [Link]) {
[Link](row["Name"] + " - " + row["Marks"]);
Insert Row:
DataRow newRow = [Link]();
newRow["Name"] = "Alice";
newRow["Marks"] = 90;
[Link](newRow);
Update with SqlCommandBuilder:
SqlCommandBuilder builder = new SqlCommandBuilder(da);
[Link](ds, "Students"); // syncs changes back to DB
DataSet Features:
• Multiple tables: [Link][0], [Link]["Name"]
• Relations between tables: [Link]
• Filtered/sorted views: DataView
DataView for filtering:
DataView dv = new DataView(dt);
[Link] = "Marks > 80";
[Link] = "Name ASC";
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Explain Website Security, Authentication and Authorization in [Link].
[7 Marks]
Answer:
[Link] Website Security:
Authentication – Verifying WHO the user is.
Authorization – Verifying WHAT the user can access.
1. Forms Authentication:
Most common for web apps. Login form stores credentials.
[Link] setup:
<authentication mode="Forms">
<forms loginUrl="~/[Link]" timeout="30" />
</authentication>
<authorization>
<deny users="?" /> <!-- deny anonymous -->
</authorization>
Login Code:
if ([Link](username, password))
[Link](username, false);
Logout:
[Link]();
[Link]("[Link]");
2. Windows Authentication:
Uses Windows OS credentials.
<authentication mode="Windows" />
Good for intranet applications.
3. Role-Based Authorization:
Restrict pages by role:
<location path="Admin">
<[Link]>
<authorization>
<allow roles="Admin" />
<deny users="*" />
</authorization>
</[Link]>
</location>
Check role in code:
if ([Link]("Admin"))
[Link] = true;
4. Membership and Login Controls:
• Login – Username/password form
• LoginView – Content based on login state
• PasswordRecovery – Reset password
• CreateUserWizard – Registration
5. SSL/HTTPS: Encrypts data in transit.
5(b). Write a complete Login page using Forms Authentication.
[7 Marks]
Answer:
Forms Authentication Implementation:
[Link]:
<connectionStrings>
<add name="myCS" connectionString="Server=.;Database=UsersDB;Integrated Security=True;" />
</connectionStrings>
<[Link]>
<authentication mode="Forms">
<forms loginUrl="~/[Link]" timeout="60" name=".ASPXAUTH" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</[Link]>
[Link]:
<asp:TextBox ID="txtUser" runat="server" />
<asp:TextBox ID="txtPass" TextMode="Password" runat="server" />
<asp:Button ID="btnLogin" Text="Login" OnClick="btnLogin_Click" runat="server" />
<asp:Label ID="lblMsg" ForeColor="Red" runat="server" />
[Link]:
protected void btnLogin_Click(object sender, EventArgs e) {
string cs = [Link]["myCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs)) {
SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) FROM Users WHERE Username=@u AND Password=@p", con);
[Link]("@u", [Link]);
[Link]("@p", [Link]);
[Link]();
int count = (int)[Link]();
if (count > 0) {
[Link]([Link], false);
} else {
[Link] = "Invalid username or password!";
Logout button on any page:
[Link]();
[Link]();
[Link]("~/[Link]");
— End of Model 4 —
MODEL QUESTION PAPER – 5
Subject: [Link] Web Programming Model: 5 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Compare for, while, do-while and foreach loops in C#.
[7 Marks]
Answer:
Loops in C#:
1. for loop – known iterations:
for (int i=0; i<5; i++)
[Link](i);
Structure: initialization; condition; increment
2. while loop – condition checked before:
int i = 0;
while (i < 5) { [Link](i); i++; }
May not execute if condition is false initially
3. do-while loop – executes at least once:
int i = 0;
do { [Link](i); i++; } while (i < 5);
4. foreach loop – iterates over collections:
int[] arr = {1,2,3,4,5};
foreach (int x in arr)
[Link](x);
Comparison:
• for: best when count is known
• while: best when condition-based
• do-while: best when at least one execution needed
• foreach: best for arrays/collections, no index manipulation
Break and Continue:
• break – exits the loop
• continue – skips current iteration
1(b). Explain classes, objects, constructors and methods in C#.
[7 Marks]
Answer:
Object-Oriented Concepts in C#:
Class Definition:
class Student {
public string Name;
public int Age;
// Constructor
public Student(string n, int a) {
Name = n;
Age = a;
// Method
public void Display() {
[Link](Name + " " + Age);
Creating Object:
Student s1 = new Student("Alice", 20);
[Link]();
Constructors:
• Default constructor – no parameters
• Parameterized constructor – accepts parameters
• Copy constructor – copies another object
Access Modifiers:
• public – accessible everywhere
• private – accessible only within class
• protected – accessible in class and derived classes
• internal – accessible within same assembly
The 'this' keyword refers to the current instance of the class.
PART 2 – Unit II – [Link] and Web Forms
2(a). Explain HTML server controls in [Link].
[7 Marks]
Answer:
HTML Server Controls:
HTML controls are standard HTML elements with runat="server" attribute added, making them accessible
from server-side code.
Converting HTML to Server Control:
<input type="text" id="txtName" runat="server" />
Now accessible as: [Link]
Common HTML Server Controls:
1. HtmlInputText:
<input type="text" id="txt1" runat="server" />
Properties: Value, MaxLength, Size, ReadOnly
2. HtmlInputButton:
<input type="button" id="btn1" runat="server" />
Events: ServerClick
3. HtmlInputCheckBox:
<input type="checkbox" id="chk1" runat="server" />
Properties: Checked, Value
4. HtmlInputRadioButton:
<input type="radio" id="rb1" runat="server" />
Properties: Checked, Value, Name (for grouping)
5. HtmlSelect:
<select id="sel1" runat="server"></select>
Properties: Items, SelectedIndex, Multiple
6. HtmlTextArea:
<textarea id="ta1" runat="server"></textarea>
Properties: Value, Rows, Cols
7. HtmlAnchor:
<a id="lnk1" runat="server">Click</a>
Properties: HRef, Target
Difference from [Link] Server Controls:
• HTML controls map directly to HTML elements
• Less overhead, simpler model
• [Link] controls provide richer functionality
2(b). Explain List controls in [Link] with properties and events.
[7 Marks]
Answer:
[Link] List Controls:
1. DropDownList:
Displays a single-select dropdown.
Properties: Items, SelectedIndex, SelectedValue, [Link]
Events: SelectedIndexChanged (set AutoPostBack=true)
Adding items in code:
[Link](new ListItem("Text", "Value"));
2. ListBox:
Shows multiple items, supports multi-selection.
Properties: SelectionMode (Single/Multiple), Rows
Events: SelectedIndexChanged
Get selected: [Link]
3. CheckBoxList:
Group of checkboxes as a list.
Properties: Items, RepeatLayout (Table/Flow), RepeatColumns
Events: SelectedIndexChanged
Check selected:
foreach(ListItem item in [Link])
if([Link]) result += [Link];
4. RadioButtonList:
Group of radio buttons.
Properties: Items, RepeatDirection (Horizontal/Vertical)
Events: SelectedIndexChanged
5. BulletedList:
Renders as HTML <ul> or <ol>.
Properties: BulletStyle (Disc/Circle/Square/Numbered)
Events: Click (when DisplayMode=HyperLink or LinkButton)
Common ListItem Properties:
• Text – Display text
• Value – Hidden value
• Selected – Whether selected
• Enabled – Whether enabled
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Write programs to read from and write to files in C#.
[7 Marks]
Answer:
File Operations in C#:
Writing to a File:
Method 1 – StreamWriter:
using (StreamWriter writer = new StreamWriter("[Link]")) {
[Link]("Roll No, Name, Marks");
[Link]("1, Alice, 90");
[Link]("2, Bob, 85");
Method 2 – File class shortcut:
[Link]("[Link]", "Hello World");
[Link]("[Link]", [Link] + "\n");
Reading from a File:
Method 1 – StreamReader:
using (StreamReader reader = new StreamReader("[Link]")) {
string line;
while ((line = [Link]()) != null)
[Link](line);
Method 2 – ReadToEnd:
string content = [Link]("[Link]");
[Link](content);
Method 3 – Read all lines:
string[] lines = [Link]("[Link]");
foreach (string line in lines)
[Link](line);
Check if file exists:
if ([Link]("[Link]"))
[Link]("File found!");
[Link]() – appends multiple lines.
[Link]() – reads binary files.
[Link]() – writes binary files.
3(b). Explain creating, copying, moving and deleting files using C#.
[7 Marks]
Answer:
File Management in C# ([Link]):
1. Creating a File:
[Link]("[Link]").Close();
// or
using (StreamWriter sw = [Link]("[Link]")) {
[Link]("Created!");
2. Copying a File:
[Link]("[Link]", "[Link]");
// Overwrite if exists:
[Link]("[Link]", "[Link]", true);
3. Moving a File:
[Link]("oldpath\\[Link]", "newpath\\[Link]");
// Also renames if same directory
4. Deleting a File:
[Link]("[Link]");
// Safe delete:
if ([Link]("[Link]"))
[Link]("[Link]");
5. Directory Operations:
[Link]("NewFolder");
[Link]("OldFolder", true); // true = recursive
[Link]("src", "dest");
bool exists = [Link]("path");
6. FileInfo Class (object-oriented approach):
FileInfo fi = new FileInfo("[Link]");
[Link]("[Link]");
[Link]("archive\\[Link]");
[Link]();
[Link]([Link]); // file size in bytes
[Link]([Link]); // creation date
7. Getting File Information:
FileInfo fi = new FileInfo("[Link]");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
PART 4 – Unit IV – [Link] and Database
4(a). Explain DataAdapter and DataSet with CRUD operations.
[7 Marks]
Answer:
DataAdapter and DataSet:
Disconnected Architecture Pattern:
Connection → DataAdapter → DataSet → (work offline) → DataAdapter → Database
Loading Data into DataSet:
string cs = "Server=.;Database=SchoolDB;Integrated Security=True;";
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", con);
DataSet ds = new DataSet();
[Link](ds, "Students"); // fills DataTable named "Students"
// Bind to GridView
[Link] = [Link]["Students"];
[Link]();
DataTable Access:
DataTable dt = [Link]["Students"];
foreach (DataRow row in [Link]) {
[Link](row["Name"] + " - " + row["Marks"]);
Insert Row:
DataRow newRow = [Link]();
newRow["Name"] = "Alice";
newRow["Marks"] = 90;
[Link](newRow);
Update with SqlCommandBuilder:
SqlCommandBuilder builder = new SqlCommandBuilder(da);
[Link](ds, "Students"); // syncs changes back to DB
DataSet Features:
• Multiple tables: [Link][0], [Link]["Name"]
• Relations between tables: [Link]
• Filtered/sorted views: DataView
DataView for filtering:
DataView dv = new DataView(dt);
[Link] = "Marks > 80";
[Link] = "Name ASC";
4(b). Explain Data Binding and Data Controls in [Link].
[7 Marks]
Answer:
[Link] Data Controls and Binding:
Data Controls:
1. GridView – Tabular display with sort/page/edit
2. DetailsView – Single record display/edit
3. FormView – Template-based single record
4. ListView – Flexible item display
5. DataList – Template-based list
6. Repeater – Lightweight template repeater
Data Binding:
1. Simple Binding:
[Link] = [Link]([Link], "Name").ToString();
Short form: <%# Eval("Name") %>
2. Bind() Method (two-way):
<%# Bind("Name") %> – works in edit templates
3. Binding GridView to DataSet:
[Link] = [Link]["Students"];
[Link]();
4. Binding DropDownList:
[Link] = [Link]["Cities"];
[Link] = "CityName";
[Link] = "CityID";
[Link]();
5. SqlDataSource Control (declarative):
<asp:SqlDataSource ID="sds" runat="server"
ConnectionString="<%$ ConnectionStrings:myCS %>"
SelectCommand="SELECT * FROM Students" />
Then: [Link] = "sds";
DataBind() must be called after setting DataSource for binding to take effect.
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Write a complete Login page using Forms Authentication.
[7 Marks]
Answer:
Forms Authentication Implementation:
[Link]:
<connectionStrings>
<add name="myCS" connectionString="Server=.;Database=UsersDB;Integrated Security=True;" />
</connectionStrings>
<[Link]>
<authentication mode="Forms">
<forms loginUrl="~/[Link]" timeout="60" name=".ASPXAUTH" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</[Link]>
[Link]:
<asp:TextBox ID="txtUser" runat="server" />
<asp:TextBox ID="txtPass" TextMode="Password" runat="server" />
<asp:Button ID="btnLogin" Text="Login" OnClick="btnLogin_Click" runat="server" />
<asp:Label ID="lblMsg" ForeColor="Red" runat="server" />
[Link]:
protected void btnLogin_Click(object sender, EventArgs e) {
string cs = [Link]["myCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs)) {
SqlCommand cmd = new SqlCommand(
"SELECT COUNT(*) FROM Users WHERE Username=@u AND Password=@p", con);
[Link]("@u", [Link]);
[Link]("@p", [Link]);
[Link]();
int count = (int)[Link]();
if (count > 0) {
[Link]([Link], false);
} else {
[Link] = "Invalid username or password!";
Logout button on any page:
[Link]();
[Link]();
[Link]("~/[Link]");
5(b). Explain role-based authorization and access control in [Link].
[7 Marks]
Answer:
Authorization in [Link]:
Authorization determines what an authenticated user can do.
1. URL Authorization ([Link]):
Allow specific users:
<authorization>
<allow users="alice,bob" />
<deny users="*" />
</authorization>
Allow specific roles:
<location path="~/Admin">
<[Link]>
<authorization>
<allow roles="Administrator" />
<deny users="*" />
</authorization>
</[Link]>
</location>
Allow all authenticated:
<allow users="*" /> <!-- or -->
<deny users="?" /> <!-- deny only anonymous -->
2. Code-Based Authorization:
if ([Link])
[Link] = "Welcome " + [Link];
if ([Link]("Admin")) {
[Link] = true;
[Link] = true;
3. Roles API:
[Link]("alice", "Admin");
[Link]("alice", "Admin");
string[] roles = [Link]("alice");
4. LoginView Control:
<asp:LoginView runat="server">
<AnonymousTemplate>
<a href="[Link]">Login</a>
</AnonymousTemplate>
<LoggedInTemplate>
Welcome <%: [Link] %>
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>Admin Panel</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
— End of Model 5 —
MODEL QUESTION PAPER – 6
Subject: [Link] Web Programming Model: 6 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Explain classes, objects, constructors and methods in C#.
[7 Marks]
Answer:
Object-Oriented Concepts in C#:
Class Definition:
class Student {
public string Name;
public int Age;
// Constructor
public Student(string n, int a) {
Name = n;
Age = a;
// Method
public void Display() {
[Link](Name + " " + Age);
Creating Object:
Student s1 = new Student("Alice", 20);
[Link]();
Constructors:
• Default constructor – no parameters
• Parameterized constructor – accepts parameters
• Copy constructor – copies another object
Access Modifiers:
• public – accessible everywhere
• private – accessible only within class
• protected – accessible in class and derived classes
• internal – accessible within same assembly
The 'this' keyword refers to the current instance of the class.
1(b). Explain single-dimensional, multi-dimensional and jagged arrays in C#.
[7 Marks]
Answer:
Arrays in C#:
1. Single-Dimensional Array:
int[] marks = new int[5];
marks[0] = 90; marks[1] = 85;
// or
int[] nums = {10, 20, 30, 40, 50};
Length: [Link] → 5
2. Multi-Dimensional Array:
int[,] matrix = new int[3,3];
matrix[0,0] = 1;
// Declaration with values:
int[,] m = { {1,2,3}, {4,5,6}, {7,8,9} };
Access: m[row, col]
3. Jagged Array (array of arrays):
int[][] jag = new int[3][];
jag[0] = new int[]{1,2};
jag[1] = new int[]{3,4,5};
jag[2] = new int[]{6};
Common Array Methods:
• [Link](arr) – sorts array
• [Link](arr) – reverses array
• [Link] – number of elements
• [Link]() – copies elements
Foreach with array:
foreach(int x in marks)
[Link](x + " ");
PART 2 – Unit II – [Link] and Web Forms
2(a). Explain List controls in [Link] with properties and events.
[7 Marks]
Answer:
[Link] List Controls:
1. DropDownList:
Displays a single-select dropdown.
Properties: Items, SelectedIndex, SelectedValue, [Link]
Events: SelectedIndexChanged (set AutoPostBack=true)
Adding items in code:
[Link](new ListItem("Text", "Value"));
2. ListBox:
Shows multiple items, supports multi-selection.
Properties: SelectionMode (Single/Multiple), Rows
Events: SelectedIndexChanged
Get selected: [Link]
3. CheckBoxList:
Group of checkboxes as a list.
Properties: Items, RepeatLayout (Table/Flow), RepeatColumns
Events: SelectedIndexChanged
Check selected:
foreach(ListItem item in [Link])
if([Link]) result += [Link];
4. RadioButtonList:
Group of radio buttons.
Properties: Items, RepeatDirection (Horizontal/Vertical)
Events: SelectedIndexChanged
5. BulletedList:
Renders as HTML <ul> or <ol>.
Properties: BulletStyle (Disc/Circle/Square/Numbered)
Events: Click (when DisplayMode=HyperLink or LinkButton)
Common ListItem Properties:
• Text – Display text
• Value – Hidden value
• Selected – Whether selected
• Enabled – Whether enabled
2(b). Explain the architecture and features of [Link].
[7 Marks]
Answer:
[Link] Architecture:
[Link] is a server-side web framework built on .NET Framework for building web applications and
services.
Request-Response Cycle:
1. Browser sends HTTP request to IIS server
2. IIS passes request to [Link] runtime
3. [Link] processes the request (runs code-behind)
4. HTML response is generated and sent back to browser
Key Features:
• Web Forms – Drag-and-drop controls, event-driven model
• Code-Behind – Separation of HTML and C# logic
• Master Pages – Consistent page layout
• State Management – ViewState, Session, Cookies
• Cache Support – Improves performance
• Built-in Security – Forms authentication, Windows authentication
• Rich Server Controls – GridView, DetailsView, etc.
[Link] Page Lifecycle:
1. Page_Init – Page and controls initialized
2. Page_Load – Data loaded, IsPostBack checked
3. Event Handling – Button click, etc.
4. Page_PreRender – Before rendering
5. Page_Unload – Cleanup
File Extensions:
• .aspx – Web Form page
• .cs – C# code-behind file
• .config – Configuration file ([Link])
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain creating, copying, moving and deleting files using C#.
[7 Marks]
Answer:
File Management in C# ([Link]):
1. Creating a File:
[Link]("[Link]").Close();
// or
using (StreamWriter sw = [Link]("[Link]")) {
[Link]("Created!");
}
2. Copying a File:
[Link]("[Link]", "[Link]");
// Overwrite if exists:
[Link]("[Link]", "[Link]", true);
3. Moving a File:
[Link]("oldpath\\[Link]", "newpath\\[Link]");
// Also renames if same directory
4. Deleting a File:
[Link]("[Link]");
// Safe delete:
if ([Link]("[Link]"))
[Link]("[Link]");
5. Directory Operations:
[Link]("NewFolder");
[Link]("OldFolder", true); // true = recursive
[Link]("src", "dest");
bool exists = [Link]("path");
6. FileInfo Class (object-oriented approach):
FileInfo fi = new FileInfo("[Link]");
[Link]("[Link]");
[Link]("archive\\[Link]");
[Link]();
[Link]([Link]); // file size in bytes
[Link]([Link]); // creation date
7. Getting File Information:
FileInfo fi = new FileInfo("[Link]");
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
3(b). Explain file uploading in [Link] with FileUpload control.
[7 Marks]
Answer:
File Upload in [Link]:
Using FileUpload Server Control:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<asp:Label ID="lblStatus" runat="server" />
Code-Behind:
protected void btnUpload_Click(object sender, EventArgs e) {
if ([Link]) {
string fileName = [Link];
string savePath = [Link]("~/Uploads/") + fileName;
// Check file size (limit 2MB)
if ([Link] > 2 * 1024 * 1024) {
[Link] = "File too large!";
return;
// Check file extension
string ext = [Link](fileName).ToLower();
if (ext != ".jpg" && ext != ".png" && ext != ".pdf") {
[Link] = "Invalid file type!";
return;
[Link](savePath);
[Link] = "File uploaded: " + fileName;
} else {
[Link] = "No file selected!";
Important Properties:
• HasFile – true if file selected
• FileName – file name without path
• FileBytes – file as byte array
• [Link] – size in bytes
• [Link] – MIME type
• [Link] – file as stream
[Link] – increase maxRequestLength for large files.
PART 4 – Unit IV – [Link] and Database
4(a). Explain Data Binding and Data Controls in [Link].
[7 Marks]
Answer:
[Link] Data Controls and Binding:
Data Controls:
1. GridView – Tabular display with sort/page/edit
2. DetailsView – Single record display/edit
3. FormView – Template-based single record
4. ListView – Flexible item display
5. DataList – Template-based list
6. Repeater – Lightweight template repeater
Data Binding:
1. Simple Binding:
[Link] = [Link]([Link], "Name").ToString();
Short form: <%# Eval("Name") %>
2. Bind() Method (two-way):
<%# Bind("Name") %> – works in edit templates
3. Binding GridView to DataSet:
[Link] = [Link]["Students"];
[Link]();
4. Binding DropDownList:
[Link] = [Link]["Cities"];
[Link] = "CityName";
[Link] = "CityID";
[Link]();
5. SqlDataSource Control (declarative):
<asp:SqlDataSource ID="sds" runat="server"
ConnectionString="<%$ ConnectionStrings:myCS %>"
SelectCommand="SELECT * FROM Students" />
Then: [Link] = "sds";
DataBind() must be called after setting DataSource for binding to take effect.
4(b). Compare connected and disconnected architectures in [Link].
[7 Marks]
Answer:
Connected vs Disconnected Architecture:
Connected Architecture:
• Uses: Connection + Command + DataReader
• Connection stays open during data access
• Forward-only, read-only data access
• Fast, minimal memory usage
• Best for: Real-time data, large result sets read once
Code:
SqlConnection con = new SqlConnection(cs);
[Link]();
SqlCommand cmd = new SqlCommand("SELECT * FROM Emp", con);
SqlDataReader dr = [Link]();
while([Link]())
[Link](dr["Name"] + "<br/>");
[Link](); [Link]();
Disconnected Architecture:
• Uses: DataAdapter + DataSet
• Connection opened only to fill/update data
• Data cached in DataSet (in-memory)
• Supports random access, editing, relations
• Best for: Offline work, passing data between layers
Code:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Emp", cs);
DataSet ds = new DataSet();
[Link](ds, "Emp");
[Link] = ds;
[Link]();
Comparison Table:
Feature | DataReader | DataSet
Connection | Always open | Closed after Fill
Direction | Forward only | Any direction
Memory | Low | Higher
Editing | Not supported | Supported
Multiple tables | Not directly | Yes
Binding | Limited | Full support
Performance | Faster | Slower (overhead)
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Explain role-based authorization and access control in [Link].
[7 Marks]
Answer:
Authorization in [Link]:
Authorization determines what an authenticated user can do.
1. URL Authorization ([Link]):
Allow specific users:
<authorization>
<allow users="alice,bob" />
<deny users="*" />
</authorization>
Allow specific roles:
<location path="~/Admin">
<[Link]>
<authorization>
<allow roles="Administrator" />
<deny users="*" />
</authorization>
</[Link]>
</location>
Allow all authenticated:
<allow users="*" /> <!-- or -->
<deny users="?" /> <!-- deny only anonymous -->
2. Code-Based Authorization:
if ([Link])
[Link] = "Welcome " + [Link];
if ([Link]("Admin")) {
[Link] = true;
[Link] = true;
3. Roles API:
[Link]("alice", "Admin");
[Link]("alice", "Admin");
string[] roles = [Link]("alice");
4. LoginView Control:
<asp:LoginView runat="server">
<AnonymousTemplate>
<a href="[Link]">Login</a>
</AnonymousTemplate>
<LoggedInTemplate>
Welcome <%: [Link] %>
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>Admin Panel</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
5(b). Explain steps to create and deploy an [Link] Web Application.
[7 Marks]
Answer:
Creating a Complete [Link] Web Application:
Step 1: Create Project
• Open Visual Studio → New Project
• Select [Link] Web Application (.NET Framework)
• Choose template: Web Forms
• Name: StudentManagement
Step 2: Project Structure
StudentManagement/
■■■ App_Data/ (database files)
■■■ App_Start/ (route config)
■■■ Content/ (CSS files)
■■■ Scripts/ (JS files)
■■■ [Link] (home page)
■■■ [Link] (configuration)
■■■ [Link] (app events)
Step 3: Design the UI ([Link])
Add a master page for consistent layout.
Create pages: Login, Register, Dashboard, StudentList.
Step 4: Configure Database
Add connection string in [Link]:
<connectionStrings>
<add name="CS" connectionString="Server=.;Database=StudentDB;Integrated Security=True;"/>
</connectionStrings>
Step 5: Implement CRUD
• Read: SqlDataAdapter + DataSet → GridView
• Create: Form + [Link]() INSERT
• Update: GridView edit + UPDATE SQL
• Delete: GridView delete + DELETE SQL
Step 6: Add Security
• Forms Authentication in [Link]
• Login/Logout pages
• Role-based authorization
Step 7: Test and Run
• Press F5 to run with IIS Express
• Test all pages and functionality
Step 8: Publish/Deploy
• Right-click project → Publish
• Target: IIS server or Azure Web App
• Click Publish
— End of Model 6 —
MODEL QUESTION PAPER – 7
Subject: [Link] Web Programming Model: 7 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Explain single-dimensional, multi-dimensional and jagged arrays in C#.
[7 Marks]
Answer:
Arrays in C#:
1. Single-Dimensional Array:
int[] marks = new int[5];
marks[0] = 90; marks[1] = 85;
// or
int[] nums = {10, 20, 30, 40, 50};
Length: [Link] → 5
2. Multi-Dimensional Array:
int[,] matrix = new int[3,3];
matrix[0,0] = 1;
// Declaration with values:
int[,] m = { {1,2,3}, {4,5,6}, {7,8,9} };
Access: m[row, col]
3. Jagged Array (array of arrays):
int[][] jag = new int[3][];
jag[0] = new int[]{1,2};
jag[1] = new int[]{3,4,5};
jag[2] = new int[]{6};
Common Array Methods:
• [Link](arr) – sorts array
• [Link](arr) – reverses array
• [Link] – number of elements
• [Link]() – copies elements
Foreach with array:
foreach(int x in marks)
[Link](x + " ");
1(b). Explain important string methods and properties in C# with examples.
[7 Marks]
Answer:
String Operations in C#:
String Declaration:
string s = "Hello World";
Properties:
• [Link] → 11
• s[0] → 'H' (character access)
Common Methods:
• [Link]() → "HELLO WORLD"
• [Link]() → "hello world"
• [Link]() → removes leading/trailing spaces
• [Link]("World") → true
• [Link]("He") → true
• [Link]("ld") → true
• [Link]("World","C#") → "Hello C#"
• [Link](6) → "World"
• [Link](0,5) → "Hello"
• [Link](' ') → ["Hello","World"]
• [Link]('o') → 4
• [Link](5) → "Hello"
• [Link](s1,s2) → joins strings
String Comparison:
• s1 == s2 – equality
• [Link](s1,s2) – returns 0,1,-1
• [Link](s2) – true/false
String Builder (mutable):
StringBuilder sb = new StringBuilder();
[Link]("Hello");
[Link](" World");
string result = [Link]();
PART 2 – Unit II – [Link] and Web Forms
2(a). Explain the architecture and features of [Link].
[7 Marks]
Answer:
[Link] Architecture:
[Link] is a server-side web framework built on .NET Framework for building web applications and
services.
Request-Response Cycle:
1. Browser sends HTTP request to IIS server
2. IIS passes request to [Link] runtime
3. [Link] processes the request (runs code-behind)
4. HTML response is generated and sent back to browser
Key Features:
• Web Forms – Drag-and-drop controls, event-driven model
• Code-Behind – Separation of HTML and C# logic
• Master Pages – Consistent page layout
• State Management – ViewState, Session, Cookies
• Cache Support – Improves performance
• Built-in Security – Forms authentication, Windows authentication
• Rich Server Controls – GridView, DetailsView, etc.
[Link] Page Lifecycle:
1. Page_Init – Page and controls initialized
2. Page_Load – Data loaded, IsPostBack checked
3. Event Handling – Button click, etc.
4. Page_PreRender – Before rendering
5. Page_Unload – Cleanup
File Extensions:
• .aspx – Web Form page
• .cs – C# code-behind file
• .config – Configuration file ([Link])
2(b). Describe Visual Studio IDE features for [Link] development.
[7 Marks]
Answer:
Visual Studio IDE for [Link]:
Key Windows/Panels:
• Solution Explorer – Manages project files
• Toolbox – Drag-and-drop server controls
• Properties Window – Configure control properties
• Error List – Compilation errors
• Output Window – Build results
Design Views:
• Design View – Visual drag-and-drop interface
• Source View – HTML/ASPX markup
• Split View – Both simultaneously
Code Editor Features:
• IntelliSense – Auto-completion and suggestions
• Syntax Highlighting – Different colors for keywords
• Code Snippets – Templates for common code
• Refactoring – Rename, extract method
• Debugger – Breakpoints, step over/into, watch window
Built-in Tools:
• IIS Express – Local web server for testing
• NuGet Package Manager – Third-party library management
• Database Explorer – Connect to SQL Server
• Browser Link – Live browser reload
Languages Supported by [Link]:
• C# – Primary language, strongly typed
• [Link] – Visual Basic, readable syntax
• F# – Functional programming
• J# – Deprecated, Java-like syntax
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain file uploading in [Link] with FileUpload control.
[7 Marks]
Answer:
File Upload in [Link]:
Using FileUpload Server Control:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
<asp:Label ID="lblStatus" runat="server" />
Code-Behind:
protected void btnUpload_Click(object sender, EventArgs e) {
if ([Link]) {
string fileName = [Link];
string savePath = [Link]("~/Uploads/") + fileName;
// Check file size (limit 2MB)
if ([Link] > 2 * 1024 * 1024) {
[Link] = "File too large!";
return;
// Check file extension
string ext = [Link](fileName).ToLower();
if (ext != ".jpg" && ext != ".png" && ext != ".pdf") {
[Link] = "Invalid file type!";
return;
[Link](savePath);
[Link] = "File uploaded: " + fileName;
} else {
[Link] = "No file selected!";
Important Properties:
• HasFile – true if file selected
• FileName – file name without path
• FileBytes – file as byte array
• [Link] – size in bytes
• [Link] – MIME type
• [Link] – file as stream
[Link] – increase maxRequestLength for large files.
3(b). Write a program using Calendar and AdRotator controls.
[7 Marks]
Answer:
Rich Controls Programs:
1. Calendar Control Program:
ASPX:
<asp:Calendar ID="Calendar1" runat="server"
SelectionMode="Day"
OnSelectionChanged="Calendar1_SelectionChanged" />
<asp:Label ID="lblSelected" runat="server" />
C#:
protected void Calendar1_SelectionChanged(object sender, EventArgs e) {
DateTime selected = [Link];
[Link] = "Selected: " + [Link]("dd/MM/yyyy");
// Highlight weekends
if ([Link] == [Link] ||
[Link] == [Link])
[Link] = [Link];
2. AdRotator Setup:
Create [Link]:
<Advertisements>
<Ad>
<ImageUrl>~/images/[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText>Company 1 Ad</AlternateText>
<Impressions>80</Impressions>
</Ad>
<Ad>
<ImageUrl>~/images/[Link]</ImageUrl>
<NavigateUrl>[Link]
<Impressions>20</Impressions>
</Ad>
</Advertisements>
ASPX:
<asp:AdRotator ID="AdRotator1" runat="server"
AdvertisementFile="~/[Link]"
Target="_blank" />
Impressions value determines relative frequency of display.
PART 4 – Unit IV – [Link] and Database
4(a). Compare connected and disconnected architectures in [Link].
[7 Marks]
Answer:
Connected vs Disconnected Architecture:
Connected Architecture:
• Uses: Connection + Command + DataReader
• Connection stays open during data access
• Forward-only, read-only data access
• Fast, minimal memory usage
• Best for: Real-time data, large result sets read once
Code:
SqlConnection con = new SqlConnection(cs);
[Link]();
SqlCommand cmd = new SqlCommand("SELECT * FROM Emp", con);
SqlDataReader dr = [Link]();
while([Link]())
[Link](dr["Name"] + "<br/>");
[Link](); [Link]();
Disconnected Architecture:
• Uses: DataAdapter + DataSet
• Connection opened only to fill/update data
• Data cached in DataSet (in-memory)
• Supports random access, editing, relations
• Best for: Offline work, passing data between layers
Code:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Emp", cs);
DataSet ds = new DataSet();
[Link](ds, "Emp");
[Link] = ds;
[Link]();
Comparison Table:
Feature | DataReader | DataSet
Connection | Always open | Closed after Fill
Direction | Forward only | Any direction
Memory | Low | Higher
Editing | Not supported | Supported
Multiple tables | Not directly | Yes
Binding | Limited | Full support
Performance | Faster | Slower (overhead)
4(b). Explain Master-Detail binding and DataRelation in [Link].
[7 Marks]
Answer:
Advanced Data Binding:
Master-Detail Relationship:
// Load both tables
SqlDataAdapter da1 = new SqlDataAdapter("SELECT * FROM Departments", cs);
SqlDataAdapter da2 = new SqlDataAdapter("SELECT * FROM Employees", cs);
DataSet ds = new DataSet();
[Link](ds, "Departments");
[Link](ds, "Employees");
// Create relation
DataRelation rel = new DataRelation(
"Dept_Emp",
[Link]["Departments"].Columns["DeptID"],
[Link]["Employees"].Columns["DeptID"]
);
[Link](rel);
// Navigate: get employees of department
DataRow deptRow = [Link]["Departments"].Rows[0];
DataRow[] empRows = [Link]("Dept_Emp");
DropDownList driving GridView:
protected void ddlDept_SelectedIndexChanged(object sender, EventArgs e) {
string filter = "DeptID = " + [Link];
DataView dv = new DataView([Link]["Employees"]);
[Link] = filter;
[Link] = dv;
[Link]();
DataColumn Properties:
• ColumnName, DataType, MaxLength
• AllowDBNull, DefaultValue, Unique
DataRow States:
• Added, Modified, Deleted, Unchanged
• [Link] property
• [Link]() – returns only changed rows
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Explain steps to create and deploy an [Link] Web Application.
[7 Marks]
Answer:
Creating a Complete [Link] Web Application:
Step 1: Create Project
• Open Visual Studio → New Project
• Select [Link] Web Application (.NET Framework)
• Choose template: Web Forms
• Name: StudentManagement
Step 2: Project Structure
StudentManagement/
■■■ App_Data/ (database files)
■■■ App_Start/ (route config)
■■■ Content/ (CSS files)
■■■ Scripts/ (JS files)
■■■ [Link] (home page)
■■■ [Link] (configuration)
■■■ [Link] (app events)
Step 3: Design the UI ([Link])
Add a master page for consistent layout.
Create pages: Login, Register, Dashboard, StudentList.
Step 4: Configure Database
Add connection string in [Link]:
<connectionStrings>
<add name="CS" connectionString="Server=.;Database=StudentDB;Integrated Security=True;"/>
</connectionStrings>
Step 5: Implement CRUD
• Read: SqlDataAdapter + DataSet → GridView
• Create: Form + [Link]() INSERT
• Update: GridView edit + UPDATE SQL
• Delete: GridView delete + DELETE SQL
Step 6: Add Security
• Forms Authentication in [Link]
• Login/Logout pages
• Role-based authorization
Step 7: Test and Run
• Press F5 to run with IIS Express
• Test all pages and functionality
Step 8: Publish/Deploy
• Right-click project → Publish
• Target: IIS server or Azure Web App
• Click Publish
5(b). Explain XML Web Services and security best practices in [Link].
[7 Marks]
Answer:
XML Web Services and Security in [Link]:
XML Web Services (.asmx):
A web service exposes methods over HTTP using XML/SOAP.
Creating a Web Service:
[WebService(Namespace="[Link]
public class MathService : [Link] {
[WebMethod]
public int Add(int a, int b) {
return a + b;
[WebMethod]
public DataSet GetStudents() {
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", cs);
DataSet ds = new DataSet();
[Link](ds, "Students");
return ds; // Serialized as XML
Consuming a Web Service:
Add Web Reference → generate proxy class → call methods.
Security Best Practices:
1. Input Validation:
• Always validate user input server-side
• Use validation controls
• Whitelist allowed characters
2. SQL Injection Prevention:
• Use parameterized queries: [Link]()
• Never concatenate user input into SQL strings
3. XSS Prevention:
• [Link]() before displaying user input
• ValidateRequest="true" (default) in page directive
4. HTTPS:
• Use SSL certificate
• Force HTTPS with requireSSL="true" in forms auth
5. ViewState Encryption:
ViewStateEncryptionMode="Always"
6. Error Handling:
• Custom error pages (customErrors in [Link])
• Never expose stack traces to users
7. Session Security:
• Use HttpOnly and Secure cookie flags
• Set reasonable session timeout
— End of Model 7 —
MODEL QUESTION PAPER – 8
Subject: [Link] Web Programming Model: 8 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Explain important string methods and properties in C# with examples.
[7 Marks]
Answer:
String Operations in C#:
String Declaration:
string s = "Hello World";
Properties:
• [Link] → 11
• s[0] → 'H' (character access)
Common Methods:
• [Link]() → "HELLO WORLD"
• [Link]() → "hello world"
• [Link]() → removes leading/trailing spaces
• [Link]("World") → true
• [Link]("He") → true
• [Link]("ld") → true
• [Link]("World","C#") → "Hello C#"
• [Link](6) → "World"
• [Link](0,5) → "Hello"
• [Link](' ') → ["Hello","World"]
• [Link]('o') → 4
• [Link](5) → "Hello"
• [Link](s1,s2) → joins strings
String Comparison:
• s1 == s2 – equality
• [Link](s1,s2) – returns 0,1,-1
• [Link](s2) – true/false
String Builder (mutable):
StringBuilder sb = new StringBuilder();
[Link]("Hello");
[Link](" World");
string result = [Link]();
1(b). Explain the architecture of .NET Framework with CLR and FCL.
[7 Marks]
Answer:
The .NET Framework has two main components:
CLR (Common Language Runtime):
• Managed execution environment
• Handles garbage collection, memory management, JIT compilation
• Converts MSIL to native code using JIT compiler
• Provides exception handling, thread management, and security
• Languages like C#, [Link] compile to MSIL which CLR executes
FCL (Framework Class Library):
• Large library of pre-built classes
• Organized into namespaces: System, [Link], [Link], [Link], [Link]
• Supports file I/O, networking, database access, UI development
• Reduces development time by providing reusable components
Execution Flow: Source Code → Compiler → MSIL → CLR (JIT) → Native Code → Execution
PART 2 – Unit II – [Link] and Web Forms
2(a). Describe Visual Studio IDE features for [Link] development.
[7 Marks]
Answer:
Visual Studio IDE for [Link]:
Key Windows/Panels:
• Solution Explorer – Manages project files
• Toolbox – Drag-and-drop server controls
• Properties Window – Configure control properties
• Error List – Compilation errors
• Output Window – Build results
Design Views:
• Design View – Visual drag-and-drop interface
• Source View – HTML/ASPX markup
• Split View – Both simultaneously
Code Editor Features:
• IntelliSense – Auto-completion and suggestions
• Syntax Highlighting – Different colors for keywords
• Code Snippets – Templates for common code
• Refactoring – Rename, extract method
• Debugger – Breakpoints, step over/into, watch window
Built-in Tools:
• IIS Express – Local web server for testing
• NuGet Package Manager – Third-party library management
• Database Explorer – Connect to SQL Server
• Browser Link – Live browser reload
Languages Supported by [Link]:
• C# – Primary language, strongly typed
• [Link] – Visual Basic, readable syntax
• F# – Functional programming
• J# – Deprecated, Java-like syntax
2(b). Explain the Web Forms model in [Link] including page lifecycle.
[7 Marks]
Answer:
[Link] Web Forms:
Web Forms is an event-driven model for building web applications, similar to Windows Forms.
Page Structure (.aspx file):
<%@ Page Language="C#" CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form runat="server">
<!-- Server controls go here -->
</form>
</body>
</html>
Code-Behind (.[Link] file):
public partial class Default : [Link] {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
[Link] = "Welcome!";
}
PostBack:
• When user submits form, page posts back to server
• IsPostBack property is true on subsequent requests
• ViewState preserves control values across postbacks
Page Lifecycle Events:
1. PreInit – Set master page, themes
2. Init – Initialize controls
3. InitComplete – Initialization complete
4. PreLoad – Before Load
5. Load – Page_Load fires here
6. Control Events – Button_Click etc.
7. PreRender – Last chance to modify output
8. Render – HTML is generated
9. Unload – Cleanup resources
AutoPostBack – Controls like DropDownList post back automatically when changed.
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Write a program using Calendar and AdRotator controls.
[7 Marks]
Answer:
Rich Controls Programs:
1. Calendar Control Program:
ASPX:
<asp:Calendar ID="Calendar1" runat="server"
SelectionMode="Day"
OnSelectionChanged="Calendar1_SelectionChanged" />
<asp:Label ID="lblSelected" runat="server" />
C#:
protected void Calendar1_SelectionChanged(object sender, EventArgs e) {
DateTime selected = [Link];
[Link] = "Selected: " + [Link]("dd/MM/yyyy");
// Highlight weekends
if ([Link] == [Link] ||
[Link] == [Link])
[Link] = [Link];
}
2. AdRotator Setup:
Create [Link]:
<Advertisements>
<Ad>
<ImageUrl>~/images/[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText>Company 1 Ad</AlternateText>
<Impressions>80</Impressions>
</Ad>
<Ad>
<ImageUrl>~/images/[Link]</ImageUrl>
<NavigateUrl>[Link]
<Impressions>20</Impressions>
</Ad>
</Advertisements>
ASPX:
<asp:AdRotator ID="AdRotator1" runat="server"
AdvertisementFile="~/[Link]"
Target="_blank" />
Impressions value determines relative frequency of display.
3(b). Explain Rich Controls in [Link]: Calendar, FileUpload, AdRotator.
[7 Marks]
Answer:
[Link] Rich Controls:
1. Calendar Control:
Displays a monthly calendar.
Properties:
• SelectedDate – Currently selected date
• TodaysDate – Today's date
• SelectionMode (Day/DayWeek/DayWeekMonth/None)
• FirstDayOfWeek
Events: SelectionChanged, VisibleMonthChanged
Example:
protected void cal_SelectionChanged(object sender, EventArgs e) {
[Link] = [Link]();
}
2. FileUpload Control:
Allows users to upload files to server.
Properties:
• HasFile – true if file selected
• FileName – Name of uploaded file
• PostedFile – The uploaded file object
Usage:
if ([Link])
[Link]([Link]("~/uploads/") + [Link]);
3. AdRotator:
Displays rotating advertisements.
Properties:
• AdvertisementFile – XML file with ad info
• Target – Window to open ad
Events: AdCreated
XML Format:
<Advertisements>
<Ad><ImageUrl>[Link]</ImageUrl><NavigateUrl>[Link]
</Advertisements>
4. MultiView / View:
Creates multiple views in one page.
ActiveViewIndex property switches between views.
5. Wizard Control:
Multi-step form with Next/Back navigation.
PART 4 – Unit IV – [Link] and Database
4(a). Explain Master-Detail binding and DataRelation in [Link].
[7 Marks]
Answer:
Advanced Data Binding:
Master-Detail Relationship:
// Load both tables
SqlDataAdapter da1 = new SqlDataAdapter("SELECT * FROM Departments", cs);
SqlDataAdapter da2 = new SqlDataAdapter("SELECT * FROM Employees", cs);
DataSet ds = new DataSet();
[Link](ds, "Departments");
[Link](ds, "Employees");
// Create relation
DataRelation rel = new DataRelation(
"Dept_Emp",
[Link]["Departments"].Columns["DeptID"],
[Link]["Employees"].Columns["DeptID"]
);
[Link](rel);
// Navigate: get employees of department
DataRow deptRow = [Link]["Departments"].Rows[0];
DataRow[] empRows = [Link]("Dept_Emp");
DropDownList driving GridView:
protected void ddlDept_SelectedIndexChanged(object sender, EventArgs e) {
string filter = "DeptID = " + [Link];
DataView dv = new DataView([Link]["Employees"]);
[Link] = filter;
[Link] = dv;
[Link]();
DataColumn Properties:
• ColumnName, DataType, MaxLength
• AllowDBNull, DefaultValue, Unique
DataRow States:
• Added, Modified, Deleted, Unchanged
• [Link] property
• [Link]() – returns only changed rows
4(b). Explain [Link] architecture and its components.
[7 Marks]
Answer:
[Link] Architecture:
[Link] (ActiveX Data Objects .NET) is the data access layer in .NET Framework for interacting with
databases.
Two Main Architectures:
1. Connected Architecture:
Requires continuous connection to database.
Components: Connection → Command → DataReader
Best for: Small data reads, quick operations
2. Disconnected Architecture:
Data loaded into memory, connection closed.
Components: Connection → DataAdapter → DataSet
Best for: Large data sets, offline processing
Core [Link] Components:
• Connection (SqlConnection):
Manages database connection
Connection string: "Server=.;Database=myDB;Integrated Security=True;"
• Command (SqlCommand):
Executes SQL: SELECT, INSERT, UPDATE, DELETE
Types: Text, StoredProcedure, TableDirect
• DataReader (SqlDataReader):
Forward-only, read-only data stream
Fast and lightweight
• DataAdapter (SqlDataAdapter):
Bridge between DataSet and database
SelectCommand, InsertCommand, UpdateCommand, DeleteCommand
• DataSet:
In-memory database representation
Contains DataTables, DataRelations, Constraints
• DataTable:
Represents one table of in-memory data
Namespaces:
• [Link] – Core [Link] types
• [Link] – SQL Server provider
• [Link] – Access, Excel provider
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Explain XML Web Services and security best practices in [Link].
[7 Marks]
Answer:
XML Web Services and Security in [Link]:
XML Web Services (.asmx):
A web service exposes methods over HTTP using XML/SOAP.
Creating a Web Service:
[WebService(Namespace="[Link]
public class MathService : [Link] {
[WebMethod]
public int Add(int a, int b) {
return a + b;
[WebMethod]
public DataSet GetStudents() {
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", cs);
DataSet ds = new DataSet();
[Link](ds, "Students");
return ds; // Serialized as XML
Consuming a Web Service:
Add Web Reference → generate proxy class → call methods.
Security Best Practices:
1. Input Validation:
• Always validate user input server-side
• Use validation controls
• Whitelist allowed characters
2. SQL Injection Prevention:
• Use parameterized queries: [Link]()
• Never concatenate user input into SQL strings
3. XSS Prevention:
• [Link]() before displaying user input
• ValidateRequest="true" (default) in page directive
4. HTTPS:
• Use SSL certificate
• Force HTTPS with requireSSL="true" in forms auth
5. ViewState Encryption:
ViewStateEncryptionMode="Always"
6. Error Handling:
• Custom error pages (customErrors in [Link])
• Never expose stack traces to users
7. Session Security:
• Use HttpOnly and Secure cookie flags
• Set reasonable session timeout
5(b). Write a complete program for GridView with Edit, Delete, Sort and Page.
[7 Marks]
Answer:
GridView Complete Program:
ASPX:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" PageSize="5"
DataKeyNames="StudentID"
OnSorting="gv_Sorting"
OnPageIndexChanging="gv_PageIndexChanging"
OnRowEditing="gv_RowEditing"
OnRowUpdating="gv_RowUpdating"
OnRowCancelingEdit="gv_RowCancelingEdit"
OnRowDeleting="gv_RowDeleting">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Marks" HeaderText="Marks" SortExpression="Marks" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
C# Code-Behind:
protected void BindGrid() {
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", cs);
DataTable dt = new DataTable();
[Link](dt);
[Link] = dt;
[Link]();
protected void gv_PageIndexChanging(object s, GridViewPageEventArgs e) {
[Link] = [Link]; BindGrid();
}
protected void gv_RowEditing(object s, GridViewEditEventArgs e) {
[Link] = [Link]; BindGrid();
protected void gv_RowCancelingEdit(object s, GridViewCancelEditEventArgs e) {
[Link] = -1; BindGrid();
protected void gv_RowUpdating(object s, GridViewUpdateEventArgs e) {
string name = ((TextBox)[Link][[Link]].Cells[0].Controls[0]).Text;
// Execute UPDATE SQL
[Link] = -1; BindGrid();
protected void gv_RowDeleting(object s, GridViewDeleteEventArgs e) {
int id = (int)[Link][[Link]].Value;
// Execute DELETE SQL WHERE StudentID = id
BindGrid();
— End of Model 8 —
MODEL QUESTION PAPER – 9
Subject: [Link] Web Programming Model: 9 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Explain the architecture of .NET Framework with CLR and FCL.
[7 Marks]
Answer:
The .NET Framework has two main components:
CLR (Common Language Runtime):
• Managed execution environment
• Handles garbage collection, memory management, JIT compilation
• Converts MSIL to native code using JIT compiler
• Provides exception handling, thread management, and security
• Languages like C#, [Link] compile to MSIL which CLR executes
FCL (Framework Class Library):
• Large library of pre-built classes
• Organized into namespaces: System, [Link], [Link], [Link], [Link]
• Supports file I/O, networking, database access, UI development
• Reduces development time by providing reusable components
Execution Flow: Source Code → Compiler → MSIL → CLR (JIT) → Native Code → Execution
1(b). Describe all primitive data types in C# with size and examples.
[7 Marks]
Answer:
C# Primitive Data Types:
bool – 1 bit – true/false – bool flag = true;
byte – 1 byte – 0 to 255 – byte b = 200;
sbyte – 1 byte – -128 to 127
short – 2 bytes – -32768 to 32767
int – 4 bytes – -2.1B to 2.1B – int age = 25;
long – 8 bytes – large integers – long l = 100000L;
float – 4 bytes – 7 digits precision – float f = 3.14f;
double – 8 bytes – 15 digits precision – double d = 3.14159;
decimal – 16 bytes – financial – decimal price = 99.99m;
char – 2 bytes – single Unicode char – char c = 'A';
string – variable – text – string s = "Hello";
object – base type of all types
Variable naming rules:
• Must start with letter or underscore
• Cannot use C# reserved keywords
• Case-sensitive (age ≠ Age)
PART 2 – Unit II – [Link] and Web Forms
2(a). Explain the Web Forms model in [Link] including page lifecycle.
[7 Marks]
Answer:
[Link] Web Forms:
Web Forms is an event-driven model for building web applications, similar to Windows Forms.
Page Structure (.aspx file):
<%@ Page Language="C#" CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form runat="server">
<!-- Server controls go here -->
</form>
</body>
</html>
Code-Behind (.[Link] file):
public partial class Default : [Link] {
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
[Link] = "Welcome!";
PostBack:
• When user submits form, page posts back to server
• IsPostBack property is true on subsequent requests
• ViewState preserves control values across postbacks
Page Lifecycle Events:
1. PreInit – Set master page, themes
2. Init – Initialize controls
3. InitComplete – Initialization complete
4. PreLoad – Before Load
5. Load – Page_Load fires here
6. Control Events – Button_Click etc.
7. PreRender – Last chance to modify output
8. Render – HTML is generated
9. Unload – Cleanup resources
AutoPostBack – Controls like DropDownList post back automatically when changed.
2(b). List and explain all standard [Link] server controls with properties and events.
[7 Marks]
Answer:
[Link] Standard Server Controls:
1. TextBox:
Properties: Text, TextMode, MaxLength, Columns, Rows, ReadOnly
Events: TextChanged (fires on postback)
2. Button / LinkButton / ImageButton:
Properties: Text, CommandName, CommandArgument
Events: Click, Command
3. Label:
Properties: Text, ForeColor, BackColor, Font, Visible
4. HyperLink:
Properties: Text, NavigateUrl, Target, ImageUrl
5. Image:
Properties: ImageUrl, AlternateText, Width, Height
6. CheckBox:
Properties: Text, Checked, TextAlign, AutoPostBack
Events: CheckedChanged
7. RadioButton:
Properties: Text, GroupName, Checked, AutoPostBack
Events: CheckedChanged
8. DropDownList:
Properties: Items, SelectedIndex, SelectedValue, SelectedItem
Events: SelectedIndexChanged
9. ListBox:
Properties: Items, SelectionMode (Single/Multiple), Rows
Events: SelectedIndexChanged
10. Panel:
Properties: GroupingText, ScrollBars, Visible
Used as container for other controls
11. PlaceHolder:
Holds dynamically added controls
All server controls have runat="server" attribute.
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain Rich Controls in [Link]: Calendar, FileUpload, AdRotator.
[7 Marks]
Answer:
[Link] Rich Controls:
1. Calendar Control:
Displays a monthly calendar.
Properties:
• SelectedDate – Currently selected date
• TodaysDate – Today's date
• SelectionMode (Day/DayWeek/DayWeekMonth/None)
• FirstDayOfWeek
Events: SelectionChanged, VisibleMonthChanged
Example:
protected void cal_SelectionChanged(object sender, EventArgs e) {
[Link] = [Link]();
2. FileUpload Control:
Allows users to upload files to server.
Properties:
• HasFile – true if file selected
• FileName – Name of uploaded file
• PostedFile – The uploaded file object
Usage:
if ([Link])
[Link]([Link]("~/uploads/") + [Link]);
3. AdRotator:
Displays rotating advertisements.
Properties:
• AdvertisementFile – XML file with ad info
• Target – Window to open ad
Events: AdCreated
XML Format:
<Advertisements>
<Ad><ImageUrl>[Link]</ImageUrl><NavigateUrl>[Link]
</Advertisements>
4. MultiView / View:
Creates multiple views in one page.
ActiveViewIndex property switches between views.
5. Wizard Control:
Multi-step form with Next/Back navigation.
3(b). Explain all validation controls in [Link] with examples.
[7 Marks]
Answer:
[Link] Validation Controls:
1. RequiredFieldValidator:
Ensures a field is not empty.
<asp:RequiredFieldValidator ControlToValidate="txtName"
ErrorMessage="Name required!" runat="server" />
2. RangeValidator:
Validates value within min-max range.
Properties: MinimumValue, MaximumValue, Type
Example: Age between 18 and 60.
3. RegularExpressionValidator:
Pattern matching using regex.
Email: ValidationExpression="\\w+@\\w+\\.\\w+"
Mobile: ValidationExpression="^[0-9]{10}$"
4. CompareValidator:
Compares two field values.
Used for password confirmation.
Properties: ControlToCompare, Operator (Equal/GreaterThan/etc.)
5. CustomValidator:
Server-side or client-side custom logic.
Events: ServerValidate
protected void cv_ServerValidate(object src, ServerValidateEventArgs e) {
[Link] = ([Link] > 5);
6. ValidationSummary:
Shows all errors in one place.
Properties: DisplayMode, ShowSummary, ShowMessageBox
Key Properties (all validators):
• ControlToValidate – Target control ID
• ErrorMessage – Message to display
• Display (Static/Dynamic/None)
• IsValid – validation result
[Link] – true only if all validators pass.
PART 4 – Unit IV – [Link] and Database
4(a). Explain [Link] architecture and its components.
[7 Marks]
Answer:
[Link] Architecture:
[Link] (ActiveX Data Objects .NET) is the data access layer in .NET Framework for interacting with
databases.
Two Main Architectures:
1. Connected Architecture:
Requires continuous connection to database.
Components: Connection → Command → DataReader
Best for: Small data reads, quick operations
2. Disconnected Architecture:
Data loaded into memory, connection closed.
Components: Connection → DataAdapter → DataSet
Best for: Large data sets, offline processing
Core [Link] Components:
• Connection (SqlConnection):
Manages database connection
Connection string: "Server=.;Database=myDB;Integrated Security=True;"
• Command (SqlCommand):
Executes SQL: SELECT, INSERT, UPDATE, DELETE
Types: Text, StoredProcedure, TableDirect
• DataReader (SqlDataReader):
Forward-only, read-only data stream
Fast and lightweight
• DataAdapter (SqlDataAdapter):
Bridge between DataSet and database
SelectCommand, InsertCommand, UpdateCommand, DeleteCommand
• DataSet:
In-memory database representation
Contains DataTables, DataRelations, Constraints
• DataTable:
Represents one table of in-memory data
Namespaces:
• [Link] – Core [Link] types
• [Link] – SQL Server provider
• [Link] – Access, Excel provider
4(b). Explain database connections in [Link] with connection string examples.
[7 Marks]
Answer:
Database Connections in [Link]:
SqlConnection Class:
Used to connect to Microsoft SQL Server.
Connection String Formats:
1. Windows Authentication (Integrated Security):
string cs = "Server=localhost;Database=SchoolDB;Integrated Security=True;";
2. SQL Server Authentication:
string cs = "Server=localhost;Database=SchoolDB;User Id=sa;Password=pass123;";
3. Named Instance:
string cs = "Server=PC\\SQLEXPRESS;Database=myDB;Integrated Security=True;";
Opening and Closing Connection:
SqlConnection con = new SqlConnection(connectionString);
try {
[Link]();
// Perform database operations
[Link]("State: " + [Link]); // Open
} catch (SqlException ex) {
[Link]("Error: " + [Link]);
} finally {
[Link](); // Always close in finally
Using Statement (recommended):
using (SqlConnection con = new SqlConnection(cs)) {
[Link]();
// Operations here
} // Auto-closed
ConnectionState Enum:
• Open, Closed, Connecting, Executing, Fetching
Best Practices:
• Store connection string in [Link] <connectionStrings> section
• Always use try-catch-finally
• Use 'using' statement for automatic disposal
• Connection pooling is automatic in [Link]
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Write a complete program for GridView with Edit, Delete, Sort and Page.
[7 Marks]
Answer:
GridView Complete Program:
ASPX:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" PageSize="5"
DataKeyNames="StudentID"
OnSorting="gv_Sorting"
OnPageIndexChanging="gv_PageIndexChanging"
OnRowEditing="gv_RowEditing"
OnRowUpdating="gv_RowUpdating"
OnRowCancelingEdit="gv_RowCancelingEdit"
OnRowDeleting="gv_RowDeleting">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Marks" HeaderText="Marks" SortExpression="Marks" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
C# Code-Behind:
protected void BindGrid() {
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", cs);
DataTable dt = new DataTable();
[Link](dt);
[Link] = dt;
[Link]();
protected void gv_PageIndexChanging(object s, GridViewPageEventArgs e) {
[Link] = [Link]; BindGrid();
protected void gv_RowEditing(object s, GridViewEditEventArgs e) {
[Link] = [Link]; BindGrid();
protected void gv_RowCancelingEdit(object s, GridViewCancelEditEventArgs e) {
[Link] = -1; BindGrid();
protected void gv_RowUpdating(object s, GridViewUpdateEventArgs e) {
string name = ((TextBox)[Link][[Link]].Cells[0].Controls[0]).Text;
// Execute UPDATE SQL
[Link] = -1; BindGrid();
protected void gv_RowDeleting(object s, GridViewDeleteEventArgs e) {
int id = (int)[Link][[Link]].Value;
// Execute DELETE SQL WHERE StudentID = id
BindGrid();
5(b). Explain XML classes in .NET for reading and writing XML.
[7 Marks]
Answer:
XML in .NET Framework:
Key XML Classes ([Link] namespace):
1. XmlDocument:
DOM-based approach (loads entire XML into memory).
Reading XML:
XmlDocument doc = new XmlDocument();
[Link]([Link]("[Link]"));
XmlNodeList nodes = [Link]("Student");
foreach (XmlNode node in nodes) {
string name = node["Name"].InnerText;
string marks = node["Marks"].InnerText;
[Link](name + " - " + marks + "<br/>");
Creating XML:
XmlDocument doc = new XmlDocument();
XmlElement root = [Link]("Students");
XmlElement student = [Link]("Student");
[Link]("ID", "1");
XmlElement name = [Link]("Name");
[Link] = "Alice";
[Link](name);
[Link](student);
[Link](root);
[Link]([Link]("[Link]"));
2. XmlReader (forward-only reading, fast):
using (XmlReader reader = [Link]("[Link]")) {
while ([Link]()) {
if ([Link] == [Link])
[Link]([Link]);
3. XmlWriter (forward-only writing):
using (XmlWriter writer = [Link]("[Link]")) {
[Link]();
[Link]("Root");
[Link]("Name", "Alice");
[Link]();
[Link]();
— End of Model 9 —
MODEL QUESTION PAPER – 10
Subject: [Link] Web Programming Model: 10 / 10
Answer ALL Questions Each Question: 14 Marks | Total: 70 Marks
PART 1 – Unit I – C# and .NET Framework
1(a). Describe all primitive data types in C# with size and examples.
[7 Marks]
Answer:
C# Primitive Data Types:
bool – 1 bit – true/false – bool flag = true;
byte – 1 byte – 0 to 255 – byte b = 200;
sbyte – 1 byte – -128 to 127
short – 2 bytes – -32768 to 32767
int – 4 bytes – -2.1B to 2.1B – int age = 25;
long – 8 bytes – large integers – long l = 100000L;
float – 4 bytes – 7 digits precision – float f = 3.14f;
double – 8 bytes – 15 digits precision – double d = 3.14159;
decimal – 16 bytes – financial – decimal price = 99.99m;
char – 2 bytes – single Unicode char – char c = 'A';
string – variable – text – string s = "Hello";
object – base type of all types
Variable naming rules:
• Must start with letter or underscore
• Cannot use C# reserved keywords
• Case-sensitive (age ≠ Age)
1(b). Explain different types of operators in C# with examples.
[7 Marks]
Answer:
C# Operators:
1. Arithmetic Operators: +, -, *, /, %
int a=10, b=3; a/b=3, a%b=1
2. Relational Operators: ==, !=, >, <, >=, <=
Return bool: (5 > 3) → true
3. Logical Operators: && (AND), || (OR), ! (NOT)
Used to combine boolean expressions
4. Assignment Operators: =, +=, -=, *=, /=, %=
a += 5 means a = a + 5
5. Increment/Decrement: ++, --
Pre: ++a (increment then use)
Post: a++ (use then increment)
6. Bitwise Operators: &, |, ^, ~, <<, >>
Operate on binary representation
7. Ternary Operator: condition ? true_val : false_val
int max = (a > b) ? a : b;
8. typeof and sizeof operators
sizeof(int) returns 4
PART 2 – Unit II – [Link] and Web Forms
2(a). List and explain all standard [Link] server controls with properties and events.
[7 Marks]
Answer:
[Link] Standard Server Controls:
1. TextBox:
Properties: Text, TextMode, MaxLength, Columns, Rows, ReadOnly
Events: TextChanged (fires on postback)
2. Button / LinkButton / ImageButton:
Properties: Text, CommandName, CommandArgument
Events: Click, Command
3. Label:
Properties: Text, ForeColor, BackColor, Font, Visible
4. HyperLink:
Properties: Text, NavigateUrl, Target, ImageUrl
5. Image:
Properties: ImageUrl, AlternateText, Width, Height
6. CheckBox:
Properties: Text, Checked, TextAlign, AutoPostBack
Events: CheckedChanged
7. RadioButton:
Properties: Text, GroupName, Checked, AutoPostBack
Events: CheckedChanged
8. DropDownList:
Properties: Items, SelectedIndex, SelectedValue, SelectedItem
Events: SelectedIndexChanged
9. ListBox:
Properties: Items, SelectionMode (Single/Multiple), Rows
Events: SelectedIndexChanged
10. Panel:
Properties: GroupingText, ScrollBars, Visible
Used as container for other controls
11. PlaceHolder:
Holds dynamically added controls
All server controls have runat="server" attribute.
2(b). Explain HTML server controls in [Link].
[7 Marks]
Answer:
HTML Server Controls:
HTML controls are standard HTML elements with runat="server" attribute added, making them accessible
from server-side code.
Converting HTML to Server Control:
<input type="text" id="txtName" runat="server" />
Now accessible as: [Link]
Common HTML Server Controls:
1. HtmlInputText:
<input type="text" id="txt1" runat="server" />
Properties: Value, MaxLength, Size, ReadOnly
2. HtmlInputButton:
<input type="button" id="btn1" runat="server" />
Events: ServerClick
3. HtmlInputCheckBox:
<input type="checkbox" id="chk1" runat="server" />
Properties: Checked, Value
4. HtmlInputRadioButton:
<input type="radio" id="rb1" runat="server" />
Properties: Checked, Value, Name (for grouping)
5. HtmlSelect:
<select id="sel1" runat="server"></select>
Properties: Items, SelectedIndex, Multiple
6. HtmlTextArea:
<textarea id="ta1" runat="server"></textarea>
Properties: Value, Rows, Cols
7. HtmlAnchor:
<a id="lnk1" runat="server">Click</a>
Properties: HRef, Target
Difference from [Link] Server Controls:
• HTML controls map directly to HTML elements
• Less overhead, simpler model
• [Link] controls provide richer functionality
PART 3 – Unit III – Rich Controls, Validation and File Handling
3(a). Explain all validation controls in [Link] with examples.
[7 Marks]
Answer:
[Link] Validation Controls:
1. RequiredFieldValidator:
Ensures a field is not empty.
<asp:RequiredFieldValidator ControlToValidate="txtName"
ErrorMessage="Name required!" runat="server" />
2. RangeValidator:
Validates value within min-max range.
Properties: MinimumValue, MaximumValue, Type
Example: Age between 18 and 60.
3. RegularExpressionValidator:
Pattern matching using regex.
Email: ValidationExpression="\\w+@\\w+\\.\\w+"
Mobile: ValidationExpression="^[0-9]{10}$"
4. CompareValidator:
Compares two field values.
Used for password confirmation.
Properties: ControlToCompare, Operator (Equal/GreaterThan/etc.)
5. CustomValidator:
Server-side or client-side custom logic.
Events: ServerValidate
protected void cv_ServerValidate(object src, ServerValidateEventArgs e) {
[Link] = ([Link] > 5);
6. ValidationSummary:
Shows all errors in one place.
Properties: DisplayMode, ShowSummary, ShowMessageBox
Key Properties (all validators):
• ControlToValidate – Target control ID
• ErrorMessage – Message to display
• Display (Static/Dynamic/None)
• IsValid – validation result
[Link] – true only if all validators pass.
3(b). Explain FileStream, StreamReader and StreamWriter with examples.
[7 Marks]
Answer:
File Handling in C# ([Link] Namespace):
1. FileStream Class:
Provides byte-level file access.
Constructor: FileStream(path, FileMode, FileAccess)
FileAccess: Read, Write, ReadWrite
Example – Write bytes:
FileStream fs = new FileStream("[Link]", [Link], [Link]);
byte[] data = {65, 66, 67}; // ABC
[Link](data, 0, [Link]);
[Link]();
2. StreamWriter Class:
Writes text to files.
Example:
StreamWriter sw = new StreamWriter("[Link]");
[Link]("Hello World");
[Link]("[Link] Programming");
[Link]();
Using statement (auto-closes):
using (StreamWriter sw = new StreamWriter("[Link]")) {
[Link]("Content here");
3. StreamReader Class:
Reads text from files.
Example:
StreamReader sr = new StreamReader("[Link]");
string line;
while ((line = [Link]()) != null)
[Link](line);
[Link]();
ReadToEnd() – reads entire file as string:
string content = [Link]();
Note: Always close streams in finally block or use 'using' statement to free resources.
PART 4 – Unit IV – [Link] and Database
4(a). Explain database connections in [Link] with connection string examples.
[7 Marks]
Answer:
Database Connections in [Link]:
SqlConnection Class:
Used to connect to Microsoft SQL Server.
Connection String Formats:
1. Windows Authentication (Integrated Security):
string cs = "Server=localhost;Database=SchoolDB;Integrated Security=True;";
2. SQL Server Authentication:
string cs = "Server=localhost;Database=SchoolDB;User Id=sa;Password=pass123;";
3. Named Instance:
string cs = "Server=PC\\SQLEXPRESS;Database=myDB;Integrated Security=True;";
Opening and Closing Connection:
SqlConnection con = new SqlConnection(connectionString);
try {
[Link]();
// Perform database operations
[Link]("State: " + [Link]); // Open
} catch (SqlException ex) {
[Link]("Error: " + [Link]);
} finally {
[Link](); // Always close in finally
Using Statement (recommended):
using (SqlConnection con = new SqlConnection(cs)) {
[Link]();
// Operations here
} // Auto-closed
ConnectionState Enum:
• Open, Closed, Connecting, Executing, Fetching
Best Practices:
• Store connection string in [Link] <connectionStrings> section
• Always use try-catch-finally
• Use 'using' statement for automatic disposal
• Connection pooling is automatic in [Link]
4(b). Explain SqlCommand class with ExecuteReader, ExecuteNonQuery and
ExecuteScalar.
[7 Marks]
Answer:
SqlCommand in [Link]:
SqlCommand executes SQL statements against SQL Server.
Creating Command:
SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con);
// or
[Link] = "INSERT INTO Students VALUES(@name, @age)";
[Link] = [Link];
CommandType Enum:
• Text – SQL string (default)
• StoredProcedure – Calls a stored procedure
• TableDirect – Returns entire table
1. ExecuteReader():
Returns SqlDataReader for SELECT queries.
SqlDataReader dr = [Link]();
while ([Link]()) {
[Link](dr["Name"] + " " + dr["Age"]);
[Link]();
2. ExecuteNonQuery():
For INSERT, UPDATE, DELETE. Returns rows affected.
[Link] = "DELETE FROM Students WHERE ID=@id";
[Link]("@id", 5);
int rows = [Link]();
[Link](rows + " row(s) deleted.");
3. ExecuteScalar():
Returns single value (first row, first column).
[Link] = "SELECT COUNT(*) FROM Students";
int count = (int)[Link]();
Parameters (prevent SQL Injection):
[Link]("@name", [Link]);
[Link]("@age", [Link]).Value = 20;
Always use parameters instead of string concatenation!
PART 5 – Unit V – GridView, XML, Security and Web Application
5(a). Explain XML classes in .NET for reading and writing XML.
[7 Marks]
Answer:
XML in .NET Framework:
Key XML Classes ([Link] namespace):
1. XmlDocument:
DOM-based approach (loads entire XML into memory).
Reading XML:
XmlDocument doc = new XmlDocument();
[Link]([Link]("[Link]"));
XmlNodeList nodes = [Link]("Student");
foreach (XmlNode node in nodes) {
string name = node["Name"].InnerText;
string marks = node["Marks"].InnerText;
[Link](name + " - " + marks + "<br/>");
}
Creating XML:
XmlDocument doc = new XmlDocument();
XmlElement root = [Link]("Students");
XmlElement student = [Link]("Student");
[Link]("ID", "1");
XmlElement name = [Link]("Name");
[Link] = "Alice";
[Link](name);
[Link](student);
[Link](root);
[Link]([Link]("[Link]"));
2. XmlReader (forward-only reading, fast):
using (XmlReader reader = [Link]("[Link]")) {
while ([Link]()) {
if ([Link] == [Link])
[Link]([Link]);
3. XmlWriter (forward-only writing):
using (XmlWriter writer = [Link]("[Link]")) {
[Link]();
[Link]("Root");
[Link]("Name", "Alice");
[Link]();
[Link]();
5(b). Write an [Link] program to add, display and delete XML records.
[7 Marks]
Answer:
XML Manipulation using Web Forms:
[Link] structure:
<Students>
<Student>
<ID>1</ID>
<Name>Alice</Name>
<Marks>90</Marks>
</Student>
</Students>
[Link]:
<asp:TextBox ID="txtName" runat="server" />
<asp:TextBox ID="txtMarks" runat="server" />
<asp:Button ID="btnAdd" Text="Add" OnClick="btnAdd_Click" runat="server" />
<asp:Button ID="btnLoad" Text="Load" OnClick="btnLoad_Click" runat="server" />
<asp:GridView ID="gvStudents" runat="server" />
Code-Behind:
string xmlPath;
protected void Page_Load(object sender, EventArgs e) {
xmlPath = [Link]("~/App_Data/[Link]");
protected void btnAdd_Click(object sender, EventArgs e) {
XmlDocument doc = new XmlDocument();
if ([Link](xmlPath)) [Link](xmlPath);
else [Link]([Link]("Students"));
XmlElement s = [Link]("Student");
XmlElement nm = [Link]("Name");
[Link] = [Link];
XmlElement mk = [Link]("Marks");
[Link] = [Link];
[Link](nm); [Link](mk);
[Link](s);
[Link](xmlPath);
[Link] = "Record added!";
protected void btnLoad_Click(object sender, EventArgs e) {
DataSet ds = new DataSet();
[Link](xmlPath);
[Link] = ds;
[Link]();
— End of Model 10 —