CSC378 · TU past paper
NET Centric Computing 2080 question paper
The complete TU 2080 exam paper for NET Centric Computing (CSC378), all 12 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksState Management on stateless HTTPHideAnswer
How do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.[10]
Managing State on Stateless HTTP and Form Validation Using jQuery
Part 1: Managing State on Stateless HTTP (5 marks)
What is the Problem?
HTTP is a stateless protocol, meaning each request from a client to the server is independent. The server does not remember any previous request. However, real-world web applications (like shopping carts, login sessions, etc.) need to remember user data across multiple requests. This is called state management.
State Management Approaches in ASP.NET
The following storage approaches are used to manage state on stateless HTTP:
Storage Approach Description Cookies HTTP cookies. May include data using server-side app code. Session State HTTP cookies and server-side app code. TempData HTTP cookies or session state. Query Strings HTTP query strings. Hidden Fields HTTP form fields. HTTP Content Server-side app code. Cache Cache server-side app code.
Detailed Explanation of Each Approach
1. Cookies
- Small pieces of data stored on the client's browser.
- Sent automatically with every HTTP request to the server.
- Used to remember user preferences, login tokens, etc.
// Setting a cookie in ASP.NET MVC Response.Cookies.Append("Username", "JohnDoe"); // Reading a cookie string username = Request.Cookies["Username"];Limitation: Cookies can be tampered with by the client, so sensitive data should not be stored directly.
2. Session State
- Data is stored on the server side.
- A unique session ID is stored in a cookie on the client side.
- The server uses this ID to retrieve the corresponding session data.
// Storing data in session HttpContext.Session.SetString("UserName", "JohnDoe"); // Retrieving data from session string name = HttpContext.Session.GetString("UserName");Advantage: More secure than cookies since actual data stays on the server.
3. TempData
- Used to pass data between two consecutive requests (e.g., from one action to another after a redirect).
- Internally uses cookies or session state.
// Storing in TempData TempData["Message"] = "Record saved successfully!"; // Reading in the next request string msg = TempData["Message"].ToString();
4. Query Strings
- Data is passed as part of the URL.
https://example.com/products?category=electronics&page=2string category = Request.Query["category"];Limitation: Visible in the URL, not suitable for sensitive data.
5. Hidden Fields
- Data is stored in HTML form fields that are not visible to the user but are submitted with the form.
<input type="hidden" name="UserId" value="101" />Limitation: Can be viewed and modified by inspecting the page source.
6. Cache
- Data is stored server-side in memory for fast access.
- Suitable for data that is expensive to compute and shared across users.
// Using IMemoryCache _cache.Set("ProductList", products, TimeSpan.FromMinutes(10));
Summary Diagram
Client (Browser) Server | | |--- HTTP Request (stateless) --->| | | | State managed via: | | - Cookies (client-side) | | - Session (server-side) | | - TempData (redirect) | | - Query Strings (URL) | | - Hidden Fields (form) | | - Cache (server memory) | |<-- HTTP Response ---------------|
Part 2: Form Validation Using jQuery (5 marks)
What is jQuery Form Validation?
jQuery provides a simple and powerful way to validate HTML forms on the client side before the data is submitted to the server. This improves user experience by giving instant feedback without a page reload.
The most commonly used plugin is the jQuery Validation Plugin.
Assumptions
- We have a Student Registration Form with fields: Name, Email, Age, and Password.
- jQuery and jQuery Validation plugin are included via CDN.
- Validation is done client-side before form submission.
Step 1: HTML Form Structure
<!DOCTYPE html> <html> <head> <title>Student Registration</title> <!-- Include jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Include jQuery Validation Plugin --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script> <style> .error { color: red; font-size: 12px; } input { display: block; margin: 8px 0; padding: 5px; } </style> </head> <body> <h2>Student Registration Form</h2> <form id="registrationForm"> <label>Full Name:</label> <input type="text" id="name" name="name" placeholder="Enter your name" /> <label>Email:</label> <input type="email" id="email" name="email" placeholder="Enter your email" /> <label>Age:</label> <input type="number" id="age" name="age" placeholder="Enter your age" /> <label>Password:</label> <input type="password" id="password" name="password" placeholder="Enter password" /> <label>Confirm Password:</label> <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Confirm password" /> <button type="submit">Register</button> </form> </body> </html>
Step 2: jQuery Validation Script
<script> $(document).ready(function () { $("#registrationForm").validate({ rules: { name: { required: true, minlength: 3 }, email: { required: true, email: true }, age: { required: true, number: true, min: 16, max: 100 }, password: { required: true, minlength: 6 }, confirmPassword: { required: true, equalTo: "#password" } }, messages: { name: "Please enter your full name (at least 3 characters).", email: "Please enter a valid email address.", age: "Age must be between 16 and 100.", password: "Password must be at least 6 characters long.", confirmPassword: "Passwords do not match." }, submitHandler: function (form) { alert("Registration form is valid! Submitting..."); form.submit(); } }); }); </script>The jQuery Validation Plugin's
.validate()call attaches arulesobject (what each field must satisfy) and a matchingmessagesobject (what to show when a rule fails) directly to the form, and it re-checks every field automatically on blur and on keyup, so the student sees an inline error the moment a field becomes invalid, without any page reload. ThesubmitHandleronly fires once every rule passes, at which point the form is genuinely submitted to the server, giving the registration page instant client-side feedback backed by the plugin's built-inrequired,email,number,minlength, andequalTovalidators. - 210 marksNumericalQuerying and Saving data to databaseHideAnswer
How do you cache the information of the client and what are its uses? Create a table named BAG(ID, Brand, Price, Date). Perform the following operations using Entity Framework Core. a. Update the Price of those Book to 2000 which are published on 2022. b. Delete the Book which are published in 1981. c. Retrieve the Brand of Book having price greater than 500.[10]
--- Caching is the technique of storing frequently accessed data temporarily in fast-access memory so that subsequent requests can be served without repeatedly querying the database or recomputing results. In web applications (ASP.NET Co...
- 310 marksPartial classHideAnswer
What are the needs for partial class and sealed class? How do you relate delegate with events? State the steps to deploy .NET core application.[10]
--- A partial class allows a single class definition to be split across multiple files. All parts are combined into one class at compile time using the partial keyword. Syntax: Needs / Reasons to use Partial Class: Need Explanation -----...
- 45 marksUnderstanding Tag HelpersHideAnswer
What are tag helpers? What tag helper provides? [5]
Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag Helpers are authored in C and they target HTML elements based on: - The element name - The attribute name - The parent tag Tag...
- 55 marksMVC PatternHideAnswer
Describe the importance of MVC pattern in designing web applications. [5]
MVC (Model-View-Controller) is an architectural pattern that separates an application into three distinct components: Model, View, and Controller. This separation is fundamental to building well-structured, maintainable web applications....
- 65 marksControllers and ActionsHideAnswer
How do you create controller? Mention some requirements for rendering HTML. [5]
A Controller is the central unit of an ASP.NET MVC application that combines the Model with a View and serves the result to the end-user. It handles user requests, executes application logic, builds a model, and returns the result in HTM...
- 75 marksADO.NET basicsHideAnswer
What is the role of adapter class in ADO.NET? List some features of URL routing. [5]
--- The DataAdapter class in ADO.NET acts as a bridge between a DataSet and a data source (such as a SQL Server database). It is found in the System.Data.SqlClient namespace (e.g., SqlDataAdapter). Role Description ------------------- Fi...
- 85 marksCommon VulnerabilitiesHideAnswer
Explain the chances of SQL injection attack with a scenario. [5]
SQL Injection (SQLI) is a common attack vector that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. It usually occurs when a user provides an SQL statement as input i...
- 95 marksAuthorizationHideAnswer
Define claim and policy in terms of authorization. How and when do you create hidden fields? [5]
--- A claim is a name-value pair that represents a piece of information about a user. It describes who the user is, not what they can do. Claims are issued by a trusted authority and are stored in the user's identity. Examples of claims:...
- 105 marksDependency Injection and IOC containersHideAnswer
Mention the two types of services managed by IoC container and how they are registered? [5]
Two Types of Services Managed by IoC Container and Their Registration
Types of Services (Lifetimes)
The built-in IoC container in ASP.NET Core supports three kinds of service lifetimes, of which the two most commonly highlighted types are:
1. Singleton
- The IoC container creates and shares a single instance of a service throughout the application's lifetime.
- The instance is created the first time it is requested, and every subsequent request uses that same instance.
- Suitable for services that maintain global state or are expensive to create.
2. Transient
- The IoC container creates a new instance of the specified service type every time it is requested.
- This lifetime works best for lightweight, stateless services.
- Each request gets a completely fresh object.
3. Scoped (also managed by IoC)
- The IoC container creates one instance per HTTP request.
- The same instance is shared within a single request but a different instance is created for different requests.
How Services Are Registered
Services are registered inside the
ConfigureServicesmethod using theIServiceCollectioninterface. Registration is done usingServiceDescriptor:public void ConfigureServices(IServiceCollection services) { // Singleton registration services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger())); // Transient registration services.Add(new ServiceDescriptor( typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Scoped registration services.Add(new ServiceDescriptor( typeof(ILog), typeof(MyConsoleLogger), ServiceLifetime.Scoped)); }Summary Table
Lifetime Instance Created Shared? Singleton Once (first request) Across entire application Transient Every request Not shared Scoped Once per HTTP request Within the same request only Once registered, the IoC container automatically performs constructor injection wherever the service type is used as a constructor parameter.
- 115 marksGenericsHideAnswer
Differentiate between generic and non-generic collections. Write a simple program to create generic class with generic constructor, generic member variable, generic property and generic method. [5]
Feature Generic Collection Non-Generic Collection --------- Namespace System.Collections.Generic System.Collections Type Safety Type-safe at compile time Not type-safe (stores object) Boxing/Unboxing No boxing/unboxing needed Requires bo...
- 1215 marksLINQHideAnswer
Write short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]
Short Notes (Any Two)
a. Lambda Expression
Definition
A lambda expression is an anonymous function that can be used to create delegates or expression tree types. Lambda expressions are a concise way to write inline functions and are heavily used in LINQ (Language Integrated Query) in C#.
Syntax
(parameters) => expressionor for a block body:
(parameters) => { statements; }Key Characteristics
- The
=>operator is called the lambda operator and is read as "goes to". - Lambda expressions can have zero, one, or multiple parameters.
- They can be used wherever a delegate type is expected.
- They are a core part of LINQ support in C#, alongside query expressions, object initializers, and collections.
Example
// Simple lambda expression Func<int, int> square = x => x * x; Console.WriteLine(square(5)); // Output: 25 // Lambda with LINQ int[] scores = new int[] { 97, 92, 83, 60 }; var highScores = scores.Where(score => score > 80); foreach (int s in highScores) Console.WriteLine(s); // Output: 97 92 83Why Use Lambda Expressions?
- Makes code shorter and more readable.
- Eliminates the need to define a separate named method for simple operations.
- Integrates seamlessly with LINQ to query collections, databases, XML, and more.
- Supports functional programming style in C#.
b. Cross Site Request Forgery (CSRF)
Definition
Cross-Site Request Forgery (CSRF) is a web security attack where an attacker tricks an authenticated user into unknowingly submitting a malicious request to a web application on which the user is currently authenticated.
How CSRF Works
- The user logs into a trusted website (e.g., a banking site) and a session cookie is stored in the browser.
- Without logging out, the user visits a malicious website.
- The malicious site contains a hidden request (e.g., a form or image tag) that sends a request to the trusted website.
- Since the browser automatically includes the session cookie, the trusted website processes the request as if it came from the legitimate user.
Example Attack Scenario
<!-- Malicious page sends a hidden request to the bank --> <img src="http://bank.com/transfer?amount=10000&to=attacker" />The browser automatically sends the authenticated cookie along with this request.
Difference from XSS
Feature XSS CSRF Attack target Other users via injected scripts Authenticated user's session Mechanism Injects malicious scripts into pages Forges requests using existing session Trust exploited User trusts the website Website trusts the user's browser Prevention Techniques
- Anti-CSRF Tokens: Include a unique, secret token in every form that the server validates.
- SameSite Cookie Attribute: Restricts cookies from being sent with cross-site requests.
- Re-authentication: Require password confirmation for sensitive actions.
- Checking Referer/Origin headers: Validate that requests originate from the expected domain.
c. Single Page Application (SPA)
Definition
A Single Page Application (SPA) is a web application that loads a single HTML page and dynamically updates the content as the user interacts with the app, without requiring a full page reload from the server.
How SPA Works
- On the first request, the server sends a single HTML page along with all necessary JavaScript and CSS.
- Subsequent interactions (navigation, data loading) are handled via AJAX calls to the server, which returns only data (typically JSON), not full HTML pages.
- The browser's JavaScript framework (e.g., Angular, React, Vue.js) updates the DOM dynamically.
Architecture Diagram
User Action --> JavaScript (Client Side) --> AJAX Request --> Server API | | DOM Updated <-------------- JSON Response -----+Key Characteristics
- Only one full page load occurs (at the start).
- Uses client-side routing to simulate navigation between pages.
- Heavy use of JavaScript frameworks like Angular, React, or Vue.js.
- Communicates with the backend via REST APIs or GraphQL.
Advantages
Advantage Description Fast and responsive No full page reloads; only data is exchanged Better user experience Feels like a desktop application Reduced server load Server only sends data, not full HTML Separation of concerns Frontend and backend are clearly separated Disadvantages
- SEO challenges: Search engines may struggle to index dynamically loaded content.
- Initial load time can be slow as all JavaScript is loaded upfront.
- Browser history management requires extra handling.
- Security: Requires careful handling of authentication tokens (e.g., JWT).
Example Technologies
- Frameworks: Angular, React, Vue.js
- Communication: AJAX, Fetch API, Axios
- Routing: React Router, Angular Router
- The