0% found this document useful (0 votes)
88 views120 pages

Developer's Guide to C# & ASP.NET

Uploaded by

pavel7747
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views120 pages

Developer's Guide to C# & ASP.NET

Uploaded by

pavel7747
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

RESTRICTED

Contents
Data Structures and Algorithm .............................................................................................................................................. 3
Data Structures: .................................................................................................................................................................. 3
Classification/Types of Data Structures: ............................................................................................................................. 3
Most Popular Data Structures: ........................................................................................................................................... 4
❖ Array: ...................................................................................................................................................................... 4
❖ Linked Lists: ............................................................................................................................................................ 4
❖ Stack:....................................................................................................................................................................... 4
❖ Queue: .................................................................................................................................................................... 5
❖ Matrix: .................................................................................................................................................................... 5
Data Types:.......................................................................................................................................................................... 7
❖ LIFO - Last In, First Out: .............................................................................................................................................. 7
❖ FIFO - First In, First Out: ............................................................................................................................................. 8
Algorithms: .......................................................................................................................................................................... 9
Fibonacci Series – Algorithm: ......................................................................................................................................... 9
Sample Q&A: ....................................................................................................................................................................... 9
Object Oriented Programming – C# ..................................................................................................................................... 11
Sample Questionnaires on Object Oriented Programming – C# ...................................................................................... 28
C# - Design Pattern (For Advanced) ..................................................................................................................................... 36
Sample Questionnaires on Design Pattern in C#: ............................................................................................................. 38
ASP.NET ................................................................................................................................................................................ 39
ASP.NET Web Forms Model .............................................................................................................................................. 39
The ASP.NET Component Model ...................................................................................................................................... 39
Components of .Net Framework ...................................................................................................................................... 40
ASP.NET Application Life Cycle ......................................................................................................................................... 41
ASP.NET Page Life Cycle .................................................................................................................................................... 41
ASP.NET Page Life Cycle Events ........................................................................................................................................ 42
ASP.NET - Event Handling ................................................................................................................................................. 42
ASP.NET - Data Sources..................................................................................................................................................... 44
Sample Questionnaires on ASP.NET: ................................................................................................................................ 45
ASP.NET (MVC) ..................................................................................................................................................................... 48
Overview: Definition ......................................................................................................................................................... 48
ASP.NET MVC Folder Structure: ........................................................................................................................................ 50
Routing in MVC: ................................................................................................................................................................ 52
1
RESTRICTED
RESTRICTED

Configure a Route:........................................................................................................................................................ 52
ASP.NET MVC- Filters: ....................................................................................................................................................... 53
ASP.NET MVC – Scaffolding: ............................................................................................................................................. 54
Sample Questionnaires on ASP.NET (MVC): ..................................................................................................................... 54
ASP.NET Core ........................................................................................................................................................................ 57
Overview: Definition ......................................................................................................................................................... 57
ASP.NET Core - Project Structure: ..................................................................................................................................... 57
Sample Questionnaires on ASP.NET Core: ........................................................................................................................ 64
ASP.NET Core - Authorization & Authentication................................................................................................................. 78
Sample Questionnaires on ASP.NET Core - Authorization & Authentication ................................................................ 79
ASP.NET Core – Configuration ............................................................................................................................................. 80
Sample Questionnaires on ASP.NET Core – Configuration: .............................................................................................. 81
ASP.NET Core - Logging and Monitoring ............................................................................................................................. 83
Sample Questionnaires on ASP.NET Core - Logging and Monitoring: .............................................................................. 84
ASP.NET Core - Middleware ................................................................................................................................................. 86
Sample Questionnaires on ASP.NET Core Middleware: ................................................................................................... 90
ASP.NET Core - Host ............................................................................................................................................................. 92
Sample Questionnaires on ASP.NET Core – HOST: ........................................................................................................... 92
ASP.NET – Worker Service & Background Service .............................................................................................................. 94
Sample Questionnaires on Worker Service & Background Service: ............................................................................... 95
ASP.NET Core - Globalization & Localization ....................................................................................................................... 96
Sample Questionnaires on ASP.NET Core – Globalization & Localization: ....................................................................... 97
ASP.NET Core - SignalR ......................................................................................................................................................... 97
Sample Questionnaires on ASP.NET Core – SignalR: ...................................................................................................... 99
Sample Questionnaires on ASP.NET Core - WEB API: ....................................................................................................... 100
Sample Questionnaires on HTML: ..................................................................................................................................... 103
Sample Questionnaires on CSS: ......................................................................................................................................... 106
Sample Questionnaires on Javascript: ............................................................................................................................... 109
Sample Questionnaires on jQuery: .................................................................................................................................... 114

2
RESTRICTED
RESTRICTED

Data Structures and Algorithm


Data:
Data refers to a collection of facts, statistics, or information that is often represented in a structured or
unstructured form. It can be in various formats, such as numbers, text, images, audio, or video. Data is the raw
material from which information and knowledge are derived through analysis, interpretation, and processing.

Information:
Information refers to processed or organized data that has been given context, meaning, and relevance. It results from
interpreting and analyzing data to extract insights, patterns, and relationships. Information provides a deeper
understanding and allows individuals to make informed decisions or draw conclusions.

Data Structures:

A data structure is a specialized format for organizing, processing, retrieving and storing data. There are several basic
and advanced types of data structures, all designed to arrange data to suit a specific purpose.

Classification/Types of Data Structures:

i. Linear Data Structure


➢ Elements are arranged in one dimension, also known as linear dimension.
➢ Example: lists, stack, queue, etc.
ii. Non-Linear Data Structure
➢ Elements are arranged in one-many, many-one and many-many dimensions.
➢ Example: tree, graph, table, etc.

3
RESTRICTED
RESTRICTED

Most Popular Data Structures:

❖ Array:
An array is a collection of data items stored at contiguous memory locations. The idea is to store multiple items
of the same type together. This makes it easier to calculate the position of each element by simply adding an
offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name
of the array).

❖ Linked Lists:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous
location; the elements are linked using pointers.

❖ Stack:
Stack is a linear data structure which follows a particular order in which the operations are performed. The order
may be LIFO(Last In First Out) or FILO(First In Last Out). In stack, all insertion and deletion are permitted at only
one end of the list.

4
RESTRICTED
RESTRICTED

❖ Queue:
Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed.
The order is First In First Out (FIFO). In the queue, items are inserted at one end and deleted from the other end.
A good example of the queue is any queue of consumers for a resource where the consumer that came first is
served first. The difference between stacks and queues is in removing. In a stack we remove the item the most
recently added; in a queue, we remove the item the least recently added.

❖ Matrix:
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose
the elements of a matrix in parentheses or brackets.

A matrix with 9 elements is shown below.

Difference between Stack and Queue Data Structures:


Stacks Queues

A queue is a data structure that stores a collection of elements,


A stack is a data structure that stores a collection
with operations to enqueue (add) elements at the back of the
of elements, with operations to push (add) and
queue, and dequeue (remove) elements from the front of the
pop (remove) elements from the top of the stack.
queue.

5
RESTRICTED
RESTRICTED

Stacks Queues

Stacks are based on the LIFO principle, i.e., the


Queues are based on the FIFO principle, i.e., the element
element inserted at the last, is the first element to
inserted at the first, is the first element to come out of the list.
come out of the list.

Insertion and deletion in queues takes place from the opposite


Insertion and deletion in stacks takes place only
ends of the list. The insertion takes place at the rear of the list
from one end of the list called the top.
and the deletion takes place from the front of the list.

Insert operation is called push operation. Insert operation is called enqueue operation.

Stacks are implemented using an array or linked Queues are implemented using an array or linked list data
list data structure. structure.

Delete operation is called pop operation. Delete operation is called dequeue operation.

Examples of stack-based languages include Examples of queue-based algorithms include Breadth-First


PostScript and Forth. Search (BFS) and printing a binary tree level-by-level.

Difference between Array and Linked List:


ARRAY LINKED LIST

An array is a grouping of data elements of A linked list is a group of entities called a node. The node
equivalent data type. includes two segments: data and address.

It stores the data elements in a contiguous It stores elements randomly, or we can say anywhere in the
memory zone. memory zone.

In the case of an array, memory size is fixed, and it In the linked list, the placement of elements is allocated during
is not possible to change it during the run time. the run time.

The elements are not dependent on each other. The data elements are dependent on each other.

The memory is assigned at compile time. The memory is assigned at run time.

It is easier and faster to access the element in an In a linked list, the process of accessing elements takes more
array. time.

In the case of an array, memory utilization is In the case of the linked list, memory utilization is effective.
ineffective.

6
RESTRICTED
RESTRICTED

When it comes to executing any operation like When it comes to executing any operation like insertion,
insertion, deletion, array takes more time. deletion, the linked list takes less time.

Applications of Data Structures:


Data structures are used in various fields such as:

✓ Operating system
✓ Graphics
✓ Computer Design
✓ Blockchain
✓ Genetics
✓ Image Processing
✓ Simulation

Data Types:

If data structures are the building blocks of algorithms and computer programs, the primitive -- or base -- data types are
the building blocks of data structures. The typical base data types include the following:

✓ Boolean: which stores logical values that are either true or false.
✓ Integer: which stores a range on mathematical integers -- or counting numbers. Different sized integers hold a
different range of values -- e.g., a signed 8-bit integer holds values from -128 to 127, and an unsigned long 32-bit
integer holds values from 0 to 4,294,967,295.
✓ Floating-point numbers: which store a formulaic representation of real numbers.
✓ Fixed-point numbers: which are used in some programming languages and hold real values but are managed as
digits to the left and the right of the decimal point.
✓ Character: which uses symbols from a defined mapping of integer values to symbols.
✓ Pointers: which are reference values that point to other values.
✓ String: which is an array of characters followed by a stop code -- usually a "0" value -- or is managed using a
length field that is an integer value.

Orderings in Data Structures:


Orderings in data structures refer to the way elements are accessed, added, or removed from the structure. There are
two main orderings:

❖ LIFO - Last In, First Out:


• LIFO is a principle where the last item added to a collection is the first one to be removed.
• It's analogous to a stack of plates. The last plate you put on the stack is the first one you can take off.
• Commonly used in data structures like stacks.

Real-life example:

7
RESTRICTED
RESTRICTED

❖ FIFO - First In, First Out:


• FIFO is a principle where the first item added to a collection is the first one to be removed.
• It's like a queue in real-life scenarios. The first person waiting in line is the first one to be served.
• Commonly used in data structures like queues.
Real-life example:

❖ FIFO vs LIFO:

FIFO LIFO

It stands for First-In-First-Out approach in It stands for Last-In-First-Out approach in


programming. programming.

In this, the new element is inserted below the existing In this, the new element is inserted above the existing
element, So that the oldest element can be at the top element, So that the newest element can be at the top
and taken out first. and taken out first.

Therefore, the first element to be entered in this Therefore, the first element to be entered in this
approach, gets out First. approach, gets out Last.

Time complexity of inserting element in FIFO is O(1). Time complexity of inserting element in LIFO is O(1).

The data structure that implements FIFO is Queue. The data structure that implements LIFO is Stack.

Basic Terminology:

8
RESTRICTED
RESTRICTED

▪ Data − Data are values or set of values.


▪ Data Item − Data item refers to single unit of values.
▪ Group Items − Data items that are divided into sub items are called as Group Items.
▪ Elementary Items − Data items that cannot be divided are called as Elementary Items.
▪ Attribute and Entity − An entity is that which contains certain attributes or properties, which may be assigned
values.
▪ Entity Set − Entities of similar attributes form an entity set.
▪ Field − Field is a single elementary unit of information representing an attribute of an entity.
▪ Record − Record is a collection of field values of a given entity.
▪ File − File is a collection of records of the entities in a given entity set.

Algorithms:

Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the
desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.

Fibonacci Series – Algorithm:


Fibonacci series is a special kind of series in which the next term is equal to the sum of the previous two terms. Thus, the
initial two numbers of the series are always given to us.
For example, let F0 and F1 denote the first two terms of the Fibonacci series. Then, let F0 = 0 and F1 = 1.
Suppose we wish to calculate 10 terms of this Fibonacci series. Then, the series will be:
F10 = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.

Algorithm for Iterative Fibonacci Series: The iterative approach is the dynamic programming approach. It makes use of a
loop to perform the addition of the previous two terms. The algorithm for the iterative approach will be:

Procedure Fibonacci(n)
declare f0, f1, fib, loop

set f0 to 0
set f1 to 1

<b>display f0, f1</b>

for loop ← 1 to n

fib ← f0 + f1
f0 ← f1
f1 ← fib

<b>display fib</b>
end for

end procedure

Sample Q&A:

9
RESTRICTED
RESTRICTED

❖ What is a data structure?


A data structure is a way of organizing and storing data in a computer's memory to facilitate efficient access,
modification, and management.
❖ Why are data structures important?
Data structures play a crucial role in computer science and programming, as they enable the efficient
organization, manipulation, and retrieval of data.
❖ What is a multidimensional array?
A multidimensional array is a multidimensional array with more than one dimension. It is an array of arrays or an
array with numerous layers. The 2D array, or two-dimensional array, is the most basic multidimensional array. As
you'll see in the code, it's technically an array of arrays. A 2D array is also referred to as a matrix or a table with
rows and columns. Declaring a multidimensional array is the same as saying a one-dimensional array. We need to
notify C that we have two dimensions for a two-dimensional array.

❖ What is the difference between an array and a linked list?


An array is a linear data structure that stores elements of the same type in contiguous memory locations. A linked
list is also a linear data structure, but it stores elements in separate nodes, each containing both the data and a
reference (or link) to the next node.

❖ What is a stack?
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. Elements are added and
removed from the top of the stack. Common operations include push (add element) and pop (remove element).

❖ What is the difference between a stack and a queue?


A stack follows the Last-In-First-Out (LIFO) principle, meaning the last element added is the first one to be
removed. A queue follows the First-In-First-Out (FIFO) principle, where the first element added is the first one to
be removed.

10
RESTRICTED
RESTRICTED

Object Oriented Programming – C#

Object-Oriented Programming (OOP):


Procedural programming is about writing procedures or methods that perform operations on the data, while object-
oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:


✓ OOP is faster and easier to execute
✓ OOP provides a clear structure for the programs
✓ OOP makes it possible to create full reusable applications with less code and shorter development time

Classes and Objects:


Classes and objects are the two main aspects of object-oriented programming.
✓ A class is a blueprint or template for creating objects. It defines the attributes (data) and methods (functions)
that the objects will have.
✓ An object is an instance of a class. It represents a real-world entity and encapsulates both data (attributes) and
behaviors (methods).
Everything in C# is associated with classes and objects, along with its attributes and methods. For example: in real life, a
car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
Example:
Create a class named "Car" with a variable color:
class Car
{
string color = "red";
}
Create an object called "myObj" and use it to print the value of color:
namespace MyApplication
{
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}

11
RESTRICTED
RESTRICTED

}
C# Methods: A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known as
functions.
Example: Create a method inside the Program class:
class Program
{
static void MyMethod()
{
// code to be executed
}
}
Class Members:
Fields and methods inside classes are often referred to as "Class Members":
Example: Create a Car class with three class members: two fields and one method.
// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}

Constructors:
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when
an object of a class is created. It can be used to set initial values for fields:
Example:

Create a constructor:
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
12
RESTRICTED
RESTRICTED

}
// Outputs "Mustang"

✓ Constructors can also take parameters, which is used to initialize fields.

Destructors:
Destructors in C# are methods inside the class used to destroy instances of that class when they are no longer needed.
✓ A Destructor is unique to its class i.e. there cannot be more than one destructor in a class.
✓ A Destructor has no return type and has exactly the same name as the class name (Including the same case).
Example:
class Example
{ // Destructor
~Example()
{
}
}
Access Modifiers:
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
C# has the following access modifiers:
Modifier Description

public The code is accessible for all classes

private The code is only accessible within the same class

protected The code is accessible within the same class, or in a class that is inherited from that class. You will
learn more about inheritance in a later chapter

internal The code is only accessible within its own assembly, but not from another assembly. You will learn
more about this in a later chapter

Example:
using System;

class BankAccount
{
public string AccountNumber { get; private set; } // Only accessible within the class
public decimal Balance { get; protected set; } // Accessible within the class and derived classes
internal string BankName { get; set; } // Accessible within the same assembly
protected internal string OwnerName { get; set; } // Accessible within the same assembly and derived classes

public BankAccount(string accountNumber, decimal initialBalance, string bankName, string ownerName)


{
AccountNumber = accountNumber;
Balance = initialBalance;
BankName = bankName;
13
RESTRICTED
RESTRICTED

OwnerName = ownerName;
}

public void DisplayAccountInfo()


{
Console.WriteLine($"Account Number: {AccountNumber}, Balance: {Balance}, Bank: {BankName}, Owner:
{OwnerName}");
}
}

class Program
{
static void Main(string[] args)
{
BankAccount account = new BankAccount("123456789", 1000, "ABC Bank", "John Doe");
account.DisplayAccountInfo(); // Accessing public method
account.Balance = 1500; // Accessing protected set from within the class
account.BankName = "XYZ Bank"; // Accessing internal property within the same assembly
account.OwnerName = "Jane Smith"; // Accessing protected internal property within the same assembly
}
}
In this example:
✓ BankAccount class has properties with different access modifiers (private, protected, internal, protected internal).
✓ The Program class creates a BankAccount instance and accesses properties with different access levels.
Access modifiers provide control over the visibility and accessibility of class members, allowing you to enforce
encapsulation and control the interactions between classes.

C# Data Types:
In c# programming language, Data Types are useful to define a type of data the variable can hold, such as integer, float,
string, etc., in our application. Before we perform any operation on variables, it’s mandatory to define a variable with the
required data type to indicate what type of data that variable can hold in our application.
❖ Syntax of Defining C# Data Types:
• [Data Type] [Variable Name];
• [Data Type] [Variable Name] = [Value];
❖ Different Data Types in C#:
In C# programming language, we have a 3 different type of data types, those are

Type Data Types

Value Data Type int, bool, char, double, float, etc.

Reference Data Type string, class, object, interface, delegate, etc.

Pointer Data Type Pointers.

❖ Following is the example of using the data types in the c# programming language.

14
RESTRICTED
RESTRICTED

namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23;
char gender = 'M';
bool isVerified = true;
}
}
}
C# Variables:
In c#, Variables will represent storage locations, and each variable has a particular type that determines what type of
values can be stored in the variable.
❖ Syntax of C# Variables Declaration
Following is the syntax of declaring and initializing variables in the c# programming language.
• [Data Type] [Variable Name];
• [Data Type] [Variable Name] = [Value];
• [Access Specifier] [Data Type] [Variable Name] = [Value];
❖ C# Variables Declaration Example
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23;
char gender = 'M';
bool isVerified = true;
Console.WriteLine("Id: " + number);
Console.WriteLine("Name: " + name);
Console.WriteLine("Percentage: " + percentage); Console.WriteLine("Gender: " + gender);
Console.ReadLine();
}
}
}

C# Namespaces:
In c#, Namespace is used to organize multiple classes in our applications, reducing the code redundancy in our .NET
applications. By using the namespace keyword, we can define the namespaces in our c# applications.

Following is the syntax of defining a namespace in the c# programming language.


15
RESTRICTED
RESTRICTED

namespace Tutlane
{
class Welcome
{
public void GreetMessage()
{
// your method code
}
}
}
If we observe the above syntax, we defined a namespace in c# using the namespace keyword.

C# Operators:
In c#, the Operator is a programming element that specifies what kind of operation needs to perform on operands or
variables. For example, an addition (+) operator in c# is used to perform the sum operation on operands.

✓ C# Arithmetic Operators
In c#, Arithmetic Operators are useful to perform basic arithmetic calculations like addition, subtraction, division,
etc. based on our requirements.
int result;
int x= 20,y= 10;
result = (x + y);
✓ C# Relational Operators
In c#, Relational Operators are useful to check the relation between two operands like we can determine whether
two operand values equal or not, etc. based on our requirements.
For example, we have integer variables a = 10, b = 20. If we apply a relational operator >= (a >= b), we will get the
result false because the variable “a” contains a value that is less than variable b.
✓ C# Logical Operators
In c#, Logical Operators are useful to perform the logical operation between two operands like AND, OR and NOT
based on our requirements and the operands must contain only Boolean values otherwise Logical Operators will
throw an error.
✓ C# Bitwise Operators
In c#, Bitwise Operators will work on bits and these are useful to perform the bit by bit operations such as Bitwise
AND (&), Bitwise OR (|), Bitwise Exclusive OR (^), etc. on operands and we can perform bit-level operations on
Boolean and integer data.
✓ C# Assignment Operators
In c#, Assignment Operators are useful to assign a new value to the operand and these operators will work with
only one operand.

C# Control Statement:
❖ C# IF Statement: The C# if statement tests the condition. It is executed if condition is true.
Syntax:

16
RESTRICTED
RESTRICTED

❖ C# IF-else Statement: The C# if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
Syntax:

❖ C# switch Statement: The C# switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C#.

Syntax:

❖ C# For Loop: The C# for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.

17
RESTRICTED
RESTRICTED

❖ C# While Loop: In C#, while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed, it is recommended to use while loop than for loop.

❖ C# Do-While Loop: The C# do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while
loop.

❖ C# Break Statement: The C# break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.

C# Function:

18
RESTRICTED
RESTRICTED

Function is a block of code that has a signature. Function is used to execute statements specified in the code block. A
function consists of the following components:
✓ Function name: It is a unique name that is used to make Function call.
✓ Return type: It is used to specify the data type of function return value.
✓ Body: It is a block that contains executable statements.
✓ Access specifier: It is used to specify function accessibility in the application.
✓ Parameters: It is a list of arguments that we can pass to the function during call.
Example:

C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that have contiguous memory
location. In C#, array is an object of base type System.Array. In C#, array index starts from 0. We can store only fixed set
of elements in C# array.

➢ C# Array Types
There are 3 types of arrays in C# programming:
• Single Dimensional Array: To create single dimensional array, you need to use square brackets
[] after the type.
Example: int[] arr = new int[5];//creating array
• Multidimensional Array: The multidimensional array is also known as rectangular arrays in C#. It
can be two dimensional or three dimensional. The data is stored in tabular form (row * column)
which is also known as matrix.
Example: int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
• Jagged Array: In C#, jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.
Example: int[][] arr = new int[2][];

19
RESTRICTED
RESTRICTED

C# this:
In c# programming, this is a keyword that refers to the current instance of the class.
✓ It can be used to refer current class instance variable. It is used if field names (instance variables) and parameter
names are same, that is why both can be distinguish easily.
✓ It can be used to pass current object as a parameter to another method.
✓ It can be used to declare indexers.
C# static class:
The C# static class is like the normal class but it cannot be instantiated. It can have only static members. The advantage
of static class is that it provides you guarantee that instance of static class cannot be created.

C# Enum:
Enum in C# is also known as enumeration. It is used to store a set of named constants such as season, days, month, size
etc. The enum constants are also known as enumerators. Enum in C# can be declared within or outside class and structs.
Enum constants has default values which starts from 0 and incremented to one by one. But we can change the default
value.

Let's see a simple example of C# enum.

using System;
public class EnumExample
{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void Main()


{
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Console.WriteLine("WINTER = {0}", x);
Console.WriteLine("SUMMER = {0}", y);
}
}

