CSC378 · Exam intelligence
NET Centric Computing important questions
From 5 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.
Most likely in the next examStatistical
Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2081 paper. No guarantees; study the whole syllabus.
1asked 5xavg 6 marks · due (skipped 2081) · Common VulnerabilitiesAnswerHideExplain the chances of SQL injection attack with a scenario. [5]
Explain the chances of SQL injection attack with a scenario. [5]
SQL Injection (SQLI) is a common attack vector that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. It usually occurs when a user provides an SQL statement as input i...
2asked 3xavg 15 marks · due (skipped 2081) · LINQAnswerHideWrite short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]
Write short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]
Short Notes (Any Two)
a. Lambda Expression
Definition
A lambda expression is an anonymous function that can be used to create delegates or expression tree types. Lambda expressions are a concise way to write inline functions and are heavily used in LINQ (Language Integrated Query) in C#.
Syntax
(parameters) => expression
or for a block body:
(parameters) => { statements; }
Key Characteristics
- The
=>operator is called the lambda operator and is read as "goes to". - Lambda expressions can have zero, one, or multiple parameters.
- They can be used wherever a delegate type is expected.
- They are a core part of LINQ support in C#, alongside query expressions, object initializers, and collections.
Example
// Simple lambda expression
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
// Lambda with LINQ
int[] scores = new int[] { 97, 92, 83, 60 };
var highScores = scores.Where(score => score > 80);
foreach (int s in highScores)
Console.WriteLine(s);
// Output: 97 92 83
Why Use Lambda Expressions?
- Makes code shorter and more readable.
- Eliminates the need to define a separate named method for simple operations.
- Integrates seamlessly with LINQ to query collections, databases, XML, and more.
- Supports functional programming style in C#.
b. Cross Site Request Forgery (CSRF)
Definition
Cross-Site Request Forgery (CSRF) is a web security attack where an attacker tricks an authenticated user into unknowingly submitting a malicious request to a web application on which the user is currently authenticated.
How CSRF Works
- The user logs into a trusted website (e.g., a banking site) and a session cookie is stored in the browser.
- Without logging out, the user visits a malicious website.
- The malicious site contains a hidden request (e.g., a form or image tag) that sends a request to the trusted website.
- Since the browser automatically includes the session cookie, the trusted website processes the request as if it came from the legitimate user.
Example Attack Scenario
<!-- Malicious page sends a hidden request to the bank -->
<img src="http://bank.com/transfer?amount=10000&to=attacker" />
The browser automatically sends the authenticated cookie along with this request.
Difference from XSS
| Feature | XSS | CSRF |
|---|---|---|
| Attack target | Other users via injected scripts | Authenticated user's session |
| Mechanism | Injects malicious scripts into pages | Forges requests using existing session |
| Trust exploited | User trusts the website | Website trusts the user's browser |
Prevention Techniques
- Anti-CSRF Tokens: Include a unique, secret token in every form that the server validates.
- SameSite Cookie Attribute: Restricts cookies from being sent with cross-site requests.
- Re-authentication: Require password confirmation for sensitive actions.
- Checking Referer/Origin headers: Validate that requests originate from the expected domain.
c. Single Page Application (SPA)
Definition
A Single Page Application (SPA) is a web application that loads a single HTML page and dynamically updates the content as the user interacts with the app, without requiring a full page reload from the server.
How SPA Works
- On the first request, the server sends a single HTML page along with all necessary JavaScript and CSS.
- Subsequent interactions (navigation, data loading) are handled via AJAX calls to the server, which returns only data (typically JSON), not full HTML pages.
- The browser's JavaScript framework (e.g., Angular, React, Vue.js) updates the DOM dynamically.
Architecture Diagram
User Action --> JavaScript (Client Side) --> AJAX Request --> Server API
| |
DOM Updated <-------------- JSON Response -----+
Key Characteristics
- Only one full page load occurs (at the start).
- Uses client-side routing to simulate navigation between pages.
- Heavy use of JavaScript frameworks like Angular, React, or Vue.js.
- Communicates with the backend via REST APIs or GraphQL.
Advantages
| Advantage | Description |
|---|---|
| Fast and responsive | No full page reloads; only data is exchanged |
| Better user experience | Feels like a desktop application |
| Reduced server load | Server only sends data, not full HTML |
| Separation of concerns | Frontend and backend are clearly separated |
Disadvantages
- SEO challenges: Search engines may struggle to index dynamically loaded content.
- Initial load time can be slow as all JavaScript is loaded upfront.
- Browser history management requires extra handling.
- Security: Requires careful handling of authentication tokens (e.g., JWT).
Example Technologies
- Frameworks: Angular, React, Vue.js
- Communication: AJAX, Fetch API, Axios
- Routing: React Router, Angular Router
3asked 5xavg 6 marks · App Servers and Hosting modelsAnswerHideDescribe the procedure of deploying .NET core application. [5]
Describe the procedure of deploying .NET core application. [5]
Deploying a .NET Core Application
Introduction
.NET Core is a cross-platform framework, and its Command-Line Interface (CLI) provides tools to build, run, test, and publish .NET Core applications. The .NET Core CLI is installed with the .NET Core SDK and does not need to be installed separately.
Step-by-Step Deployment Procedure
Step 1: Verify .NET Core CLI Installation
Before deploying, confirm that the CLI is properly installed by opening the command prompt and typing:
dotnet
If it displays usage information, the CLI is installed correctly.
Step 2: Create the Application
Create a new project directory and initialize the application using CLI commands:
mkdir myapp
cd myapp
dotnet new console
This creates the necessary project files:
Program.cs(main source file)myapp.csproj(project configuration file)
Step 3: Restore Packages
Restore all required NuGet packages and dependencies:
dotnet restore
This ensures all dependencies defined in the .csproj file are downloaded and available.
Step 4: Build the Application
Compile the application to check for errors and generate the build output:
dotnet build
Note: When using .NET Core SDK, the application is built automatically when needed, so there is no need to worry about executing outdated code.
Step 5: Run the Application (Testing)
Test the application locally before deployment:
dotnet run
This compiles (if needed) and executes the application directly.
Step 6: Publish the Application
Publish the application to prepare it for deployment on a target server:
dotnet publish -c Release -o ./publish
-c Releasespecifies the Release configuration (optimized build)-o ./publishspecifies the output directory where published files are placed
This generates all necessary files (DLLs, configuration files, runtime files) in the output folder.
Step 7: Deploy to the Server
Copy the published output to the target server. For a web application, the deployment typically involves:
- Placing the published files on the server
- Configuring a reverse proxy (such as IIS, Nginx, or Apache)
- The reverse proxy receives requests from the browser and passes them to the ASP.NET Core application, which runs a self-hosted web server (Kestrel)
Browser --> Reverse Proxy (IIS/Nginx) --> ASP.NET Core App (Kestrel)
Summary Table
| Step | Command | Purpose |
|---|---|---|
| Verify CLI | dotnet | Check installation |
| Create App | dotnet new console | Initialize project |
| Restore | dotnet restore | Download dependencies |
| Build | dotnet build | Compile source code |
| Run | dotnet run | Test locally |
| Publish | dotnet publish | Prepare for deployment |
Conclusion
The .NET Core CLI provides a simple and consistent cross-platform procedure for deploying applications. Higher-level IDEs like Visual Studio internally use the same CLI commands to restore, build, and publish .NET Core applications.
4asked 4xavg 6 marks · ADO.NET basicsAnswerHideList some advantages of Entity Framework over ADO.NET. Assume a database named 'IOST' with a table FACULTY(Course_Name, CourseID, No_of_Semester, fee). Insert some records using ADO.NET and retrive the fee of records having name CSIT.[10]
List some advantages of Entity Framework over ADO.NET. Assume a database named 'IOST' with a table FACULTY(Course_Name, CourseID, No_of_Semester, fee). Insert some records using ADO.NET and retrive the fee of records having name CSIT.[10]
Entity Framework vs ADO.NET and ADO.NET Database Operations
Part 1: Advantages of Entity Framework over ADO.NET
Entity Framework (EF) is an Object/Relational Mapping (O/RM) framework that is an enhancement to ADO.NET giving developers an automated mechanism for accessing and storing data in the database.
| # | Advantage of Entity Framework | ADO.NET Limitation |
|---|---|---|
| 1 | Automated Data Access: EF provides automated mechanism for accessing and storing data; no need to write raw SQL queries manually | ADO.NET requires writing explicit SQL queries for every operation |
| 2 | O/RM Support: Maps database tables directly to C# classes (domain objects), so developers work with objects instead of tables | ADO.NET works at a lower level with DataReaders, DataSets, and manual mapping |
| 3 | Cross-Platform: EF Core is open-source, lightweight, extensible and cross-platform | ADO.NET has limited cross-platform support |
| 4 | Two Development Approaches: Supports Code-First and Database-First approaches giving flexibility in design | ADO.NET does not support code-first or migration-based schema generation |
| 5 | Migration Support: In Code-First, EF Core API creates the database and tables using migration based on conventions and configuration in domain classes | ADO.NET requires manual creation and management of database schema |
| 6 | Less Boilerplate Code: CRUD operations require significantly fewer lines of code using EF | ADO.NET requires verbose code (connection, command, reader, etc.) for every operation |
| 7 | Domain Driven Design (DDD): Code-First approach is useful in DDD, making it suitable for enterprise applications | ADO.NET is not aligned with DDD principles |
| 8 | Works with .NET Core and .NET 4.5+: EF Core is intended for .NET Core but also supports standard .NET 4.5+ applications | ADO.NET is primarily tied to the traditional .NET framework |
Part 2: ADO.NET - Insert Records and Retrieve Fee for CSIT
Database Setup Assumption
- Database Name:
IOST - Table:
FACULTY(Course_Name, CourseID, No_of_Semester, fee)
Step 1: Create the Table in SQL Server (for reference)
CREATE DATABASE IOST;
USE IOST;
CREATE TABLE FACULTY (
Course_Name VARCHAR(100),
CourseID INT PRIMARY KEY,
No_of_Semester INT,
fee DECIMAL(10, 2)
);
Step 2: Full ADO.NET C# Code - Insert Records and Retrieve Fee for CSIT
using System;
using System.Data;
using System.Data.SqlClient;
namespace IOSTFacultyApp
{
class Program
{
// Connection string pointing to IOST database
static string connectionString =
"Data Source=.;Initial Catalog=IOST;Integrated Security=True";
static void Main(string[] args)
{
// Step 1: Insert records into FACULTY table
InsertFaculty("CSIT", 1, 8, 75000.00m);
InsertFaculty("BCA", 2, 6, 55000.00m);
InsertFaculty("CSIT", 3, 8, 80000.00m);
InsertFaculty("BIT", 4, 8, 60000.00m);
Console.WriteLine("Records inserted successfully.\n");
// Step 2: Retrieve fee of records where Course_Name = 'CSIT'
RetrieveCSITFee();
Console.ReadLine();
}
// -------------------------------------------------------
// Method to INSERT a record into FACULTY table
// -------------------------------------------------------
static void InsertFaculty(string courseName, int courseID,
int noOfSemester, decimal fee)
{
// SQL INSERT query using parameterized query to prevent SQL injection
string insertQuery = @"INSERT INTO FACULTY
(Course_Name, CourseID, No_of_Semester, fee)
VALUES
(@CourseName, @CourseID, @NoOfSemester, @Fee)";
// Using block ensures connection is closed automatically
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, con))
{
// Add parameters to avoid SQL injection
cmd.Parameters.AddWithValue("@CourseName", courseName);
cmd.Parameters.AddWithValue("@CourseID", courseID);
cmd.Parameters.AddWithValue("@NoOfSemester", noOfSemester);
cmd.Parameters.AddWithValue("@Fee", fee);
// Open connection
con.Open();
// Execute the INSERT command
int rowsAffected = cmd.ExecuteNonQuery();
Console.WriteLine($"Inserted: {courseName} | Rows Affected: {rowsAffected}");
}
// Connection is closed automatically at end of using block
}
}
// -------------------------------------------------------
// Method to RETRIEVE fee of FACULTY records where
// Course_Name = 'CSIT'
// -------------------------------------------------------
static void RetrieveCSITFee()
{
// SQL SELECT query with WHERE clause to filter CSIT records
string selectQuery = @"SELECT Course_Name, CourseID,
No_of_Semester, fee
FROM FACULTY
WHERE Course_Name = @CourseName";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(selectQuery, con))
{
// Parameterized filter for Course_Name
cmd.Parameters.AddWithValue("@CourseName, "CSIT");
con.Open();
// Execute the query and read results row by row
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Fee details for CSIT:");
Console.WriteLine("Course_Name | CourseID | No_of_Semester | Fee");
while (reader.Read())
{
Console.WriteLine(
$"{reader["Course_Name"]} | {reader["CourseID"]} | " +
$"{reader["No_of_Semester"]} | {reader["fee"]}"
);
}
reader.Close();
}
// Connection is closed automatically at end of using block
}
}
}
}
The InsertFaculty method uses a parameterized INSERT with AddWithValue for every field, guarding against SQL injection while adding the four faculty records (two of which are CSIT). The RetrieveCSITFee method then runs a parameterized SELECT ... WHERE Course_Name = @CourseName filtered to "CSIT", opens a SqlDataReader, and loops over reader.Read() to print each matching row's course name, course ID, number of semesters, and fee, giving exactly the fee details for the CSIT records that were inserted.
5asked 3xavg 5 marks · due (skipped 2081) · Server-side strategiesAnswerHideGive an example to manage the session state. [5]
Give an example to manage the session state. [5]
Session State is an ASP.NET Core mechanism to store user data while the user browses the application. It uses a store maintained by the application to carry on data across requests from a client. ASP.NET Core maintains the session state ...
Most repeated questions
Topics asked at least twice, most-asked first.
asked 5xavg 6 marks · 2080, 2079, 2078AnswerHideExplain the chances of SQL injection attack with a scenario. [5]
Explain the chances of SQL injection attack with a scenario. [5]
SQL Injection (SQLI) is a common attack vector that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. It usually occurs when a user provides an SQL statement as input i...
asked 5xavg 6 marks · 2081, 2079, 2078, 2076AnswerHideDescribe the procedure of deploying .NET core application. [5]
Describe the procedure of deploying .NET core application. [5]
Deploying a .NET Core Application
Introduction
.NET Core is a cross-platform framework, and its Command-Line Interface (CLI) provides tools to build, run, test, and publish .NET Core applications. The .NET Core CLI is installed with the .NET Core SDK and does not need to be installed separately.
Step-by-Step Deployment Procedure
Step 1: Verify .NET Core CLI Installation
Before deploying, confirm that the CLI is properly installed by opening the command prompt and typing:
dotnet
If it displays usage information, the CLI is installed correctly.
Step 2: Create the Application
Create a new project directory and initialize the application using CLI commands:
mkdir myapp
cd myapp
dotnet new console
This creates the necessary project files:
Program.cs(main source file)myapp.csproj(project configuration file)
Step 3: Restore Packages
Restore all required NuGet packages and dependencies:
dotnet restore
This ensures all dependencies defined in the .csproj file are downloaded and available.
Step 4: Build the Application
Compile the application to check for errors and generate the build output:
dotnet build
Note: When using .NET Core SDK, the application is built automatically when needed, so there is no need to worry about executing outdated code.
Step 5: Run the Application (Testing)
Test the application locally before deployment:
dotnet run
This compiles (if needed) and executes the application directly.
Step 6: Publish the Application
Publish the application to prepare it for deployment on a target server:
dotnet publish -c Release -o ./publish
-c Releasespecifies the Release configuration (optimized build)-o ./publishspecifies the output directory where published files are placed
This generates all necessary files (DLLs, configuration files, runtime files) in the output folder.
Step 7: Deploy to the Server
Copy the published output to the target server. For a web application, the deployment typically involves:
- Placing the published files on the server
- Configuring a reverse proxy (such as IIS, Nginx, or Apache)
- The reverse proxy receives requests from the browser and passes them to the ASP.NET Core application, which runs a self-hosted web server (Kestrel)
Browser --> Reverse Proxy (IIS/Nginx) --> ASP.NET Core App (Kestrel)
Summary Table
| Step | Command | Purpose |
|---|---|---|
| Verify CLI | dotnet | Check installation |
| Create App | dotnet new console | Initialize project |
| Restore | dotnet restore | Download dependencies |
| Build | dotnet build | Compile source code |
| Run | dotnet run | Test locally |
| Publish | dotnet publish | Prepare for deployment |
Conclusion
The .NET Core CLI provides a simple and consistent cross-platform procedure for deploying applications. Higher-level IDEs like Visual Studio internally use the same CLI commands to restore, build, and publish .NET Core applications.
asked 4xavg 6 marks · 2081, 2080, 2079, 2076AnswerHideList some advantages of Entity Framework over ADO.NET. Assume a database named 'IOST' with a table FACULTY(Course_Name, CourseID, No_of_Semester, fee). Insert some records using ADO.NET and retrive the fee of records having name CSIT.[10]
List some advantages of Entity Framework over ADO.NET. Assume a database named 'IOST' with a table FACULTY(Course_Name, CourseID, No_of_Semester, fee). Insert some records using ADO.NET and retrive the fee of records having name CSIT.[10]
Entity Framework vs ADO.NET and ADO.NET Database Operations
Part 1: Advantages of Entity Framework over ADO.NET
Entity Framework (EF) is an Object/Relational Mapping (O/RM) framework that is an enhancement to ADO.NET giving developers an automated mechanism for accessing and storing data in the database.
| # | Advantage of Entity Framework | ADO.NET Limitation |
|---|---|---|
| 1 | Automated Data Access: EF provides automated mechanism for accessing and storing data; no need to write raw SQL queries manually | ADO.NET requires writing explicit SQL queries for every operation |
| 2 | O/RM Support: Maps database tables directly to C# classes (domain objects), so developers work with objects instead of tables | ADO.NET works at a lower level with DataReaders, DataSets, and manual mapping |
| 3 | Cross-Platform: EF Core is open-source, lightweight, extensible and cross-platform | ADO.NET has limited cross-platform support |
| 4 | Two Development Approaches: Supports Code-First and Database-First approaches giving flexibility in design | ADO.NET does not support code-first or migration-based schema generation |
| 5 | Migration Support: In Code-First, EF Core API creates the database and tables using migration based on conventions and configuration in domain classes | ADO.NET requires manual creation and management of database schema |
| 6 | Less Boilerplate Code: CRUD operations require significantly fewer lines of code using EF | ADO.NET requires verbose code (connection, command, reader, etc.) for every operation |
| 7 | Domain Driven Design (DDD): Code-First approach is useful in DDD, making it suitable for enterprise applications | ADO.NET is not aligned with DDD principles |
| 8 | Works with .NET Core and .NET 4.5+: EF Core is intended for .NET Core but also supports standard .NET 4.5+ applications | ADO.NET is primarily tied to the traditional .NET framework |
Part 2: ADO.NET - Insert Records and Retrieve Fee for CSIT
Database Setup Assumption
- Database Name:
IOST - Table:
FACULTY(Course_Name, CourseID, No_of_Semester, fee)
Step 1: Create the Table in SQL Server (for reference)
CREATE DATABASE IOST;
USE IOST;
CREATE TABLE FACULTY (
Course_Name VARCHAR(100),
CourseID INT PRIMARY KEY,
No_of_Semester INT,
fee DECIMAL(10, 2)
);
Step 2: Full ADO.NET C# Code - Insert Records and Retrieve Fee for CSIT
using System;
using System.Data;
using System.Data.SqlClient;
namespace IOSTFacultyApp
{
class Program
{
// Connection string pointing to IOST database
static string connectionString =
"Data Source=.;Initial Catalog=IOST;Integrated Security=True";
static void Main(string[] args)
{
// Step 1: Insert records into FACULTY table
InsertFaculty("CSIT", 1, 8, 75000.00m);
InsertFaculty("BCA", 2, 6, 55000.00m);
InsertFaculty("CSIT", 3, 8, 80000.00m);
InsertFaculty("BIT", 4, 8, 60000.00m);
Console.WriteLine("Records inserted successfully.\n");
// Step 2: Retrieve fee of records where Course_Name = 'CSIT'
RetrieveCSITFee();
Console.ReadLine();
}
// -------------------------------------------------------
// Method to INSERT a record into FACULTY table
// -------------------------------------------------------
static void InsertFaculty(string courseName, int courseID,
int noOfSemester, decimal fee)
{
// SQL INSERT query using parameterized query to prevent SQL injection
string insertQuery = @"INSERT INTO FACULTY
(Course_Name, CourseID, No_of_Semester, fee)
VALUES
(@CourseName, @CourseID, @NoOfSemester, @Fee)";
// Using block ensures connection is closed automatically
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, con))
{
// Add parameters to avoid SQL injection
cmd.Parameters.AddWithValue("@CourseName", courseName);
cmd.Parameters.AddWithValue("@CourseID", courseID);
cmd.Parameters.AddWithValue("@NoOfSemester", noOfSemester);
cmd.Parameters.AddWithValue("@Fee", fee);
// Open connection
con.Open();
// Execute the INSERT command
int rowsAffected = cmd.ExecuteNonQuery();
Console.WriteLine($"Inserted: {courseName} | Rows Affected: {rowsAffected}");
}
// Connection is closed automatically at end of using block
}
}
// -------------------------------------------------------
// Method to RETRIEVE fee of FACULTY records where
// Course_Name = 'CSIT'
// -------------------------------------------------------
static void RetrieveCSITFee()
{
// SQL SELECT query with WHERE clause to filter CSIT records
string selectQuery = @"SELECT Course_Name, CourseID,
No_of_Semester, fee
FROM FACULTY
WHERE Course_Name = @CourseName";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(selectQuery, con))
{
// Parameterized filter for Course_Name
cmd.Parameters.AddWithValue("@CourseName, "CSIT");
con.Open();
// Execute the query and read results row by row
SqlDataReader reader = cmd.ExecuteReader();
Console.WriteLine("Fee details for CSIT:");
Console.WriteLine("Course_Name | CourseID | No_of_Semester | Fee");
while (reader.Read())
{
Console.WriteLine(
$"{reader["Course_Name"]} | {reader["CourseID"]} | " +
$"{reader["No_of_Semester"]} | {reader["fee"]}"
);
}
reader.Close();
}
// Connection is closed automatically at end of using block
}
}
}
}
The InsertFaculty method uses a parameterized INSERT with AddWithValue for every field, guarding against SQL injection while adding the four faculty records (two of which are CSIT). The RetrieveCSITFee method then runs a parameterized SELECT ... WHERE Course_Name = @CourseName filtered to "CSIT", opens a SqlDataReader, and loops over reader.Read() to print each matching row's course name, course ID, number of semesters, and fee, giving exactly the fee details for the CSIT records that were inserted.
asked 3xavg 15 marks · 2080, 2079, 2078AnswerHideWrite short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]
Write short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]
Short Notes (Any Two)
a. Lambda Expression
Definition
A lambda expression is an anonymous function that can be used to create delegates or expression tree types. Lambda expressions are a concise way to write inline functions and are heavily used in LINQ (Language Integrated Query) in C#.
Syntax
(parameters) => expression
or for a block body:
(parameters) => { statements; }
Key Characteristics
- The
=>operator is called the lambda operator and is read as "goes to". - Lambda expressions can have zero, one, or multiple parameters.
- They can be used wherever a delegate type is expected.
- They are a core part of LINQ support in C#, alongside query expressions, object initializers, and collections.
Example
// Simple lambda expression
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
// Lambda with LINQ
int[] scores = new int[] { 97, 92, 83, 60 };
var highScores = scores.Where(score => score > 80);
foreach (int s in highScores)
Console.WriteLine(s);
// Output: 97 92 83
Why Use Lambda Expressions?
- Makes code shorter and more readable.
- Eliminates the need to define a separate named method for simple operations.
- Integrates seamlessly with LINQ to query collections, databases, XML, and more.
- Supports functional programming style in C#.
b. Cross Site Request Forgery (CSRF)
Definition
Cross-Site Request Forgery (CSRF) is a web security attack where an attacker tricks an authenticated user into unknowingly submitting a malicious request to a web application on which the user is currently authenticated.
How CSRF Works
- The user logs into a trusted website (e.g., a banking site) and a session cookie is stored in the browser.
- Without logging out, the user visits a malicious website.
- The malicious site contains a hidden request (e.g., a form or image tag) that sends a request to the trusted website.
- Since the browser automatically includes the session cookie, the trusted website processes the request as if it came from the legitimate user.
Example Attack Scenario
<!-- Malicious page sends a hidden request to the bank -->
<img src="http://bank.com/transfer?amount=10000&to=attacker" />
The browser automatically sends the authenticated cookie along with this request.
Difference from XSS
| Feature | XSS | CSRF |
|---|---|---|
| Attack target | Other users via injected scripts | Authenticated user's session |
| Mechanism | Injects malicious scripts into pages | Forges requests using existing session |
| Trust exploited | User trusts the website | Website trusts the user's browser |
Prevention Techniques
- Anti-CSRF Tokens: Include a unique, secret token in every form that the server validates.
- SameSite Cookie Attribute: Restricts cookies from being sent with cross-site requests.
- Re-authentication: Require password confirmation for sensitive actions.
- Checking Referer/Origin headers: Validate that requests originate from the expected domain.
c. Single Page Application (SPA)
Definition
A Single Page Application (SPA) is a web application that loads a single HTML page and dynamically updates the content as the user interacts with the app, without requiring a full page reload from the server.
How SPA Works
- On the first request, the server sends a single HTML page along with all necessary JavaScript and CSS.
- Subsequent interactions (navigation, data loading) are handled via AJAX calls to the server, which returns only data (typically JSON), not full HTML pages.
- The browser's JavaScript framework (e.g., Angular, React, Vue.js) updates the DOM dynamically.
Architecture Diagram
User Action --> JavaScript (Client Side) --> AJAX Request --> Server API
| |
DOM Updated <-------------- JSON Response -----+
Key Characteristics
- Only one full page load occurs (at the start).
- Uses client-side routing to simulate navigation between pages.
- Heavy use of JavaScript frameworks like Angular, React, or Vue.js.
- Communicates with the backend via REST APIs or GraphQL.
Advantages
| Advantage | Description |
|---|---|
| Fast and responsive | No full page reloads; only data is exchanged |
| Better user experience | Feels like a desktop application |
| Reduced server load | Server only sends data, not full HTML |
| Separation of concerns | Frontend and backend are clearly separated |
Disadvantages
- SEO challenges: Search engines may struggle to index dynamically loaded content.
- Initial load time can be slow as all JavaScript is loaded upfront.
- Browser history management requires extra handling.
- Security: Requires careful handling of authentication tokens (e.g., JWT).
Example Technologies
- Frameworks: Angular, React, Vue.js
- Communication: AJAX, Fetch API, Axios
- Routing: React Router, Angular Router
asked 3xavg 5 marks · 2078, 2076AnswerHideGive an example to manage the session state. [5]
Give an example to manage the session state. [5]
Session State is an ASP.NET Core mechanism to store user data while the user browses the application. It uses a store maintained by the application to carry on data across requests from a client. ASP.NET Core maintains the session state ...
asked 3xavg 5 marks · 2081, 2080, 2079AnswerHideDistinguish between roles and policies. Explain about Kestrel web server in ASP.NET core. [5]
Distinguish between roles and policies. Explain about Kestrel web server in ASP.NET core. [5]
Roles vs Policies and Kestrel Web Server in ASP.NET Core
Part 1: Distinguish Between Roles and Policies
| Basis | Roles | Policies |
|---|---|---|
| Definition | Roles are a way to group users based on their job or function (e.g., Admin, User, Manager) | Policies are a set of requirements that must be satisfied for authorization to succeed |
| Approach | Role-based authorization checks if a user belongs to a specific role | Policy-based authorization checks one or more requirements against the current user |
| Flexibility | Less flexible; limited to simple role membership checks | More flexible; can combine multiple requirements (claims, roles, custom logic) |
| Declaration | Declared using [Authorize(Roles = "Admin")] | Declared using [Authorize(Policy = "PolicyName")] |
| Configuration | Roles are assigned directly to users | Policies are defined in Startup.cs using AddAuthorization() |
| Complexity | Suitable for simple access control scenarios | Suitable for complex, fine-grained access control scenarios |
| Example | A user is in the "Admin" role | A policy may require a user to be over 18 AND have a verified email |
Part 2: Kestrel Web Server in ASP.NET Core
Definition
Kestrel is a cross-platform, lightweight web server for ASP.NET Core. It is the web server that is included by default in ASP.NET Core project templates and is built into the ASP.NET Core framework.
Key Features of Kestrel
- Cross-platform: Kestrel runs on Windows, Linux, and macOS, making ASP.NET Core applications truly cross-platform.
- Default web server: It is automatically included when an ASP.NET Core project is created using the default templates.
- High performance: Kestrel is designed to be fast and efficient for handling HTTP requests.
- Self-hosted: It can run independently without requiring an external web server.
Hosting Models Using Kestrel
There are two ways Kestrel is used in the Out-of-Process Hosting Model:
1. Using Kestrel Directly (Edge Server)
- Kestrel itself acts as an edge server, which directly serves user requests from the internet.
- No additional web server (like IIS or NGINX) is needed.
- Suitable for simpler applications or internal services.
Browser Request --> Kestrel Server --> ASP.NET Core Application
2. Using Kestrel with a Reverse Proxy Server
- Due to limitations of Kestrel, it cannot be used in all scenarios (e.g., sharing a port, advanced security features).
- In such cases, powerful servers like IIS, NGINX, or Apache act as a reverse proxy server.
- The reverse proxy receives the request from the browser and redirects/forwards it to the internal Kestrel server.
- Kestrel then processes the request and returns the response.
Browser Request --> Reverse Proxy (IIS/NGINX/Apache) --> Kestrel Server --> ASP.NET Core App
In-Process Hosting (IIS)
- In this model, the ASP.NET Core app is hosted inside the IIS worker process (
w3wp.exe). - IIS forwards web requests to the backend ASP.NET Core app running the Kestrel server (out-of-process hosting model).
Summary
Kestrel is the heart of ASP.NET Core's web serving capability. It provides a fast, cross-platform, and lightweight server that can either work standalone as an edge server or work behind a powerful reverse proxy like IIS or NGINX for production-grade deployments.
asked 3xavg 5 marks · 2081, 2080, 2079AnswerHideDescribe the life cycle of Dependency Injection container. [5]
Describe the life cycle of Dependency Injection container. [5]
Life Cycle of Dependency Injection (DI) Container
In ASP.NET Core, the built-in IoC (Inversion of Control) container manages the creation and lifetime of service instances. The lifetime of a service defines how long an instance lives and when a new instance is created. There are three main service lifetimes:
1. Transient
- The IoC container creates a new instance every time the service is requested.
- Each call to resolve the service produces a fresh object.
- Best suited for lightweight, stateless services.
Registration Example:
services.Add(new ServiceDescriptor(
typeof(ILog),
typeof(MyConsoleLogger),
ServiceLifetime.Transient));
Use case: A simple utility/helper service that holds no shared state.
2. Scoped
- The IoC container creates one instance per HTTP request and shares that same instance throughout the entire request.
- Different requests get different instances.
- Best suited for services that need to maintain state within a single request (e.g., database context).
Registration Example:
services.Add(new ServiceDescriptor(
typeof(ILog),
typeof(MyConsoleLogger),
ServiceLifetime.Scoped));
Use case: A database context or unit-of-work that should be consistent within one request.
3. Singleton
- The IoC container creates only one instance for the entire application lifetime.
- The same instance is reused for every request and every user.
- Best suited for services that are stateless and expensive to create, or that hold shared application-wide state.
Registration Example:
services.Add(new ServiceDescriptor(
typeof(ILog),
new MyConsoleLogger())); // single instance passed directly
Use case: A logging service or configuration service shared across the whole application.
Summary Table
| Lifetime | Instance Created | Shared Within |
|---|---|---|
| Transient | Every time requested | Not shared |
| Scoped | Once per HTTP request | Single request |
| Singleton | Once per application | Entire application |
How Registration Works
Services are registered inside the ConfigureServices() method in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Singleton
services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));
// Transient
services.Add(new ServiceDescriptor(typeof(ILog),
typeof(MyConsoleLogger), ServiceLifetime.Transient));
// Scoped
services.Add(new ServiceDescriptor(typeof(ILog),
typeof(MyConsoleLogger), ServiceLifetime.Scoped));
}
Once registered, the IoC container automatically injects the service via constructor injection wherever the service type is used as a constructor parameter, without the developer needing to manually instantiate it.
asked 2xavg 10 marks · 2080, 2078AnswerHideHow do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.[10]
How do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.[10]
Managing State on Stateless HTTP and Form Validation Using jQuery
Part 1: Managing State on Stateless HTTP (5 marks)
What is the Problem?
HTTP is a stateless protocol, meaning each request from a client to the server is independent. The server does not remember any previous request. However, real-world web applications (like shopping carts, login sessions, etc.) need to remember user data across multiple requests. This is called state management.
State Management Approaches in ASP.NET
The following storage approaches are used to manage state on stateless HTTP:
| Storage Approach | Description |
|---|---|
| Cookies | HTTP cookies. May include data using server-side app code. |
| Session State | HTTP cookies and server-side app code. |
| TempData | HTTP cookies or session state. |
| Query Strings | HTTP query strings. |
| Hidden Fields | HTTP form fields. |
| HTTP Content | Server-side app code. |
| Cache | Cache server-side app code. |
Detailed Explanation of Each Approach
1. Cookies
- Small pieces of data stored on the client's browser.
- Sent automatically with every HTTP request to the server.
- Used to remember user preferences, login tokens, etc.
// Setting a cookie in ASP.NET MVC
Response.Cookies.Append("Username", "JohnDoe");
// Reading a cookie
string username = Request.Cookies["Username"];
Limitation: Cookies can be tampered with by the client, so sensitive data should not be stored directly.
2. Session State
- Data is stored on the server side.
- A unique session ID is stored in a cookie on the client side.
- The server uses this ID to retrieve the corresponding session data.
// Storing data in session
HttpContext.Session.SetString("UserName", "JohnDoe");
// Retrieving data from session
string name = HttpContext.Session.GetString("UserName");
Advantage: More secure than cookies since actual data stays on the server.
3. TempData
- Used to pass data between two consecutive requests (e.g., from one action to another after a redirect).
- Internally uses cookies or session state.
// Storing in TempData
TempData["Message"] = "Record saved successfully!";
// Reading in the next request
string msg = TempData["Message"].ToString();
4. Query Strings
- Data is passed as part of the URL.
https://example.com/products?category=electronics&page=2
string category = Request.Query["category"];
Limitation: Visible in the URL, not suitable for sensitive data.
5. Hidden Fields
- Data is stored in HTML form fields that are not visible to the user but are submitted with the form.
<input type="hidden" name="UserId" value="101" />
Limitation: Can be viewed and modified by inspecting the page source.
6. Cache
- Data is stored server-side in memory for fast access.
- Suitable for data that is expensive to compute and shared across users.
// Using IMemoryCache
_cache.Set("ProductList", products, TimeSpan.FromMinutes(10));
Summary Diagram
Client (Browser) Server
| |
|--- HTTP Request (stateless) --->|
| |
| State managed via: |
| - Cookies (client-side) |
| - Session (server-side) |
| - TempData (redirect) |
| - Query Strings (URL) |
| - Hidden Fields (form) |
| - Cache (server memory) |
|<-- HTTP Response ---------------|
Part 2: Form Validation Using jQuery (5 marks)
What is jQuery Form Validation?
jQuery provides a simple and powerful way to validate HTML forms on the client side before the data is submitted to the server. This improves user experience by giving instant feedback without a page reload.
The most commonly used plugin is the jQuery Validation Plugin.
Assumptions
- We have a Student Registration Form with fields: Name, Email, Age, and Password.
- jQuery and jQuery Validation plugin are included via CDN.
- Validation is done client-side before form submission.
Step 1: HTML Form Structure
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include jQuery Validation Plugin -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
<style>
.error { color: red; font-size: 12px; }
input { display: block; margin: 8px 0; padding: 5px; }
</style>
</head>
<body>
<h2>Student Registration Form</h2>
<form id="registrationForm">
<label>Full Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name" />
<label>Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email" />
<label>Age:</label>
<input type="number" id="age" name="age" placeholder="Enter your age" />
<label>Password:</label>
<input type="password" id="password" name="password" placeholder="Enter password" />
<label>Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword"
placeholder="Confirm password" />
<button type="submit">Register</button>
</form>
</body>
</html>
Step 2: jQuery Validation Script
<script>
$(document).ready(function () {
$("#registrationForm").validate({
rules: {
name: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
age: {
required: true,
number: true,
min: 16,
max: 100
},
password: {
required: true,
minlength: 6
},
confirmPassword: {
required: true,
equalTo: "#password"
}
},
messages: {
name: "Please enter your full name (at least 3 characters).",
email: "Please enter a valid email address.",
age: "Age must be between 16 and 100.",
password: "Password must be at least 6 characters long.",
confirmPassword: "Passwords do not match."
},
submitHandler: function (form) {
alert("Registration form is valid! Submitting...");
form.submit();
}
});
});
</script>
The jQuery Validation Plugin's .validate() call attaches a rules object (what each field must satisfy) and a matching messages object (what to show when a rule fails) directly to the form, and it re-checks every field automatically on blur and on keyup, so the student sees an inline error the moment a field becomes invalid, without any page reload. The submitHandler only fires once every rule passes, at which point the form is genuinely submitted to the server, giving the registration page instant client-side feedback backed by the plugin's built-in required, email, number, minlength, and equalTo validators.
asked 2xavg 5 marks · 2080, 2079AnswerHideWhat are tag helpers? What tag helper provides? [5]
What are tag helpers? What tag helper provides? [5]
Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag Helpers are authored in C and they target HTML elements based on: - The element name - The attribute name - The parent tag Tag...
asked 2xavg 5 marks · 2080, 2079AnswerHideDescribe the importance of MVC pattern in designing web applications. [5]
Describe the importance of MVC pattern in designing web applications. [5]
MVC (Model-View-Controller) is an architectural pattern that separates an application into three distinct components: Model, View, and Controller. This separation is fundamental to building well-structured, maintainable web applications....
asked 2xavg 5 marks · 2079, 2076AnswerHideDifferentiate between .NET and ASP.NET frameworks. How do you test the .NET core applications? [5]
Differentiate between .NET and ASP.NET frameworks. How do you test the .NET core applications? [5]
--- Feature .NET Framework ASP.NET --------- Definition A general-purpose development platform maintained by Microsoft that provides runtime, libraries, and tools for building all types of applications A web development framework built o...
asked 2xavg 5 marks · 2076AnswerHideExplain the client-side scripting with practical example.[5]
Explain the client-side scripting with practical example.[5]
Client-side scripting refers to scripts that are executed on the client's browser rather than on the web server. The script is downloaded along with the HTML page and runs locally on the user's machine without requiring a round-trip to t...
asked 2xavg 8 marks · 2081, 2078AnswerHideDistinguish between collection and generics. What are named and positional attribute parameters? Write a program to create your own exception when the user gives subject name than 'C#'.[10]
Distinguish between collection and generics. What are named and positional attribute parameters? Write a program to create your own exception when the user gives subject name than 'C#'.[10]
--- Basis Collection Generics --------- Namespace System.Collections System.Collections.Generic Type Safety Not type-safe; stores objects of any type Type-safe; stores objects of a specific type Data Type Works with object type (non-gene...
asked 2xavg 8 marks · 2081, 2080AnswerHideHow do you create controller? Illustrate with an example. Describe the procedure of rendering HTML with Razor with scenario.[10]
How do you create controller? Illustrate with an example. Describe the procedure of rendering HTML with Razor with scenario.[10]
"Controller handles the user request. Typically the user uses the view, processes request and raises an HTTP request. Controller is the request handler." A Controller is a C class that: - Handles incoming HTTP requests - Interacts with t...
asked 2xavg 5 marks · 2081, 2078AnswerHideWrite a program to validate the form that takes input user name, password and phone number using JQuery. All fields must be non-empty and phone number must contain exactly 10 digits. [5]
Write a program to validate the form that takes input user name, password and phone number using JQuery. All fields must be non-empty and phone number must contain exactly 10 digits. [5]
jQuery Form Validation - Username, Password, and Phone Number
Complete Solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation using jQuery</title>
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
.error {
color: red;
font-size: 13px;
}
.success {
color: green;
font-size: 14px;
}
input {
display: block;
margin: 5px 0 2px 0;
padding: 6px;
width: 250px;
}
label {
font-weight: bold;
margin-top: 10px;
display: block;
}
button {
margin-top: 15px;
padding: 8px 20px;
}
</style>
</head>
<body>
<h2>User Registration Form</h2>
<form id="registrationForm">
<label for="username">Username:</label>
<input type="text" id="username" placeholder="Enter username" />
<span class="error" id="usernameError"></span>
<label for="password">Password:</label>
<input type="password" id="password" placeholder="Enter password" />
<span class="error" id="passwordError"></span>
<label for="phone">Phone Number:</label>
<input type="text" id="phone" placeholder="Enter 10-digit phone number" />
<span class="error" id="phoneError"></span>
<button type="submit">Submit</button>
<p id="successMsg" class="success"></p>
</form>
<script>
$(document).ready(function () {
// Handle form submission
$("#registrationForm").submit(function (event) {
// Prevent default form submission
event.preventDefault();
// Clear previous error messages
$(".error").text("");
$("#successMsg").text("");
// Get field values and trim whitespace
var username = $("#username").val().trim();
var password = $("#password").val().trim();
var phone = $("#phone").val().trim();
var isValid = true;
// Validate Username - must be non-empty
if (username === "") {
$("#usernameError").text("Username is required.");
isValid = false;
}
// Validate Password - must be non-empty
if (password === "") {
$("#passwordError").text("Password is required.");
isValid = false;
}
// Validate Phone - must be non-empty AND exactly 10 digits
if (phone === "") {
$("#phoneError").text("Phone number is required.");
isValid = false;
} else if (!/^\d{10}$/.test(phone)) {
$("#phoneError").text("Phone number must contain exactly 10 digits.");
isValid = false;
}
// If all validations pass
if (isValid) {
$("#successMsg").text("Form submitted successfully!");
}
});
});
</script>
</body>
</html>
Explanation of Key Parts
| Part | Purpose |
|---|---|
$(document).ready() | Ensures the DOM is fully loaded before jQuery runs |
event.preventDefault() | Stops the form from reloading the page on submit |
.val().trim() | Gets the field value and removes leading/trailing spaces |
=== "" | Checks if the field is empty (non-empty validation) |
/^\d{10}$/.test(phone) | Regex to check phone has exactly 10 digits only |
isValid flag | Tracks overall validation status before showing success |
Validation Rules Applied
- Username - must not be empty
- Password - must not be empty
- Phone Number - must not be empty AND must contain exactly 10 digits (no letters or special characters allowed)
Study every one of these with model answers, flashcards, and MCQs.
Open CSC378 study modes