NET Centric Computing · Unit 1 · 8 hrs
Language Preliminaries
Exam-focused notes for Language Preliminaries (NET Centric Computing, CSC378): what the TU syllabus asks and how it has actually been tested, with 13 solved past questions from this unit.
Language Preliminaries in short
This unit lays down the C# language vocabulary that the rest of the course assumes: the .NET Framework and its runtime, the everyday language constructs, the object oriented features (constructors, properties, inheritance, interfaces, delegates), and the functional and safety features (generics, LINQ, exceptions, attributes, async/await) that ASP.NET Core code is written in.
What this unit covers
- Introduction to .Net framework
- Compilation and execution of .Net applications
- Basic Languages constructs
- Constructor
- Properties
- Arrays and String
- Indexers
- Inheritance
- use of "base" keyword
- Method hiding and overriding
- applying polymorphism in code extensibility
- structs and enums
- abstract class sealed class
- interface
- Delegate and Events
- Partial class
- Collections
- Generics
- File IO
- LINQ (Language Integrated Query) Fundamentals: Lambda Expressions
- Try statements and Exceptions
- Attributes: Attribute Classes, Named and Positional Attribute Parameters, Attribute Targets, Specifying Multiple Attributes
- Asynchronous Programming: Principle of Asynchrony, Async/Await patterns in C#
Attributes
2081 · 10 marks
Distinguish between collection and generics. What are named and positional attribute parameters? Write a program to create your own exception when the user gives subject name than 'C#'.[10]
2078 · 5 marks
What is named and positional attribute parameters? Describe the .Net architecture design and principles. [5]
Show solved answerHide answer
Named and Positional Attribute Parameters & .NET Architecture Design and Principles
Part 1: Named and Positional Attribute Parameters
From the notes, the syntax for an attribute is:
[attribute(positional_parameters, name_parameter=value, ...)]
element
Positional Parameters
- Positional parameters are the mandatory parameters of an attribute.
- They must be passed in a fixed order as defined in the attribute constructor.
- They correspond directly to the constructor arguments of the attribute class.
Example:
[Obsolete("This method is deprecated")]
public void OldMethod() { }
Here, "This method is deprecated" is a positional parameter passed in order.
Named Parameters
- Named parameters are optional parameters of an attribute.
- They are specified using a name=value syntax and can be provided in any order.
- They correspond to properties or fields of the attribute class.
Example:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
Here:
AttributeTargets.Classis the positional parameter (mandatory, in order).AllowMultiple = trueandInherited = falseare named parameters (optional, any order).
Part 2: .NET Architecture Design and Principles
.NET Architecture Overview
The layered architecture of .NET (as described in the notes) is as follows:
+------------------------------------------+
| VB.NET | C# | JScript.NET | More Languages |
+------------------------------------------+
| Common Language Specification (CLS) |
+------------------------------------------+
| Common Type System (CTS) |
+------------------------------------------+
| .NET Framework Class Library (FCL) |
+------------------------------------------+
| ASP.NET | Windows Forms | Console | ADO.NET |
| Web Forms | XML Web Services | .NET Remoting |
+------------------------------------------+
| Common Language Runtime (CLR) |
| [JIT Compilers, Security Manager, etc.] |
+------------------------------------------+
| Common Language Infrastructure (CLI) |
+------------------------------------------+
| Operating System |
+------------------------------------------+
Key Components Explained
| Component | Description |
|---|---|
| CLR (Common Language Runtime) | The heart of .NET Framework. Resides above the OS and handles all .NET applications. Manages garbage collection, Code Access Security (CAS), and memory management. |
| CLI (Common Language Infrastructure) | Provides a language-independent platform for app development. Handles exception handling, garbage collection, and security. |
| CTS (Common Type System) | Specifies a standard that defines what types of data and values can be defined and managed in memory at runtime. |
| CLS (Common Language Specification) | A subset of CTS that defines rules and regulations that every .NET language must follow to ensure interoperability. |
| FCL (Framework Class Library) | Provides system functionality including classes, interfaces, and data types to build desktop, web, and mobile applications. |
Design Principles of .NET
-
Clean Architecture: Applications following the Dependency Inversion Principle and Domain-Driven Design (DDD) are known as clean architecture. It places business logic and application model at the center.
-
MVC Pattern: Separates the application into three components:
- Model: Represents the shape/structure of data.
- View: User interface that displays model data.
- Controller: Handles user requests and manages the flow.
-
N-Tier Architecture: ASP.NET Core automatically creates a pre-defined N-tier architecture for developers, saving time and effort, and easing tier deployment.
-
Separation of Concerns: Each layer/component handles a specific responsibility, making the application maintainable and testable.
-
Language Interoperability: Through CLS and CTS, .NET supports multiple languages (C#, VB.NET, JScript.NET) that can work together seamlessly.
Summary: .NET architecture is a layered, language-independent framework where CLR acts as the execution engine, CTS/CLS ensure type safety and interoperability, and FCL provides reusable libraries. Its design principles promote clean, maintainable, and scalable application development.
Inheritance
2081 · 5 marks
Create a class named EMPLOYEE as super class and ENGINEER and DOCTOR as sub class. Make your own assumptions as properties and methods. [5]
applying polymorphism in code extensibility
2081 · 10 marks
Write short notes on: a. Polymorphism b. Hidden Field [5+5]
Show solved answerHide answer
Short Notes
a. Polymorphism (5 Marks)
Definition
The word polymorphism means "having many forms." It is the ability of a function, method, or object to behave differently in different contexts. In C#, polymorphism can be static (compile-time) or dynamic (run-time).
1. Static Polymorphism (Compile-Time Polymorphism)
The mechanism of linking a function with an object during compile time is called static binding. C# implements static polymorphism through function overloading.
In function overloading, multiple methods share the same name but differ in the number or type of parameters.
Example:
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int g) {
Console.WriteLine(g);
}
void print(double f) {
Console.WriteLine(f);
}
void print(string s) {
Console.WriteLine(s);
}
}
}
Here, the method print() is overloaded to handle int, double, and string data types. The compiler decides which version to call at compile time.
2. Dynamic Polymorphism (Run-Time Polymorphism)
C# allows the creation of abstract classes that provide partial class implementation. The implementation is completed when a derived class inherits from the abstract class and overrides its methods. The correct method is resolved at run time.
Key Points:
- Uses
abstractkeyword for the base class and methods. - Derived classes use
overridekeyword to provide specific implementations. - Enables method overriding.
Example:
abstract class Shape {
public abstract void Draw();
}
class Circle : Shape {
public override void Draw() {
Console.WriteLine("Drawing Circle");
}
}
class Rectangle : Shape {
public override void Draw() {
Console.WriteLine("Drawing Rectangle");
}
}
Importance of Polymorphism
- Promotes code extensibility and reusability.
- Allows a single interface to represent different underlying forms (data types or classes).
- Makes programs easier to maintain and scale.
b. Hidden Field (5 Marks)
Definition
A hidden field is an HTML form element that allows data to be stored on the client side without being displayed on the page. When the user performs an action (such as form submission), the hidden field value is passed back to the server side along with the form data.
Purpose
Sometimes we require certain data (such as a user ID or session-related value) to be available across requests without showing it to the user. Hidden fields serve this purpose by embedding the data in the HTML form invisibly.
How Hidden Fields Work in ASP.NET Core MVC
Step 1: GET Method - Set the hidden field value
The GET version of the action method creates an object and passes it to the view:
[HttpGet]
public IActionResult SetHiddenFieldValue() {
User newUser = new User() {
Id = 101,
Name = "John",
Age = 31
};
return View(newUser);
}
Step 2: View - Render the hidden field
In the view, the Id field is rendered as a hidden input so it is not visible to the user but is included in the form:
@model User
<form method="post">
<input type="hidden" name="Id" value="@Model.Id" />
<input type="text" name="Name" value="@Model.Name" />
<button type="submit">Submit</button>
</form>
Step 3: POST Method - Read the hidden field value
The POST version reads the hidden field value from IFormCollection:
[HttpPost]
public IActionResult SetHiddenFieldValue(IFormCollection keyValues) {
var id = keyValues["Id"]; // Retrieves the hidden field value
return View();
}
Key Points
| Aspect | Detail |
|---|---|
| Visibility | Not visible to the user on the page |
| Transmission | Sent to the server on form submission |
| Use Case | Storing IDs, tokens, or state data across requests |
| Security | Should not be used for sensitive data as it can be viewed in page source |
Summary
Hidden fields are a simple and effective way to persist data between HTTP requests in a stateless web environment without exposing it in the UI. In ASP.NET Core MVC, they are commonly used with IFormCollection or model binding to retrieve the stored values on the server side.
Partial class
2080 · 10 marks
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]
Generics
2080 · 5 marks
Differentiate between generic and non-generic collections. Write a simple program to create generic class with generic constructor, generic member variable, generic property and generic method. [5]
LINQ
2080 · 15 marks
Write short notes on: (any two) a. Lambda Expression b. Cross Site Request Forgery c. Single Page Application [5+5+5]
Show solved answerHide answer
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) => expression
or 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 83
Why 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
2079 · 15 marks
Write short notes on: (any two) 1. Lambda Expression 2. Containerization using Docker 3. Delegates and Events [5+5+5]
2078 · 15 marks
Write short notes on (any two): a. LINQ b. Open Redirected Attack c. Query String [5+5+5]
Collections
2079 · 10 marks
What is the purpose of web form? Write a program to demonstrate the concept of collection and generics.[10]
structs and enums
2078 · 10 marks
Differentiate between struct and enum. Why do we need to handle the exception? Illustrate with an example with your own customized exception.[10]
Try statements and Exceptions
File IO
2076 · 5 marks
Explain about file access with ASP with example.[5]
Make Unit 1 stick
Practice CSC378 with flashcards & quizzes