C# Strings:
In C#, string is an object of System.String class that represent sequence of characters. We can perform many operations
on strings such as concatenation, comparision, getting substring, search, trim, replacement etc.

using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
20
RESTRICTED
RESTRICTED

char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };


string s2 = new string(ch);

Console.WriteLine(s1);
Console.WriteLine(s2);
}
}

C# StringBuilder:
In c#, StringBuilder is a class that is useful to represent a mutable string of characters, and it is an object of the
System.Text namespace. Like string in c#, we can use a StringBuilder to create variables to hold any text, a sequential
collection of characters based on our requirements.

In c#, both string and StringBuilder will represent a sequence of characters and perform the same kind of operations, but
the only difference is strings are immutable, and StringBuilder is mutable.

StringBuilder sb= new StringBuilder();


//or
StringBuilder sb = new StringBuilder("Welcome to Kuwait");

OOPs Concepts:
The key concepts of OOPs are
i. Abstraction
ii. Encapsulation
iii. Inheritance
iv. Polymorphism

Abstraction
Abstraction is "To represent the essential feature without representing the background details."

✓ Abstraction lets you focus on what the object does instead of how it does it.
✓ Abstraction provides a generalized view of your classes or objects by providing relevant information.
✓ Abstraction is the process of hiding the working style of an object and showing the information about an object
understandably.

Real-world Example of Abstraction


Suppose you have an object Mobile Phone.
Suppose you have three mobile phones as in the following:

• Nokia 1400 (Features: Calling, SMS)


• Nokia 2700 (Features: Calling, SMS, FM Radio, MP3, Camera)
• BlackBerry (Features: Calling, SMS, FM Radio, MP3, Camera, Video Recording, Reading E-mails)
So, for a mobile phone object, you will have the abstract class as in the following:

21
RESTRICTED
RESTRICTED

Encapsulation:
Wrapping up a data member and a method together into a single unit (in other words, class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is, enclosing the related operations and data related to an object into
that object.

Encapsulation is like your bag in which you can keep your pen, book, etcetera. It means this is the property of
encapsulating members and functions.
✓ Encapsulation means hiding the internal details of an object, in other words, how an object does something.
✓ Encapsulation prevents clients from seeing its inside view, where the behavior of the abstraction is
implemented.
✓ Encapsulation is a technique used to protect the information in an object from another object.
✓ Hide the data for security, such as making the variables private, and expose the property to access the private
data that will be public.

Real-world Example of Encapsulation:


Let's use as an example Mobile Phones and Mobile Phone Manufacturers.

Suppose you are a Mobile Phone Manufacturer and have designed and developed a Mobile Phone design (a
class). Now by using machinery, you are manufacturing Mobile Phones (objects) for selling; when you sell your
Mobile Phone, the user only learns how to use the Mobile Phone but not how the Mobile Phone works.

This means that you are creating the class with functions and by with objects (capsules), of which you are
making available the functionality of your class by that object and without interference in the original class.
22
RESTRICTED
RESTRICTED

Inheritance
When a class includes a property of another class, it is known as inheritance. Inheritance is a process of object
reusability.
For example, a child includes the properties of its parents.

The following are the types of inheritance in C#.

Single inheritance in C#:


It is the type of inheritance in which there is one base class and one derived class.

Hierarchical inheritance in C#: This is the type of inheritance in which there are multiple classes derived from one base
class. This type of inheritance is used when there is a requirement of one class feature that is needed in multiple classes.

Multilevel inheritance in C#: When one class is derived from another, this type of inheritance is called multilevel
inheritance.

23
RESTRICTED
RESTRICTED

C# does not support multiple inheritances of classes. To overcome this problem, we can use interfaces.

In the preceding program, the ICar class inherits the features of the two interfaces; hence this type of
inheritance is called Multiple Inheritance.

The following are some key points about inheritance:


✓ C# does not support multiple inheritances of classes, the same thing can be done using interfaces.
✓ Private members are not accessed in a derived class when one class is derived from another.

Polymorphism:
Polymorphism means one name, many forms. One function behaves in different forms. In other words, "Many forms of a
single object is called Polymorphism. It occurs when we have many classes that are related to each other by inheritance.

Real-world Example of Polymorphism:


Your mobile phone, one name but many forms:
• As phone
• As camera
• As mp3 player
• As radio

24
RESTRICTED
RESTRICTED

In the above example, we have created a class Program inside which we have two methods of the same name greet().
Here, one of the greet() methods takes no parameters and displays "Hello". While the other greet() method takes a
parameter and displays "Hello Tim". Hence, the greet() method behaves differently in different scenarios. Or, we can say
greet() is polymorphic.

Differences between Abstraction and Encapsulation:


Abstraction Encapsulation
1. Abstraction solves the problem at the design
1. Encapsulation solves the problem at the implementation level.
level.
2. Abstraction hides unwanted data and provides 2. Encapsulation means hiding the code and data in a single unit to
relevant data. protect the data from the outside world.
3. Abstraction lets you focus on what the object 3. Encapsulation means hiding the internal details or mechanics of how
does instead of how it does it an object does something.
4. Abstraction: Outer layout, used in terms of
4. Encapsulation- Inner layout, used in terms of implementation.
design.
For example:
For example, the internal details of a Mobile Phone and how the
An external Mobile Phone like it has a display
keypad button and display screen are connected using circuits.
screen and keypad buttons to dial a number.

C# Interface:
Interface in C# is a blueprint of a class. It is like an abstract class because all the methods declared inside the interface
are abstract methods. It cannot have a method body and cannot be instantiated. Declare an interface with a capital
letter I in front of the name.

In C#, an interface can be defined using the interface keyword. An interface can contain declarations of methods,
properties, indexers, and events. However, it cannot contain instance fields.

The following interface declares some basic functionalities for the file operations.
Example: C# Interface
interface IFile
{
void ReadFile();

25
RESTRICTED
RESTRICTED

void WriteFile(string text);


}

class FileInfo : IFile


{
public void ReadFile()
{
Console.WriteLine("Reading File");
}

public void WriteFile(string text)


{
Console.WriteLine("Writing to file");
}
}

To implement multiple interfaces in C#, you separate each included interface with a comma. For example, to include
both an Ishape and an IshapeDisplay interface in a Square class, you use the following:

class Square : IShape, IShapeDisplay


{
...
}
You then need to implement all the constructs within both interfaces.

Method Overloading:
Method Overloading is a type of polymorphism. It has several names like “Compile Time Polymorphism” or “Static
Polymorphism,” and sometimes it is called “Early Binding”.

Method Overloading means creating multiple methods in a class with the same names but different signatures
(Parameters). It permits a class, struct, or interface to declare multiple methods with the same name with unique
signatures. The compiler automatically calls the required method to check the number of parameters and their type
passed into that method.
Example:

Method Overriding:

26
RESTRICTED
RESTRICTED

Method Overriding is a type of polymorphism. It has several names like “Run Time Polymorphism” or “Dynamic
Polymorphism,” and sometimes it is called “Late Binding”.

Method Overriding means having two methods with the same name and same signatures [parameters]; one should be in
the base class, and another method should be in a derived class [child class]. You can override the functionality of a base
class method to create the same name method with the same signature in a derived class. You can achieve method
overriding using inheritance. Virtual and Override keywords are used to achieve method overriding.
Example:

Comparison between method overloading and method overriding:

Method Overloading Method Overriding


Creating more than one method or function having same name Creating a method in the derived class with the
but different signatures or the parameters in the same class is same signature as a method in the base class is
called method overloading. called as method overriding
It is called the compile time polymorphism It is called runtime polymorphism
It has the same method name but with different signatures or It must have same method name as well as the
the parameters signatures or the parameters.
Method overloading doesn’t need inheritance Method overriding needs inheritance
Method overriding needs hierarchy level of the
Method overloading is possible in single class only
classes i.e. one parent class and another child class.
Access modifier can be any Access modifier must be public.
Method overloading is also called early binding. Method overriding is also called late binding.

27
RESTRICTED
RESTRICTED

Sample Questionnaires on Object Oriented Programming – C#

1. What is meant by object-oriented programming?


Answer: Object-oriented programming (OOP) is an approach to programming where software is primarily
designed by using objects (essentially data) that interact with each other.
When different pieces of data are put together, they come to form the software as a whole. OOP is an
alternative to functional or procedural programming and it’s also the approach used by C#.

2. What is an object in C#?


Answer: An object is a real-world entity and in C# it’s a single instance of a class. For example, if you had a class
of ‘dogs’, ‘labradors’, ‘bulldogs’, and ‘golden retrievers’ would all be objects.

3. What is a constructor in C#?


Answer: In C#, a constructor is a type of method that forms a part of a class. The main purpose of a constructor
is to initialize the fields of a class. They are invoked automatically when a new class object is created.

4. What is a destructor in C#?


Answer: In C#, a destructor is a type of method that forms a part of a class. The main purpose of a destructor is
to destroy instances of a class when they are no longer needed in order to free up memory. Destructors are also
referred to as finalizers.

5. What is an array in C#?


Answer: In C#, an array is a collection of data that stores a fixed number of values of the same data type. Arrays
can be retrieved easily for the developer’s reference.

6. What are boxing and unboxing in C#?


Answer: In C#, boxing and unboxing allow developers to convert .NET data types from reference type to value
type and vice versa.
Unboxing is used to convert a reference type to a value type, while boxing is used to convert a value type to a
reference type. These two processes underpin the unified view of C#.

7. What is the difference between String and StringBuilder in C#?


Answer: A string object is immutable, meaning that it cannot be changed after it’s created. Any operation that
tries to modify the string object will simply create a new string object. On the other hand, a string builder object
is mutable and can be modified as the developer sees fit.
8. What are the key differences between Array and ArrayList in C#?
Answer: An ArrayList has wider usage than an Array. The key differences include:
✓ An Array is strongly-typed, meaning it only stores the same type of data. An ArrayList is a non-generic
collection type, meaning it can store multiple types of data
✓ An Array stores a fixed number of elements. An ArrayList features a variable number of elements and
can continually be added to
28
RESTRICTED
RESTRICTED

✓ An Array cannot accept null values, whereas an ArrayList can


✓ The relative simplicity of an Array means it typically provides better performance than an ArrayList
9. How is exception handling performed in C#?
Answer: In C#, exception handling helps detect errors in code at runtime. The process is implemented using four
different keywords:
✓ identifies blocks of code where exceptions are activated
✓ catches the exceptions that have been identified by
✓ executes a given set of statements depending on whether an exception is thrown out or not
✓ removes the exception

10. What are Access Specifiers?


Answer: There are 5 access specifiers:
• Public can be accessible outside the class through object reference.
• Private can be accessible inside the class only through member functions.
• Protected can be just like private but accessible in derived classes also through member functions.
• Internal can be visible inside the assembly. Accessible through objects.
• Protected Internal can be visible inside the assembly through objects and in derived classes outside the
assembly through member functions.

11. How would you explain the four fundamental concepts of object-oriented programming?

Answer: The four fundamental concepts of object-oriented programming can be explained as follows:

✓ Encapsulation is the bundling of data, including the methods that operate on that data, into a single,
private unit
✓ Polymorphism is the ability of a type to take on many forms using a single interface
✓ Abstraction is the concealment of unnecessary program details so that the user only sees the essential
attributes
✓ Inheritance is the process where one class derives (or inherits) its attributes and methods from another

12. What are the four fundamental principles of Object-Oriented Programming (OOP) in C#?
Answer: The four fundamental principles of Object-Oriented Programming (OOP) in C# are:

• Encapsulation: Encapsulation is the process of bundling the data and the methods (functions) that
operate on the data within a single unit called a class. This helps to hide the implementation details from
the outside world, allowing access only through a well-defined interface.
• Inheritance: Inheritance is the ability of a class to inherit properties and methods from a parent class
(base class). This helps to promote code reusability and maintainability by allowing new classes (derived
classes) to reuse the functionality of existing classes without modifying them.
• Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common
superclass. This enables a single function or method to operate on multiple types of objects, making the
code more flexible and extensible.
• Abstraction: Abstraction is the process of simplifying complex systems by breaking them down into
smaller, more manageable parts. In OOP, abstraction is achieved through the use of abstract classes and
interfaces, which define the common properties and methods that a group of related classes should
have.
29
RESTRICTED
RESTRICTED

13. What is encapsulation in C#?


Answer: Encapsulation is a fundamental principle of object-oriented programming in C#. It involves bundling
data (attributes) and methods (functions) that operate on the data into a single unit called a class. Encapsulation
restricts direct access to internal members, promoting data hiding and controlled access.
14. What is the purpose of using access modifiers in C#, and can you provide examples of the different access
modifiers available?
Answer: Access modifiers in C# are used to control the visibility and accessibility of class members (properties,
methods, and fields). They help to define the scope of the members and enforce encapsulation. There are five
different access modifiers available in C#:

• public: Members declared as public are accessible from any part of the code. They have the least
restriction on their visibility. Example:
public class MyClass {
public int MyProperty;
}

• private: Members declared as private are only accessible within the same class. They have the most
restriction on their visibility and are used to encapsulate implementation details. Example:
class MyClass {
private int MyProperty;
}

• protected: Members declared as protected are accessible within the same class and any derived classes.
This access modifier is useful when you want to provide access to members for subclasses, but not for
the rest of the code. Example:
class MyClass {
protected int MyProperty;
}

• internal: Members declared as internal are accessible within the same assembly. This access modifier is
useful when you want to expose members within a single assembly but hide them from external
assemblies. Example:
class MyClass {
internal int MyProperty;
}

• protected internal: Members declared as protected internal are accessible within the same assembly
and any derived classes, even if they are defined in a different assembly. This access modifier combines
the functionality of both protected and internal. Example:
class MyClass {
protected internal int MyProperty;
}

15. Describe the difference between encapsulation and abstraction in C#.


Answer: Encapsulation focuses on bundling data and methods into a class, restricting access to internal
members. Abstraction, on the other hand, emphasizes providing a simplified and generalized view of an object,

30
RESTRICTED
RESTRICTED

often achieved through interfaces or abstract classes. Encapsulation enforces data hiding, while abstraction
hides unnecessary implementation details.

16. Explain the term "getter" and "setter" in the context of encapsulation and properties in C#.
Answer: A "getter" is a method that retrieves the value of a private field within a class. A "setter" is a method
that assigns a value to a private field. Getters and setters are used to encapsulate access to data and allow
controlled interaction with the internal state of an object.

17. What is abstraction in C#?


Answer: Abstraction is a fundamental concept in object-oriented programming that involves simplifying complex
reality by modeling classes with essential attributes and behaviors. It provides a high-level, generalized view of
an object, hiding unnecessary implementation details.

18. How does abstraction differ from encapsulation in C#?


Answer: Encapsulation focuses on bundling data and methods into a single unit (class), while abstraction
emphasizes providing a simplified, generalized view of an object. Encapsulation controls access to internal
members, while abstraction hides unnecessary complexities.

19. What are abstract classes in C#?


Answer: An abstract class is a class that cannot be instantiated on its own and can have both abstract
(unimplemented) and concrete (implemented) methods. It serves as a blueprint for derived classes to inherit
and implement.

20. Can you create an instance of an abstract class in C#?


Answer: No, you cannot create an instance of an abstract class directly. Abstract classes are meant to be
inherited and serve as a foundation for more specific derived classes.

21. What is Polymorphism?


Answer: When a message can be processed in different ways it is called polymorphism.
Polymorphism means many forms.
There are 2 types of polymorphism:
✓ Compile time polymorphism also known as Overloading
✓ Run time polymorphism also known as Overriding

22. What is method Overloading?


Answer: Creating multiple methods in a class with the same name but with different parameters and different
types is called method overloading.
23. When and why to use method Overloading?
Answer:
✓ You have to use method overloading in situations where you want a class to be able to do something,
but there is more than one possibility for what information is supplied to the method that carries out
the task.
✓ You should consider overloading a method when you need a couple of methods that take different
parameters, but conceptually do the same thing.
24. What is method Overriding?

31
RESTRICTED
RESTRICTED

Answer:
✓ Overriding means to change the functionality of a method without changing the signature.
✓ You can override a method in base class by creating a similar method in derived class.
✓ Base class method has to be marked with virtual keyword and you can override it in derived class using
override keyword.
✓ Derived class method will completely overrides base class method i.e. when you refer base class object
created by casting derived class object a method in derived class will be called.
25. What is Operator Overloading?
Answer:
✓ Overloaded operators are functions with special names the keyword operator followed by the symbol
for the operator being defined.
✓ Similar to any other function, an overloaded operator has a return type and a parameter list.
26. What is Interface?
Answer:
✓ An interface looks like a class, but it has no implementation.
✓ The only thing it contains is declarations of events, indexers, methods and/or properties.
✓ The reason interfaces only provide declarations is because they are inherited by structs and classes,
which must provide an implementation for each interface member declared.

27. What are the different techniques for overloading a method in C#?
Answer: Method overloading can be achieved in the three following ways:
✓ By using different types of data for parameters in a method
✓ By changing the number of parameters in a method
✓ By changing the order of parameters in a method

28. Differentiate between overloading and overriding.


Aspect Method Overloading Method Overriding
Definition Defining multiple methods with Providing a new implementation
the same name for a base class method
Inheritance Not dependent on inheritance. Requires inheritance; involves a
base and derived class.
Compile-Time Determined at compile-time Method to be executed is
based on parameter types. determined at runtime based on
Access Modifier Can have the same or different Must have the same access
access modifiers. modifier as the base method.
Parameters Must have a unique combination Must have the same parameter
of parameter types. list as the base method.

29. How can you implement multiple inheritance in C#?


Answer: In C#, a class can inherit from only one base class directly. This is known as single inheritance. However,
C# provides a way to achieve similar functionality to multiple inheritance through interfaces.

Interfaces allow you to define contracts that classes must adhere to, and a class can implement multiple
interfaces. This allows a class to inherit multiple sets of behavior without the limitations of multiple inheritance.

32
RESTRICTED
RESTRICTED

Here's an example demonstrating how to implement multiple inheritance-like behavior using interfaces in C#:

interface IShape
{
double CalculateArea();
}

interface IDrawable
{
void Draw();
}

class Circle : IShape, IDrawable


{
public double Radius { get; set; }
public double CalculateArea()
{
return Math.PI * Radius * Radius;
}

public void Draw()


{
Console.WriteLine("Drawing a circle.");
}
}

In this example, the Circle class implements both the IShape and IDrawable interfaces. As a result, the
Circle class inherits the CalculateArea method from the IShape interface and the Draw method from the
IDrawable interface.

30. Does .NET support multiple inheritance?


Answer: C# supports single inheritance, which means a class can inherit from only one base class.
However, C# does provide a way to achieve similar functionality to multiple inheritance through interfaces. A
class can implement multiple interfaces, allowing it to inherit behavior from multiple sources without the
complexities and issues associated with traditional multiple inheritance.

So, while C# doesn't support multiple inheritance in the same way as some other programming languages, it
does offer a more controlled and flexible approach to achieving similar results through interfaces.

31. What are the key differences among abstraction, polymorphism, inheritance, and encapsulation in C#?

33
RESTRICTED
RESTRICTED

Concept Definition Purpose Example

Focuses on essential Provides a high-level view Defining an interface for different


Abstraction characteristics and of an object's shapes (IShape).

behaviors, hiding functionality, simplifying


unnecessary details. interaction.

Allows objects of Enhances code flexibility, Treating a base class Animal and
Polymorphism different types to be reusability, derived classes (Dog, Cat)

treated as objects of a and adaptability by interchangeably through a


common base class enabling dynamic common interface (IPet).

behavior selection based


or interface. on object type.

Enables a class to inherit Facilitates code reuse by Creating a hierarchy: Vehicle (base)
Inheritance properties and sharing common and Car (derived).

behaviors from another functionality and creating Car "is-a" Vehicle, inheriting Vehicle
class, creating a an "is-a" properties/methods.

34
RESTRICTED
RESTRICTED

relationship between
hierarchical structure. classes.

Bundles data and Ensures data integrity, Using private fields and public
Encapsulation methods into a single reduces unintended methods to control access

unit (class), controlling interactions, and separates to data and provide controlled
access to the implementation interactions.

internal state. details from external code.

35
RESTRICTED
RESTRICTED

C# - Design Pattern (For Advanced)


Definition: A design pattern is a template or blueprint for solving specific types of challenges that software developers
often face when designing and implementing software systems. Design patterns are not complete solutions or ready-to-
use code snippets; rather, they are high-level descriptions or guidelines that help developers structure their code and
design software in a more organized, maintainable, and efficient manner.

Types of Design Pattern:

1) Creational patterns:
Deal with object creation mechanisms, providing ways to create objects in a manner that is more flexible, controlled,
and efficient.
● Singleton Pattern
● Factory Method Pattern
● Abstract Factory Pattern
● Builder Pattern
● Prototype Pattern

2) Structural patterns:
focus on the composition, structure, and relationships between classes and objects, thereby promoting flexibility,
reusability, and maintainability in software design
● Adapter Pattern
● Bridge Pattern
● Composite Pattern
● Decorator Pattern
● Facade Pattern
● Flyweight Pattern
● Proxy Pattern
3) Behavioral patterns:
focus on the communication, interaction, and collaboration between objects in a way that promotes flexibility,
maintainability, and understandability of the software.
● Mediator Pattern
● Chain of Responsibility Pattern
● Command Pattern
● Interpreter Pattern
● Iterator Pattern
● Observer Pattern
● State Pattern
● Strategy Pattern
● Template Method Pattern
● Memento Pattern

❖ Façade Pattern: It is used as a camouflage to cover the complexities of a large system and therefore provides a
simple interface to the client. In other words, it is a wrapper class used to hide the implementation details.

36
RESTRICTED
RESTRICTED

❖ Mediator Pattern: The Mediator design pattern promotes loose coupling between classes by encapsulating the
interactions between these classes within a separate mediator object. The classes do not interact directly with
each other, instead, they use the mediator to communicate.

37
RESTRICTED
RESTRICTED

Sample Questionnaires on Design Pattern in C#:

32. What problem does the Facade Pattern address?


Answer: It addresses the problem of high complexity and tight coupling between client code and a complex
subsystem by providing a single-entry point and hiding the details.

33. How does the Facade Pattern achieve its goal?


Answer: It encapsulates the interactions and coordination among various classes or components within a single
higher-level interface, making the system easier to use.
34. What are the main components in a Facade Pattern implementation?
Answer: The main components are the Facade (simplified interface) and the underlying subsystem (comprising
multiple classes).
35. What benefits does the Facade Pattern offer to clients?
Answer: It shields clients from the complexities of the underlying subsystem, reduces the learning curve, and
improves maintainability.
36. Can a Facade have multiple methods for different functionalities?
Answer: Yes, a Facade can have multiple methods that encapsulate various interactions with the subsystem,
simplifying multiple aspects of the system.
37. Is the Facade Pattern about creating new functionality or just simplifying access?
Answer: The primary goal is to simplify access and coordination; however, it can also involve creating new high-
level methods that use existing components.
38. Can the Facade Pattern be applied to both class-level and subsystem-level interactions?
Answer: Yes, the Facade Pattern can be applied at various levels of a system's architecture, depending on the
desired simplification and abstraction.

39. What problem does the Mediator Pattern solve?


Answer: The Mediator Pattern solves the problem of tight coupling between interacting objects by providing a
central point of control for their communication.

40. What is the main advantage of using the Mediator Pattern?


Answer: The main advantage is that it reduces the direct dependencies between objects, promoting better
organization and easier maintenance of a system.

