BIT351 · TU past paper
NET Centric Computing 2081.1 question paper
The complete TU 2081.1 exam paper for NET Centric Computing (BIT351), all 12 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksNumericalThrowing and catching exceptionsHideAnswer
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.[10]
Errors and exceptions, and validating five subject marks
How the two differ
In everyday use an error is any fault in a program, but as a technical term the two words describe faults of very different severity, and the .NET framework treats them differently from Java.
In .NET there is no separate
Errorbase class. Everything that can be thrown derives fromSystem.Exception. The distinction that matters is between the ordinary exceptions an application is expected to anticipate and recover from, such asFormatException,IOExceptionorSqlException, and the fatal conditions raised by the runtime itself, such asOutOfMemoryException,StackOverflowExceptionandAccessViolationException. The second group corresponds to what Java calls anError, and .NET makes the point sharply: since .NET 2.0 aStackOverflowExceptioncannot be caught at all, the process is simply terminated, because once the stack is gone there is no reliable way to keep running. The word error is also used for a compile time error, which the compiler refuses to build, and for an ordinary failure that a method reports through a return value or a status code rather than by throwing.Basis Error (fatal condition) Exception (handled condition) Meaning The environment can no longer run the program correctly An abnormal but foreseeable situation in the application Raised by The CLR or the operating system The application, a library, or the CLR for bad arguments Typical examples OutOfMemoryException,StackOverflowException,AccessViolationExceptionFormatException,DivideByZeroException,FileNotFoundException, a customInvalidMarksExceptionRecoverable Normally not; a stack overflow cannot even be caught Yes, that is the point of catching it Right response Let the process fail and log it outside the process try,catch,finally, or ausingblockIn Java A separate java.lang.ErrorhierarchyThe java.lang.ExceptionhierarchyThe practical consequence is that a program should catch the exception types it can actually do something about. Writing
catch (Exception)around everything hides genuine defects such as a null reference, and it cannot rescue the fatal conditions anyway, so it buys nothing and costs a great deal in lost diagnostics.Within the exception family, .NET also distinguishes exceptions by who is at fault.
ArgumentException,ArgumentNullExceptionandInvalidOperationExceptionsay the calling code used the API wrongly and should be fixed rather than caught, whereasIOExceptionor a timeout describes the outside world misbehaving, which the caller must genuinely handle. A custom type for a business rule, like the marks rule below, belongs to that second group.A C# program that validates five subject marks
The program reads marks for five subjects, and a method throws a custom exception when a value is negative or greater than 100. Each subject is validated inside its own
tryblock so that one bad value does not stop the remaining subjects from being checked.using System; // A custom exception carries the offending data as well as the message. public class InvalidMarksException : Exception { public string Subject { get; } public int Marks { get; } public InvalidMarksException(string subject, int marks, string message) : base(message) { Subject = subject; Marks = marks; } } public static class Program { private static readonly string[] Subjects = { "Mathematics", "Physics", "Chemistry", "English", "Computer" }; private static void ValidateMarks(string subject, int marks) { if (marks < 0) { throw new InvalidMarksException(subject, marks, subject + ": " + marks + " is negative, marks cannot fall below 0."); } if (marks > 100) { throw new InvalidMarksException(subject, marks, subject + ": " + marks + " is too high, marks cannot exceed 100."); } } public static void Main() { int[] marks = new int[Subjects.Length]; Console.WriteLine("Enter the marks obtained in five subjects."); for (int i = 0; i < Subjects.Length; i++) { Console.Write(Subjects[i] + " (0 to 100): "); string typed = Console.ReadLine(); // Console input is untrusted text, so it is parsed rather than assumed numeric. // TryParse reports failure through its return value instead of throwing. while (!int.TryParse(typed, out marks[i])) { Console.Write("Please type a whole number for " + Subjects[i] + ": "); typed = Console.ReadLine(); } } int total = 0; int accepted = 0; Console.WriteLine(); Console.WriteLine("Checking the marks."); for (int i = 0; i < Subjects.Length; i++) { try { ValidateMarks(Subjects[i], marks[i]); Console.WriteLine(Subjects[i] + ": " + marks[i] + " is valid."); total += marks[i]; accepted++; } catch (InvalidMarksException ex) { // Only the exception this code knows how to handle is caught. Console.WriteLine("Invalid entry. " + ex.Message); } } Console.WriteLine(); Console.WriteLine(accepted + " of 5 subjects accepted, total " + total + " marks."); } }A sample run:
Enter the marks obtained in five subjects. Mathematics (0 to 100): 85 Physics (0 to 100): -10 Chemistry (0 to 100): 110 English (0 to 100): 75 Computer (0 to 100): 90 Checking the marks. Mathematics: 85 is valid. Invalid entry. Physics: -10 is negative, marks cannot fall below 0. Invalid entry. Chemistry: 110 is too high, marks cannot exceed 100. English: 75 is valid. Computer: 90 is valid. 3 of 5 subjects accepted, total 250 marks.Two details are worth defending in the viva.
int.TryParseis used instead ofint.Parsebecause a typing mistake is expected input and not an exceptional condition, so it is cheaper and clearer to test the return value than to throw and catch aFormatException. The customInvalidMarksExceptionderives fromExceptionand adds the subject and the marks as properties, so the handler can report precisely which entry failed rather than parsing the message text. If the same validation were reached from an ASP.NET Core page instead of the console, the message would be surfaced through model validation and rendered with Razor, which HTML encodes the value so that whatever the user typed cannot be treated as markup. - 210 marksDependency injection principlesHideAnswer
What do you mean by dependency injection and IOC container? Describe the methods for creating controller and action with example.[10]
Dependency Injection and IOC Container in ASP.NET MVC
Note: The reference notes were not available for this topic. The following answer is based on standard ASP.NET MVC / .NET Core curriculum content as taught in TU BSc CSIT.
1. Dependency Injection (DI)
Dependency Injection is a design pattern and a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Instead of a class creating its own dependencies (objects it needs), those dependencies are injected from outside, typically through a constructor, property, or method.
Why DI?
- Reduces tight coupling between classes
- Makes code more testable, maintainable, and reusable
- Follows the Dependency Inversion Principle (SOLID)
Types of Dependency Injection
Type Description Constructor Injection Dependencies passed through the constructor Property Injection Dependencies set through public properties Method Injection Dependencies passed as method parameters Example Without DI (Tightly Coupled)
public class StudentController : Controller { private StudentRepository _repo = new StudentRepository(); // tight coupling }Example With DI (Loosely Coupled)
public class StudentController : Controller { private readonly IStudentRepository _repo; // Constructor Injection public StudentController(IStudentRepository repo) { _repo = repo; } public IActionResult Index() { var students = _repo.GetAll(); return View(students); } }
2. IOC Container (Inversion of Control Container)
An IoC Container (also called a DI Container) is a framework or component that:
- Manages the creation and lifetime of objects (dependencies)
- Automatically injects dependencies wherever required
- Maintains a registry of interfaces and their concrete implementations
In ASP.NET Core, the built-in IoC container is accessed through
IServiceCollectioninProgram.csorStartup.cs.Service Lifetimes in IoC Container
Lifetime Method Description Transient AddTransient<>()New instance every time it is requested Scoped AddScoped<>()One instance per HTTP request Singleton AddSingleton<>()One instance for the entire application lifetime Registering Services in IoC Container (ASP.NET Core)
// Program.cs var builder = WebApplication.CreateBuilder(args); // Register services in IoC container builder.Services.AddScoped<IStudentRepository, StudentRepository>(); builder.Services.AddTransient<IEmailService, EmailService>(); builder.Services.AddSingleton<ILoggerService, LoggerService>(); builder.Services.AddControllersWithViews(); var app = builder.Build(); app.MapDefaultControllerRoute(); app.Run();When
StudentControlleris requested, the IoC container automatically resolvesIStudentRepositoryand injectsStudentRepository.
3. Creating Controllers in ASP.NET MVC
A Controller is a class that:
- Handles incoming HTTP requests
- Processes user input
- Returns appropriate responses (Views, JSON, Redirects, etc.)
Rules for Creating a Controller
- The class name must end with the suffix Controller (e.g.,
HomeController) - It must inherit from the Controller base class (or
ControllerBasefor APIs) - It must be placed in the Controllers folder (by convention)
- It must be a public class
Methods of Creating a Controller
Method 1: Inheriting from Controller Class
using Microsoft.AspNetCore.Mvc; public class HomeController : Controller { public IActionResult Index() { return View(); } }Method 2: Using Dependency Injection in Controller
using Microsoft.AspNetCore.Mvc; public class ProductController : Controller { private readonly IProductService _productService; // Constructor Injection via IoC Container public ProductController(IProductService productService) { _productService = productService; } public IActionResult Index() { var products = _productService.GetAllProducts(); return View(products); } }Method 3: API Controller (inheriting ControllerBase)
[ApiController] [Route("api/[controller]")] public class StudentApiController : ControllerBase { [HttpGet] public IActionResult GetAll() { return Ok(new { message = "All Students" }); } }
4. Creating Action Methods
An Action Method is a public method inside a controller that:
- Responds to a specific HTTP request (GET, POST, PUT, DELETE)
- Returns an
IActionResult(or specific result types)
Types of Action Results
Return Type Method Description ViewResultView()Returns an HTML view RedirectResultRedirect()Redirects to a URL JsonResultJson()Returns JSON data ContentResultContent()Returns plain text NotFoundResultNotFound()Returns 404 Example: Various Action Methods
public class StudentController : Controller { private readonly IStudentRepository _repo; public StudentController(IStudentRepository repo) { _repo = repo; } // GET: /Student/Index [HttpGet] public IActionResult Index() { var students = _repo.GetAll(); return View(students); // returns a View } // GET: /Student/Details/5 [HttpGet] public IActionResult Details(int id) { var student = _repo.GetById(id); if (student == null) { return NotFound(); // returns 404 } return View(student); } // POST: /Student/Create [HttpPost] public IActionResult Create(Student student) { if (!ModelState.IsValid) { return View(student); // redisplay the form with errors } _repo.Add(student); return RedirectToAction("Index"); // redirect after POST } // GET: /Student/Json [HttpGet] public IActionResult GetJson() { return Json(_repo.GetAll()); // returns JSON data } }Notice that
IStudentRepositoryis never created withnewinside the controller: the IoC container sees the constructor parameter, resolves the registered implementation and injects it, which is constructor injection in practice.
Conclusion
Dependency injection means a class receives the services it needs from outside instead of constructing them itself, which removes the tight coupling between a controller and a concrete repository and makes the controller testable with a fake implementation. The IoC container is the piece of infrastructure that performs the injection: services are registered once in
Program.cswith a lifetime of transient, scoped or singleton, and the container then creates every controller and supplies its dependencies. Controllers themselves are created by inheritingController(orControllerBasefor a Web API), and their public action methods return anIActionResultsuch asView(),Json(),RedirectToAction()orNotFound()according to what the request needs. - 310 marksNumericalDataReader and DataAdapter classesHideAnswer
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.[10]
- Relation: BOOK (id, author, name, price) - Task: Delete books where price < 500 - Conceptual question: Need for DataReader and DataAdapter classes No numeric matrices or scheduling data involved. This is a conceptual + programming ques...
- 45 marksMSIL and CLR architectureHideAnswer
Explain about MSIL and CLR. [5]
MSIL and CLR
Note: The reference notes did not contain this topic. The following answer is based on standard .NET / C# curriculum content taught in BSc CSIT.
1. MSIL (Microsoft Intermediate Language)
MSIL (also called CIL - Common Intermediate Language) is a low-level, platform-independent instruction set into which all .NET-compatible languages (C#, VB.NET, F#, etc.) are compiled before being converted to native machine code.
Key Points:
- When a programmer writes code in C# (or any .NET language) and compiles it, the compiler does not produce native machine code directly.
- Instead, it produces MSIL code stored inside an assembly (
.exeor.dllfile). - MSIL is CPU-independent - it is not tied to any specific processor or operating system.
- MSIL contains instructions for loading, storing, calling methods, arithmetic operations, etc., in a generalized form.
- It also contains metadata - information about types, methods, and references used in the program.
Compilation Flow:
Source Code (.cs) | [C# Compiler] | MSIL Code + Metadata (stored in Assembly) | [CLR / JIT Compiler] | Native Machine Code (executed by CPU)
2. CLR (Common Language Runtime)
CLR is the execution engine (runtime environment) of the .NET Framework. It is responsible for loading, executing, and managing .NET programs.
Key Responsibilities of CLR:
Function Description JIT Compilation Converts MSIL into native machine code at runtime using the Just-In-Time (JIT) compiler Memory Management Automatically allocates and deallocates memory Garbage Collection (GC) Automatically reclaims unused objects from the heap Type Safety Ensures that code accesses only the memory it is authorized to access Exception Handling Provides a structured mechanism to handle runtime errors Security Enforces code access security and role-based security Thread Management Manages multithreading and synchronization Interoperability Allows .NET code to interact with unmanaged (native) code How CLR Works:
- The CLR loads the assembly (containing MSIL).
- The JIT compiler inside CLR converts MSIL to native machine code specific to the current CPU.
- The native code is then executed by the operating system.
- CLR continuously manages the running program (GC, exceptions, security, etc.).
Relationship Between MSIL and CLR
MSIL CLR Intermediate code produced by compiler Runtime that executes the intermediate code Platform-independent Platform-specific (different CLR for different OS) Stored in assembly files Installed as part of .NET Framework Input to CLR Processes and runs MSIL
Summary
MSIL is the intermediate, platform-independent bytecode that .NET compilers produce. CLR is the runtime environment that takes this MSIL, compiles it to native code via JIT, and manages its execution including memory, security, and exception handling. Together, they form the foundation of the .NET execution model.
- 55 marksMVC pattern componentsHideAnswer
Describe the MVC pattern in ASP.NET. [5]
MVC (Model-View-Controller) is a software architectural design pattern that separates an application into three interconnected components, promoting organized code, separation of concerns, and easier maintainability. --- - Represents the...
- 65 marksReact form creationHideAnswer
How do you create form using React? Illustrate with an example. [5]
In React, forms are handled differently from regular HTML forms. React uses controlled components to manage form data, where form input values are controlled by the component's state. --- A controlled component is an input element whose ...
- 75 marksCookies definition and usesHideAnswer
Define cookies. What are the uses of hidden fields? [5]
Cookies and Hidden Fields
Cookies (Definition)
A cookie is a small piece of text data that a web server sends to a client's browser, which the browser stores locally on the user's machine. When the browser makes subsequent requests to the same server, it automatically sends the stored cookie back, allowing the server to identify and remember the user across multiple requests.
Key characteristics of cookies:
- Stored on the client side (user's browser/machine)
- Have an expiry date/time (session cookies expire when browser closes; persistent cookies have a set expiry)
- Associated with a specific domain and path
- Set using the
Set-CookieHTTP response header - Sent back to the server via the
CookieHTTP request header
Example:
Set-Cookie: username=JohnDoe; expires=Fri, 31 Dec 2025 12:00:00 GMT; path=/Common uses of cookies:
- User authentication and session management
- Storing user preferences
- Tracking user behavior
- Shopping cart persistence
Hidden Fields
A hidden field is an HTML form element (
<input type="hidden">) that stores data within a web form but is not visible to the user on the browser screen. The data is submitted to the server when the form is submitted.Syntax:
<input type="hidden" name="userID" value="1023">Uses of Hidden Fields
Use Description State Management Maintain state information (e.g., user ID, session token) across multiple page requests without cookies Passing Data Between Pages Transfer data from one page to another through form submission without displaying it to the user Security Tokens (CSRF Protection) Store anti-CSRF tokens to validate that form submissions are legitimate Tracking Form Progress In multi-step forms (wizards), carry forward data collected in previous steps Storing Record IDs Pass database record IDs (e.g., product ID, order ID) back to the server during form submission Preserving Original Values Store original field values to detect changes made by the user before update
Key Difference
Feature Cookies Hidden Fields Storage Client's browser/disk Inside HTML form Visibility Not visible in page Not visible on screen but visible in page source Persistence Can persist across sessions Only available during form submission Sent to server With every HTTP request Only on form submission - 85 marksClient-side validation justificationHideAnswer
Why do we need to validate form in client side? Justify with an example. [5]
Client-side form validation is the process of checking user input directly in the browser (using HTML5 attributes or JavaScript) before the data is sent to the server. It is an essential part of web development for the following reasons:...
- 95 marksSQL injection attacks and preventionHideAnswer
Illustrate the concept of SQL injection with an example. [5]
SQL Injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It occurs when untrusted user input is directly embedded into an SQL query without proper vali...
- 105 marksSession state managementHideAnswer
What is the use of session state? Discuss about single page application. [5]
Session state is a server-side mechanism used in web applications to store and maintain user-specific data across multiple HTTP requests during a user's visit (session) to a website. Since HTTP is a stateless protocol, session state is u...
- 115 marksBase keyword usageHideAnswer
Define JSON. What is the use of base keyword? Give an example. [5]
--- JSON is a lightweight, text-based, language-independent data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is based on a subset of JavaScript but is language-independent...
- 125 marksDocker uses and benefitsHideAnswer
List the uses of docker. How do you secure controller and action methods? [5]
Uses of Docker and Securing Controller/Action Methods
Uses of Docker [2.5 marks]
Docker is a containerization platform that packages applications and their dependencies into lightweight, portable containers. Its main uses include:
-
Application Portability
- Docker containers run consistently across different environments (development, testing, production), eliminating the "it works on my machine" problem.
-
Microservices Architecture
- Docker enables breaking down large applications into small, independent microservices, each running in its own container.
-
Continuous Integration and Continuous Deployment (CI/CD)
- Docker integrates with CI/CD pipelines (Jenkins, GitHub Actions) to automate building, testing, and deploying applications.
-
Isolation and Resource Management
- Each container runs in isolation with its own filesystem, network, and process space, preventing conflicts between applications.
-
Rapid Deployment and Scaling
- Containers start in seconds and can be scaled up or down quickly using orchestration tools like Kubernetes or Docker Swarm.
-
Version Control for Environments
- Docker images can be versioned, allowing rollback to previous application states easily.
-
Simplified Dependency Management
- All dependencies are bundled inside the container image, removing the need to install them separately on the host machine.
Securing Controller and Action Methods in ASP.NET MVC [2.5 marks]
In ASP.NET MVC, controllers and action methods can be secured primarily using the
[Authorize]attribute.1. Using
[Authorize]AttributeThe
[Authorize]attribute restricts access to authenticated users only.On a Controller (secures all actions):
[Authorize] public class AdminController : Controller { public ActionResult Dashboard() { return View(); } }On a specific Action Method:
public class HomeController : Controller { [Authorize] public ActionResult SecretPage() { return View(); } public ActionResult PublicPage() { return View(); } }2. Role-Based Authorization
Restrict access to users belonging to specific roles:
[Authorize(Roles = "Admin, Manager")] public ActionResult ManageUsers() { return View(); }3. Using
[AllowAnonymous]AttributeAllows specific actions to be publicly accessible even when the controller is secured:
[Authorize] public class AccountController : Controller { [AllowAnonymous] public ActionResult Login() { return View(); } public ActionResult Profile() { return View(); } }4. Global Authorization Filter
Apply authorization globally to all controllers in
FilterConfig.cs:public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new AuthorizeAttribute()); } }Summary Table
Method Scope [Authorize]on ControllerAll actions in the controller [Authorize]on ActionOnly that specific action [Authorize(Roles="Admin")]Only users in specified role [AllowAnonymous]Bypasses authorization Global Filter Entire application -