2081.1

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.

Past Papers2081.120812080

Tap a question to open its answer.

  1. 110 marksNumericalThrowing and catching exceptionsAnswer

    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 Error base class. Everything that can be thrown derives from System.Exception. The distinction that matters is between the ordinary exceptions an application is expected to anticipate and recover from, such as FormatException, IOException or SqlException, and the fatal conditions raised by the runtime itself, such as OutOfMemoryException, StackOverflowException and AccessViolationException. The second group corresponds to what Java calls an Error, and .NET makes the point sharply: since .NET 2.0 a StackOverflowException cannot 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.

    BasisError (fatal condition)Exception (handled condition)
    MeaningThe environment can no longer run the program correctlyAn abnormal but foreseeable situation in the application
    Raised byThe CLR or the operating systemThe application, a library, or the CLR for bad arguments
    Typical examplesOutOfMemoryException, StackOverflowException, AccessViolationExceptionFormatException, DivideByZeroException, FileNotFoundException, a custom InvalidMarksException
    RecoverableNormally not; a stack overflow cannot even be caughtYes, that is the point of catching it
    Right responseLet the process fail and log it outside the processtry, catch, finally, or a using block
    In JavaA separate java.lang.Error hierarchyThe java.lang.Exception hierarchy

    The 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, ArgumentNullException and InvalidOperationException say the calling code used the API wrongly and should be fixed rather than caught, whereas IOException or 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 try block 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.TryParse is used instead of int.Parse because 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 a FormatException. The custom InvalidMarksException derives from Exception and 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.

  2. 210 marksDependency injection principlesAnswer

    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

    TypeDescription
    Constructor InjectionDependencies passed through the constructor
    Property InjectionDependencies set through public properties
    Method InjectionDependencies 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 IServiceCollection in Program.cs or Startup.cs.

    Service Lifetimes in IoC Container

    LifetimeMethodDescription
    TransientAddTransient<>()New instance every time it is requested
    ScopedAddScoped<>()One instance per HTTP request
    SingletonAddSingleton<>()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 StudentController is requested, the IoC container automatically resolves IStudentRepository and injects StudentRepository.


    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

    1. The class name must end with the suffix Controller (e.g., HomeController)
    2. It must inherit from the Controller base class (or ControllerBase for APIs)
    3. It must be placed in the Controllers folder (by convention)
    4. 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 TypeMethodDescription
    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 IStudentRepository is never created with new inside 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.cs with a lifetime of transient, scoped or singleton, and the container then creates every controller and supplies its dependencies. Controllers themselves are created by inheriting Controller (or ControllerBase for a Web API), and their public action methods return an IActionResult such as View(), Json(), RedirectToAction() or NotFound() according to what the request needs.

  3. 310 marksNumericalDataReader and DataAdapter classesAnswer

    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...
  4. 45 marksMSIL and CLR architectureAnswer

    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 (.exe or .dll file).
    • 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:

    FunctionDescription
    JIT CompilationConverts MSIL into native machine code at runtime using the Just-In-Time (JIT) compiler
    Memory ManagementAutomatically allocates and deallocates memory
    Garbage Collection (GC)Automatically reclaims unused objects from the heap
    Type SafetyEnsures that code accesses only the memory it is authorized to access
    Exception HandlingProvides a structured mechanism to handle runtime errors
    SecurityEnforces code access security and role-based security
    Thread ManagementManages multithreading and synchronization
    InteroperabilityAllows .NET code to interact with unmanaged (native) code

    How CLR Works:

    1. The CLR loads the assembly (containing MSIL).
    2. The JIT compiler inside CLR converts MSIL to native machine code specific to the current CPU.
    3. The native code is then executed by the operating system.
    4. CLR continuously manages the running program (GC, exceptions, security, etc.).

    Relationship Between MSIL and CLR

    MSILCLR
    Intermediate code produced by compilerRuntime that executes the intermediate code
    Platform-independentPlatform-specific (different CLR for different OS)
    Stored in assembly filesInstalled as part of .NET Framework
    Input to CLRProcesses 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.

  5. 55 marksMVC pattern componentsAnswer

    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...

  6. 65 marksReact form creationAnswer

    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 ...

  7. 75 marksCookies definition and usesAnswer

    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-Cookie HTTP response header
    • Sent back to the server via the Cookie HTTP 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

    UseDescription
    State ManagementMaintain state information (e.g., user ID, session token) across multiple page requests without cookies
    Passing Data Between PagesTransfer 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 ProgressIn multi-step forms (wizards), carry forward data collected in previous steps
    Storing Record IDsPass database record IDs (e.g., product ID, order ID) back to the server during form submission
    Preserving Original ValuesStore original field values to detect changes made by the user before update

    Key Difference

    FeatureCookiesHidden Fields
    StorageClient's browser/diskInside HTML form
    VisibilityNot visible in pageNot visible on screen but visible in page source
    PersistenceCan persist across sessionsOnly available during form submission
    Sent to serverWith every HTTP requestOnly on form submission
  8. 85 marksClient-side validation justificationAnswer

    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:...

  9. 95 marksSQL injection attacks and preventionAnswer

    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...

  10. 105 marksSession state managementAnswer

    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...

  11. 115 marksBase keyword usageAnswer

    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...

  12. 125 marksDocker uses and benefitsAnswer

    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:

    1. Application Portability

      • Docker containers run consistently across different environments (development, testing, production), eliminating the "it works on my machine" problem.
    2. Microservices Architecture

      • Docker enables breaking down large applications into small, independent microservices, each running in its own container.
    3. Continuous Integration and Continuous Deployment (CI/CD)

      • Docker integrates with CI/CD pipelines (Jenkins, GitHub Actions) to automate building, testing, and deploying applications.
    4. Isolation and Resource Management

      • Each container runs in isolation with its own filesystem, network, and process space, preventing conflicts between applications.
    5. Rapid Deployment and Scaling

      • Containers start in seconds and can be scaled up or down quickly using orchestration tools like Kubernetes or Docker Swarm.
    6. Version Control for Environments

      • Docker images can be versioned, allowing rollback to previous application states easily.
    7. 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] Attribute

    The [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] Attribute

    Allows 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

    MethodScope
    [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 FilterEntire application