41. How does the Mediator Pattern improve scalability?


Answer: It can improve scalability by allowing easier addition of new Colleagues or changes to existing
communication logic without affecting the entire system.

42. Can the Mediator Pattern be combined with other design patterns?
Answer: Yes, the Mediator Pattern can be combined with patterns like Singleton, Factory, and Observer to
create more comprehensive and flexible designs.

38
RESTRICTED
RESTRICTED

43. How does the Mediator Pattern differ from the Observer Pattern?
Answer: While both patterns facilitate communication between objects, the Mediator centralizes the
communication, whereas the Observer allows objects to subscribe and receive updates from a subject.

ASP.NET
Definition:
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic
web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily.

ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-server bilateral
communication and cooperation.

ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the extensible and
reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net
framework.

The ASP.NET application codes can be written in any of the following languages:

➢ C#
➢ Visual Basic.Net
➢ Jscript
➢ J#

ASP.NET Web Forms Model

ASP.NET web forms extend the event-driven model of interaction to the web applications. The browser submits a web
form to the web server and the server returns a full markup page or HTML page in response.

All client-side user activities are forwarded to the server for stateful processing. The server processes the output of the
client actions and triggers the reactions.

Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information regarding the state of the
application, which consists of:

❖ Page state

The page state is the state of the client, i.e., the content of various input fields in the web form.

❖ Session state

The session state is the collective information obtained from various pages the user visited and worked with,
i.e., the overall session state.

The ASP.NET Component Model


39
RESTRICTED
RESTRICTED

The ASP.NET component model provides various building blocks of ASP.NET pages. Basically it is an object model, which
describes:
❖ Server-side counterparts of almost all HTML elements or tags, such as <form> and <input>.
❖ Server controls, which help in developing complex user-interface. For example, the Calendar control or the
Gridview control.

Components of .Net Framework


Components and their Description

(1) Common Language Runtime or CLR


It performs memory management, exception handling, debugging, security checking, thread execution, code
execution, code safety, verification, and compilation. The code that is directly managed by the CLR is called the
managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent
intermediate language (IL) code. A Just In Time(JIT) compiler compiles the IL code into native code, which is CPU
specific.

(2) .Net Framework Class Library


It contains a huge library of reusable types. classes, interfaces, structures, and enumerated values, which are
collectively called types.

(3) Common Language Specification


It contains the specifications for the .Net supported languages and implementation of language integration.

(4) Common Type System


It provides guidelines for declaring, using, and managing types at runtime, and cross-language communication.

(5) Metadata and Assemblies


Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or
in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code, and a set of
resources like image files.

(6) Windows Forms


Windows Forms contain the graphical representation of any window displayed in the application.

(7) ASP.NET and ASP.NET AJAX


ASP.NET is the web development model and AJAX is an extension of ASP.NET for developing and implementing AJAX
functionality. ASP.NET AJAX contains the components that allow the developer to update data on a website without a
complete reload of the page.

40
RESTRICTED
RESTRICTED

(8) ADO.NET
It is the technology used for working with data and databases. It provides access to data sources like SQL server, OLE
DB, XML etc. The ADO.NET allows connection to data sources for retrieving, manipulating, and updating data.

(9) Windows Workflow Foundation (WF)


It helps in building workflow-based applications in Windows. It contains activities, workflow runtime, workflow
designer, and a rules engine.

(10) Windows Presentation Foundation


It provides a separation between the user interface and the business logic. It helps in developing visually stunning
interfaces using documents, media, two and three dimensional graphics, animations, and more.

(11) Windows Communication Foundation (WCF)


It is the technology used for building and executing connected systems.

(12) Windows CardSpace


It provides safety for accessing resources and sharing personal information on the internet.

(13) LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language
SQL.

ASP.NET Application Life Cycle

I. User makes a request for accessing application resource, a page. Browser sends this request to the web server.
II. A unified pipeline receives the first request and the following events take place:
a. An object of the class ApplicationManager is created.
b. An object of the class HostingEnvironment is created to provide information regarding the resources.
c. Top level items in the application are compiled.
III. Response objects are created. The application objects such as HttpContext, HttpRequest and HttpResponse are
created and initialized.
IV. An instance of the HttpApplication object is created and assigned to the request.
V. The request is processed by the HttpApplication class. Different events are raised by this class for processing the
request.

ASP.NET Page Life Cycle


Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life
cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-
state data and run control behavior code.
ollowing are the different stages of an ASP.NET page:
➢ Page request - When ASP.NET gets a page request, it decides whether to parse and compile the page, or there
would be a cached version of the page; accordingly the response is sent.
➢ Starting of page life cycle - At this stage, the Request and Response objects are set. If the request is an old
request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is
also set.

41
RESTRICTED
RESTRICTED

➢ Page initialization - At this stage, the controls on the page are assigned unique ID by setting the UniqueID
property and the themes are applied. For a new request, postback data is loaded and the control properties are
restored to the view-state values.
➢ Page load - At this stage, control properties are set using the view state and control state values.
➢ Validation - Validate method of the validation control is called and on its successful execution, the IsValid
property of the page is set to true.
➢ Postback event handling - If the request is a postback (old request), the related event handler is invoked.
➢ Page rendering - At this stage, view state for the page and all controls are saved. The page calls the Render
method for each control and the output of rendering is written to the OutputStream class of the Response
property of page.
➢ Unload - The rendered page is sent to the client and page properties, such as Response and Request, are
unloaded and all cleanup done.

ASP.NET Page Life Cycle Events


At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a
function or subroutine, bound to the event, using declarative attributes such as Onclick or handle.
➢ PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the
page is a postback. It sets the themes and master pages, creates dynamic controls, and gets and sets profile
property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit
handler.
➢ Init - Init event initializes the control property and the control tree is built. This event can be handled by
overloading the OnInit method or creating a Page_Init handler.
➢ InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
➢ LoadViewState - LoadViewState event allows loading view state information into the controls.
➢ LoadPostData - During this phase, the contents of all the input fields are defined with the <form> tag are
processed.
➢ PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be handled by
overloading the OnPreLoad method or creating a Page_PreLoad handler.
➢ Load - The Load event is raised for the page first and then recursively for all child controls. The controls in the
control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load
handler.
➢ LoadComplete - The loading process is completed, control event handlers are run, and page validation takes place.
This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler
➢ PreRender - The PreRender event occurs just before the output is rendered. By handling this event, pages and
controls can perform any updates before the output is rendered.
➢ PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event ensures the
completion of the pre-rendering phase.
➢ SaveStateComplete - State of control on the page is saved. Personalization, control state and view state
information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method
or creating a Page_Render handler.
➢ UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls
recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database
connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad
handler.
ASP.NET - Event Handling

42
RESTRICTED
RESTRICTED

An event is an action or occurrence such as a mouse click, a key press, mouse movements, or any system-
generated notification. A process communicates through events. For example, interrupts are system-
generated events.

❖ Event Arguments
ASP.NET event handlers generally take two parameters and return void. The first parameter represents the
object raising the event and the second parameter is event argument.

❖ Application and session events


The most important application events are:
➢ Application_Start - It is raised when the application/website is started.
➢ Application_End - It is raised when the application/website is stopped.
Similarly, the most used Session events are:
➢ Session_Start - It is raised when a user first requests a page from the application.
➢ Session_End - It is raised when the session ends.
❖ Page and control event
➢ DataBinding - It is raised when a control binds to a data source.
➢ Disposed - It is raised when the page or the control is released.
➢ Error - It is a page event, occurs when an unhandled exception is thrown.
➢ Init - It is raised when the page or the control is initialized.
➢ Load - It is raised when the page or a control is loaded.
➢ PreRender - It is raised when the page or the control is to be rendered.
➢ Unload - It is raised when the page or control is unloaded from memory.

❖ Event handling using controls


All ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain
action on them. For example, when a user clicks a button the 'Click' event is generated. For handling events, there are
in-built attributes and event handlers. Event handler is coded to respond to an event, and take appropriate action on it.
Event Attribute Controls

Click OnClick Button, image button, link button, image map

Command OnCommand Button, image button, link button

TextChanged OnTextChanged Text box

SelectedIndexChanged OnSelectedIndexChanged Drop-down list, list box, radio button list, check box list.

CheckedChanged OnCheckedChanged Check box, radio button

❖ Default events
43
RESTRICTED
RESTRICTED

The default event for the Page object is Load event. Similarly, every control has a default event. For example, default
event for the button control is the Click event.
Control Default Event

AdRotator AdCreated

BulletedList Click

Button Click

Calender SelectionChanged

CheckBox CheckedChanged

CheckBoxList SelectedIndexChanged

DataGrid SelectedIndexChanged

DataList SelectedIndexChanged

DropDownList SelectedIndexChanged

HyperLink Click

ImageButton Click

ImageMap Click

LinkButton Click

ListBox SelectedIndexChanged

Menu MenuItemClick

RadioButton CheckedChanged

RadioButtonList SelectedIndexChanged
ASP.NET - Data Sources
A data source control interacts with the data-bound controls and hides the complex data binding processes.
These are the tools that provide data to the data bound controls and support execution of operations like
insertions, deletions, sorting, and updates.
Each data source control wraps a particular data provider-relational databases, XML documents, or custom
classes and helps in:
✓ Managing connection
✓ Selecting data
✓ Managing presentation aspects like paging, caching, etc.
44
RESTRICTED
RESTRICTED

✓ Manipulating data
There are many data source controls available in ASP.NET for accessing data from SQL Server, from ODBC or
OLE DB servers, from XML files, and from business objects.
Based on type of data, these controls could be divided into two categories:
✓ Hierarchical data source controls
✓ Table-based data source controls
The data source controls used for hierarchical data are:
❖ XMLDataSource - It allows binding to XML files and strings with or without schema information.
❖ SiteMapDataSource - It allows binding to a provider that supplies site map information.

The data source controls used for tabular data are:


Data source controls Description

SqlDataSource It represents a connection to an ADO.NET data provider that returns SQL data,
including data sources accessible via OLEDB and ODBC.

ObjectDataSource It allows binding to a custom .Net business object that returns data.

LinqdataSource It allows binding to the results of a Linq-to-SQL query (supported by ASP.NET 3.5
only).

AccessDataSource It represents connection to a Microsoft Access database.

Sample Questionnaires on ASP.NET:


44. What is ASP.NET?
• ASP.NET is a web application framework developed by Microsoft for building dynamic web
applications and services.
45. What does ASP.NET stand for?
• ASP.NET stands for Active Server Pages .NET.
46. What is the latest version of ASP.NET?
• .NET 7.0 is the latest version. However, newer versions may have been released since then.
47. What is the difference between ASP.NET and ASP.NET Core?
• ASP.NET is the older framework, while ASP.NET Core is a cross-platform and open-source
framework. ASP.NET Core is more lightweight and modular.

45
RESTRICTED
RESTRICTED

48. What are the two main components of ASP.NET?


• ASP.NET Web Forms and ASP.NET MVC (Model-View-Controller) are the two main components.
49. What is a web form in ASP.NET?
• A web form is a user interface page in an ASP.NET application that allows users to interact with
the application.
50. What is an ASP.NET MVC application?
• ASP.NET MVC is a design pattern that separates an application into three components: Model,
View, and Controller, promoting a more organized and maintainable code structure.
51. What is the role of the Model in ASP.NET MVC?
• The Model represents the application's data and business logic.
52. What is the role of the View in ASP.NET MVC?
• The View is responsible for rendering the user interface based on the Model's data.
53. What is the role of the Controller in ASP.NET MVC?
• The Controller handles user input, processes requests, and updates the Model accordingly.
54. What is an ASP.NET Web API?
• ASP.NET Web API is a framework for building HTTP services that can be accessed by a wide
range of clients, including browsers and mobile devices.
55. What is ASP.NET Core Razor Pages?
• Razor Pages is a feature in ASP.NET Core that simplifies page-focused scenarios, allowing you to
create web pages with minimal ceremony.
56. What is ViewState in ASP.NET Web Forms?
• ViewState is a mechanism in ASP.NET Web Forms that allows the preservation of state
information across postbacks.
57. What is a Code-Behind file in ASP.NET Web Forms?
• A Code-Behind file contains the logic associated with an ASP.NET Web Forms page, separating
code from the markup.
58. What is authentication and authorization in ASP.NET?
• Authentication is the process of verifying the identity of a user, while authorization is
determining what actions or resources a user can access.
59. What is the ASP.NET Membership Provider?

46
RESTRICTED
RESTRICTED

• It is a built-in feature in ASP.NET that provides a way to manage user accounts and implement
authentication and authorization.
60. What is routing in ASP.NET MVC?
• Routing is the process of mapping URLs to controller actions in ASP.NET MVC applications.
61. What is the purpose of the Global.asax file?
• The Global.asax file contains application-level events and settings, such as handling application-
wide exceptions.
62. What is the difference between GET and POST requests in ASP.NET?
• GET requests are used to retrieve data from the server, while POST requests are used to send
data to the server for processing.
63. What is a Session in ASP.NET?
• Session is a server-side state management technique that allows data to be persisted across
multiple requests for a single user.
64. What is caching in ASP.NET?
• Caching is the process of storing frequently used data in memory to improve application
performance.
65. What is the Web.config file used for in ASP.NET?
• The Web.config file contains configuration settings for an ASP.NET application, including
database connections, authentication, and custom error pages.
66. What is a Master Page in ASP.NET?
• A Master Page is a template that defines the common structure and layout for a set of web
pages.
67. What is AJAX in ASP.NET?
• AJAX (Asynchronous JavaScript and XML) is a technique for making asynchronous requests to
the server to update parts of a web page without a full page refresh.
68. What is the role of the @ symbol in Razor views?
• The @ symbol is used to switch between HTML markup and C# code in Razor views.
69. What is the purpose of the ModelState object in ASP.NET MVC?
• ModelState is used to store validation errors and other data associated with form submission in
ASP.NET MVC applications.
70. What is Entity Framework in ASP.NET?

47
RESTRICTED
RESTRICTED

• Entity Framework is an Object-Relational Mapping (ORM) framework that simplifies database


access and manipulation in ASP.NET applications.
71. What is the difference between ViewBag and ViewData in ASP.NET MVC?
• Both ViewBag and ViewData are used to pass data from a controller to a view, but ViewBag
uses dynamic typing while ViewData uses a dictionary.
72. What is the role of the App_Start folder in ASP.NET?
• The App_Start folder is used to store configuration code that runs when the application starts,
such as route configuration and filter registration.
73. What is dependency injection in ASP.NET Core?
• Dependency injection is a design pattern in ASP.NET Core that allows you to inject
dependencies (e.g., services) into your application's components, promoting modularity and
testability.
74. Explain the difference between ASP.NET Web Forms and ASP.NET MVC.
Answer: ASP.NET Web Forms is a framework that provides a more rapid way to build web applications using a
visual drag-and-drop model. ASP.NET MVC is a pattern-based approach that separates an application into
Model, View, and Controller components, offering greater control over the application's structure and behavior.

75. What is the ASP.NET Page Life Cycle?


Answer: The ASP.NET Page Life Cycle refers to the series of events that occur when a web page is requested and
processed by the server. It includes stages like Initialization, Load, Postback Data Handling, Rendering, and
Unload.

76. What is ASP.NET Routing?


Answer: ASP.NET Routing is a URL mapping technique that enables you to define URL patterns for your
application's pages. It allows for cleaner, more user-friendly URLs and supports dynamic handling of URLs.

ASP.NET (MVC)

Overview: Definition
48
RESTRICTED
RESTRICTED

ASP.NET Core MVC is a rich framework for building web apps and APIs using the Model-View-Controller design pattern.
MVC stands for Model, View, and Controller. MVC separates an application into three components - Model, View, and
Controller. Each architecture component is built to handle specific development aspect of an application.

MVC separates the business logic and presentation layer from each other. It was traditionally used for desktop graphical
user interfaces (GUIs). Nowadays, MVC architecture in web technology has become popular for designing web
applications as well as mobile apps.

Model: Model represents the shape of the data. A class in C# is used to describe a model. Model objects store data
retrieved from the database. The Model in an MVC application represents the state of the application and any business
logic or operations that should be performed by it. Business logic should be encapsulated in the model, along with any
implementation logic for persisting the state of the application

View: Views are responsible for presenting content through the user interface. They use the Razor view engine to embed
.NET code in HTML markup. There should be minimal logic within views, and any logic in them should relate to presenting
content. If you find the need to perform a great deal of logic in view files in order to display data from a complex model,
consider using a View Component, ViewModel, or view template to simplify the view.

Controller: Controllers are the components that handle user interaction, work with the model, and ultimately select a
view to render. In an MVC application, the view only displays information; the controller handles and responds to user
input and interaction. In the MVC pattern, the controller is the initial entry point, and is responsible for selecting which
model types to work with and which view to render (hence its name - it controls how the app responds to a given request).

The following figure illustrates the flow of the user's request in ASP.NET MVC.

As per the above figure, when a user enters a URL in the browser, it goes to the webserver and routed to a controller. A
controller executes related view and models for that request and create the response and sends it back to the browser.

MVC Examples: Let’s see Model View Controller example from daily life:

49
RESTRICTED
RESTRICTED

Assume Car driving mechanism is example of the MVC model.

✓ Every car consists of three main parts.


✓ View= User interface: (Gear lever, panels, steering wheel, brake, etc.)
✓ Controller- Mechanism (Engine)
✓ Model- Storage (Petrol or Diesel tank)

Advantages of MVC: Key Benefits


✓ Easy code maintenance which is easy to extend and grow
✓ MVC Model component can be tested separately from the user
✓ Easier support for new types of clients
✓ Development of the various components can be performed parallelly.
✓ It helps you to avoid complexity by dividing an application into the three units. Model, view, and controller
✓ It only uses a Front Controller pattern which process web application requests through a single controller.
✓ Offers the best support for test-driven development
✓ It works well for Web apps which are supported by large teams of web designers and developers.
✓ Provides clean separation of concerns (SoC).
✓ Search Engine Optimization (SEO) Friendly.
✓ All classes and objects are independent of each other so that you can test them separately.
✓ MVC design pattern allows logical grouping of related actions on a controller together.

ASP.NET MVC Folder Structure:

50
RESTRICTED
RESTRICTED

▪ App_Data: The App_Data folder can contain application data files like LocalDB, .mdf files, XML files, and other
data related files. IIS will never serve files from App_Data folder.

▪ App_Start: The App_Start folder can contain class files that will be executed when the application starts.
Typically, these would be config files like AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, RouteConfig.cs etc. MVC
5 includes BundleConfig.cs, FilterConfig.cs and RouteConfig.cs by default.

▪ Content: The Content folder contains static files like CSS files, images, and icons files. MVC 5 application includes
bootstrap.css, bootstrap.min.css, and Site.css by default.

▪ Controllers: The Controllers folder contains class files for the controllers. A Controller handles users' request and
returns a response. MVC requires the name of all controller files to end with "Controller".

▪ Fonts: The Fonts folder contains custom font files for your application.

▪ Models: The Models folder contains model class files. Typically, model class includes public properties, which will
be used by the application to hold and manipulate application data.

▪ Scripts: The Scripts folder contains JavaScript or VBScript files for the application. MVC 5 includes javascript files
for bootstrap, jquery 1.10, and modernizer by default.

▪ Views: The Views folder contains HTML files for the application. Typically view file is a .cshtml file where you
write HTML and C# or VB.NET code. The Views folder includes a separate folder for each controller. For example,
all the .cshtml files, which will be rendered by HomeController will be in View > Home folder.

▪ Global.asax: Global.asax file allows you to write code that runs in response to application-level events, such as
Application_BeginRequest, application_start, application_error, session_start, session_end, etc.

▪ Packages.config: Packages.config file is managed by NuGet to track what packages and versions you have
installed in the application.

51
RESTRICTED
RESTRICTED

▪ Web.config: Web.config file contains application-level configurations.

Routing in MVC:
In the ASP.NET Web Forms application, every URL must match with a specific .aspx file. For example, a URL
http://domain/studentsinfo.aspx must match with the file studentsinfo.aspx that contains code and markup for rendering
a response to the browser.

Route: Route defines the URL pattern and handler information. All the configured routes of an application stored in
RouteTable and will be used by the Routing engine to determine appropriate handler class or file for an incoming request.
The following figure illustrates the Routing process.

Configure a Route:

As you can see in the above figure, the route is configured using the MapRoute() extension method of RouteCollection,
where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method
and id parameter. Defaults specify which controller, action method, or value of id parameter should be used if they do not
exist in the incoming request URL.

Action method: All the public methods of the Controller class are called Action methods. They are like any other
normal methods with the following restrictions:
• Action method must be public. It cannot be private or protected
• Action method cannot be overloaded
52
RESTRICTED
RESTRICTED

• Action method cannot be a static method.


The following illustrates the Index() action method in the StudentController class.

ActionResult: MVC framework includes various Result classes, which can be returned from an action method. The
result classes represent different types of responses, such as HTML, file, string, JSON, javascript, etc. The following table
lists all the result classes available in ASP.NET MVC.

Result Class Description


ViewResult Represents HTML and markup.
EmptyResult Represents No response.
ContentResult Represents string literal.
FileContentResult/ FilePathResult/ FileStreamResult Represents the content of a file.
JavaScriptResult Represent a JavaScript script.
JsonResult Represent JSON that can be used in AJAX.
RedirectResult Represents a redirection to a new URL.
RedirectToRouteResult Represent another action of same or other controller.
PartialViewResult Returns HTML from Partial view.
HttpUnauthorizedResult Returns HTTP 403 status.

ASP.NET MVC- Filters:

In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be
circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides
filters for this purpose.
MVC provides different types of filters. The following table list filter types, built-in filters, and interface that must be
implemented to create custom filters.
Filter Type Description Built-in Filter Interface
Authorization Performs authentication and authorizes before executing an [Authorize], IAuthorizationFilter
filters action method. [RequireHttps]
Action filters Performs some operation before and after an action method IActionFilter
executes.
Result filters Performs some operation before or after the execution of the [OutputCache] IResultFilter
view.
Exception filters Performs some operation if there is an unhandled exception [HandleError] IExceptionFilter
thrown during the execution of the ASP.NET MVC pipeline.

53
RESTRICTED
RESTRICTED

ASP.NET MVC – Scaffolding:

Scaffolding is a technique used by many MVC frameworks like ASP.NET MVC, Ruby on Rails, Cake PHP and Node. JS etc.,
to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively. Further
you can edit or customize this auto generated code according to your need.

Sample Questionnaires on ASP.NET (MVC):

77. What is ASP.NET MVC?


Answer: ASP.NET MVC is a web application framework that helps programmers and developers build
applications using software engineering architecture. It uses the MVC pattern, which stands for model-view-
controller, to separate a computer program into distinguishable parts.

78. What is the difference between TempData, ViewData, and ViewBag?

Here are definitions for each of these terms:

TempData: Software engineers can use the TempDataDictionary class to pass data through each request. It
holds on to the information and transfers data between controllers or actions. TempData stores temporary
information before removing it after the request is completed.

ViewData: This feature stores internal information. It uses typecasting to form complex data types and prevent
errors in the system. You can only use ViewData for a current request that contains key-value pairs in a
dictionary.

ViewBag: This dynamic property passes data from a controller to the desired view. This temporary data also
enables you to share values without the need for typecasting or a complex data type.

79. State the differences between a view and a partial view.


