Chapter 1
.NET Centric Computing
TU BIT past exam questions
Past questions and answers
35 questions set from this chapter, 1 of them more than once. Most repeated first.
- Asked 2 times
- 2080 · 5 marks
- 2081.1 · 5 marks
Explain about MSIL and CLR.
Answer
MSIL (Microsoft Intermediate Language)
When a .NET program (C#, VB.NET, F#) is compiled, the compiler does not produce machine code directly. It produces an assembly (.exe/.dll) containing MSIL (also called IL or CIL) plus metadata. MSIL is a CPU-independent, object-oriented instruction set, so the same assembly can run on any platform that has the .NET runtime. It enables language interoperability, because all languages compile to the same IL, and allows verification of type safety.
CLR (Common Language Runtime)
CLR is the execution engine of .NET that runs the MSIL code and provides services:
- JIT compiler converts MSIL into native machine code at run time, method by method, when first called.
- Memory management and garbage collection: automatic allocation and freeing of memory.
- Type safety and verification through the Common Type System (CTS).
- Exception handling, security (code access security) and thread management.
- Assembly loading and versioning (class loader), and interoperability with unmanaged code.
Execution flow: Source code > language compiler > MSIL + metadata (assembly) > CLR (JIT) > native code > execution.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How do you publish application to Azure cloud? Illustrate the concept of SQL injection attack with example and its prevention procedure.
Answer
Publishing an application to Azure
- Build and test the ASP.NET Core app locally (
dotnet build,dotnet test). - Create an Azure account and a resource group. Create an App Service (choose runtime .NET, OS, region, pricing plan) in the Azure portal or with the CLI:
az group create -n myRG -l southeastasia
az appservice plan create -n myPlan -g myRG --sku B1
az webapp create -n mynepalapp -g myRG --plan myPlan
- Publish: in Visual Studio use Build > Publish > Azure > Azure App Service and pick the app; or run
dotnet publish -c Releaseand deploy the output by zip deploy (az webapp deploy), or use CI/CD with GitHub Actions/Azure DevOps linked to the repository. - Configure connection strings and secrets in App Service Configuration (or Key Vault), and an Azure SQL Database if needed (allow the App Service in the SQL firewall).
- Browse
https://mynepalapp.azurewebsites.net; enable HTTPS, logging and scaling.
SQL injection attack
SQL injection happens when user input is concatenated into an SQL statement so that the attacker's input changes the structure of the query.
Vulnerable code:
string sql = "SELECT * FROM Users WHERE Name='" + name + "' AND Password='" + pwd + "'";
If the user enters ' OR '1'='1' -- as name, the query becomes
SELECT * FROM Users WHERE Name='' OR '1'='1' --' AND Password=''
which is always true, so the attacker logs in without a password. Input such as '; DROP TABLE Users; -- can even destroy data.
Prevention
- Use parameterized queries / stored procedures:
var cmd = new SqlCommand("SELECT * FROM Users WHERE Name=@n AND Password=@p", con);
cmd.Parameters.AddWithValue("@n", name);
cmd.Parameters.AddWithValue("@p", hashedPwd);
- Use an ORM such as Entity Framework (LINQ queries are parameterized).
- Validate and whitelist input (type, length, format).
- Give the database account least privilege.
- Hide detailed error messages; store only hashed passwords.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
What are the significances of Single Page Application? How do you integrate REST API calls? Describe.
Answer
Single Page Application (SPA)
An SPA loads one HTML page once and then updates the content dynamically with JavaScript, fetching only data (JSON) from the server instead of reloading full pages (e.g. Angular, React, Vue apps).
Significance
- Fast and smooth user experience: no full page reloads, only the changed part is updated.
- Less server load and bandwidth, because only data is transferred, not whole pages.
- Clear separation of front end (UI) and back end (API); the same API can serve web and mobile apps.
- Behaves like a desktop/native application; easier to cache assets and work offline (service workers).
- Easier development and debugging with component-based frameworks.
Limitations: weaker SEO unless server-side rendering is used, longer initial load, and browser history/routing must be handled by client-side routing.
Integrating REST API calls
The SPA talks to a REST API (e.g. ASP.NET Core Web API) with HTTP verbs: GET (read), POST (create), PUT (update), DELETE (remove), exchanging JSON.
Angular (HttpClient):
@Injectable({providedIn:'root'})
export class StudentService {
private url = 'https://localhost:5001/api/students';
constructor(private http: HttpClient) {}
getAll(): Observable<Student[]> { return this.http.get<Student[]>(this.url); }
add(s: Student) { return this.http.post<Student>(this.url, s); }
remove(id: number) { return this.http.delete(`${this.url}/${id}`); }
}
React (fetch):
useEffect(() => {
fetch('/api/students')
.then(r => r.json())
.then(data => setStudents(data));
}, []);
Steps: enable CORS on the server if the SPA is on another origin, call the API from a service, handle the asynchronous response (Promise/Observable), update component state to re-render, handle errors, and send an auth token (JWT) in the Authorization header.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Define URL routing with its features. Discuss about ASP.Net core architecture.
Answer
URL routing
Routing maps an incoming request URL to a handler (a controller action, Razor Page or endpoint) and also generates URLs from route values. In ASP.NET Core it is done by endpoint routing middleware (UseRouting, UseEndpoints / MapControllerRoute).
Example:
app.MapControllerRoute(name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
/Student/Details/5 calls StudentController.Details(5).
Features
- Convention-based routing (pattern templates) and attribute routing (
[Route("api/students/{id}")],[HttpGet]). - Route parameters, default values and optional parameters (
{id?}). - Route constraints (
{id:int},{name:alpha},{age:min(18)}). - Clean, readable, SEO friendly URLs independent of physical files.
- URL generation (
Url.Action, tag helpersasp-controller,asp-action) so links change automatically when routes change. - Support for areas, HTTP-verb based selection and route order/priority.
ASP.NET Core architecture
ASP.NET Core is a cross-platform, open-source, modular, high-performance framework.
- Host and Kestrel:
Program.csbuilds a host (WebApplication) that sets up configuration, logging, dependency injection and the Kestrel web server (optionally behind IIS/Nginx reverse proxy). - Dependency injection: built-in IoC container; services are registered in
builder.Services(singleton, scoped, transient). - Middleware pipeline: a request passes through a chain of middleware (exception handling, HTTPS redirection, static files, routing, authentication, authorization, endpoints). Each component can handle the request or call the next one; the response travels back in reverse order.
- Configuration:
appsettings.json, environment variables, user secrets, with the options pattern. - Application models: MVC (Model-View-Controller), Razor Pages, Web API, Blazor, SignalR.
- Data access: Entity Framework Core / ADO.NET.
- Runs on the .NET runtime (CoreCLR), with the base class library.
Request flow: Client > Kestrel > Middleware > Routing > Controller/Action > Model/Database > View or JSON > Response.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
When do you need hidden field? Explain with an example.
Answer
A hidden field (<input type="hidden">) stores a value in the HTML form that is submitted with the form but is not displayed to the user. It is needed when data must be carried between requests without showing it, because HTTP is stateless.
Typical uses:
- Passing the record id when editing (
StudentId) so the server knows which row to update. - Carrying values between pages of a multi-step form.
- Storing a CSRF/anti-forgery token (ASP.NET adds
__RequestVerificationTokenautomatically). - Keeping page state such as a return URL or a page number.
Example:
<form asp-action="Edit" method="post">
<input type="hidden" name="Id" value="@Model.Id" />
<input type="text" name="Name" value="@Model.Name" />
<button type="submit">Save</button>
</form>
On submit, Id is posted with Name, and the action receives it through model binding. Note that hidden fields can be viewed and changed by the user (view source / dev tools), so they must never hold sensitive data, and server-side validation is still required.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Describe about data models and data context.
Answer
Data model
A data model is a set of classes (entities) that represent the data of the application and the relationships between them. In ASP.NET Core MVC with Entity Framework Core, each model class maps to a database table and each property to a column.
public class Student {
public int Id { get; set; } // primary key
[Required, StringLength(50)]
public string Name { get; set; }
public int DepartmentId { get; set; } // foreign key
public Department Department { get; set; }
}
Data annotations ([Key], [Required], [MaxLength]) define constraints and validation. Models also can be view models carrying data to views.
Data context
The data context is a class derived from DbContext that represents a session with the database. It:
- Holds
DbSet<T>properties, one per entity/table. - Holds the connection and configuration (
OnConfiguring, or options passed via dependency injection). - Configures mapping with Fluent API (
OnModelCreating). - Tracks changes to entities and writes them to the database with
SaveChanges(). - Executes LINQ queries translated into SQL.
public class SchoolContext : DbContext {
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options) {}
public DbSet<Student> Students { get; set; }
public DbSet<Department> Departments { get; set; }
}
Registered with builder.Services.AddDbContext<SchoolContext>(o => o.UseSqlServer(connString)); and injected into controllers.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Differentiate between collection and generics.
Answer
| Basis | Collections | Generics |
|---|---|---|
| Namespace | System.Collections (non-generic: ArrayList, Hashtable, Stack, Queue) | System.Collections.Generic (List<T>, Dictionary<K,V>, Stack<T>, Queue<T>) |
| Type safety | Stores object; any type can be added, errors appear at run time | Strongly typed; errors found at compile time |
| Performance | Boxing/unboxing of value types and casting cost time | No boxing for value types; faster |
| Casting | Explicit cast needed on retrieval | Not needed |
| Reusability | Same collection holds mixed types | One definition works for any type given as parameter T |
| Example | ArrayList a = new ArrayList(); a.Add(1); a.Add("x"); | List<int> l = new List<int>(); l.Add(1); |
Generics is the language feature (type parameters such as class Box<T>), whereas "collections" are data structure classes; the generic collections are built using generics and are preferred in modern C#.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Why do we need abstract class? Explain with an example.
Answer
An abstract class is a class declared with the abstract keyword that cannot be instantiated and may contain abstract methods (no body) as well as ordinary methods, fields and constructors. Derived classes must override all abstract members.
Why it is needed
- To define a common base with shared code (reuse) while forcing subclasses to supply their own implementation of certain behaviour.
- To provide a common contract/template for related classes and achieve runtime polymorphism.
- To prevent creation of objects of an incomplete, general concept (e.g. a generic "Shape").
Example
abstract class Shape {
public string Name { get; set; }
public abstract double Area(); // must be overridden
public void Show() => Console.WriteLine(Name + " area = " + Area());
}
class Circle : Shape {
double r;
public Circle(double r) { this.r = r; Name = "Circle"; }
public override double Area() => Math.PI * r * r;
}
class Rectangle : Shape {
double l, b;
public Rectangle(double l, double b) { this.l = l; this.b = b; Name = "Rectangle"; }
public override double Area() => l * b;
}
// Shape s = new Circle(2); s.Show();
new Shape() is a compile error, but a Shape reference can point to Circle or Rectangle.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Do binding and validation refer to same? Justify.
Answer
No, binding and validation are different, although they happen one after another in the request pipeline.
Model binding converts the data of an HTTP request (form fields, route values, query string, JSON body) into .NET objects or action parameters. For example, form fields Name and Age are bound to the properties of a Student object. If conversion fails (e.g. "abc" for an int), a binding error is added to ModelState.
Model validation checks whether the bound values satisfy the rules, such as [Required], [Range(18,60)], [EmailAddress], [StringLength], or custom rules through IValidatableObject. The result is stored in ModelState.IsValid, and errors are shown with asp-validation-for.
| Binding | Validation |
|---|---|
| Maps request data to objects/parameters | Checks the data against rules |
| Happens first | Happens after binding |
| Failure means wrong type/format | Failure means business/format rule broken |
[HttpPost]
public IActionResult Create(Student s) { // binding
if (!ModelState.IsValid) return View(s); // validation result
...
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is the purpose of object relational mapper? Describe.
Answer
Object Relational Mapper (ORM) is a tool that maps object-oriented classes in code to tables of a relational database, so developers work with objects instead of writing SQL and handling rows and columns. Examples: Entity Framework Core, NHibernate, Dapper (micro ORM).
Purpose
- Bridges the "impedance mismatch" between the object model (classes, inheritance, references) and the relational model (tables, keys).
- Reduces boilerplate ADO.NET code: no manual connections, commands, readers and conversions.
- Allows queries in the programming language (LINQ) with compile-time checking, and generates parameterized SQL, which protects against SQL injection.
- Tracks changes of objects and saves them with one call (
SaveChanges). - Provides database independence (switch SQL Server to PostgreSQL by changing the provider), migrations for schema changes, lazy/eager loading and relationship handling.
- Improves productivity and maintainability.
Mapping: class to table, property to column, object reference/collection to foreign key/relationship, object instance to row.
var students = context.Students.Where(s => s.Age > 20).OrderBy(s => s.Name).ToList();
context.Students.Add(new Student { Name = "Ram", Age = 21 });
context.SaveChanges();
Drawback: some performance overhead and less control over complex SQL.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Why do we need to define roles, policies and claims? Explain.
Answer
Authentication tells who the user is; authorization decides what the authenticated user may do. Roles, policies and claims are the building blocks of authorization in ASP.NET Core.
Claims: a claim is a name-value statement about a user issued by a trusted source, e.g. Email = ram@x.com, Department = IT, Age = 25. The user's identity is a collection of claims.
Roles: named groups of users such as Admin, Teacher, Student. A role is simply a claim of type Role and gives coarse-grained access:
[Authorize(Roles = "Admin,Manager")]
public IActionResult Delete(int id) { ... }
Policies: named, reusable authorization rules made of requirements (role, claim, minimum age, custom handler):
builder.Services.AddAuthorization(o =>
o.AddPolicy("AdultOnly", p => p.RequireClaim("Age").RequireAssertion(c => ...)));
[Authorize(Policy = "AdultOnly")]
Why we need them
- To restrict resources (pages, actions, APIs) to permitted users and protect sensitive data and operations.
- Roles make management easy: permissions are assigned to a role, and users are added to roles.
- Claims allow fine-grained, attribute-based decisions beyond roles.
- Policies centralize rules, avoid repeating logic in many controllers, and are easy to change and test.
- Supports the principle of least privilege and separation of duties.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Discuss the use of Angular with an example.
Answer
Angular is an open-source, TypeScript-based front-end framework by Google for building single page applications. It uses components, templates, data binding, directives, services with dependency injection, routing and HttpClient.
Uses
- Building SPAs and dynamic, responsive web apps with fast navigation.
- Two-way data binding keeps the view and model in sync.
- Reusable components and modules; easy testing and maintenance.
- Calling REST APIs (e.g. ASP.NET Core Web API) and routing between views.
- Form handling with validation, and cross-platform (PWA, mobile) development.
Example: a student list component
// student.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-student',
template: `
<h3>Students</h3>
<input [(ngModel)]="name" placeholder="Name">
<button (click)="add()">Add</button>
<ul><li *ngFor="let s of students">{{ s }}</li></ul>`
})
export class StudentComponent {
name = '';
students: string[] = ['Sita', 'Hari'];
add() { if (this.name) { this.students.push(this.name); this.name = ''; } }
}
{{ }} is interpolation, [(ngModel)] is two-way binding, (click) is event binding and *ngFor is a structural directive. Adding <app-student></app-student> to the root template displays the list, which updates instantly without page reload.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
Define indexers. What is the use of base keyword? How can you apply polymorphism in code extensibility?
Answer
Indexers
An indexer lets an object be accessed like an array using [ ]. It is declared like a property with the this keyword and parameters.
class Marks {
private int[] data = new int[5];
public int this[int i] {
get { return data[i]; }
set { data[i] = value; }
}
}
// Marks m = new Marks(); m[0] = 80; Console.WriteLine(m[0]);
Indexers can be overloaded (different index types) and may be read-only.
Use of base keyword
base refers to the immediate parent class. It is used to:
- Call a base class constructor:
public Student(string n) : base(n) { } - Call a base class method or property hidden or overridden in the derived class:
base.Display();
class Person { public virtual void Show() => Console.WriteLine("Person"); }
class Student : Person {
public override void Show() { base.Show(); Console.WriteLine("Student"); }
}
Polymorphism for code extensibility
With runtime polymorphism (virtual/override, abstract classes, interfaces) code is written against a base type or interface, and new behaviour is added by creating new derived classes without modifying the existing code (open/closed principle).
interface IPayment { void Pay(double amt); }
class Card : IPayment { public void Pay(double a) { ... } }
class Esewa : IPayment { public void Pay(double a) { ... } }
void Checkout(IPayment p, double amt) { p.Pay(amt); } // unchanged when new method added
Adding a Khalti : IPayment class extends the system, and Checkout works with it as is. This reduces conditional logic (if/switch), improves reuse and maintainability.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
What are the tasks of ASP.NET web forms? Explain the MVC pattern of ASP.NET.
Answer
Tasks of ASP.NET Web Forms
ASP.NET Web Forms is the event-driven, page-based model for building web apps with server controls. Its tasks are:
- Provide a drag-and-drop UI built from server controls (TextBox, GridView, Button) in
.aspxpages with code-behind files. - Handle events (Click, SelectedIndexChanged) on the server in a way similar to desktop programming.
- Manage state across requests using ViewState, Session, Application, cookies.
- Perform validation using validation controls (RequiredFieldValidator, RangeValidator).
- Data binding to databases (SqlDataSource, GridView, Repeater), master pages, themes and user controls.
- Manage the page life cycle (Init, Load, event handling, PreRender, Render, Unload), authentication/authorization, caching.
- Generate HTML output from server controls for the browser.
MVC pattern in ASP.NET
MVC separates an application into three parts:
- Model: data and business logic (entity classes, validation rules, data access).
- View: the user interface (Razor
.cshtmlfiles) that displays model data. - Controller: handles the incoming request, works with the model and selects the view or result.
Flow: browser request > routing > controller action > model (fetch/update data) > controller passes model to view > view renders HTML > response.
public class StudentController : Controller {
public IActionResult Index() {
var list = _context.Students.ToList(); // model
return View(list); // view
}
}
Advantages: separation of concerns, easier unit testing, clean URLs through routing, full control of HTML, parallel development of UI and logic, and support for TDD.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
How do you create Controllers, Actions and Action results? Explain.
Answer
Controllers
A controller is a class (name ending with Controller, in the Controllers folder) that derives from Controller (or ControllerBase for APIs). It receives requests, works with models and returns a response. Create it in Visual Studio with Add > Controller, or manually:
public class StudentController : Controller {
private readonly SchoolContext _db;
public StudentController(SchoolContext db) { _db = db; }
public IActionResult Index() { return View(_db.Students.ToList()); }
public IActionResult Details(int id) {
var s = _db.Students.Find(id);
if (s == null) return NotFound();
return View(s);
}
[HttpPost]
public IActionResult Create(Student s) {
if (!ModelState.IsValid) return View(s);
_db.Add(s); _db.SaveChanges();
return RedirectToAction("Index");
}
}
Actions
Actions are public methods of a controller that handle a request. They are selected by routing (/Student/Details/3). They can take parameters bound from route, query string or form, and are restricted with attributes such as [HttpGet], [HttpPost], [Authorize], [NonAction].
Action results
An action returns an IActionResult that describes the response:
| Result | Helper method | Output |
|---|---|---|
| ViewResult | View() | HTML view |
| RedirectToActionResult | RedirectToAction() | redirect to another action |
| JsonResult | Json(obj) | JSON data |
| ContentResult | Content("text") | plain text |
| FileResult | File(...) | file download |
| NotFoundResult / BadRequestResult | NotFound(), BadRequest() | 404 / 400 |
| StatusCodeResult / OkObjectResult | StatusCode(500), Ok(obj) | status codes, API responses |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
List the advantages of Entity framework over ADO.NET.
Answer
Advantages of Entity Framework (EF) over ADO.NET:
- Less code: no manual connection, command, reader and data-table code; one
DbContexthandles it. - Object-oriented access: works with entities (classes) instead of rows/columns, removing the object-relational mismatch.
- LINQ support: strongly typed, compile-time checked queries instead of SQL strings.
- Automatic change tracking:
SaveChanges()generates INSERT/UPDATE/DELETE statements. - Database independence: provider model supports SQL Server, MySQL, PostgreSQL, SQLite with minimal change.
- Migrations and code-first: schema is created and versioned from the model classes.
- Security: generates parameterized queries, reducing SQL injection risk.
- Relationships and loading: handles navigation properties, lazy/eager loading, and caching of the identity map.
- Higher productivity and easier maintenance.
(ADO.NET is faster for raw operations and gives full control, but needs much more code.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How do you manage state on stateless HTTP?
Answer
HTTP is stateless: each request is independent and the server does not remember earlier requests. State is maintained by storing data on the client or server.
Client-side techniques
- Cookies: small text data stored in the browser and sent with every request (user preferences, session id).
- Query strings: data appended to the URL (
?id=5). - Hidden fields: values carried in forms.
- ViewState / client storage: encoded page state in Web Forms;
localStorage/sessionStoragein browsers.
Server-side techniques
- Session state: per-user data stored on the server and identified by a session id cookie (
HttpContext.Session.SetString("user","Ram")). - Application state: data shared by all users.
- TempData: data kept until the next request (used for redirects).
- Cache: server memory/distributed cache (Redis).
- Database: persistent state.
Token-based: JWT tokens carry user claims in each request for APIs.
Choice depends on size, security and scalability: sensitive or large data should stay on the server, while small non-sensitive data can go to the client.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Why do we need to validate the form? Describe.
Answer
Form validation checks that the data entered by the user is complete, correct and safe before it is processed or stored.
Why it is needed
- Data integrity: ensures required fields are filled and values have the correct type, range and format (email, phone, age).
- Security: prevents malicious input such as SQL injection and cross-site scripting.
- Application stability: invalid data can cause exceptions or corrupt the database.
- User experience: immediate, clear error messages help users correct mistakes.
- Business rules: enforces rules like unique username, password strength, marks between 0 and 100.
- Reduces server load: client-side validation avoids useless round trips.
Types
- Client-side (JavaScript, HTML5 attributes, jQuery validation): fast feedback but can be bypassed.
- Server-side (data annotations,
ModelState.IsValid): mandatory and secure.
public class Student {
[Required(ErrorMessage="Name required")] public string Name { get; set; }
[Range(18,60)] public int Age { get; set; }
[EmailAddress] public string Email { get; set; }
}
Both should be used together.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Create a form using React with your own assumption.
Answer
A controlled React form stores input values in state and updates them on every change.
import React, { useState } from 'react';
function StudentForm() {
const [form, setForm] = useState({ name: '', email: '', course: 'BIT' });
const [errors, setErrors] = useState({});
const handleChange = (e) =>
setForm({ ...form, [e.target.name]: e.target.value });
const handleSubmit = (e) => {
e.preventDefault();
const err = {};
if (!form.name.trim()) err.name = 'Name is required';
if (!/\S+@\S+\.\S+/.test(form.email)) err.email = 'Invalid email';
setErrors(err);
if (Object.keys(err).length === 0) {
console.log('Submitted', form);
alert('Registered ' + form.name);
}
};
return (
<form onSubmit={handleSubmit}>
<label>Name: <input name="name" value={form.name} onChange={handleChange} /></label>
{errors.name && <span>{errors.name}</span>}
<label>Email: <input name="email" value={form.email} onChange={handleChange} /></label>
{errors.email && <span>{errors.email}</span>}
<label>Course:
<select name="course" value={form.course} onChange={handleChange}>
<option>BIT</option><option>BCA</option>
</select>
</label>
<button type="submit">Register</button>
</form>
);
}
export default StudentForm;
Assumption: a student registration form with name, email and course fields, validated on submit.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How do you detect and prevent vulnerabilities in ASP.NET core application.
Answer
Common vulnerabilities and prevention in ASP.NET Core
| Vulnerability | Prevention |
|---|---|
| SQL injection | Parameterized queries, stored procedures, EF Core/LINQ |
| Cross-site scripting (XSS) | Razor encodes output by default; avoid Html.Raw; validate input; Content Security Policy |
| Cross-site request forgery (CSRF) | Anti-forgery tokens ([ValidateAntiForgeryToken], form tag helper) |
| Broken authentication/session | ASP.NET Core Identity, strong password policy, lockout, MFA, secure cookies (HttpOnly, Secure, SameSite) |
| Broken access control | [Authorize] with roles/policies; check ownership of data |
| Open redirect | Url.IsLocalUrl() before redirecting |
| Sensitive data exposure | HTTPS (UseHttpsRedirection, HSTS), data protection API, hashed passwords, user secrets/Key Vault |
| Over-posting | View models or [Bind] |
| Misconfiguration | Disable developer exception page in production, security headers, CORS restriction |
| Vulnerable packages | Update NuGet packages |
Detection: code review, static analysis (SonarQube, Roslyn analyzers), dotnet list package --vulnerable, dependency scanning, penetration tests (OWASP ZAP), logging and monitoring.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What are the purposes of adding authentications to apps? Explain.
Answer
Authentication is the process of verifying the identity of a user (who are you?) using credentials such as password, OTP, biometrics or tokens.
Purposes of adding authentication
- Identify users and provide personalized content and settings.
- Protect resources and data from unauthorized access; it is the base for authorization (roles, policies).
- Security and privacy: protects confidential information such as personal and financial data.
- Accountability and auditing: actions can be traced to a particular user through logs.
- Prevent misuse: stops anonymous users from abusing features such as posting, payment or admin tools.
- Legal and compliance requirements for data protection.
- Session management and enabling features like shopping carts, profiles and order history.
In ASP.NET Core it is added with the authentication middleware (app.UseAuthentication()), ASP.NET Core Identity (cookies), JWT bearer tokens for APIs, or external providers (Google, Facebook, OAuth/OpenID Connect).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe any two hosting models for ASP.NET core application.
Answer
1. In-process hosting model (IIS)
The ASP.NET Core app runs inside the IIS worker process (w3wp.exe) through the ASP.NET Core Module. It gives better performance because requests do not travel over a loopback network connection; IIS HTTP Server is used instead of Kestrel. It is the default model for IIS on Windows. Suited to Windows servers where IIS features (management, SSL, authentication) are needed.
2. Out-of-process hosting model (Kestrel with reverse proxy)
The app runs in its own process (dotnet app.dll) using the Kestrel web server. A reverse proxy server (IIS, Nginx, Apache) forwards requests to Kestrel and returns the responses. This adds proxy benefits such as load balancing, SSL termination, request filtering and security hardening. It is cross-platform (Linux with Nginx) and is the usual model for Linux, containers (Docker) and cloud hosting, though it has some overhead from the proxy hop.
(Kestrel can also be exposed directly as an edge server.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Given a table BOOK(ISBN,Name,Author,Price), write a program to update the price of the book to 1000 whose author is John.
Answer
using System;
using System.Data.SqlClient;
class Program {
static void Main() {
string cs = "Server=.;Database=LibraryDB;Trusted_Connection=True;";
string sql = "UPDATE BOOK SET Price = @price WHERE Author = @author";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("@price", 1000);
cmd.Parameters.AddWithValue("@author", "John");
try {
con.Open();
int rows = cmd.ExecuteNonQuery();
Console.WriteLine(rows + " book(s) updated.");
}
catch (SqlException ex) {
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
ExecuteNonQuery() runs the UPDATE and returns the number of affected rows. 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
How rendering HTML with views is done? Explain.
Answer
In ASP.NET Core MVC a view is a Razor file (.cshtml) that generates the HTML sent to the browser. Razor mixes HTML with C# code using the @ symbol.
Steps of rendering
- A controller action finishes its work and returns
View(model). - The view engine locates the view by convention:
Views/<Controller>/<Action>.cshtml, thenViews/Shared/. - The
_ViewStart.cshtmlsets the layout;_Layout.cshtmlprovides the common page structure (header, menu, footer) and@RenderBody()places the view's content. - The Razor engine compiles the view into a C# class, executes the C# code with the data in the
@model(strongly typed),ViewData/ViewBag, and produces pure HTML. - The HTML is sent as the response.
public IActionResult Index() {
var students = _db.Students.ToList();
return View(students);
}
@model List<Student>
<h2>Students</h2>
<table>
@foreach (var s in Model) {
<tr><td>@s.Id</td><td>@s.Name</td></tr>
}
</table>
Other features: tag helpers (asp-action), HTML helpers, partial views (<partial name="_Menu" />), view components and sections.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 10 marks
Differentiate between error and exception. Write a program to take the input for any five subjects and throw the exception if the given marks is negative or exceed 100.
Answer
Error vs exception
| Error | Exception |
|---|---|
| A serious problem, often outside the program's control (out of memory, stack overflow, hardware failure) | An abnormal event during execution that can be anticipated and handled (divide by zero, invalid input, file not found) |
| Usually cannot be recovered; the program normally terminates | Can be caught and handled with try/catch, so execution continues |
| Includes compile-time (syntax) errors and logical errors | Occurs at run time |
Example: syntax error, StackOverflowException | Example: FormatException, DivideByZeroException, custom exception |
Program
using System;
class InvalidMarksException : Exception
{
public InvalidMarksException(string message) : base(message) { }
}
class Program
{
static void Main()
{
int[] marks = new int[5];
try
{
for (int i = 0; i < 5; i++)
{
Console.Write("Enter marks of subject " + (i + 1) + ": ");
int m = int.Parse(Console.ReadLine());
if (m < 0 || m > 100)
throw new InvalidMarksException("Marks must be between 0 and 100, but got " + m);
marks[i] = m;
}
int total = 0;
foreach (int m in marks) total += m;
Console.WriteLine("Total = " + total + ", Percentage = " + total / 5.0);
}
catch (InvalidMarksException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
catch (FormatException)
{
Console.WriteLine("Please enter a numeric value.");
}
finally
{
Console.WriteLine("Program finished.");
}
}
}
A custom exception is thrown as soon as an invalid mark (negative or above 100) is entered, and the catch block displays the message.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 10 marks
What do you mean by dependency injection and IOC container? Describe the methods for creating controller and action with example.
Answer
Dependency injection (DI)
Dependency injection is a design pattern in which an object receives the objects it depends on (its dependencies) from outside, usually through the constructor, instead of creating them with new. It gives loose coupling, easier unit testing (mock dependencies) and better maintainability.
IoC container
Inversion of Control means the framework, not the class, controls creation and lifetime of dependencies. The IoC container (service container, IServiceProvider) is the component that holds registrations (interface to implementation), creates objects when needed, resolves their dependencies automatically and manages lifetimes: Transient (new instance each time), Scoped (one per request) and Singleton (one for the application).
Registration in Program.cs:
builder.Services.AddScoped<IStudentService, StudentService>();
builder.Services.AddDbContext<SchoolContext>(...);
Creating controller and action with DI
- Constructor injection (most common) in a controller:
public class StudentController : Controller
{
private readonly IStudentService _service;
public StudentController(IStudentService service) { _service = service; }
public IActionResult Index() => View(_service.GetAll());
}
- Action injection with
[FromServices], when a service is needed by one action only:
public IActionResult Report([FromServices] IReportService rs)
{
return View(rs.Build());
}
-
Creating the controller: add a class ending with
Controller, deriving fromController(MVC) orControllerBasewith[ApiController](API). The default controller activator asks the IoC container to build it, injecting constructor parameters. Actions are public methods returningIActionResult, mapped by routing ([HttpGet],[HttpPost("{id}")]). -
Property or view injection with
@inject IStudentService Servicein Razor views.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 10 marks
Why do we need reader and adapter class? Using ADO.NET, in a relation BOOK (id, author, name, price), delete the books having price less than 500.
Answer
Reader and adapter classes in ADO.NET
DataReader (SqlDataReader) provides fast, forward-only, read-only access to query results while the connection stays open (connected architecture). It is needed when data is only to be displayed or processed row by row, because it uses little memory and is the quickest way to read.
DataAdapter (SqlDataAdapter) is the bridge between the database and a disconnected DataSet/DataTable. Its Fill() method loads data and Update() pushes the changes back using Select, Insert, Update and Delete commands. It is needed when data must be cached, edited, sorted, or bound offline, and when the connection should not be held open.
| DataReader | DataAdapter |
|---|---|
| Connected, forward-only, read-only | Disconnected, read/write via DataSet |
| Faster, less memory | More memory, more flexible |
Program: delete books having price less than 500
using System;
using System.Data.SqlClient;
class DeleteBooks
{
static void Main()
{
string connStr = "Data Source=.;Initial Catalog=Library;Integrated Security=True";
string sql = "DELETE FROM BOOK WHERE price < @limit";
using (SqlConnection con = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@limit", 500);
con.Open();
int n = cmd.ExecuteNonQuery();
Console.WriteLine(n + " book(s) deleted.");
}
}
}
The same can be done in disconnected mode with an adapter: fill a DataTable using SELECT * FROM BOOK, call Delete() on rows with price below 500, and then call adapter.Update(table) (with a SqlCommandBuilder) to apply the deletions.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
Describe the MVC pattern in ASP.NET.
Answer
MVC pattern in ASP.NET
Model-View-Controller is an architectural pattern that separates an application into three interacting components, so that data, presentation and request handling are independent.
- Model: represents the data and business logic: entity classes, validation rules and data access (Entity Framework). It knows nothing about the user interface.
- View: the presentation layer. Razor
.cshtmlfiles render the model into HTML. It contains minimal logic. - Controller: handles the incoming request, interacts with the model (get/update data), chooses the view and passes the model to it.
Request flow
- The user sends a request (
/Student/Details/3). - Routing maps it to
StudentController.Details(3). - The controller asks the model for the student.
- The controller returns
View(student). - The Razor view produces HTML, which is sent to the browser.
public IActionResult Details(int id)
{
var s = _context.Students.Find(id);
if (s == null) return NotFound();
return View(s);
}
Advantages: separation of concerns, testability (controllers can be unit tested without UI), multiple views for the same model, clean URLs, full control over HTML, and teams can work in parallel.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
How do you create form using React? Illustrate with an example.
Answer
In React, forms are normally built as controlled components: the form input values are stored in component state and updated through onChange handlers, so React is the single source of truth. On submit, onSubmit is handled with e.preventDefault() to avoid a page reload.
Steps: (1) create state with useState; (2) bind value and onChange to every input; (3) handle onSubmit; (4) validate and send data to the server.
Example: login form
import React, { useState } from "react";
function LoginForm() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const handleSubmit = async e => {
e.preventDefault();
if (!username || password.length < 6) {
setError("Enter username and a password of at least 6 characters");
return;
}
setError("");
const res = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password })
});
console.log(await res.json());
};
return (
<form onSubmit={handleSubmit}>
<input value={username} onChange={e => setUsername(e.target.value)} placeholder="Username" />
<input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Password" />
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit">Login</button>
</form>
);
}
export default LoginForm;
Whenever the user types, the state changes and the component re-renders with the new value. Uncontrolled forms (using useRef) or libraries such as Formik and React Hook Form are alternatives.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
Define cookies. What are the uses of hidden fields?
Answer
Cookies
A cookie is a small piece of text data (name-value pair, up to about 4 KB) that the server sends to the browser, which stores it and returns it with every subsequent request to the same site. Cookies overcome the stateless nature of HTTP. They may be session cookies (deleted when the browser closes) or persistent cookies (with an expiry date).
Response.Cookies.Append("username", "ram", new CookieOptions { Expires = DateTime.Now.AddDays(7), HttpOnly = true });
string name = Request.Cookies["username"];
Uses: keeping a user logged in, storing the session ID, remembering preferences (language, theme), shopping cart identification, and tracking/analytics.
Uses of hidden fields
A hidden field (<input type="hidden">) holds a value in the form that is submitted but not shown to the user. It is used to:
- Pass record identifiers (e.g. the ID of the item being edited) with the form.
- Maintain state across pages of a multi-step form.
- Carry anti-forgery tokens and return URLs.
- Send calculated or default values to the server without user input.
Because users can view and change hidden values through browser tools, they must not store sensitive data and must be validated on the server.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
Why do we need to validate form in client side? Justify with an example.
Answer
Client-side validation checks the input in the user's browser (JavaScript, HTML5 attributes, jQuery Validation) before the form is sent to the server.
Why it is needed
- Instant feedback: the user sees errors immediately without waiting for a server round trip.
- Reduced server load and bandwidth: invalid requests are stopped in the browser.
- Better user experience: errors can be highlighted next to the field, and the user does not lose entered data.
- Basic data quality before submission (required fields, format, range).
It cannot replace server-side validation because users can disable JavaScript or alter requests; both are used together.
Example
<form onsubmit="return validate()">
Name: <input type="text" id="name"><br>
Age: <input type="number" id="age"><br>
Email: <input type="text" id="email"><br>
<button type="submit">Submit</button>
</form>
<script>
function validate() {
var name = document.getElementById('name').value.trim();
var age = document.getElementById('age').value;
var email = document.getElementById('email').value;
if (name === '') { alert('Name is required'); return false; }
if (age < 18 || age > 60) { alert('Age must be between 18 and 60'); return false; }
if (!/^\S+@\S+\.\S+$/.test(email)) { alert('Invalid email'); return false; }
return true; // form is submitted only if all checks pass
}
</script>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
Illustrate the concept of SQL injection with an example.
Answer
SQL injection is an attack in which a malicious user inserts SQL code into an input field so that the application executes it as part of its query, changing the intended query. It happens when SQL strings are built by concatenating user input.
Example
Vulnerable login code:
string sql = "SELECT * FROM Users WHERE Username='" + user + "' AND Password='" + pass + "'";
Attacker enters admin' -- as username (any password). The query becomes:
SELECT * FROM Users WHERE Username='admin' --' AND Password=''
-- comments out the password check, so the attacker logs in as admin. Entering ' OR '1'='1 makes the condition always true. Input like '; DROP TABLE Users; -- can delete data, and UNION queries can read other tables.
Consequences: unauthorized access, data theft, modification or deletion.
Prevention: parameterized queries (@user, @pass), stored procedures, ORM/LINQ, input validation, least-privilege database accounts, and hashed passwords.
var cmd = new SqlCommand("SELECT * FROM Users WHERE Username=@u AND Password=@p", con);
cmd.Parameters.AddWithValue("@u", user);
cmd.Parameters.AddWithValue("@p", pass);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
What is the use of session state? Discuss about single page application.
Answer
Session state
Session state stores user-specific data on the server across multiple requests of the same user, overcoming the statelessness of HTTP. The server creates a unique session id, sent to the browser in a cookie, and uses it to find that user's data. Uses: keeping login information, shopping cart, user preferences, multi-step form data. Session data lives in server memory (or a distributed cache such as Redis/SQL Server) and expires after a timeout.
builder.Services.AddSession(); app.UseSession();
HttpContext.Session.SetString("User", "Ram");
string u = HttpContext.Session.GetString("User");
Single page application (SPA)
An SPA is a web application that loads a single HTML page and dynamically updates the content using JavaScript as the user interacts, fetching only data (JSON) from the server through APIs rather than loading whole new pages. Examples are Angular, React and Vue apps (Gmail). Advantages: fast, smooth navigation, reduced server load, and a clean front-end/back-end separation. Drawbacks: slower first load and SEO challenges (solved with server-side rendering).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
Define JSON. What is the use of base keyword? Give an example.
Answer
JSON (JavaScript Object Notation)
JSON is a lightweight, text-based, language-independent data interchange format that is easy for humans to read and for machines to parse. Data is written as name-value pairs in objects { } and ordered lists in arrays [ ]. It is widely used in REST APIs and SPAs, replacing XML in many cases.
{ "id": 1, "name": "Ram", "marks": [80, 75, 90], "active": true }
In .NET it is handled with System.Text.Json (JsonSerializer.Serialize/Deserialize) or Newtonsoft.Json.
Use of base keyword
base refers to the immediate parent class and is used to call a parent constructor or to access a parent member hidden or overridden in the child class.
class Person {
protected string name;
public Person(string n) { name = n; }
public virtual void Show() { Console.WriteLine("Name: " + name); }
}
class Student : Person {
int roll;
public Student(string n, int r) : base(n) { roll = r; } // parent constructor
public override void Show() {
base.Show(); // parent method
Console.WriteLine("Roll: " + roll);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081.1 · 5 marks
List the uses of docker. How do you secure controller and action methods?
Answer
Uses of Docker
Docker packages an application with its dependencies into a lightweight container.
- Portability: the same container runs identically on a developer machine, test server and cloud ("works on my machine" problem is removed).
- Isolation: each app has its own environment, so there are no dependency conflicts.
- Fast deployment and scaling: containers start in seconds; used with Kubernetes/Azure.
- Resource efficiency: lighter than virtual machines because they share the host kernel.
- CI/CD and consistent environments, versioned images, easy rollback.
- Microservices support and easy testing of different versions.
Securing controller and action methods
- Use the
[Authorize]attribute on a controller or action to require authentication;[AllowAnonymous]for exceptions. - Restrict by role or policy:
[Authorize(Roles="Admin")],[Authorize(Policy="AdultOnly")]. - Apply
[HttpPost]etc. for correct verbs and[ValidateAntiForgeryToken]against CSRF. - Validate input (
ModelState.IsValid), use view models to avoid over-posting, and parameterized queries. - Use HTTPS and apply a global authorization filter.
[Authorize]
public class AccountController : Controller {
[Authorize(Roles = "Admin")]
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Delete(int id) { ... }
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BIT 2080 Sixth Semester .NET Centric Computing (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Sixth Semester .NET Centric Computing (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.1 Sixth Semester .NET Centric Computing (TU IOST semester board exam, 2081.1 (BS), via StudyNp), TU BIT 2080 Sixth Semester Database Administration (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Sixth Semester Database Administration (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.1 Sixth Semester Database Administration (TU IOST semester board exam, 2081.1 (BS), via StudyNp), TU BIT 2080 Sixth Semester Management Information System (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Sixth Semester Management Information System (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.1 Sixth Semester Management Information System (TU IOST semester board exam, 2081.1 (BS), via StudyNp), TU BIT 2080 Sixth Semester Geographical Information System (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Sixth Semester Multimedia Computing (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081 Sixth Semester Wireless Networking (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081 Sixth Semester Society and Ethics in IT (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2081.1 Sixth Semester Society and Ethics in IT (TU IOST semester board exam, 2081.1 (BS), via StudyNp), TU BIT 2080 Sixth Semester Research Methodology (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Sixth Semester Research Methodology (TU IOST semester board exam, 2081 (BS), via StudyNp) and TU BIT 2081.1 Sixth Semester Research Methodology (TU IOST semester board exam, 2081.1 (BS), via StudyNp). Answers are written for this site; check them against your class notes.