✓ View: In the context of MVC, the view is responsible for rendering an app’s interface and showing data
to users. It usually contains HTML markup along with server-side code. It generates the HTML output
displayed in the user’s web browser.

✓ Partial view: On the other hand, a partial view is an independent, modular view component that can be
included within another view. It can render HTML output within another file’s rendered output. Many
app developers use partial views to reuse parts of a UI across different views.

80. What is Web API?

ASP.NET Web API is a framework for building services based on the Hypertext Transfer Protocol (HTTP). It
enables developers to build RESTful APIs that can be used for web applications.

54
RESTRICTED
RESTRICTED

Send applicants a REST API test to gain a basic understanding of their programming skills and ability to maintain
a scalable application programming interface.

81. What are the GET and POST action types?


✓ GET: This action type retrieves data from a server by sending a request. Developers use GET to read or
retrieve information from a specified resource. GET requests have length restrictions and should not be
used for sensitive data.
✓ POST: You can use this action to send data to a server to create or update a resource. POST requests
aren’t restricted in terms of data length, though large amounts of data may require more time for
processing and data encapsulation.

82. What are the Filters in MVC?


✓ Action Filters: Action filters are used to implement logic that gets executed before and after a controller
action executes. We will look at Action Filters in detail in this chapter.
✓ Authorization Filters: Authorization filters are used to implement authentication and authorization for
controller actions.
✓ Result Filters: Result filters contain logic that is executed before and after a view result is executed. For
example, you might want to modify a view result right before the view is rendered to the browser.
✓ Exception Filters: Exception filters are the last type of filter to run. You can use an exception filter to
handle errors raised by either your controller actions or controller action results. You can also use
exception filters to log errors.

83. What is routing in asp.net MVC/ Core?


Routing in ASP.NET Core refers to the process of matching incoming URLs to specific actions and controllers
within an application. It plays a crucial role in determining how requests are handled and how different
components of an application are invoked based on the URL patterns.

84. What is Default Route in ASP.NET MVC or Core?


In ASP.NET MVC, the Default Route is a predefined route configuration that is automatically registered when you
create a new MVC application. It serves as a fallback route that is used when no other routes match the
incoming URL. The Default Route is a conventional route that follows a specific URL pattern and maps to a
controller and action method.

The Default Route is defined by the MapRoute method in the RouteConfig.cs (or similar) file of your MVC
application. It typically follows the format:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

85. What is the difference between Temp data, View, and View Bag?
In Asp.Net MVC there are three ways to pass/store data between the controllers and views.
ViewData
✓ ViewData is used to pass data from controller to view
✓ It is derived from ViewDataDictionary class
55
RESTRICTED
RESTRICTED

✓ It is available for the current request only


✓ Requires typecasting for complex data type and checks for null values to avoid error
✓ If redirection occurs, then its value becomes null
ViewBag
✓ ViewBag is also used to pass data from the controller to the respective view
✓ ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
✓ It is also available for the current request only
✓ If redirection occurs, then its value becomes null
✓ Doesn’t require typecasting for complex data type
TempData
✓ TempData is derived from TempDataDictionary class
✓ TempData is used to pass data from the current request to the next request
✓ It keeps the information for the time of an HTTP Request. This means only from one page to another. It
helps to maintain the data when we move from one controller to another controller or from one action
to another action
✓ It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is
used to store only one time messages like the error messages and validation messages
86. What is Partial View in MVC?
A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most commonly, partial
views are used to componentize Razor views and make them easier to build and update. Partial views can also
be returned directly from controller methods.

87. What are HTML helpers in MVC/core?


HTML Helpers in ASP.NET MVC and ASP.NET Core are utility methods that simplify the process of generating
HTML markup within views. They provide a convenient way to render HTML elements, form controls, and other
components while encapsulating the underlying HTML generation logic

Example:
@Html.TextBox("username", null, new { @class = "form-control" })
@Html.ActionLink("Home", "Index", "Home")

88. Explain attribute based routing in MVC?


Attribute-based routing in ASP.NET MVC and ASP.NET Core is an approach that allows you to define routing
directly on controller actions or methods using attributes. This provides a more intuitive and declarative way to
specify how URLs should be mapped to actions without relying solely on the traditional route configuration.
Example:
[Route("products")]
public class ProductsController : Controller
{
// ...
}

56
RESTRICTED
RESTRICTED

ASP.NET Core

Overview: Definition

ASP.NET Core is an open source and cloud-optimized web framework for developing modern web applications that can
be developed and run on Windows, Linux and the Mac. It includes the MVC framework, which now combines the features
of MVC and Web API into a single web programming framework.

Why ASP.NET Core?


✓ Supports Multiple Platforms: ASP.NET Core applications can run on Windows, Linux, and Mac. So you don't need
to build different apps for different platforms using different frameworks.
✓ Fast: ASP.NET Core no longer depends on System.Web.dll for browser-server communication. ASP.NET Core
allows us to include packages that we need for our application. This reduces the request pipeline and improves
performance and scalability.
✓ IoC Container: It includes the built-in IoC container for automatic dependency injection which makes it
maintainable and testable.
✓ Integration with Modern UI Frameworks: It allows you to use and manage modern UI frameworks such as
AngularJS, ReactJS, Umber, Bootstrap, etc. using Bower (a package manager for the web).
✓ Hosting: ASP.NET Core web application can be hosted on multiple platforms with any web server such as IIS,
Apache etc. It is not dependent only on IIS as a standard .NET Framework.
✓ Code Sharing: It allows you to build a class library that can be used with other .NET frameworks such as .NET
Framework 4.x or Mono. Thus, a single code base can be shared across frameworks.

ASP.NET Core - Project Structure:

The following is a default project structure when you create an empty ASP.NET Core application in Visual Studio.

57
RESTRICTED
RESTRICTED

➢ ASP.NET Core - wwwroot Folder: By default, the wwwroot folder in the ASP.NET Core project is treated as a
web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to
that root.

➢ ASP.NET Core - Program.cs: ASP.NET Core web application is actually a console project which starts executing
from the entry point public static void Main() in Program class where we can create a host for the web application.

➢ ASP.NET Core - Startup Class: ASP.NET Core application must include Startup class. It is like Global.asax in the
traditional .NET application. As the name suggests, it is executed first when the application starts.

Entity Framework Core:


Entity Framework Core (EF Core) is an Object-Relational Mapping (ORM) framework that simplifies database access by
mapping database tables to .NET objects. It provides a set of APIs for performing database operations in a more object-
oriented manner.

Middleware:
Middleware refers to components in ASP.NET Core that handle requests and responses in the request pipeline. Each
middleware can perform specific tasks, such as authentication, logging, and routing, as the request flows through the
pipeline.

58
RESTRICTED
RESTRICTED

Routing:
Routing in ASP.NET Core determines how URLs are mapped to controller actions. It directs incoming requests to the
appropriate controller based on defined routes.

Tag Helpers:
Tag Helpers are a feature in ASP.NET Core that enable you to create custom HTML-like elements that can include server-
side C# code. They enhance the readability and maintainability of views.

Authentication and Authorization:


Authentication is the process of verifying a user's identity, while authorization determines whether a user has permission
to access certain resources. ASP.NET Core provides mechanisms for implementing both authentication and authorization.

59
RESTRICTED
RESTRICTED

Logging:
Logging is the process of recording events and information during the execution of an application. ASP.NET Core provides
a built-in logging framework that allows developers to capture and manage logs for debugging and monitoring purposes.

ViewModel:
A ViewModel is a concept used to pass data from the Controller to the View. It's a separate class that contains only the
data needed for the View to render, helping to keep the View lightweight and focused on display logic.

ViewComponent:
A ViewComponent is a reusable UI component in ASP.NET Core that encapsulates a specific piece of functionality or
rendering logic. It's more lightweight than a full-blown controller and view and is often used for rendering widgets or parts
of a page.

60
RESTRICTED
RESTRICTED

ViewBag and ViewData:


ViewBag and ViewData are dynamic objects provided by ASP.NET Core to pass data from the controller to the view. They
allow you to share data between the controller and view without explicitly defining a model.

Partial View:
A partial view is a reusable view component that can be included within other views. It's used to encapsulate and reuse
UI components across multiple views.

View Components vs. Partial Views:


View components and partial views are both used to create reusable UI components. View components are more powerful
and self-contained, while partial views are simpler and often used for rendering smaller sections of a view.

Web API:
A Web API (Application Programming Interface) is a set of HTTP endpoints that allow applications to communicate with
each other over the internet. ASP.NET Core allows developers to build RESTful Web APIs.

61
RESTRICTED
RESTRICTED

JWT (JSON Web Token):


JSON Web Token is a compact and self-contained method for securely transmitting information between parties as a JSON
object. JWTs are commonly used for authentication and authorization in ASP.NET Core applications.

SignalR:
SignalR is a library in ASP.NET Core that enables real-time communication between clients and the server. It's particularly
useful for building applications that require live updates, such as chat applications or collaborative tools.

Docker:
Docker is a platform for developing, shipping, and running applications in containers. Containers provide a consistent and
isolated environment for applications to run, ensuring portability across different environments.

Session State:
Session state is a mechanism that allows the application to maintain user-specific data across multiple requests. ASP.NET
Core provides session management to store and retrieve user-specific information during a user's session.

ModelState:
ModelState is a property in the controller that holds information about the validation state of model data. It helps manage
and report validation errors and other model-related information.

62
RESTRICTED
RESTRICTED

Caching:
Caching involves storing frequently accessed data in memory to reduce the load on the server and improve performance.
ASP.NET Core provides caching mechanisms that can be applied to various types of data.

63
RESTRICTED
RESTRICTED

Sample Questionnaires on ASP.NET Core:


89. What is ASP.NET Core?
ASP.NET Core is an open-source, cross-platform and high-performance platform that allows you to build
modern, Internet-connected and cloud enabled applications. With ASP.NET Core you can

• build web applications, IoT (Internet of things) apps, services and mobile Backends.
• run on .Net Core.
• You can do your development on Linux, Windows and MacOS.
• deploy your code to cloud or on-premises.

90. What are the benefits of using ASP.NET Core over ASP.NET?
ASP.NET Core comes with the following benefits over ASP.NET:
✓ Cross platform, provide ability to develop and run on Windows, Linux and MacOS.
✓ Open-source
✓ Unified Platform to develop Web UI and services.
✓ Built-in dependency injection.
✓ Ability to deploy on more than one server like IIS, Kestrel, Nginx, Docker, Apache etc
✓ cloud enabled framework, provide support for environment based configuration systems.
✓ Lightweight, High performance and modern HTTP request pipelines.
✓ well suited architecture for testability
✓ Integration of many client-side frameworks like Angular any version
✓ Blazor allow you to use C# code in browser with JavaScript code.

91. What are the key features of ASP.NET Core?


✓ Cross-Platform: ASP.NET Core is compatible with Windows, macOS, and Linux, allowing developers to
build and deploy applications on a variety of operating systems.
✓ High Performance: The framework is optimized for speed, utilizing asynchronous programming and a
lightweight architecture to handle requests efficiently.
✓ Modular Design: ASP.NET Core's modular structure promotes a clean separation of concerns and
supports a more maintainable codebase.
✓ Dependency Injection: Built-in dependency injection simplifies managing and injecting dependencies,
enhancing code modularity and testability.
✓ Authentication and Authorization: Supports various authentication methods and authorization policies,
ensuring secure user access control.

92. What is Razor Pages in ASP.NET Core?


Razor Pages is a feature in ASP.NET Core that simplifies building web pages without the complexities of the full
MVC framework. It's designed to make web development more straightforward, especially for simpler scenarios.

93. What are the differences Between Asp.Net VS Asp.Net Core?


ASP.Net ASP.NET CORE
Asp.Net Build for Windows Asp.Net Core Build for Windows, Mac and Linux
Asp.Net has a Good Performance ASP.Net core has higher performances than ASP.Net 4x.
It runs on .Net Framework or commonly called as full .Net It runs on .Net Core and Full .Net Framework.
Framework

64
RESTRICTED
RESTRICTED

Asp.Net Supports WebForm, Asp.Net MVC and Asp.Net Asp.Net Core does not support WebForm. It supports
WebAPI. MVC, Web API and Asp.Net Web pages originally added
in .Net Core 2.0.
Asp.Net used the only IIS with dependent on Asp.Net Core has not dependent System.web.dll and so
System.web.dll. the IIS.
Support C#, VB and many other languages and also Support only C#, F# language. VB support to added a
support WCF, WPF and WF short time and no support WCF, WPF and WF but support
for WCF client libraries are available.
Asp.Net MVC application added Web.config, Global.asax, Core did not support Web.config and Global.asax files. It
Application Start. is supporting appsettings.json.
Container support not more than better as the ASP.Net Container support best suited for deployments like
Core application. Docker.
All major versions supported Support Core from Visual Studio 2015 update 3 and
current version VS 2017.
We Need to re-compile after the code change. Core Browser refresh will compile and executed the code
no need for re-compile.

94. What is the role of Kestrel in ASP.NET Core?


Kestrel is a lightweight, cross-platform web server that's used as the default web server for ASP.NET Core
applications. It's designed to work well with ASP.NET Core and can be used standalone or behind a reverse proxy.

95. Can we run ASP.NET Core on IIS (Internet Information Services)?


Yes, ASP.NET Core applications can be run on IIS. However, they are hosted using a reverse proxy server, such as
IIS or Nginx, in front of the Kestrel web server.

96. What is the purpose of IWebHostEnvironment in ASP.NET Core?


IWebHostEnvironment provides information about the hosting environment, allowing you to tailor your
application's behavior based on whether it's running in Development, Staging, or Production environments.

97. Explain how HTTP protocol works?


Hypertext Transfer Protocol (HTTP) is an application-layer protocol for transmitting hypermedia documents,
such as HTML. It handles communication between web browsers and web servers. HTTP follows a classical
client-server model. A client, such as a web browser, opens a connection to make a request, then waits until it
receives a response from the server.

HTTP is a protocol that allows the fetching of resources, such as HTML documents. It is the foundation of any
data exchange on the Web, and it is a client-server protocol, which means requests are initiated by the recipient,
usually the Web browser.

98. What is the role of Startup class?

65
RESTRICTED
RESTRICTED

The Startup class in ASP.NET Core plays a pivotal role in configuring and setting up your application's behavior,
services, middleware, and more. Startup class is responsible for configuration related things as below.
• It configures the services which are required by the app.
• It defines the app's request handling pipeline as a series of middleware components.

The Startup class is typically found in the Startup.cs file and contains two primary methods: ConfigureServices
and Configure.

// Startup class example


public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)


{
services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
// other middleware components
}
}

99. What is the role of ConfigureServices and Configure method?


In the ConfigureServices method is optional and defined inside startup class as mentioned in above code, you
configure and add services to the Dependency Injection (DI) container. This method is where you register
services like database contexts, authentication, authorization, and other services that your application requires.
Here's what the method does:
✓ Dependency Injection Configuration: It configures the DI container to provide instances of services when
they're requested by other parts of the application. This promotes modularity, reusability, and
testability.
✓ Service Registration: You use this method to register services with their corresponding implementations
or configurations. This is where you add services like Entity Framework contexts, authentication
handlers, and other custom services.
Example:

66
RESTRICTED
RESTRICTED

100. Describe the Service Lifetimes.


✓ Transient - Services with transient lifetime are created each time they are requested from service
container. So, it's best suited for stateless, light weight services.
✓ Scoped - Services with scoped lifetime are created once per connection or client request. When using
scoped service in middleware then inject the service via invoke or invokeAsync method. You should not
inject the service via constructor injection as it treats the service behavior like Singleton.
✓ Singleton - Service with singleton lifetime is created once when first time the service is requested. For
subsequent requests same instance is served by service container.

101. Explain the Middleware in ASP.NET Core.


The Request handling pipeline is a sequence of middleware components where each component performs the
operation on request and either call the next middleware component or terminate the request. When a
middleware component terminates the request, it's called Terminal Middleware as It prevents next middleware
from processing the request. You can add a middleware component to the pipeline by calling .Use... extension
method as below.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

So, Middleware component is program that's build into an app's pipeline to handle the request and response.
Each middleware component can decide whether to pass the request to next component and to perform any
operation before or after next component in pipeline.
102. What is Host in ASP.NET Core?
Host encapsulates all the resources for the app. On startup, ASP.NET Core application creates the host. The
Resources which are encapsulated by the host include:

✓ HTTP Server implementation


✓ Dependency Injection
✓ Configuration
✓ Logging
✓ Middleware components

103. Describe the Generic Host and Web Host.


The host setup the server, request pipeline and responsible for app startup and lifetime management. There are
two hosts:

✓ .NET Generic Host


✓ ASP.NET Core Web Host

67
RESTRICTED
RESTRICTED

.NET Generic Host is recommended and ASP.NET Core template builds a .NET Generic Host on app startup.
ASP.NET Core Web host is only used for backwards compatibility.

// Host creation
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>


WebHost.CreateDefaultBuilder(args)
.UseStartup();
}

104. Describe the Servers in ASP.NET Core.


Server is required to run any application. ASP.NET Core provides an in-process HTTP server implementation to
run the app. This server implementation listen for HTTP requests and surface them to the application as a set of
request features composed into an HttpContext.
ASP.NET Core use the Kestrel web server by default. ASP.NET Core comes with:

✓ Default Kestrel web server that's cross platform HTTP server implementation.
✓ IIS HTTP Server that's in-process server for IIS.
✓ HTTP.sys server that's a Windows-only HTTP server and it's based on the HTTP.sys kernel driver and
HTTP Server API.

105. How to use multiple environments in ASP.NET Core?


ASP.NET Core use environment variables to configure application behavior based on runtime environment.
launchSettings.json file sets ASPNETCORE_ENVIRONMENT to Development on local Machine. For more visit How
to use multiple environments in ASP.NET Core.

106. How Routing works in ASP.NET Core?


Routing is used to handle incoming HTTP requests for the app. Routing find matching executable endpoint for
incoming requests. These endpoints are registered when app starts. Matching process use values from incoming
request url to process the requests. You can configure the routing in middleware pipeline of configure method in
startup class.

app.UseRouting(); // It adds route matching to middlware pipeline

// It adds endpoints execution to middleware pipeline


app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>

68
RESTRICTED
RESTRICTED

{
await context.Response.WriteAsync("Hello World!");
});
});

107. How to handle errors in ASP.NET Core?


ASP.NET Core provides a better way to handle the errors in Startup class as below.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

108. How ASP.NET Core serve static files?


In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are the served directly to the clients.
ASP.NET Core template provides a root folder called wwwroot which contains all these static files.
UseStaticFiles() method inside Startup.Configure enables the static files to be served to client.
You can serve files outside of this webroot folder by configuring Static File Middleware as following.

app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "MyStaticFiles")), // MyStaticFiles is new folder
RequestPath = "/StaticFiles" // this is requested path by client
});
// now you can use your file as below
<img src="/StaticFiles/images/profile.jpg" class="img" alt="A red rose" />
// profile.jpg is image inside MyStaticFiles/images folder

109. Explain Session and State management in ASP.NET Core


As we know HTTP is a stateless protocol. HTTP requests are independent and does not retain user values. There
are different ways to maintain user state between multiple HTTP requests.
✓ Cookies
✓ Session State
✓ TempData
✓ Query strings
✓ Hidden fields
✓ HttpContext.Items
✓ Cache
110. Explain different types of Filters.

69
RESTRICTED
RESTRICTED

Filters provide the capability to run the code before or after the specific stage in request processing pipeline, it
could be either MVC app or Web API service. Filters performs the tasks like Authorization, Caching
implementation, Exception handling etc. ASP.NET Core also provide the option to create custom filters. There
are 5 types of filters supported in ASP.NET Core Web apps or services.

✓ Authorization filters run before all or first and determine the user is authorized or not.
✓ Resource filters are executed after authorization. OnResourceExecuting filter runs the code before
rest of filter pipeline and OnResourceExecuted runs the code after rest of filter pipeline.
✓ Action filters run the code immediately before and after the action method execution. Action filters
can change the arguments passed to method and can change returned result.
✓ Exception filters used to handle the exceptions globally before wrting the response body
✓ Result filters allow to run the code just before or after successful execution of action results
111. What is routing in ASP.NET Core?
Routing is functionality that map incoming request to the route handler. The route can have values (extract
them from the URL) that are used to process the request. Using the route, routing can find a route handler
based on the URL. All the routes are registered when the application is started. There are two types of routing
supported by ASP.NET Core
✓ The conventional routing
✓ Attribute routing
112. What are the various JSON files available in ASP.NET Core?
There are the following JSON files in ASP.NET Core :
✓ global.json
✓ launchsettings.json
✓ appsettings.json
✓ bundleconfig.json
✓ bower.json
✓ package.json
113. What are Razor Pages in ASP.NET Core?
This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric development model just like
ASP.NET web forms. It supports all the features of ASP.NET Core.
Example:
@page
<h1> Hello, Book Reader!</h1>
<h2> This is Razor Pages </h2>

The Razor pages start with the @page directive. This directive handle request directly without passing through
the controller. The Razor pages may have code behind files, but it is not really a code-behind file. It is a class
inherited from PageModel class.
114. What’s the difference between synchronous and asynchronous programming in ASP.NET Core?
✓ Synchronous programming in ASP.NET Core blocks the execution of source code until a task is
completed. In contrast, asynchronous programming allows the execution of code to continue while a
task is being processed in the background.

✓ Asynchronous programming is useful for long-running operations that would otherwise block the
application's main thread, such as reading from a file or making a network request.

70
RESTRICTED
RESTRICTED

✓ Asynchronous programming is typically achieved using the async and await keywords in C#. The async
keyword defines an asynchronous method, which can be called by other code and will run in the
background. The await keyword indicates that the calling code should wait for the asynchronous
method to complete before continuing.

115. How do you implement caching in ASP.NET Core?


Response caching in ASP.NET Core is a technique used to improve the performance and scalability of web
applications by caching the ASP.NET Core MVC responses returned by the server for a specific period. Caching
the response can help reduce the number of requests made to the server, as clients can reuse the cached
response instead of requesting the same resource again.

116. How to access HttpContext in ASP.NET Core?


To access the HttpContext in ASP.NET Core:
✓ Inside a Controller:
Use HttpContext property within a controller action method:
var httpContext = HttpContext;
✓ Inside Middleware:
Include HttpContext as a parameter in the middleware's Invoke method:
public async Task Invoke(HttpContext context)
{
// Access HttpContext here
}
✓ Using Dependency Injection:
Inject IHttpContextAccessor into your class's constructor:
private readonly IHttpContextAccessor _httpContextAccessor;
public YourClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public void YourMethod()


{
var httpContext = _httpContextAccessor.HttpContext;
}
117. What is Distributed caching?
Applications running on multiple servers (Web Farm) should ensure that sessions are sticky. For Non-sticky
sessions, cache consistency problems can occur. Distributed caching is implemented to avoid cache consistency
issues. It offloads the memory to an external process. Distributed caching has certain advantages as below.
✓ Data is consistent across client requests to multiple server
✓ Data keeps alive during server restarts and deployments.
✓ Data does not use local memory

118. Explain the concept of middleware in ASP.NET Core.

71
RESTRICTED
RESTRICTED

Answer: Middleware in ASP.NET Core are components that handle requests and responses. They are executed in
the pipeline sequentially. Middleware can perform tasks like logging, authentication, authorization, and more.
Developers can add, remove, or reorder middleware to customize the request handling process.

119. What is Dependency Injection and why is it important in ASP.NET Core?


Answer: Dependency Injection (DI) is a design pattern used to manage object dependencies and improve code
maintainability. In ASP.NET Core, DI is built-in and helps in loosely coupling components, making testing and
code organization easier.

120. How do you handle routing in ASP.NET Core MVC?


Answer: Routing in ASP.NET Core MVC is configured using the MapRoute method in Startup.cs. It maps URLs to
controller actions. For example:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});

121. What is the difference between Razor Pages and MVC in ASP.NET Core?
Answer: Razor Pages and MVC are both patterns for building web applications. MVC (Model-View-Controller)
separates concerns into distinct components. Razor Pages, on the other hand, emphasizes simpler page-focused
development, where each page can have its own model and handler. MVC is better suited for complex
applications, while Razor Pages are great for simpler scenarios.

122. Describe the main components of an ASP.NET Core application.


Answer: An ASP.NET Core application consists of Models, Views, Controllers (for MVC), Razor Pages (if using
Razor Pages), Startup configuration, Middleware, and Dependency Injection container. It might also include
Entity Framework Core for database access.

123. How do you configure and use authentication and authorization in ASP.NET Core?
Answer: Authentication is configured using services.AddAuthentication() in Startup.cs, with strategies like JWT,
OAuth, etc. Authorization is configured with services.AddAuthorization(), specifying policies and requirements,
which are then applied to controllers or actions using attributes.

124. What is Entity Framework Core and how does it relate to ASP.NET Core?
Answer: Entity Framework Core (EF Core) is an Object-Relational Mapping (ORM) framework for database
access. It allows you to work with databases using .NET objects. EF Core is commonly used with ASP.NET Core to
simplify database operations and data modeling.

125. What is the purpose of the appsettings.json file in ASP.NET Core?


Answer: The appsettings.json file is used to store configuration settings for an ASP.NET Core application. It
provides a structured way to store environment-specific or application-wide settings. These settings can be
accessed using the Configuration object.

72
RESTRICTED
RESTRICTED

126. How does ASP.NET Core handle asynchronous programming, and why is it important?
Answer: ASP.NET Core leverages asynchronous programming to improve scalability and responsiveness. It uses
asynchronous I/O operations to avoid blocking threads, allowing the server to handle more requests
concurrently.

127. Explain the concept of custom middleware in ASP.NET Core. Provide an example.
Answer: Custom middleware are components that you can write and inject into the ASP.NET Core pipeline. They
process requests and responses. An example middleware might log information before and after the request is
handled.
public class MyCustomMiddleware
{
private readonly RequestDelegate _next;

public MyCustomMiddleware(RequestDelegate next)


{
_next = next;
}

public async Task InvokeAsync(HttpContext context)


{
// Code to execute before the request is handled

await _next(context);

// Code to execute after the request is handled


}
}

128. Describe the hosting models for ASP.NET Core applications and when you would use each one (Kestrel, IIS,
etc.).
Answer: ASP.NET Core supports various hosting models like Kestrel, IIS, and others. Kestrel is a cross-platform,
lightweight web server suitable for directly serving ASP.NET Core applications. IIS can act as a reverse proxy to
Kestrel on Windows. Choose the appropriate hosting model based on deployment scenarios and requirements.

129. How can you optimize the performance of an ASP.NET Core application?

Answer: Performance optimization can involve techniques like:

✓ Caching (output caching, data caching)


✓ Minification and bundling of static assets
✓ Asynchronous programming
✓ Database optimization (indexing, query optimization)
✓ Using a content delivery network (CDN)
✓ GZip compression for responses
✓ Properly configuring Dependency Injection to minimize overhead

73
RESTRICTED
RESTRICTED

130. Describe how to deploy an ASP.NET Core application to a production environment.


Answer: Deploying an ASP.NET Core application involves several steps:
✓ Choose an appropriate hosting environment (Kestrel, IIS, Docker, etc.)
✓ Prepare the application for deployment by optimizing performance, configuring settings, and handling
environment-specific configurations.
✓ Build the application using a tool like dotnet publish.
✓ Configure any necessary web server (e.g., IIS) or container (e.g., Docker) settings.
✓ Set up databases and other required services.
✓ Transfer the published files to the production environment.
✓ Monitor and manage the application post-deployment to ensure its health and performance.
131. How can you implement caching in ASP.NET Core to improve performance?

Answer: Caching in ASP.NET Core can be achieved through various mechanisms, including:

✓ In-memory caching using the IMemoryCache interface.


✓ Distributed caching using providers like Redis or SQL Server.
✓ Response caching to cache entire responses.
✓ Output caching to cache the output of specific actions or partial views.
✓ Using caching profiles and attributes to control cache behavior.
132. What is the purpose of the IAuthorizationFilter interface in ASP.NET Core, and how can it be used to
implement custom authorization logic?
Answer: The IAuthorizationFilter interface is part of the ASP.NET Core MVC framework and allows developers to
define custom authorization logic that runs before an action method is executed. It can be used to perform role-
based checks, access validation, or any custom authorization requirements that go beyond the built-in policies.

133. Explain the concept of CORS (Cross-Origin Resource Sharing) in ASP.NET Core and how it can be configured?
Answer: CORS is a security feature that controls how web pages or APIs hosted on one domain can request
resources from another domain. In ASP.NET Core, CORS can be configured using the AddCors method in
Startup.cs, specifying allowed origins, HTTP methods, headers, and more. This ensures that only trusted origins
can access resources on the server.

134. What is the default web server used by ASP.NET Core applications?
Answer: The default web server used by ASP.NET Core applications is Kestrel.

135. What are the key features of the Kestrel web server?
Answer: Kestrel is a cross-platform, lightweight, and high-performance web server. It supports HTTP/1.x and
HTTP/2, has asynchronous I/O capabilities for handling a large number of concurrent connections efficiently, and
can be used as an edge server or behind a reverse proxy.

136. Can you name some other web servers that can be used with ASP.NET Core, besides Kestrel?
Answer: Besides Kestrel, other web servers that can be used with ASP.NET Core include Internet Information
Services (IIS), Apache, and Nginx.

137. What are the steps involved in deploying an ASP.NET Core application using Kestrel?
Answer: Deploying an ASP.NET Core application using Kestrel typically involves:

74
RESTRICTED
RESTRICTED

✓ Building the application using dotnet publish.


✓ Setting up any necessary configuration files and environment variables.
✓ Running the application with the appropriate command, like dotnet myapp.dll.
✓ Configuring a reverse proxy (optional) to handle tasks like SSL termination and load balancing.

138. How can you configure Kestrel options in an ASP.NET Core application?
Answer: Kestrel options can be configured using the WebHostBuilder in the Program.cs file. You can set options
such as listening endpoints, SSL certificates, maximum connections, and more. For more advanced
configuration, you can access the KestrelServerOptions directly.

139. What is Redis caching, and why is it beneficial for ASP.NET Core applications?
Answer: Redis caching is a high-performance, distributed, in-memory data store. It serves as a key-value cache
that stores frequently used data in memory, providing fast access and reducing the load on the database. In
ASP.NET Core, Redis caching improves application performance by reducing data retrieval times and enhancing
scalability.

140. How does Redis caching work in ASP.NET Core?


Answer: In ASP.NET Core, Redis caching involves storing data in a Redis server's memory. When a request is
made for cached data, the application checks Redis first. If the data exists, it's retrieved from Redis. If not, the
application retrieves the data from the original source, stores it in Redis, and returns it to the user.

141. How can you configure and use Redis caching in an ASP.NET Core application?
Answer: To use Redis caching in ASP.NET Core, you need to:
✓ Install the StackExchange.Redis NuGet package.
✓ Configure the Redis connection in the appsettings.json file.
✓ Add Redis caching services in Startup.cs using services.AddDistributedRedisCache().

142. What is MongoDB, and why might it be a suitable choice for data storage in ASP.NET Core applications?
Answer: MongoDB is a NoSQL database that stores data in a flexible, schema-less document format. It's suitable
for ASP.NET Core applications that require high flexibility and scalability, as it allows developers to store and
retrieve complex, unstructured data without adhering to a rigid schema.

143. What is the purpose of the wwwroot folder in an ASP.NET Core project?
Answer: The wwwroot folder is where static files like CSS, JavaScript, and images are stored. These files are
served directly to clients without any processing.

144. How can you publish an ASP.NET Core application for deployment?
Answer: You can publish an ASP.NET Core application using the dotnet publish command, which compiles the
application and its dependencies into a deployable package.

145. What is the role of the appsettings.json file in ASP.NET Core?


Answer: The appsettings.json file is used to store application configuration settings. It can be accessed using the
Configuration object and is often used for storing connection strings, API keys, and other settings.

146. How can you pass data from a controller action to a view in ASP.NET Core?

75
RESTRICTED
RESTRICTED

Answer: Data can be passed from a controller to a view using a model. In the controller action, you create an
instance of the model, populate it with data, and pass it to the view using the return View(model) statement.

147. How can you handle HTTP GET and POST requests in ASP.NET Core?
Answer: HTTP GET requests are typically handled by controller action methods decorated with [HttpGet]
attributes. HTTP POST requests are handled similarly using [HttpPost] attributes.

148. What is the role of the Startup class in an ASP.NET Core application?
Answer: The Startup class is used to configure services and the application's request pipeline, including
middleware, routing, and dependency injection.

149. What is the purpose of the ModelState object in ASP.NET Core?


Answer: ModelState is used to track the state of model binding and validation. It helps handle and display
validation errors in views.
150. What is the default route template in an ASP.NET Core application?
Answer: The default route template is "{controller=Home}/{action=Index}/{id?}", which maps to the
HomeController's Index action by default.

151. How can you manage environment-specific configuration in an ASP.NET Core application?
Answer: Environment-specific configuration can be managed using the appsettings.json file along with
appsettings.{Environment}.json files, where {Environment} is the current environment name (e.g.,
appsettings.Production.json).

152. What is the purpose of the [HttpGet] and [HttpPost] attributes in controller actions?
Answer: [HttpGet] and [HttpPost] attributes specify the HTTP verb that the action should respond to. They allow
you to define separate methods for handling GET and POST requests.

153. How can you enable logging in an ASP.NET Core application?


Answer: Logging can be enabled by configuring logging providers in the appsettings.json file and using the built-
in ILogger interface to log messages from various parts of the application.

154. What is the purpose of the IActionResult interface in ASP.NET Core actions?
Answer: IActionResult is used to represent the result of an action method. It allows you to return different types
of results, such as views, JSON data, redirects, and more.

155. What is the purpose of the [FromBody] attribute in a controller action parameter?
Answer: The [FromBody] attribute indicates that the parameter value should be bound from the request body in
API controller actions.

156. What is the purpose of the ModelState.IsValid property in ASP.NET Core?


Answer: The ModelState.IsValid property is used to check if the model passed to the action has passed
validation rules.

157. What is the purpose of the [Authorize] attribute in ASP.NET Core?


Answer: The [Authorize] attribute is used to restrict access to controller actions to authenticated users only.

76
RESTRICTED
RESTRICTED

158. What is the purpose of Razor View Components in ASP.NET Core?


Answer: Razor View Components are reusable chunks of Razor markup and C# logic that can be included in
views to render dynamic content.

159. What is the purpose of the [ValidateAntiForgeryToken] attribute in ASP.NET Core?


Answer: The [ValidateAntiForgeryToken] attribute is used to prevent cross-site request forgery (CSRF) attacks by
ensuring that form submissions include a valid anti-forgery token.

160. How can you return a JSON response from an ASP.NET Core controller action?
Answer: You can return a JSON response using the Json() method in a controller action, passing the data you
want to serialize as a parameter.

161. What is the purpose of the AllowAnonymous attribute in ASP.NET Core?


Answer: The [AllowAnonymous] attribute is used to allow anonymous access to specific controller actions, even
when global authorization policies are applied.

162. What is the difference between asynchronous and synchronous programming in ASP.NET Core?
Answer: Synchronous programming blocks the execution of code until a task is complete, while asynchronous
programming allows the code to continue executing while waiting for a task to finish.

163. Why is asynchronous programming important in ASP.NET Core applications?


Answer: Asynchronous programming improves the scalability and responsiveness of applications by allowing
threads to be released while waiting for I/O operations, thus making better use of resources.

164. How can you define an asynchronous method in C#?


Answer: An asynchronous method is defined using the async keyword in the method signature, and it returns a
Task or Task<T> representing the asynchronous operation.

165. What is the difference between async and await in asynchronous programming?
Answer: async is used to declare a method as asynchronous, while await is used to indicate a point where the
method can asynchronously wait for a task to complete.

166. How can you implement asynchronous controllers in ASP.NET Core?


Answer: To implement an asynchronous controller, define action methods with the async keyword, use
asynchronous APIs, and return Task<IActionResult> or other appropriate async types.

167. What is threading in the context of ASP.NET Core?


Answer: Threading refers to the concurrent execution of multiple tasks or operations within an ASP.NET Core
application, allowing efficient utilization of CPU resources.

168. What is multithreading, and how does it relate to concurrency in ASP.NET Core?
Answer: Multithreading is the concurrent execution of multiple threads within a single process. In ASP.NET Core,
multithreading allows the application to handle multiple requests simultaneously, improving concurrency.

77
RESTRICTED
RESTRICTED

169. What is a View Component in ASP.NET Core?


Answer: A View Component is a reusable component in ASP.NET Core that encapsulates both logic and view
rendering. It's used to render dynamic content within views.

170. How can you create and use a View Component in ASP.NET Core?
Answer: To create a View Component, you create a class derived from ViewComponent. You can invoke it within
a view using the @await Component.InvokeAsync("ComponentName") syntax.

ASP.NET Core - Authorization & Authentication


Overview: In .NET Core, authentication and authorization work together to create secure applications. Authentication
verifies user identity, while authorization controls access to resources based on user roles, claims, or policies. The built-
in middleware, identity providers, and flexible authorization mechanisms make it possible to implement a wide range of
security scenarios in your applications.

Authentication: Authentication is the process of verifying the identity of a user, typically through credentials like a
username and password. .NET Core provides a robust authentication framework that supports various authentication
methods and external identity providers.

✓ Authentication Middleware: .NET Core includes authentication middleware that can handle various
authentication schemes, such as cookies, tokens, and more. Middleware intercepts incoming requests and
handles authentication logic.
✓ Identity Providers: You can integrate with external identity providers like OAuth, OpenID Connect, or external
identity systems like Azure Active Directory. This enables users to log in using their existing accounts from other
services.
✓ Claim-Based Identity: .NET Core uses claims to represent user identities. Claims are statements about the user,
such as their roles, name, or email. Claims-based authentication is flexible and allows you to make access control
decisions based on these claims.

Authorization: Authorization is the process of determining whether an authenticated user has the necessary permissions
to access a particular resource or perform a specific action within an application.

✓ Policy-Based Authorization: .NET Core provides policy-based authorization, where you define authorization
policies that dictate who can access specific resources based on user roles or claims.
✓ Authorization Middleware: Similar to authentication middleware, .NET Core has authorization middleware that
examines incoming requests and checks whether the user has the required permissions based on the defined
policies.
✓ Roles and Claims: You can use roles and claims to manage authorization. Roles represent groups of users with
specific permissions, while claims can be used to make fine-grained authorization decisions based on attributes.
✓ Attribute-Based Authorization: You can apply authorization attributes to controllers and actions to specify who
can access them. For example, the [Authorize] attribute restricts access to authenticated users.

Combining Authentication and Authorization: Authentication and authorization often go hand in hand. Once a user is
authenticated, authorization determines what they're allowed to do within the application.

✓ Policy-Based Authentication: You can use authentication policies to enforce specific authentication requirements
before authorization policies are evaluated. For example, ensuring a user is authenticated with a specific identity
provider.
78
RESTRICTED
RESTRICTED

✓ Custom Requirements: You can create custom authorization requirements and handlers to implement complex
authorization scenarios that go beyond simple roles or claims.

Sample Questionnaires on ASP.NET Core - Authorization & Authentication

171. What's the key difference between authentication and authorization in .NET Core?
Answer: Authentication verifies the identity of a user, while authorization controls what actions or resources a
user is allowed to access.

172. What's the purpose of the AllowAnonymous attribute in .NET Core authentication?
Answer: The AllowAnonymous attribute overrides any global or controller-level authorization policies, allowing
anonymous access to specific actions or controllers.
173. How can you implement OAuth-based authentication in a .NET Core application?
Answer: You can use middleware like AddOAuth or AddOpenIdConnect to integrate OAuth-based authentication.
Configure the client and identity provider details to enable OAuth authentication.

174. What is the purpose of a JWT (JSON Web Token) in authentication?


Answer: A JWT is a compact, self-contained token that carries user information and claims. It's commonly used
for authentication and can be used to securely transmit user data between parties.

175. Explain the difference between role-based and claim-based authorization.


Answer: Role-based authorization restricts access based on predefined user roles, while claim-based authorization
evaluates permissions based on specific claims associated with the user.

176. How do you implement policy-based authorization in .NET Core?


Answer: Define authorization policies using the AuthorizationPolicy class, then apply these policies using
attributes like [Authorize] or in middleware during request processing.

177. What's the purpose of an authentication handler in .NET Core?


Answer: An authentication handler processes authentication-related tasks, such as validating credentials or
extracting user information from tokens, allowing you to support various authentication methods.

178. Can you explain the concept of "bearer token" in token-based authentication?
Answer: A bearer token is a token included in the request header that grants access to a protected resource. It's
used in token-based authentication to authenticate and authorize API requests.

79
RESTRICTED
RESTRICTED

179. How can you customize the behavior of the [Authorize] attribute for specific actions?
Answer: You can use the [Authorize] attribute with policy names, like [Authorize(Policy = "CustomPolicy")], to
enforce custom authorization rules on specific actions.

180. Explain how you can handle authentication and authorization for API endpoints in a .NET Core application.
Answer: Use authentication middleware to validate user identity, and then apply authorization policies to
controllers or actions using attributes like [Authorize]. This ensures that only authenticated and authorized users
can access the API endpoints.

181. How can you implement two-factor authentication in a .NET Core application?
Answer: You can use the built-in SignInManager to implement two-factor authentication by adding an additional
layer of verification, such as a code sent to the user's email or phone.

ASP.NET Core – Configuration


In .NET Core, configuration refers to the process of setting up and managing various settings and options for your
application. It allows you to separate configuration from your application code, making it more flexible and easier to
manage across different environments.

Here's an overview of how configuration works in .NET Core:

Configuration Providers: Configuration data in .NET Core is provided by configuration providers. These providers
retrieve configuration values from different sources such as environment variables, JSON files, XML files, command-line
arguments, and more. Providers are used to load configuration data into your application.

Configuration Hierarchy: The configuration framework in .NET Core supports a hierarchical structure. Configuration
values are resolved in a specific order, allowing you to override settings at different levels. The hierarchy typically
includes:

Built-in Defaults: Default values are provided by the framework.

✓ appsettings.json: A JSON file where you can store configuration settings. It supports hierarchical structures for
easy organization.
✓ appsettings.{Environment}.json: JSON files for specific environments, allowing you to override settings based on
the environment.
✓ Environment Variables: Configuration values can be sourced from environment variables.
✓ Command-Line Arguments: You can pass configuration values through command-line arguments when running
your application.

Configuration API: .NET Core provides an API to access configuration values in your application. The IConfiguration
interface and its associated classes allow you to read configuration values and bind them to strongly typed objects.

Options Pattern: The Options pattern in .NET Core allows you to define strongly typed classes to represent different
sections of your configuration data. This makes it easier to work with configuration values and provides better type
safety.
80
RESTRICTED
RESTRICTED

Dependency Injection: The configuration framework integrates seamlessly with the .NET Core dependency injection
system. You can inject configuration values into your services and components using constructor injection.

Reloadable Configuration: .NET Core configuration supports automatic reloading of configuration values when they
change. This is particularly useful for scenarios where you want your application to respond dynamically to configuration
updates without restarting.

Secure Configuration: Sensitive configuration data, such as connection strings or API keys, can be stored securely using
user secrets or environment-specific configuration files.

Sample Questionnaires on ASP.NET Core – Configuration:


182. What is the recommended approach for passing configuration values through command-line arguments in .NET
Core?
Answer: Command-line arguments can be used to override configuration values during application startup. The
args parameter of the Main method can be processed using libraries like
Microsoft.Extensions.CommandLineUtils, allowing developers to parse and apply command-line configuration
overrides.
183. How does .NET Core handle environment-specific configuration settings?
Answer: .NET Core supports environment-specific configuration settings by allowing the use of configuration
files with names like appsettings.{Environment}.json. The appropriate file is loaded based on the application's
runtime environment, providing a mechanism to tailor configuration settings for different deployment
scenarios.
184. Could you describe the process of binding configuration values to strongly typed objects?
Answer: Binding configuration values to strongly typed objects involves defining a class with properties that
represent the desired configuration values. By using the IConfiguration API and its GetSection method, the
configuration data is mapped to the class properties, providing type-safe access to the values.
185. How do you dynamically reload configuration values in a running .NET Core application?
Answer: .NET Core supports dynamic configuration reloading through the use of the IOptionsMonitor interface.
When configuration values change, the application can be notified, allowing it to update its behavior without
requiring a restart.
186. What is the role of dependency injection in .NET Core configuration?
Answer: Dependency injection (DI) in .NET Core configuration allows configuration values to be injected into
services and components. This enhances modularity and testability, enabling services to access configuration
values without directly referencing the configuration framework.

81
RESTRICTED
RESTRICTED

187. What is the purpose of configuration in .NET Core applications?


Answer: Configuration in .NET Core applications serves to separate customizable settings and options from the
application code. It allows developers to modify behavior and parameters without changing code, enhancing
flexibility and adaptability across various environments.

188. Can you explain the differences between transient, scoped, and singleton lifetimes in dependency injection?
Answer: Transient lifetime creates a new instance of a dependency every time it's requested, scoped lifetime
creates a single instance per scope (e.g., per HTTP request), and singleton lifetime creates a single instance for
the entire application's lifespan. Choosing the appropriate lifetime is crucial to managing resource usage and
object state.
189. What is the purpose of named or keyed registrations in dependency injection?
Answer: Named or keyed registrations allow you to register multiple implementations of the same interface or
base class under different names or keys. This is useful when you need to differentiate between different
implementations and select the appropriate one dynamically based on runtime conditions.
190. What is the role of the ServiceProviderFactory in .NET Core dependency injection?
Answer: The ServiceProviderFactory is responsible for creating and configuring the IServiceProvider instance
that manages the application's dependencies. It allows you to customize the DI container's behavior, such as
adding additional services or modifying the default registrations.
191. How can you control disposal of IDisposable objects created through dependency injection?
Answer: You can control the disposal of IDisposable objects by specifying their lifetimes appropriately. For
example, with a scoped or request-specific lifetime, IDisposable objects will be automatically disposed of at the
end of the scope or request.
192. What is the difference between compile-time and runtime DI containers?
Answer: Compile-time DI containers perform dependency resolution and object creation at compile time, often
using code generation. Runtime DI containers resolve dependencies at runtime, typically using reflection.
Compile-time containers offer performance advantages and early error detection, while runtime containers
offer more flexibility.
193. What are some potential drawbacks or challenges of using dependency injection?
Answer: Some challenges include increased complexity in large projects, potential performance overhead due to
reflection or container setup, and difficulties in handling complex object graphs or circular dependencies. Proper
design and understanding of DI principles can help mitigate these challenges.
194. How can you configure Redis caching in a .NET Core application?
Answer: You can configure Redis caching by adding the Microsoft.Extensions.Caching.StackExchangeRedis
package, registering the RedisCache service in Startup.cs, and specifying the Redis server connection details in
your configuration.

195. What is the purpose of using Redis as a distributed cache in .NET Core?
Answer: Redis serves as a fast and scalable in-memory data store. It can be used as a distributed cache to
improve application performance by reducing the load on the primary data store and providing low-latency
access to frequently accessed data.
196. How can you handle cache expiration and eviction policies in Redis caching?
Answer: In Redis caching, you can set cache expiration using the Set method with a TimeSpan. Redis also
supports eviction policies, such as LRU (Least Recently Used) and LFU (Least Frequently Used), which can be
configured to automatically remove items when the cache reaches a certain size.

82
RESTRICTED
RESTRICTED

197. What are the potential challenges or considerations when using Redis caching?
Answer: Some challenges include ensuring data consistency between the cache and the primary data store,
handling cache misses efficiently, and monitoring the cache's memory usage and performance.
198. How can you configure MongoDB in a .NET Core application?
Answer: To configure MongoDB, you need to install the MongoDB.Driver package, set up the connection string
in your appsettings.json, and register the IMongoClient service in Startup.cs.
199. What is the primary benefit of using MongoDB in a .NET Core application?
Answer: MongoDB is a NoSQL database that provides flexibility in storing and querying data. It's suitable for
scenarios where the data structure is dynamic and may evolve over time.
200. How can you perform CRUD operations using the MongoDB driver in .NET Core?
Answer: The MongoDB driver provides methods for CRUD operations. For example, you can use the
InsertOneAsync, Find, UpdateOneAsync, and DeleteOneAsync methods to create, read, update, and delete
documents.
201. How can you model relationships between documents in MongoDB?
Answer: MongoDB supports embedded documents and references for modeling relationships. You can embed
one document within another or use references (such as ObjectId references) to link documents in separate
collections.

ASP.NET Core - Logging and Monitoring


Logging and monitoring are crucial aspects of any software application, including those built using ASP.NET Core. They
help you track and analyze the behavior of your application, diagnose issues, and ensure its overall health and
performance. In ASP.NET Core, logging and monitoring can be achieved through various mechanisms and tools. Here's an
overview of how you can set up logging and monitoring in an ASP.NET Core application:

Logging in ASP.NET Core: ASP.NET Core provides a flexible and extensible logging framework that allows you to capture
various types of log information and route it to different targets. Here's how you can set up logging in your ASP.NET Core
application:

✓ Logging Providers: ASP.NET Core supports various logging providers such as Console, Debug, EventLog,
TraceSource, and more. You can choose one or more providers to which you want to route your log messages.
✓ Logging Levels: Log messages are categorized into different levels such as Information, Warning, Error, and
Critical. You can control which log levels are captured and displayed based on your application's needs.
✓ Logging Configuration: Logging configuration can be done in the appsettings.json or
appsettings.Development.json files. You can specify the logging levels, providers, and their settings in these
configuration files.

83
RESTRICTED
RESTRICTED

✓ Logging Middleware: ASP.NET Core also offers a logging middleware that can log requests and responses,
making it useful for diagnosing issues related to incoming HTTP requests.

Monitoring in ASP.NET Core: Monitoring involves tracking the health, performance, and usage of your application in
real-time. Here are some steps to set up monitoring in your ASP.NET Core application:

✓ Application Insights: Application Insights is a powerful monitoring and telemetry service provided by Microsoft.
It allows you to collect data about your application's usage, performance, and more. You can integrate
Application Insights into your ASP.NET Core application using its SDK.
✓ Health Checks: ASP.NET Core includes a health checking framework that enables you to define custom health
checks for various components of your application. These health checks can be used to determine the overall
health of your application and its dependencies.
✓ Metrics Collection: You can use third-party libraries or frameworks like Prometheus.NET to collect and expose
metrics from your application. These metrics can help you monitor performance and resource utilization.
✓ Distributed Tracing: Distributed tracing tools like OpenTelemetry can help you track the flow of requests across
various services in a microservices architecture, allowing you to identify bottlenecks and latency issues.
✓ Error Tracking: Integrating error tracking tools like Sentry or Raygun can help you capture and analyze
application errors in real-time.

Sample Questionnaires on ASP.NET Core - Logging and Monitoring:


202. What are the advantages of using structured logging over traditional plain-text logging in ASP.NET Core?
Answer: Structured logging provides more context and flexibility compared to plain-text logging. It allows you to
log data in a structured format, such as JSON, making it easier to search, filter, and analyze logs. This is especially
useful in distributed systems and microservices architectures. Structured logs also enable better integration with
log aggregation tools, like ELK Stack (Elasticsearch, Logstash, Kibana), as they can parse and index the structured
data efficiently.
203. How can you create custom log levels in ASP.NET Core logging? Provide an example.
Answer: In ASP.NET Core, you can create custom log levels by extending the LogLevel enumeration and
configuring the logging system to recognize these levels.
204. How can you implement request-response logging in ASP.NET Core using Middleware?
84
RESTRICTED
RESTRICTED

Answer: You can implement request-response logging using a custom Middleware in ASP.NET Core.
205. Explain the concept of distributed tracing. How can you implement it in an ASP.NET Core microservices
architecture?
Answer: Distributed tracing is the practice of tracking requests as they flow through a distributed system,
allowing you to monitor the interactions between different services. In ASP.NET Core microservices architecture,
you can implement distributed tracing using tools like OpenTelemetry.

OpenTelemetry provides instrumentation libraries that you can add to your services to capture trace data. These
libraries generate unique trace IDs for each request and annotate them with context information. Trace data is
then collected by tracing backends like Jaeger or Zipkin for visualization and analysis.
206. How can you implement health checks in ASP.NET Core, and why are they important for monitoring?
Answer: Health checks are used to determine the operational status of different components of your
application. They are important for monitoring because they provide insights into the overall health of your
application and its dependencies. In ASP.NET Core, you can implement health checks by:
✓ Creating health check classes that implement the IHealthCheck interface.
✓ Registering these health checks in the ConfigureServices method using services.AddHealthChecks().
✓ Adding the health check endpoints to your application using app.UseHealthChecks() in the Configure
method.
Health checks can be used to monitor the availability of databases, third-party APIs, and other components,
ensuring that your application operates smoothly.

207. Explain the concept of log enrichment in ASP.NET Core. How can you achieve it?
Answer: Log enrichment involves adding additional contextual information to log entries to provide more insights
into the application's behavior. This is often used to enhance troubleshooting and analysis. In ASP.NET Core, you
can achieve log enrichment by implementing custom log enrichers. These enrichers can access the LogEvent and
add properties or data to it before it's written to the log. This is particularly useful for adding user-related
information, request-specific data, or environment details.

208. What is the purpose of log correlation IDs, and how can you implement them in ASP.NET Core?
Answer: Log correlation IDs are unique identifiers that are attached to logs related to a specific request or
transaction. They allow you to trace a series of log entries back to a single action or event, even in distributed
systems. In ASP.NET Core, you can implement log correlation IDs by generating a unique identifier for each request
and adding it to the log context. This identifier can be stored in the HttpContext or generated as part of a
middleware, and then included in every log entry related to that request.

209. How can you handle and log unhandled exceptions globally in an ASP.NET Core application?
Answer: To handle and log unhandled exceptions globally in an ASP.NET Core application, you can use the
IExceptionHandler middleware. This middleware catches exceptions that occur during the request processing
pipeline and logs them.

210. What are some challenges you might face when monitoring a containerized ASP.NET Core application in a
Kubernetes cluster?
Answer: Monitoring containerized ASP.NET Core applications in a Kubernetes cluster presents some unique
challenges due to the dynamic and distributed nature of container orchestration. Challenges include:

85
RESTRICTED
RESTRICTED

✓ Service Discovery: Ensuring that logs and metrics from all instances of the application are correctly
aggregated and monitored.
✓ Ephemeral Nature: Containers can be created and destroyed dynamically, requiring a solution to capture
logs and metrics before containers are terminated.
✓ Resource Isolation: Ensuring that monitoring tools don't consume excessive resources within the
containers.
✓ Networking Complexity: Handling networking challenges when dealing with services and pods in
Kubernetes, especially in distributed tracing scenarios.
Solutions often involve integrating with Kubernetes-native monitoring and logging tools, such as Prometheus for
metrics and Grafana for visualization.

211. Question: Describe the concept of log sampling. When might you use it, and how can you implement it in ASP.NET
Core?
Answer: Log sampling involves selectively capturing and recording only a portion of log entries, rather than
capturing every single log event. This can help reduce the volume of logs generated in high-traffic applications
while still providing a representative sample for analysis. Log sampling might be used when you want to balance
the need for insights with the performance impact of extensive logging. In ASP.NET Core, you can implement log
sampling by adding custom logic to decide whether a log entry should be recorded based on predefined criteria,
such as a random chance or certain conditions being met.

ASP.NET Core - Middleware


Middleware in ASP.NET Core is a crucial component that enables you to process requests and responses as they flow
through the ASP.NET Core request pipeline. Middleware components are executed in a specific order, allowing you to

86
RESTRICTED
RESTRICTED

build a series of processing steps to handle various tasks, such as authentication, routing, logging, and more. Each
middleware component can modify the request or response or even short-circuit the pipeline.

In other words, it’s the layer that every request and response have to go through.

I. Middleware Components: Middleware components are classes that handle specific tasks in the request pipeline.
They can be built-in ASP.NET Core middleware or custom middleware that you define. Examples of built-in
middleware include authentication, static files handling, and routing.
II. Order of Execution: Middleware components are executed in the order they are added to the pipeline. The order
is significant because the output of one middleware becomes the input for the next. The first middleware is closest
to the client, while the last middleware is closest to the application.
III. Middleware Configuration: Middleware components are added to the pipeline during application startup in the
Configure method of the Startup class. The Use extension methods are used to add and configure middleware.
IV. Request and Response Processing: Middleware can modify the incoming request and its context or modify the
outgoing response. This allows you to manipulate headers, content, or any other aspect of the request and
response.
V. Short-Circuiting the Pipeline: Middleware components can decide to stop processing and return a response
without invoking subsequent middleware. This can be useful for implementing authentication checks or handling
specific scenarios.
VI. Chaining Middleware: Middleware can be chained together to build complex processing flows. The output of one
middleware becomes the input for the next, allowing you to compartmentalize and modularize your application's
logic.
VII. Custom Middleware: You can create custom middleware by implementing the IMiddleware interface or using the
UseMiddleware<T> extension method. This enables you to add application-specific logic to the pipeline.

Middleware order: The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and
Razor Pages apps. You can see how, in a typical app, existing middlewares are ordered and where custom middlewares
are added. You have full control over how to reorder existing middlewares or inject new custom middlewares as necessary
for your scenarios.

87
RESTRICTED
RESTRICTED

Built-in middleware

ASP.NET Core ships with the following middleware components. The Order column provides notes on middleware
placement in the request processing pipeline and under what conditions the middleware may terminate request
processing.

Middleware Description Order

Authentication Provides authentication support. Before HttpContext.User is needed. Terminal for OAuth
callbacks.

Authorization Provides authorization support. Immediately after the Authentication Middleware.

Cookie Policy Tracks consent from users for Before middleware that issues cookies. Examples:
storing personal information and Authentication, Session, MVC (TempData).
enforces minimum standards for
cookie fields, such
as secure and SameSite.

CORS Configures Cross-Origin Resource Before components that use CORS. UseCors currently must
Sharing. go before UseResponseCaching due to this bug.

DeveloperExceptionPage Generates a page with error Before components that generate errors. The project
information that is intended for templates automatically register this middleware as the
use only in the Development first middleware in the pipeline when the environment is
environment. Development.

Diagnostics Several separate middlewares Before components that generate errors. Terminal for
that provide a developer exceptions or serving the default web page for new apps.
exception page, exception
handling, status code pages, and
the default web page for new
apps.

Forwarded Headers Forwards proxied headers onto Before components that consume the updated fields.
the current request. Examples: scheme, host, client IP, method.

Health Check Checks the health of an ASP.NET Terminal if a request matches a health check endpoint.
Core app and its dependencies,
such as checking database
availability.

Header Propagation Propagates HTTP headers from


the incoming request to the
outgoing HTTP Client requests.

88
RESTRICTED
RESTRICTED

Middleware Description Order

HTTP Logging Logs HTTP Requests and At the beginning of the middleware pipeline.
Responses.

HTTP Method Override Allows an incoming POST request Before components that consume the updated method.
to override the method.

HTTPS Redirection Redirect all HTTP requests to Before components that consume the URL.
HTTPS.

HTTP Strict Transport Security enhancement Before responses are sent and after components that
Security (HSTS) middleware that adds a special modify requests. Examples: Forwarded Headers, URL
response header. Rewriting.

MVC Processes requests with Terminal if a request matches a route.


MVC/Razor Pages.

OWIN Interop with OWIN-based apps, Terminal if the OWIN Middleware fully processes the
servers, and middleware. request.

Output Caching Provides support for caching Before components that require caching. UseRouting must
responses based on configuration. come before UseOutputCaching. UseCORS must come
before UseOutputCaching.

Response Caching Provides support for caching Before components that require caching. UseCORS must
responses. This requires client come before UseResponseCaching. Is typically not
participation to work. Use output beneficial for UI apps such as Razor Pages because
caching for complete server browsers generally set request headers that prevent
control. caching. Output caching benefits UI apps.

Request Decompression Provides support for Before components that read the request body.
decompressing requests.

Response Compression Provides support for compressing Before components that require compression.
responses.

Request Localization Provides localization support. Before localization sensitive components. Must appear
after Routing Middleware when
using RouteDataRequestCultureProvider.

Endpoint Routing Defines and constrains request Terminal for matching routes.
routes.

SPA Handles all requests from this Late in the chain, so that other middleware for serving
point in the middleware chain by static files, MVC actions, etc., takes precedence.
returning the default page for the
Single Page Application (SPA)

89
RESTRICTED
RESTRICTED

Middleware Description Order

Session Provides support for managing Before components that require Session.
user sessions.

Static Files Provides support for serving static Terminal if a request matches a file.
files and directory browsing.

URL Rewrite Provides support for rewriting Before components that consume the URL.
URLs and redirecting requests.

W3CLogging Generates server access logs in At the beginning of the middleware pipeline.
the W3C Extended Log File
Format.

WebSockets Enables the WebSockets protocol. Before components that are required to accept WebSocket
requests.

Sample Questionnaires on ASP.NET Core Middleware:


212. What's the difference between terminal and non-terminal middleware in .NET Core?
Answer: Terminal middleware are the last components in the pipeline and they don't call the next middleware.
They generate the final response to the client. Non-terminal middleware call the next middleware in the pipeline
after processing the request.

213. Can you give an example scenario where you would use custom middleware?
Answer: Custom middleware can be used for various scenarios, such as logging, authentication, authorization,
error handling, request/response transformation, and more. For example, you might create custom logging
middleware to log request details for troubleshooting.

214. How does the ApplicationBuilder class relate to middleware in .NET Core?
Answer: The ApplicationBuilder class is used to build the request processing pipeline by adding middleware
components. Middleware components are added in the Configure method of the Startup class using the Use
extension methods.

215. What is the purpose of the next parameter in a middleware component's Invoke method?
Answer: The next parameter in a middleware component's Invoke method allows you to call the next middleware
in the pipeline. If you omit calling next, the pipeline will be short-circuited, and subsequent middleware won't be
executed.

216. What is the purpose of the Map and MapWhen methods in the ApplicationBuilder class?
Answer: The Map and MapWhen methods allow you to conditionally branch the request pipeline based on certain
criteria. Map maps a subpath to a branch of the pipeline, and MapWhen conditionally runs a branch of the pipeline
based on a predicate.

90
RESTRICTED
RESTRICTED

217. Explain the concept of endpoint routing in .NET Core. How does it relate to middleware?
Answer: Endpoint routing is a pattern for routing requests to different parts of your application. It's responsible
for mapping incoming requests to specific endpoints (controllers/actions) based on the route templates.
Middleware in ASP.NET Core can be configured to run before or after endpoint routing, allowing you to apply
processing logic at different stages of request handling.

218. How can you share data between middleware components?


Answer: You can share data between middleware components using the HttpContext object's Items collection.
This collection is available throughout the entire request pipeline and allows you to pass data from one
middleware to another within the same request.

219. How would you handle exception handling in custom middleware?


Answer: To handle exceptions in custom middleware, you can use a try-catch block around the next() call in the
Invoke method. If an exception occurs, you can choose to log the error, modify the response, or even rethrow the
exception based on your application's requirements.

220. How can you implement caching using middleware in .NET Core?
Answer: You can implement caching using middleware by creating custom middleware that checks whether the
requested resource is in the cache. If it's present, the middleware can return the cached response, otherwise, it
can pass the request down the pipeline, capture the response, and store it in the cache for future requests.

221. Explain the concept of short-circuiting the middleware pipeline. When and why would you use it?
Answer: Short-circuiting the middleware pipeline means stopping the execution of further middleware
components and immediately responding to the client. You might use this when you have specific conditions that
require an early response without going through the entire pipeline. For instance, you could use short-circuiting
for authentication checks to avoid processing unnecessary middleware for unauthorized requests.

222. Can you have middleware components within Razor Pages or MVC actions?
Answer: Yes, you can execute middleware components within Razor Pages or MVC actions by using the await
next.Invoke() call within the middleware's Invoke method. However, it's not a common practice, as middleware is
typically added to the pipeline using the Use methods in the Startup class.

223. How can you share dependencies, such as services, between different middleware components?
Answer: Middleware components can share dependencies through the HttpContext.RequestServices property,
which provides access to the application's dependency injection container. You can retrieve services from the
container using this property.

224. How would you handle streaming responses or large files in a middleware component?
Answer: Middleware can handle streaming responses by using the Response.Body stream. For large files, you
could use the TransmitFileAsync method or read/write chunks of data to the response stream while allowing the
application to be responsive.

225. What are the considerations when using middleware in a multithreaded environment?

91
RESTRICTED
RESTRICTED

Answer: Middleware components should be thread-safe since they might be executed concurrently by multiple
threads. Avoid using shared state within the middleware unless it's properly synchronized. If necessary, use
dependency injection to create new instances of services per request to avoid thread-safety issues.

226. How do you handle middleware ordering when using multiple routers, like MVC and Razor Pages?
Answer: Middleware order matters across routers. When using multiple routers, ensure that middleware affecting
routing is placed before the routers in the pipeline. Also, be cautious with the order of terminal middleware, as
they might affect the responses generated by the routers.

227. What is terminal middleware?


Answer: When a middleware short-circuits the request processing pipeline and prevents further downstream
middleware from processing a request, it's called a terminal middleware.

ASP.NET Core - Host


In ASP.NET Core, the term "Host" refers to the mechanism that's responsible for setting up and managing the application's
execution environment. The host is an integral part of ASP.NET Core's design, and it's used to configure various aspects of
the application, such as dependency injection, configuration, logging, and more. There are two main types of hosts in
ASP.NET Core:

✓ Generic Host: The Generic Host is used for hosting non-HTTP services, such as background tasks, worker services,
and console applications. It's introduced in ASP.NET Core 3.0 and provides a consistent way to configure and run
background services using the same concepts as the web host. It's part of the Microsoft.Extensions.Hosting
namespace.
✓ Web Host: The Web Host is used for hosting ASP.NET Core web applications. It handles HTTP requests, routing,
middleware, and other web-related concerns. The Web Host is part of the Microsoft.AspNetCore.Hosting
namespace.

Both types of hosts share similar concepts, such as configuring services through dependency injection and setting up
application configuration. The host also manages the application's lifetime, including starting and stopping services.

Sample Questionnaires on ASP.NET Core – HOST:


228. What is the purpose of a host in ASP.NET Core?
Answer: The host in ASP.NET Core provides an environment for running and managing applications. It offers
services like dependency injection, configuration, and application lifetime management.

229. What's the difference between a Generic Host and a Web Host in ASP.NET Core?

92
RESTRICTED
RESTRICTED

Answer: The Generic Host is used for hosting non-HTTP services like background tasks, while the Web Host is
specifically designed for hosting web applications with HTTP endpoints.

230. What namespace is commonly used for working with hosting in ASP.NET Core?
Answer: For the Generic Host, you use the Microsoft.Extensions.Hosting namespace. For the Web Host, you use
the Microsoft.AspNetCore.Hosting namespace.
231. How does the host handle dependency injection in ASP.NET Core?
Answer: The host's dependency injection container provides services that can be used throughout the application.
Services are registered during application startup using the ConfigureServices method.

232. Why is configuration important in ASP.NET Core hosting?


Answer: Configuration allows you to customize various aspects of the application, such as database connections,
external API settings, and more, without modifying the code.

233. What is the role of the application's lifetime managed by the host?
Answer: The application's lifetime includes startup, running, and graceful shutdown. The host manages the
sequence of these events and ensures that resources are properly released.

234. How can you customize the behavior of a host in ASP.NET Core?
Answer: You can customize the host's behavior by modifying the configuration, adding middleware, and
configuring services during the ConfigureServices method.

235. What is the main advantage of using a host in ASP.NET Core?


Answer: Using a host provides a consistent way to set up and manage the application environment, making it
easier to configure services, handle application lifetime, and work with dependency injection.

236. Can you host an ASP.NET Core web application without using the built-in hosting libraries?
Answer: Yes, you can self-host an ASP.NET Core application without using the built-in hosting libraries by directly
using Kestrel, the web server used by ASP.NET Core. However, using the built-in hosting libraries offers benefits
like integration with configuration, logging, and dependency injection.
237. How do you manage different environments (development, staging, production) in an ASP.NET Core application's
hosting?
Answer: ASP.NET Core provides an appsettings.json file that allows you to configure environment-specific settings.
By setting the ASPNETCORE_ENVIRONMENT environment variable, the application automatically loads the
appropriate configuration file. For example, setting it to "Staging" loads appsettings.Staging.json.
238. Is it possible to have multiple instances of the same ASP.NET Core application hosted on a single server?
Answer: Yes, you can host multiple instances of an ASP.NET Core application on the same server by using different
ports or hostnames. Each instance runs in its own process and has its own isolated environment.
239. How can you handle exception logging and reporting in an ASP.NET Core application hosted on a remote server?
Answer: You can use various logging providers available in ASP.NET Core, such as ILogger, and configure them to
log exceptions to a central location like a database or an external service. Additionally, you can integrate third-
party tools like Application Insights or Sentry for more advanced exception monitoring and reporting.
240. What is the purpose of the WebHostDefaults and HostDefaults classes in ASP.NET Core hosting?

93
RESTRICTED
RESTRICTED

Answer: These classes provide default configuration settings for the Web Host and the Generic Host, respectively.
They help standardize and simplify the configuration process by providing sensible defaults for various aspects of
the host, such as URLs, environment, and more.
241. Can you run both a Web Host and a Generic Host within the same ASP.NET Core application?
Answer: Yes, it's possible to run both a Web Host and a Generic Host within the same ASP.NET Core application.
This could be useful if your application includes both web-related components and background services.
242. How can you implement custom middleware to modify the request before it reaches the endpoint in an ASP.NET
Core application?
Answer: You can create custom middleware by implementing the IMiddleware interface or using the
UseMiddleware<T> extension method. Within the middleware, you can modify the request, perform custom logic,
and even short-circuit the request pipeline.

243. Explain the concept of in-process hosting and out-of-process hosting in ASP.NET Core.
Answer: In in-process hosting, the ASP.NET Core application is hosted within the same process as the host. This is
suitable for development scenarios. In out-of-process hosting, the application is hosted in a separate process,
which provides better isolation and reliability. Out-of-process hosting is used for production deployments.

244. What are the benefits and drawbacks of using Docker containers to host ASP.NET Core applications?
Answer: Benefits of using Docker containers include consistency in deployment, isolation, and portability across
different environments. However, drawbacks might include a slightly increased learning curve, potential resource
overhead, and the need for container orchestration tools for complex deployments.

245. Explain the concept of host filtering in ASP.NET Core.


Answer: Host filtering allows you to limit which hostnames your application will respond to. This can be useful
when you want to run multiple applications on the same server but have each application respond to specific
hostnames only.

ASP.NET – Worker Service & Background Service


Worker Service: A Worker Service is a type of project template introduced in .NET Core 3.0 to simplify the creation of
long-running background services. It provides a structured way to build services that can run as Windows services, Linux
daemons, or even console applications. Worker Services are typically used for tasks like message processing, background
jobs, or any other recurring task that requires minimal interaction with the hosting environment.
Worker Services provide a Worker class where you implement your background logic. It takes advantage of the .NET Core
Hosted Service pattern to manage the lifecycle of the service and handle graceful shutdown. This means you can configure
your service to start when the application starts and stop when the application is shutting down.

Background Service: A Background Service is a lower-level concept that existed before Worker Services were
introduced. It's a more general approach for creating background tasks in .NET Core. While Worker Services provide a
higher level of abstraction and more built-in features, Background Services give you more flexibility in terms of
implementation.

94
RESTRICTED
RESTRICTED

To create a Background Service, you would typically inherit from the BackgroundService base class provided by the
Microsoft.Extensions.Hosting namespace. This base class includes methods like ExecuteAsync(CancellationToken
stoppingToken) that you override to implement your background task logic.

Sample Questionnaires on Worker Service & Background Service:


246. What is a Background Service in .NET?
Answer: A Background Service is a long-running background task that inherits from BackgroundService class in the
Microsoft.Extensions.Hosting namespace. It's a way to create and manage asynchronous tasks that run
independently of the main application and can be used for scenarios like periodic data processing, notifications,
etc.
247. How do you create a Background Service in .NET?
Answer: To create a Background Service, you inherit from the BackgroundService class and implement the
ExecuteAsync method to define your background task's logic.
248. What advantage does the BackgroundService class provide?
Answer: The BackgroundService class handles lifecycle and graceful shutdown, ensuring your background task is
properly started and stopped as the application starts and stops. It also provides access to the application's
CancellationToken for graceful shutdown handling.

249. What is a Worker Service in .NET?


Answer: A Worker Service is a type of project template introduced in .NET Core 3.0 for building long-running
background services. It simplifies the creation of services that run independently, handling aspects like hosting,
dependency injection, and lifecycle management.
250. What's the primary purpose of a Worker Service?
Answer: The primary purpose of a Worker Service is to perform background processing tasks such as message
processing, scheduled jobs, and other recurring tasks that don't require direct user interaction.
251. How is dependency injection handled in a Worker Service?
Answer: A Worker Service utilizes the built-in dependency injection system of .NET Core, allowing you to inject
services into your worker logic using constructor injection.
252. What are the main differences between a Background Service and a Worker Service?
Answer:
✓ Background Services are built on the BackgroundService class and offer more control and customization.
✓ Worker Services are a project template for creating long-running services, providing a more opinionated
structure.
✓ Worker Services include built-in hosting and lifecycle management.
253. In what scenarios would you prefer a Background Service over a Worker Service and vice versa?
Answer:
✓ Choose Background Service when you need finer control over the background task's logic and behavior.
✓ Choose Worker Service when you want a streamlined approach with built-in hosting and lifecycle
management.

254. Can you run multiple instances of a Worker Service within the same application? If so, how would you manage
them?

95
RESTRICTED
RESTRICTED

Answer: Yes, you can run multiple instances of a Worker Service by registering them with different names in the
appsettings.json file and configuring a WorkerOptions section for each. This allows you to manage and control
multiple instances separately.
255. How can you implement periodic execution in a Worker Service without using built-in timers?
Answer: You can use a combination of await Task.Delay() and a loop within the ExecuteAsync method to
implement periodic execution. However, built-in timer libraries like System.Threading.Timer or
System.Timers.Timer are generally recommended for better accuracy and efficiency.
256. How can you ensure that a Background Service continues running even if an unhandled exception occurs within
its logic?
Answer: You can wrap the logic inside the ExecuteAsync method of the Background Service with a try-catch block.
Make sure to handle exceptions appropriately, log them, and continue the execution of the loop or task.

ASP.NET Core - Globalization & Localization


Globalization and localization are essential concepts when it comes to building software that can be used by
people from different cultures, languages, and regions. In the context of .NET applications, globalizing means
designing your application to be culture-neutral and accommodating various languages and formats, while
localizing involves adapting the application to a specific culture or language.

Globalization:
✓ Resource Files: Externalize user-visible strings, messages, and other localized content into resource files.
In .NET, these are typically .resx files.
✓ Culture-Neutral Code: Write code in a culture-neutral manner. Avoid hardcoding culture-specific formats,
such as date and number formats.
✓ Culture-Aware APIs: Use culture-aware APIs when working with dates, times, numbers, and strings. These
APIs automatically format and parse values based on the user's culture.
✓ Use Resource Managers: Utilize the ResourceManager class to access resources based on the user's
culture. This ensures that the correct localized content is displayed.

Localization:
Culture-Specific Resource Files: Create separate resource files for each target culture. For example, Resources.resx
for default content and Resources.fr.resx for French content.
✓ Set Current Culture: Set the application's Thread.CurrentThread.CurrentCulture and
Thread.CurrentThread.CurrentUICulture to the desired culture. This controls how dates, numbers, and
strings are formatted and displayed.
✓ Localized Content: Load and display content from the appropriate culture-specific resource file based on
the user's chosen culture.
✓ Formatting and Parsing: Utilize culture-aware APIs to format and parse dates, times, and numbers in a
way that's appropriate for the user's culture.
✓ Testing: Thoroughly test your localized application with different cultures to ensure that content is
correctly displayed and formatted.

96
RESTRICTED
RESTRICTED

Sample Questionnaires on ASP.NET Core – Globalization & Localization:


257. What is globalization in the context of software development?
Answer: Globalization is the process of designing and developing software to be culture-neutral, allowing it to be
adapted for different languages, regions, and cultures.
258. Why is using culture-neutral code important in globalized applications?
Answer: Culture-neutral code avoids hardcoding language or culture-specific formats, ensuring the application
remains adaptable to different cultures without code changes.
259. How do you handle culture-specific formatting for numbers and dates in a globalized application?
Answer: Use culture-aware APIs such as CultureInfo and NumberFormatInfo to format and parse numbers and
dates according to the user's culture
260. What is localization in software development?
Answer: Localization is the process of adapting a software application for a specific language or culture by
providing translated content and culture-specific formats.
261. What is the purpose of resource files in localization?
Answer: Resource files store localized content, such as strings and messages, enabling the application to display
the correct content based on the user's chosen culture.
262. How do you set the culture for a user in a localized application?
Answer: Set the Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture properties to
the desired culture, ensuring correct formatting and content display.
263. Why is it important to test a localized application with various cultures?
Answer: Testing ensures that content is correctly displayed, formatted, and aligned in different languages and
regions, improving the user experience.
264. How can you handle right-to-left (RTL) languages in a localized application?
Answer: Ensure your application's layout and UI elements are compatible with RTL display by using appropriate
controls and styling.
265. What's the difference between CurrentCulture and CurrentUICulture?
Answer: CurrentCulture affects formatting of dates and numbers, while CurrentUICulture determines which
resource files to use for UI content.
266. Besides translating content, what other aspects should be considered during the localization process?
Answer: Apart from translation, consider localized images, icons, and UI layout adjustments to accommodate
longer or shorter text in different languages.
267. Are there any challenges when dealing with bidirectional languages like Arabic or Hebrew?
Answer: Yes, bidirectional languages require special consideration for layout, alignment, and rendering order to
ensure proper display.
268. Can you mention a tool or framework that can assist in managing localization resources?
Answer: The Resource Manager class provided by .NET Framework can help manage and access resources in
localized applications.
269. How can you ensure that your globalized application can handle various character encodings?
Answer: Use Unicode (UTF-8 or UTF-16) for storing and processing text, ensuring compatibility with characters
from different languages.
ASP.NET Core - SignalR

97
RESTRICTED
RESTRICTED

SignalR is a real-time communication library in .NET Core that enables bi-directional communication between the
server and connected clients over websockets or other supported transport mechanisms. It's particularly useful
for building interactive and dynamic web applications, online games, chat applications, live data visualization, and
more.

Key Concepts:
✓ Hubs: Hubs are high-level abstractions in SignalR that provide a simple way to manage communication
between clients and the server. They allow you to call methods on connected clients from the server and
vice versa.
✓ Connections: Connections represent a communication channel between a client and the server. Each
client maintains a connection to the server, enabling real-time communication.
✓ Clients: Clients are JavaScript or .NET Core code that connect to the SignalR hub. They can receive
messages and invoke methods on the server.
Features:
✓ Real-Time Communication: SignalR enables real-time updates and notifications, making it suitable for
applications requiring instant data synchronization.
✓ Multiple Transport Support: SignalR supports various transport mechanisms, including WebSockets,
Server-Sent Events (SSE), and Long Polling. It uses the most suitable transport based on the client's
capabilities.
✓ Scalability: SignalR supports scaling out across multiple servers or processes, making it suitable for high-
traffic scenarios.
✓ Automatic Reconnection: SignalR clients automatically attempt to reconnect to the server if the
connection is lost, providing a seamless experience for users.
✓ Authorization and Security: SignalR provides mechanisms for securing connections and methods to ensure
that only authorized clients can access certain functionality.
Integration with .NET Core:
✓ Installing SignalR: To use SignalR in a .NET Core application, you need to install the
Microsoft.AspNetCore.SignalR NuGet package.
✓ Creating Hubs: Define SignalR hubs by creating classes that derive from the Hub class. These classes
contain methods that can be invoked by clients.
✓ Configuring Endpoints: Configure SignalR endpoints in the Startup.cs file to specify how clients connect to
the hub.
✓ Client-Side Integration: On the client side, you can use JavaScript libraries for web applications or the
Microsoft.AspNetCore.SignalR.Client NuGet package for .NET Core clients.
Use Case:
SignalR is ideal for scenarios that require real-time updates and user interactions, such as:
✓ Chat applications
✓ Collaborative tools
✓ Multiplayer online games
✓ Live data dashboards
✓ Notifications and alerts
✓ Live customer support

98
RESTRICTED
RESTRICTED

Sample Questionnaires on ASP.NET Core – SignalR:

270. What is the primary purpose of SignalR in .NET Core?


Answer: SignalR is used to enable real-time communication between the server and connected clients, allowing
instant updates and interactions in web applications.
271. How does SignalR determine the most appropriate transport mechanism for communication?
Answer: SignalR dynamically selects the most suitable transport mechanism based on the capabilities of the client
and server. It supports WebSockets, Server-Sent Events (SSE), and Long Polling.
272. Can you explain the concept of SignalR hubs and their role in communication?
Answer: SignalR hubs provide a high-level abstraction for managing communication between the server and
clients. Hubs allow clients to invoke methods on the server and vice versa.

273. How does SignalR handle automatic reconnection when a client loses its connection?
Answer: SignalR clients automatically attempt to reconnect to the server if the connection is lost, ensuring a
continuous and seamless user experience.
274. What is the purpose of the [Authorize] attribute in SignalR hubs?
Answer: The [Authorize] attribute in SignalR hubs restricts access to methods based on user authentication and
authorization, ensuring that only authorized clients can invoke specific methods.
275. How can you handle communication between specific clients using SignalR?
Answer: SignalR provides group communication functionality, allowing you to organize clients into groups and
send messages to specific groups of clients.
276. How do you integrate SignalR with JavaScript in a web application?
Answer: In a web application, you can use the SignalR JavaScript client library to connect to the SignalR hub and
receive real-time updates from the server.
277. Can you briefly explain how to scale a SignalR application to handle high traffic?
Answer: To scale a SignalR application, you can use a backplane, such as Azure SignalR Service or Redis, to
distribute messages and manage connections across multiple servers or processes.

278. What are some potential challenges or considerations when using SignalR?
Answer: Challenges include managing state synchronization between server and clients, handling connection
timeouts and retries, and ensuring efficient use of server resources.

279. In what scenarios would you choose SignalR over traditional HTTP-based communication?
Answer: SignalR is beneficial for scenarios requiring real-time updates, interactive user experiences, and
collaborative features, such as chat applications, live data dashboards, and online gaming.

280. What are the steps to enable cross-platform communication between a .NET Core SignalR server and a JavaScript
client?
Answer: To enable cross-platform communication, use the SignalR JavaScript client library on the client side and
the Microsoft.AspNetCore.SignalR.Client package on the .NET Core server side.

99
RESTRICTED
RESTRICTED

281. In a load-balanced environment, what strategies can you use to ensure that SignalR clients are connected to the
same server instance?
Answer: To ensure that SignalR clients stay connected to the same server instance, you can use a backplane
solution like Redis, which shares state across multiple server instances.

282. What are the benefits of using the SendAsync method over the InvokeAsync method in SignalR?
Answer: The SendAsync method is used when you want to broadcast a message to all connected clients without
waiting for a response. In contrast, the InvokeAsync method is used when you want to invoke a method on a
specific client and await a response.

283. What are the steps to enable cross-platform communication between a .NET Core SignalR server and a JavaScript
client?
Answer: To enable cross-platform communication, use the SignalR JavaScript client library on the client side and
the Microsoft.AspNetCore.SignalR.Client package on the .NET Core server side.

284. How can you gracefully handle client disconnections in SignalR?


Answer: You can handle client disconnections by subscribing to the OnDisconnectedAsync event in the SignalR
hub. This event is triggered when a client disconnects, allowing you to perform cleanup tasks.

Sample Questionnaires on ASP.NET Core - WEB API:


285. What is ASP.NET Core Web API?
Answer: ASP.NET Core Web API is a framework for building HTTP-based services using the MVC pattern, designed
specifically for creating RESTful APIs.

286. How can you create a new ASP.NET Core Web API project?
Answer: You can create a new ASP.NET Core Web API project using the dotnet new webapi command or by
selecting the "ASP.NET Core Web API" template in Visual Studio.

287. How can you return JSON data from a Web API controller action in ASP.NET Core?
Answer: You can return JSON data by using the return Json(data) method or by using the return Ok(data)
method, where data is the object you want to serialize.

288. What is the purpose of the [HttpGet], [HttpPost], etc. attributes in Web API controllers?
Answer: These attributes are used to specify the HTTP verb (GET, POST, etc.) that an action method responds to.
They define the type of HTTP request the action handles.

289. How can you bind data from the request body in a Web API action method?
Answer: Data from the request body can be bound to method parameters or model properties using the
[FromBody] attribute, like [HttpPost] public IActionResult Post([FromBody] MyModel model).

290. How can you handle errors and return appropriate status codes in a Web API action?
100
RESTRICTED
RESTRICTED

Answer: You can return status codes using methods like return BadRequest(), return NotFound(), or return
StatusCode(). You can also create custom error responses.

291. What is the purpose of the [FromBody] and [FromQuery] attributes in Web API action methods?
Answer: The [FromBody] attribute binds data from the request body, while the [FromQuery] attribute binds data
from the query string. They are used to extract data for parameter binding.

292. How can you implement authentication and authorization in ASP.NET Core Web API?
Answer: Authentication and authorization can be implemented using middleware like JWT (JSON Web Tokens),
OAuth, or OpenID Connect. The [Authorize] attribute can be used to restrict access to authorized users.

293. How can you return specific HTTP status codes and custom error messages from a Web API action?
Answer: Specific HTTP status codes and custom error messages can be returned using methods like
BadRequest(), NotFound(), and StatusCode(), along with custom error model classes.

294. How do clients typically communicate with a Web API?


Answer: Clients communicate with a Web API by making HTTP requests, such as GET, POST, PUT, or DELETE, to
specific endpoints (URLs) provided by the API.

295. What are the differences between Web API and WCF REST API?
Answer: Web API is suitable for HTTP-based services, while WCF REST API is ideal for Message queues, one-way
messaging, and duplex communication. WEB API supports any media format, even XML and JSON, while WCF
supports SOAP and XML formats. ASP.Net Web API is ideal for building HTTP services, while WCF is perfect for
developing service-oriented applications. To run Web API, there is no configuration required, while in the case of
WCF, a lot of configuration is required to run it.

296. What are the several return types in ASP.Net Web API?
Answer: The various return types in ASP.Net Web API are:
✓ IHttpActionResult
✓ HttpResponseMessage
✓ Void
✓ Other Type – string, int, or other entity types.
297. How to secure an ASP.Net Web API?
Answer: To secure an ASP.Net Web API, we need to control the Web API and decide who can access the API and
who cannot access it. Web API can be accessed by anyone who knows about the URL.

298. How to host Web API?


A: There are two ways how Web API application can be hosted:
✓ Self Hosting
✓ IIS Hosting
299. How to consume Web API using HTTPClient?
Answer: HTTPClient is introduced in HTTPClient class for communicating with ASP.Net Web API. This HTTPClient
class is used either in a console application or in an MVC application.

300. What is Token Based Authentication in Web API?

101
RESTRICTED
RESTRICTED

Answer: It is an approach to secure .Net Web API as it authenticates users by a signed token, also called a token-
based approach.

301. What is Bearer Authentication in .Net Web API?


Answer: Bearer authentication is also known as Token-based authentication.

302. What is REST?


Answer:
✓ REST stands for Representational State Transfer. This is an architectural pattern that helps in exchanging
data over a disseminated environment.
✓ REST architectural pattern treats all the services as resources and a client can access these resources by
using HTTP protocol methods which include PUT, GET, POST, and DELETE.

303. What are the key principles of RESTful APIs?


The key principles include stateless communication, client-server architecture, uniform interfaces, caching,
layered system, and code-on-demand (optional).

304. How does a RESTful API represent resources?


Resources in a RESTful API are represented by URIs (Uniform Resource Identifiers), such as URLs, which clients
use to request or manipulate data.

305. What are the HTTP methods commonly used in RESTful APIs?
Common HTTP methods used are GET (retrieve data), POST (create data), PUT (update data), and DELETE
(remove data).

306. What is the role of media types (MIME types) in RESTful APIs?
Media types indicate the format of the data being sent or received. Common types include JSON
(application/json) and XML (application/xml).

307. Provide an example of a RESTful API request?


Here's an example:
GET /api/products/123 HTTP/1.1
Host: example.com
Accept: application/json

308. Which protocol is supported by Web API?


Answer: The only protocol supported by Web API is HTTP. Therefore, it can be consumed by a client that
supports HTTP protocol.
309. How to mention Roles and users using Authorize attribute in Web API?
// Restrict by Name
[Authorize(Users=”apiuser”)]
public class StudentController : ApiController{}
// Restrict by Role[Authorize(Roles=”Administrators”)]
public class StudnetController : ApiController{}
310. What are the default media types supported by Web API?

102
RESTRICTED
RESTRICTED

Answer: The default media types that are supported by Web API are XML, form-urlencoded data, JSON, BSON.
The other media types supported can be done by writing a media formatter.
311. How to implement Basic Authentication in ASP.Net Web API?
Answer: Basic Authentication in ASP.Net Web API is one where the client will send a request using the word
Basic with an Authorization header, followed by a base 64 encoded string.

The syntax for Basic Authentication –


Authorization: Basic username: password

312. What is POSTMAN?


The Postman is the most popular and most powerful HTTP client for testing restful web services. Postman makes
it easy to test the Restful Web APIs, as well as develops and documents Restful APIs by allowing the users to
quickly put together both simple and complex HTTP requests. The Postman is available as both a Google Chrome
in-browser app and Google Chrome Packaged App.

Sample Questionnaires on HTML:

313. What is HTML?


HTML stands for Hyper Text Markup Language. It is a language of World Wide Web. It is a standard text
formatting language which is used to create and display pages on the Web. It makes the text more interactive
and dynamic. It can turn text into images, tables, links.

314. What are Tags?


HTML tags are composed of three things: an opening tag, content and ending tag. Some tags are unclosed tags.
HTML documents contain two things:
✓ content
✓ tags
When a web browser reads an HTML document, the browser reads it from top to bottom and left to right. HTML
tags are used to create HTML documents and render their properties. Each HTML tags have different properties.
Syntax: <tag> content </tag>

315. Are the HTML tags and elements the same thing?
No. HTML elements are defined by a starting tag, may contain some content and a closing tag.For example,
<h1>Heading 1</h1> is a HTML element but just <h1> is a starting tag and </h1> is a closing tag.

316. What is the ‘class’ attribute in HTML?


The class attribute is used to specify the class name for an HTML element. Multiple elements in HTML can have
the same class value. Also, it is mainly used to associate the styles written in the stylesheet with the HTML
elements.

103
RESTRICTED
RESTRICTED

317. Define multipart form data?


Multipart form data is one of the values of the enctype attribute. It is used to send the file data to the server-
side for processing. The other valid values of the enctype attribute are text/plain and application/x-www-form-
urlencoded.

318. In how many ways can we specify the CSS styles for the HTML element?
There are three ways in which we can specify the styles for HTML elements:

✓ Inline: Here we use the ‘style’ attribute inside the HTML element.
✓ Internal: Here we use the <style> tag inside the <head> tag. To apply the style we bind the elements
using ‘id’ or ‘class’ attributes.
✓ External: Here we use the <link> tag inside <head> tag to reference the CSS file into our HTML code.
Again the binding between elements and styles is done using ‘id’ or ‘class’ attributes.
319. Difference between link tag <link> and anchor tag <a>?
The anchor tag <a> is used to create a hyperlink to another webpage or to a certain part of the webpage and
these links are clickable, whereas, link tag <link> defines a link between a document and an external resource
and these are not clickable.

320. What are forms and how to create forms in HTML?


The HTML form is used to collect the user inputs. HTML provides a <form> tag to create forms. To take input
from the user we use the <input> tag inside the form so that all collected user data can be sent to the server for
processing. There are different input types like ‘button’, ‘checkbox’, ‘number’, ‘text’, ‘password’, ‘submit’ etc.

<form action="/submit_data.php">
<label>Enter your name: </label>
<input type="text" name="name" />
<label>Enter Mobile number </label>
<input type="number" name="mobile_no"/>
<input type="submit" value="Submit">
</form>

321. What are some of the advantages of HTML5 over its previous versions?
Some advantages of HTML5 are:-

✓ It has Multimedia Support.


✓ It has the capabilities to store offline data using SQL databases and application cache.
✓ Javascript can be run in the background.
✓ HTML5 also allows users to draw various shapes like rectangles, circles, triangles, etc.
✓ Included new Semantic tags and form control tags.

322. What are semantic elements in HTML5?


Semantic elements like <header>, <nav>, <article>, and <footer> provide clearer meaning and structure to web
content.

323. What is the Web Storage API in HTML5 used for?

104
RESTRICTED
RESTRICTED

Web Storage API (localStorage and sessionStorage) allows storing key-value pairs in a user's browser for
persistent and session-based data storage.

324. What's the role of the <main> element in HTML5?


The <main> element represents the main content of a document, and it should be unique to the document. It's
typically used once per page.

325. How does HTML5 handle local storage?


HTML5 provides the Web Storage API, including localStorage and sessionStorage, allowing websites to store key-
value pairs locally in a user's browser.

326. How does ASP.NET Core integrate HTML5?


ASP.NET Core allows you to write HTML5 directly within Razor views, which are .cshtml files containing HTML
and C# code mixed together.

327. How can I include HTML5 input types in ASP.NET Core forms?
ASP.NET Core's HtmlHelper methods enable you to generate HTML5 input types like email, url, and number
within your Razor views.

328. How does ASP.NET Core handle responsive design using HTML5?
ASP.NET Core can be combined with CSS3 and media queries to create responsive layouts that adapt to different
screen sizes and devices.
329. How can we use HTML5's <canvas> element in ASP.NET Core?
We can integrate HTML5's <canvas> element within your Razor views to create dynamic graphics and
animations directly in the browser.
330. Is HTML5's offline storage feature compatible with ASP.NET Core?
Yes, you can utilize HTML5's offline storage features like Application Cache in combination with ASP.NET Core to
create offline-capable web applications.
331. What is the usage of a novalidate attribute for the form tag that is introduced in HTML5?
Its value is a boolean type that indicates whether or not the data being submitted by the form will be validated
beforehand. By making this false, forms can be submitted without validation which helps users to resume later
also.

332. What are HTML Attributes?


Attributes are the properties that can be added to an HTML tag. These attributes change the way the tag
behaves or is displayed. For example, a <img> tag has an src attribute, which you use to add the source from
which the image should be displayed.

333. What is a marquee in HTML?


Marquee is used for scrolling text on a web page. It scrolls the image or text up, down, left, or right
automatically. To apply for a marquee, you have to use </marquee> tags.

334. What is the difference between HTML and CSS?


HTML is used to create the structure and content of a web page, while CSS is used to define the appearance and
layout of the page.

105
RESTRICTED
RESTRICTED

335. What are HTML Entities?


HTML Entities are special characters used to represent characters that cannot be typed on a keyboard. They are
often used to display special symbols and foreign characters.

336. How do you create a hyperlink in HTML?


We use the anchor tag <a> to create a hyperlink in HTML that links one page to another page. The hyperlink can
be added to images too.

337. How do you add CSS styling in HTML?


There are three ways to include the CSS with HTML:

✓ Inline CSS: It is used when less amount of styling is needed or in cases where only a single element has
to be styled. To use inline styles add the style attribute in the relevant tag.
✓ External Style Sheet: This is used when the style is applied to many elements or HTML pages. Each
page must link to the style sheet using the <link> tag.
✓ Internal Style Sheet: It is used when a single HTML document has a unique style and several elements
need to be styled to follow the format. Internal styles sheet is added in the head section of an HTML
page, by using the <style> tag.
338. How do you add JavaScript to an HTML webpage?
To add JavaScript to an HTML webpage:
✓ Inline JavaScript:
Place JavaScript code directly within <script> tags in the HTML file's <head> or <body> section.
<script>
// Your JavaScript code here
</script>
✓ External JavaScript File:
Create a separate .js file and link it using the <script> tag's src attribute.
<script src="your-script.js"></script>
✓ Document Ready Event (Recommended):
Sample Questionnaires on CSS:

339. What is CSS3?


CSS3 is the latest version of Cascading Style Sheets used for styling and presenting the visual layout of HTML
elements on web pages.

340. What are the advantages of using CSS?


The main advantages of CSS are given below:

✓ Separation of content from presentation - CSS provides a way to present the same content in multiple
presentation formats in mobile or desktop or laptop.
✓ Easy to maintain - CSS, built effectively can be used to change the look and feel complete by making
small changes. To make a global change, simply change the style, and all elements in all the web pages
will be updated automatically.

106
RESTRICTED
RESTRICTED

✓ Bandwidth - Used effectively, the style sheets will be stored in the browser cache and they can be
used on multiple pages, without having to download again.
341. How to include CSS in the webpage?
There are different ways to include a CSS in a webpage:
✓ External Style Sheet: An external file linked to your HTML document: Using link tag, we can link the style
sheet to the HTML page.
<link rel="stylesheet" type="text/css" href="mystyles.css" />
✓ Embed CSS with a style tag: A set of CSS styles included within your HTML page.

<style type="text/css">
/*Add style rules here*/
</style>
✓ Add inline styles to HTML elements(CSS rules applied directly within an HTML tag.): Style can be added
directly to the HTML element using a style tag.
<h2 style="color:red;background:black">Inline Style</h2>
✓ Import a stylesheet file (An external file imported into another CSS file): Another way to add CSS is by
using the @import rule. This is to add a new CSS file within CSS itself.
@import "path/to/style.css";

342. What are the CSS frameworks?


CSS frameworks are the preplanned libraries which make easy and more standard compliant web page styling.
The frequently used CSS frameworks are: -
✓ Bootstrap
✓ Foundation
✓ Semantic UI
✓ Gumby
✓ Ulkit
343. What is Embedded Style Sheet?
An Embedded style sheet is a CSS style specification method used with HTML. You can embed the entire
stylesheet in an HTML document by using the STYLE element. More details...
<style>
body {
background-color: linen;
}
h1 {
color: red;
margin-left: 80px;
}
</style>
344. What are the advantages of Embedded Style Sheets?
✓ You can create classes for use on multiple tag types in the document.
✓ You can use selector and grouping methods to apply styles in complex situations.
✓ No extra download is required to import the information.
345. What is a CSS selector?

107
RESTRICTED
RESTRICTED

It is a string that identifies the elements to which a particular declaration apply. It is also referred as a link
between the HTML document and the style sheet. It is equivalent of HTML elements. There are several different
types of selectors in CSS: -

✓ CSS Element Selector


✓ CSS Id Selector
✓ CSS Class Selector
✓ CSS Universal Selector
✓ CSS Group Selector
346. Name some CSS style components.
Some CSS Style components are:
✓ Selector
✓ Property
✓ Value
347. What is the use of CSS Opacity?
The CSS opacity property is used to specify the transparency of an element. In simple word, you can say that it
specifies the clarity of the image. In technical terms, Opacity is defined as the degree to which light is allowed to
travel through an object. For example:
<style>
img.trans {
opacity: 0.4;
filter: alpha(opacity=40); /* For IE8 and earlier */
}
</style>
348. What is the difference between class selectors and id selectors?
An overall block is given to class selector while id selectors take only a single element differing from other
elements.
✓ CSS Class Selector:
<style>
.center {
text-align: center;
color: blue;
}
</style>
✓ CSS Id Selector:
<style>
#para1 {
text-align: center; color: blue;
}
</style>

349. What are the advantages of External Style Sheets?


✓ You can create classes for reusing it in many documents.
✓ By using it, you can control the styles of multiple documents from one file.
✓ In complex situations, you can use selectors and grouping methods to apply styles.

108
RESTRICTED
RESTRICTED

350. What is the difference between CSS2 and CSS3?


✓ The main difference between CSS2 and CSS3 is that CSS3 is divided into different sections which are also
known as modules. Unlike CSS2, CSS3 modules are supported by many browsers.
✓ Apart from that, CSS3 contains new General Sibling Combinators which is responsible for matching the
sibling elements with the given elements.
351. Explain the difference between visibility: hidden and display: none?
✓ visibility: hidden hides an element while keeping its space in the layout.
✓ display: none completely removes an element from the layout and rendering.
352. What is the difference between a class and an ID?
Class is a way of using HTML elements for styling. They are not unique and have multiple elements. Whereas ID
is unique and it can be assigned to a single element.

353. How media types in CSS work?


The four types of media properties are print, speech, and screen. Example of using print-media type:

@media print {
h2 {
background-color: blue;
}
}

Sample Questionnaires on Javascript:

109
RESTRICTED
RESTRICTED

354. What is JavaScript?


JavaScript is a scripting language. It is different from Java language. It is object-based, lightweight, cross-
platform translated language. It is widely used for client-side validation. The JavaScript Translator (embedded in
the browser) is responsible for translating the JavaScript code for the web browser

355. List some features of JavaScript.


Some of the features of JavaScript are:
✓ Lightweight
✓ Interpreted programming language
✓ Good for the applications which are network-centric
✓ Complementary to Java
✓ Complementary to HTML
✓ Open source
✓ Cross-platform
356. Define a named function in JavaScript.
The function which has named at the time of definition is called a named function. For example
function msg()
{
document.writeln("Named Function");
}
msg();
357. How to use external JavaScript file?
Assuming that js file name is message.js, place the following script tag inside the head tag.
<script type="text/javascript" src="message.js"></script>

358. What is DOM? What is the use of document object?


DOM stands for Document Object Model. A document object represents the HTML document. It can be used to
access and change the content of HTML.

359. What is the use of window object?


The window object is created automatically by the browser that represents a window of a browser. It is not an
object of JavaScript. It is a browser object. The window object is used to display the popup dialog box.

360. How to write a comment in JavaScript?


There are two types of comments in JavaScript.
✓ Single Line Comment: It is represented by // (double forward slash)
✓ Multi-Line Comment: Slash represents it with asterisk symbol as /* write comment here */
361. How to create a function in JavaScript?
To create a function in JavaScript, follow the following syntax.

function function_name(){
//function body
}

362. What are the different data types present in JavaScript?

110
RESTRICTED
RESTRICTED

✓ String: The string data type represents a sequence of characters. It is written within quotes and can be
represented using a single or a double quote.

Example: var str1 = "Hello JavaTpoint"; //using double quotes

✓ Number: The number data type is used to represent numeric values and can be written with or without
decimals.
Example: var x = 5; //without decimal
✓ Boolean: The Boolean data type is used to represent a Boolean value, either false or true. This data type
is generally used for conditional testing.
Example: var x = 5;

363. What is the difference between == and ===?


The == operator checks equality only whereas === checks equality, and data type, i.e., a value must be of the
same type.
364. How to write HTML code dynamically using JavaScript?
The innerHTML property is used to write the HTML code using JavaScript dynamically. Let's see a simple
Example: document.getElementById('mylocation').innerHTML="<h2>This is heading using JavaScript</h2>";

365. How to create objects in JavaScript?


There are 3 ways to create an object in JavaScript.
✓ By object literal
✓ By creating an instance of Object
✓ By Object Constructor
Let's see a simple code to create an object using object literal.
emp={id:102,name:"Rahul Kumar",salary:50000}

366. How to create an array in JavaScript?


There are 3 ways to create an array in JavaScript.
✓ By array literal
✓ By creating an instance of Array
✓ By using an Array constructor
Let's see a simple code to create an array using object literal.
var emp=["Shyam","Vimal","Ratan"];
367. What does the isNaN() function?
The isNan() function returns true if the variable value is not a number. For example:
function number(num) {
if (isNaN(num)) {
return "Not a Number";
}
return "Number";
}
console.log(number('1000F'));
// expected output: "Not a Number"

console.log(number('1000'));

111
RESTRICTED
RESTRICTED

// expected output: "Number"


368. Difference between Client side JavaScript and Server side JavaScript?
✓ Client-side JavaScript comprises the basic language and predefined objects which are relevant to running
JavaScript in a browser. The client-side JavaScript is embedded directly by in the HTML pages. The browser
interprets this script at runtime.
✓ Server-side JavaScript also resembles client-side JavaScript. It has a relevant JavaScript which is to run in
a server. The server-side JavaScript are deployed only after compilation.
369. How to submit a form using JavaScript by clicking a link?
Let's see the JavaScript code to submit the form by clicking the link.

<form name="myform" action="index.php">


Search: <input type='text' name='query' />
<a href="javascript: submitform()">Search</a>
</form>
<script type="text/javascript">
function submitform()
{
document.myform.submit();
}
</script>
370. How to validate a form in JavaScript?
✓ Attach a submit event listener to the form.
✓ Inside the event listener, retrieve input values.
✓ Check each input's value against validation criteria.
✓ If validation fails, show an error message.
✓ If validation passes, either submit the form or provide success feedback.
Example:
const form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
event.preventDefault();

const nameInput = document.getElementById("name");


const emailInput = document.getElementById("email");

if (nameInput.value === "") {


alert("Name is required");
return;
}

if (!isValidEmail(emailInput.value)) {
alert("Invalid email format");
return;
}

112
RESTRICTED
RESTRICTED

alert("Form submitted successfully");


});

function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}

371. How do you declare a variable in JavaScript?


In JavaScript, you can declare a variable using keywords like var, let, or const. Here's how:
✓ Using var: var variableName = value; (function-scoped)
✓ Using let: let variableName = value; (block-scoped, reassignable)
✓ Using const: const variableName = value; (block-scoped, constant)
For example:
var age = 25;
let name = "John";
const PI = 3.14;

113
RESTRICTED
RESTRICTED

Sample Questionnaires on jQuery:

372. What is jQuery?


A: jQuery is a fast, small, and feature-rich JavaScript library. It simplifies HTML document traversal and
manipulation, event handling, and animation for building dynamic web applications.

373. Why use jQuery? What are its advantages?


A: There are many reasons behind its popularity; some of them are listed below

✓ As it is developed using JavaScript language, it has all features that JavaScript has, with multiple inbuilt
methods it is easy to use for validation
✓ Event handling is one of the good features of jQuery
✓ It’s easy to apply CSS to the controls using jQuery
✓ jQuery has good support to AJAX.
✓ jQuery has good support to animations as well.

374. How to use jQuery?


A: We know jQuery is the collection of JavaScript classes; these classes are bundled and put it in.JS files. To use
jQuery, we just need to add the reference of its library to our page.

375. What is min.js and why it is used?


A: min.js is a minified version of jQuery will mainly be introduced to enhance application performance. As the
Size of the minified jQuery file is smaller than normal jQuery file it loads faster than a normal file.

376. What is the difference between jQuery UI and jQuery?


A: jQuery UI is built using JavaScript, but upon jQuery so to use jQuery UI you need must include jQuery, jQuery
is the library built on pure JavaScript.

377. What is the difference between jQuery And JavaScript?


A: The simple and visible difference is, jQuery is a library whereas JavaScript is a language, jQuery is created
using JavaScript only, it has methods that use JavaScript language.

378. How do you include jQuery in a web page?

114
RESTRICTED
RESTRICTED

A: You can include jQuery by adding a script tag with a link to the jQuery library in the <head> or <body> section
of your HTML document. For example:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

379. What is the purpose of the $(document).ready() function?


A: The $(document).ready() function is used to ensure that code inside it executes only when the DOM is fully
loaded. It's commonly used to bind event handlers and perform actions on elements without waiting for the
entire page to load.

380. How do you select elements using jQuery?


A: Elements can be selected using jQuery by using the $() function with a selector as its argument. For example:

// Selects all <p> elements


var paragraphs = $("p");

381. How can you change the text content of an element using jQuery?
A: You can use the .text() method to set or get the text content of an element. For example:

// Set the text content of an element


$("p").text("New text content");

382. How would you perform an AJAX request using jQuery?


A: You can use the $.ajax() function to perform AJAX requests. Here's an example using GET method:

$.ajax({
url: "https://api.example.com/data",
method: "GET",
success: function(response) {
console.log(response);
},
error: function(error) {
console.error(error);
}
});

383. What is event delegation in jQuery?


A: Event delegation is a technique where you attach an event handler to a parent element rather than individual
child elements. This allows you to handle events on dynamically added elements as well. jQuery's .on() method
is commonly used for event delegation.

384. How can you add or remove CSS classes from an element using jQuery?
A: You can use the .addClass() method to add a class, .removeClass() method to remove a class, and
.toggleClass() method to toggle a class on an element.

115
RESTRICTED
RESTRICTED

385. What is the difference between .html() and .text() methods in jQuery?
A: The .html() method sets or gets the HTML content of an element, including any HTML tags. The .text() method
sets or gets only the text content of an element, without any HTML tags.

386. How can you animate elements using jQuery?


A: jQuery provides the .animate() method for creating animations. It allows you to animate various CSS
properties over a specified duration. For example:

$("div").animate({
width: "200px",
height: "200px"
}, 1000); // Animates div to 200x200px over 1 second

387. What is the purpose of the $() function in jQuery?


A: The $() function in jQuery is an alias for the jQuery() function. It's the entry point to using jQuery methods and
selecting elements in the DOM. You use it to create jQuery objects that can perform various operations on
selected elements.

388. How can you chain multiple jQuery methods together?


A: You can chain multiple jQuery methods together by using the dot notation. This allows you to perform a
sequence of operations on the same jQuery object. For example:

$("p")
.addClass("highlight")
.text("Updated text")
.fadeOut();

389. How do you handle events in jQuery?


A: Events can be handled using methods like .click(), .on(), and .bind(). Here's an example using .click():

$("button").click(function() {
alert("Button clicked!");
});

390. What is the purpose of the $.each() function in jQuery?


A: The $.each() function is used to iterate over elements in an array or object. It provides a way to perform a
specific action for each item in the collection.

391. What is the difference between .prop() and .attr() methods in jQuery?
A: The .prop() method gets the value of a property, such as a boolean attribute, from the first matched element.
The .attr() method gets the value of an attribute for the first matched element. Generally, .prop() is used for
properties that can have true/false values, while .attr() is used for other HTML attributes.

116
RESTRICTED
RESTRICTED

392. What is the purpose of the $.get() and $.post() methods in jQuery?
A: The $.get() method is used to perform an HTTP GET request, and the $.post() method is used to perform an
HTTP POST request. These methods are shorthand for the $.ajax() function, specifically tailored for these HTTP
methods.

393. What is the purpose of the $.noConflict() method in jQuery?


A: The $.noConflict() method is used to release control of the $ variable, which is often used as a shorthand for
jQuery, to other JavaScript libraries that might also use $. This is done to prevent conflicts between libraries that
use the same variable name.

394. How can you include jQuery in an ASP.NET Core project?


A: You can include jQuery by adding a reference to the jQuery library in the <head> section of your Razor layout
file (_Layout.cshtml) or in individual views. You can use a CDN or download the library locally and reference it.

395. How do you ensure that your jQuery code executes after the DOM is fully loaded in ASP.NET Core?
A: You can use the $(document).ready() function to ensure that your jQuery code executes after the DOM is fully
loaded. Alternatively, you can use the shorthand version $(function() { /* your code here */ });.

396. How can you make an AJAX request using jQuery in ASP.NET Core?
A: You can use the $.ajax() function to make AJAX requests in ASP.NET Core. You specify the URL, type of request
(GET, POST, etc.), and handle the success or error callbacks. Make sure to provide the appropriate URL route
using Razor syntax.

397. How do you handle errors in AJAX requests with jQuery in ASP.NET Core?
A: You can handle errors in AJAX requests using the error callback of the $.ajax() function. This callback will be
invoked if the request encounters an error, such as a network issue or a server-side error.

398. What is caching in jQuery?

We know cache is the temp memory that store data, each time when access any page it accesses cache and load
data from there only, it will boost application performance, the same concept applies to jQuery we can cache
jQuery elements and use them instead of re-querying or re-executing methods/property on DOM

var $controlcahce = $("#button1")


$controlcahce.css("color", "red");
$controlcahce.text("text set!");
Code Snippet Explanation: In the above snippet, we have selected button1with its ID and store it in a
controllable variable, later on, we can use it directly to set CSS value or set text.

399. What are the jQuery get methods?


A: jQuery has more powerful ways of manipulating and changing HTML elements and attributes. Following
functions are known as jQuery Get methods

✓ text()
✓ html()
117
RESTRICTED
RESTRICTED

✓ val()
400. What is the difference between “this” and “$(this)” In jQuery?
A: To refer current element, we use ‘this’ element, in traditional, we use ‘this’ object and in jQuery, we use
‘$(this)’ this new object will also help us to explore and support jQuery methods also. No doubt you can use
‘this’ in jQuery also. Look at below sample

//Using ‘this’
$(document).ready(function () {
$('#id1').click(function () {
alert(this.innerText);
});
});
//Using $(this)
$(document).ready(function () {
$('# id1').click(function () {
alert($(this).text());
});

401. What are the supported methods to Ajax in jQuery?


Below methods are used to deal with Ajax in jQuery

✓ Get()
✓ Post()
✓ GetJSON()
✓ Ajax()

402. What is the difference between $(window).load and $(document).ready function in jQuery?
A: $(window).load is an event that fires when the DOM and all the content (everything) on the page is fully
loaded. This event is fired after the ready event.
<script type="text/javascript" lang="ja">
$(window).load(function() {
alert("Window load event fired");
});

$(document).ready(function() {
alert("document ready event fired");
});
</script>

403. What is Ajax in jQuery?


A: AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a server, without
reloading the whole page. It is a technique for creating fast and dynamic web pages.

118
RESTRICTED
RESTRICTED

In .NET, we can call server side code using two ways:

ASP .NET AJAX


jQuery AJAX
In this article we will focus on jQuery Ajax.

$.ajax () Method

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

$.ajax() - Performs an async AJAX request.


$.get() - Loads data from a server using an AJAX HTTP GET request.
$.post() - Loads data from a server using an AJAX HTTP POST request.

404. What $(document).ready(function()) is and when to use it?


A: $(document).ready(function()) is a jQuery event that fires as soon as the DOM is fully loaded and ready to be
manipulated by script. This is the earliest point in the page load process where the script can safely access
elements in the page's HTML DOM. This event is fired before all the images and CSS are fully loaded.

405. How can you use array with jQuery?


A: Arrays are zero indexed, ordered lists of values. They are really handy for storing a set of values of the same
data type.

var names = [“Name1”,”Name2”] //Recommended

Both of the preceding approaches are kind of static declarations. Now let's do some dynamic programming with
Arrays.

var namearray = [];


namearray.push(“Name1”) //Index 0
namearray.push(“Name2”) //Index 1
namearray.push(“Name3”) //Index 2
406. How do you select element by ID in jQuery?
A: To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select
element with ID "txtName", then syntax would be,

$('#txtName')

407. What does dollar sign ($) means in jQuery?


A: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.

$(document).ready(function(){
});
Over here $ sign can be replaced with "jQuery" keyword.

119
RESTRICTED
RESTRICTED

jQuery(document).ready(function(){
});

408. Is there any difference between body.onload() and document.ready() function?


A: document.ready() function is different from body onload() function for several reasons:

We can have more than one document.ready() function in a page where we can have only one body onload
function.
document.ready() function is called as soon as DOM is loaded where body.onload() function is called when
everything gets loaded on the page that includes DOM, images and all associated resources of the page.

409. What are various methods to make ajax request in jQuery?


A: Using below jQuery methods, you can make ajax calls.

load() : Load a piece of html into a container DOM


$.getJSON(): Load JSON with GET method.
$.getScript(): Load a JavaScript file.
$.get(): Use to make a GET call and play extensively with the response.
$.post(): Use to make a POST call and don't want to load the response to some container DOM.
$.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.

410. What is the difference between eq() and get() methods in jQuery?
A: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element
within that set and returns it. That means that you can use jQuery functions on it.
get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is
a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used.

411. Why jQuery is better than JavaScript?


jQuery is a library used for developing Ajax application and it helps to write the code clean and concise. It also
handles events, animation and Ajax support applications.

120
RESTRICTED

You might also like